39 Commits

Author SHA1 Message Date
9be20ab1cd UF 0 o nula actualizadas para Pago y Pie 2025-03-26 16:54:53 -03:00
1c40f18624 Pagos sin uf retornan 0 2025-03-26 16:49:27 -03:00
db36549699 Agregar Pie 2025-03-26 16:41:54 -03:00
4ce83fb270 Merge branch 'develop' into feature/cierres 2025-03-26 15:42:47 -03:00
b191a01313 Promociones 2025-03-25 19:22:38 -03:00
d3b0026ca4 Agregar, editar y eliminar promociones 2025-03-18 19:13:47 -03:00
2b3f476df7 Agregar, editar y eliminar promociones 2025-03-18 19:12:59 -03:00
39c148b7b3 Cambio nombre archivo 2025-03-17 23:03:06 -03:00
bae0f1f555 Separacion de Promocion de Contrato y Precio
"Simplificacion" de datos en listado de precios
2025-03-17 22:49:48 -03:00
2e49e2c947 Listados separados por hojas (tabs) 2025-03-13 13:16:20 -03:00
68aebdb4fe Listado de Precios para Contrato Broker 2025-03-13 12:18:08 -03:00
346001db8e SearchBuilder configuration centralizada
FIX: CentroCosto TipoCuenta
2025-03-13 09:33:42 -03:00
8b04eb262f FIX: Editar datos Broker 2025-03-12 18:31:21 -03:00
7c7c8315e2 Editar Brokers y sus contratos 2025-03-11 17:41:11 -03:00
510e05e5ca FIX: rut con otros caracteres y maximo largo 2025-03-07 17:26:36 -03:00
5055d2703c Broker Contact 2025-03-07 17:11:59 -03:00
2bc30ab9e8 Formatear porcentajes menores a 1 2025-03-07 17:11:15 -03:00
c7ee440e03 Listado de brokers 2025-03-06 20:34:43 -03:00
18dd8c4ec0 Merge branch 'develop' into feature/cierres 2025-03-06 16:23:58 -03:00
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
101 changed files with 5460 additions and 86 deletions

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

@ -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_id', '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_id', 'broker_contacts', ['id'], ['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' => 1])
->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

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateBrokerContacts 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_contacts')
->addColumn('rut', 'integer', ['signed' => false, 'null' => true])
->addColumn('digit', 'string', ['length' => 1, 'null' => true])
->addColumn('name', 'string', ['length' => 255, 'null' => true])
->addColumn('email', 'string', ['length' => 255, 'null' => true])
->addColumn('phone', 'string', ['length' => 255, 'null' => true])
->addColumn('address_id', 'integer', ['signed' => false, 'null' => true])
->addForeignKey('address_id', 'direccion', ['id'], ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
}
}

View File

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreatePromotionContract 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('promotion_contracts')
->addColumn('promotion_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('contract_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('created_at', 'datetime', ['null' => false, 'default' => 'CURRENT_TIMESTAMP'])
->addForeignKey('promotion_id', 'promotions', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->addForeignKey('contract_id', 'broker_contracts', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->create();
}
}

View File

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AlterPromotionsRemovePrice 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('promotions')
->dropForeignKey('price_id')
->removeColumn('price_id')
->update();
}
}

View File

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreatePromotionUnit 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('promotion_units')
->addColumn('promotion_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('unit_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('created_at', 'datetime', ['null' => false, 'default' => 'CURRENT_TIMESTAMP'])
->addForeignKey('promotion_id', 'promotions', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->addForeignKey('unit_id', 'unidad', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->create();
}
}

View File

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AlterPromotionsNullDates 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('promotions')
->changeColumn('end_date', 'date', ['null' => true])
->changeColumn('valid_until', 'date', ['null' => true])
->update();
}
}

View File

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AlterPromotionsAddDescriptionAndType 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('promotions')
->addColumn('description', 'string', ['limit' => 255, 'null' => false, 'after' => 'id'])
->addColumn('type', 'integer', ['limit' => 1, 'null' => false, 'default' => 0, 'after' => 'description'])
->update();
}
}

View File

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreatePromotionProjects 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('promotion_tables')
->addColumn('promotion_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('project_id', 'integer', ['signed' => false, 'null' => false])
->addForeignKey('promotion_id', 'promotions', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->addForeignKey('project_id', 'proyecto', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->create();
}
}

View File

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreatePromotionContractUnits 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('promotion_contract_units')
->addColumn('promotion_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('contract_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('unit_id', 'integer', ['signed' => false, 'null' => false])
->addForeignKey('promotion_id', 'promotions', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->addForeignKey('contract_id', 'broker_contracts', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->addForeignKey('unit_id', 'unidad', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->create();
}
}

View File

@ -2,6 +2,16 @@
use Incoviba\Controller\Proyectos;
$app->group('/proyectos', function($app) {
$folder = implode(DIRECTORY_SEPARATOR, [__DIR__, 'proyectos']);
if (file_exists($folder)) {
$files = new FilesystemIterator($folder);
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
include_once $file->getRealPath();
}
}
$app->get('/unidades[/]', [Proyectos::class, 'unidades']);
$app->get('[/]', Proyectos::class);
})->add($app->getContainer()->get(Incoviba\Middleware\Authentication::class));

View File

@ -23,6 +23,7 @@ $app->group('/venta/{venta_id:[0-9]+}', function($app) {
$app->get('[/]', [Ventas::class, 'propiedad']);
});
$app->group('/pie', function($app) {
$app->get('/add[/]', [Ventas\Pies::class, 'add']);
$app->group('/cuotas', function($app) {
$app->get('[/]', [Ventas::class, 'cuotas']);
});

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) {
@ -14,10 +21,13 @@ $app->group('/proyecto/{proyecto_id}', function($app) {
$app->get('/vendible[/]', [Proyectos::class, 'superficies']);
});
$app->group('/unidades', function($app) {
$app->post('/precios[/]', [Proyectos\Unidades::class, 'precios']);
$app->post('/estados[/]', [Proyectos\Unidades::class, 'estados']);
$app->get('/disponibles[/]', [Proyectos::class, 'disponibles']);
$app->get('[/]', [Proyectos::class, 'unidades']);
});
$app->group('/terreno', function($app) {
$app->post('/edit[/]', [Proyectos::class, 'terreno']);
});
$app->get('/brokers', [Proyectos::class, 'brokers']);
});

View File

@ -0,0 +1,30 @@
<?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->group('/contract/{contract_id}', function($app) {
$app->post('/promotions[/]', [Contracts::class, 'promotions']);
});
$app->delete('[/]', [Brokers::class, 'delete']);
$app->get('[/]', [Brokers::class, 'get']);
});

View File

@ -54,6 +54,9 @@ $app->group('/venta/{venta_id}', function($app) {
$app->group('/propietario', function($app) {
$app->put('/edit[/]', [Ventas::class, 'propietario']);
});
$app->group('/pie', function($app) {
$app->post('/add[/]', [Ventas\Pies::class, 'add']);
});
$app->post('[/]', [Ventas::class, 'edit']);
$app->get('[/]', [Ventas::class, 'get']);
});

View File

@ -0,0 +1,10 @@
<?php
use Incoviba\Controller\API\Ventas\Promotions;
$app->group('/promotions', function($app) {
$app->post('/add[/]', [Promotions::class, 'add']);
$app->post('/edit[/]', [Promotions::class, 'edit']);
});
$app->group('/promotion/{promotion_id}', function($app) {
$app->delete('/remove[/]', [Promotions::class, 'remove']);
});

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

@ -0,0 +1,12 @@
<?php
use Incoviba\Controller\Proyectos\Brokers;
$app->group('/brokers', function($app) {
$app->get('[/]', Brokers::class);
});
$app->group('/broker/{broker_rut}', function($app) {
$app->group('/contract/{contract_id}', function($app) {
$app->get('[/]', [Brokers\Contracts::class, 'show']);
});
$app->get('[/]', [Brokers::class, 'show']);
});

View File

@ -0,0 +1,9 @@
<?php
use Incoviba\Controller\Ventas\Promotions;
$app->group('/promotions', function($app) {
$app->get('[/]', Promotions::class);
});
$app->group('/promotion/{promotion_id}', function($app) {
$app->get('[/]', [Promotions::class, 'show']);
});

View File

@ -96,26 +96,7 @@
columnDefs,
order,
language: Object.assign(dtD.language, {
searchBuilder: {
add: 'Filtrar',
condition: 'Comparador',
clearAll: 'Resetear',
delete: 'Eliminar',
deleteTitle: 'Eliminar Titulo',
data: 'Columna',
left: 'Izquierda',
leftTitle: 'Titulo Izquierdo',
logicAnd: 'Y',
logicOr: 'O',
right: 'Derecha',
rightTitle: 'Titulo Derecho',
title: {
0: 'Filtros',
_: 'Filtros (%d)'
},
value: 'Opciones',
valueJoiner: 'y'
}
searchBuilder
}),
layout: {
top1: {

View File

@ -2,4 +2,26 @@
<script src="https://cdn.datatables.net/datetime/1.5.2/js/dataTables.dateTime.min.js"></script>
<script src="https://cdn.datatables.net/searchbuilder/1.7.0/js/dataTables.searchBuilder.min.js"></script>
<script src="https://cdn.datatables.net/searchbuilder/1.7.0/js/searchBuilder.semanticui.js"></script>
<script>
const searchBuilder = {
add: 'Filtrar',
condition: 'Comparador',
clearAll: 'Resetear',
delete: 'Eliminar',
deleteTitle: 'Eliminar Titulo',
data: 'Columna',
left: 'Izquierda',
leftTitle: 'Titulo Izquierdo',
logicAnd: 'Y',
logicOr: 'O',
right: 'Derecha',
rightTitle: 'Titulo Derecho',
title: {
0: 'Filtros',
_: 'Filtros (%d)'
},
value: 'Opciones',
valueJoiner: 'y'
}
</script>
@endpush

View File

@ -0,0 +1,6 @@
@prepend('page_scripts')
<script src='https://unpkg.com/simple-statistics@7.8.8/dist/simple-statistics.min.js'></script>
<script>
const Stat = ss
</script>
@endprepend

View File

@ -1,9 +1,9 @@
<head>
<meta charset="utf8" />
@hasSection('page_title')
<title>Incoviba - @yield('page_title')</title>
<title>Incoviba - @yield('page_title')</title>
@else
<title>Incoviba</title>
<title>Incoviba</title>
@endif
<link rel="icon" href="{{$urls->images}}/Isotipo 16.png" />
@include('layout.head.styles')

View File

@ -0,0 +1,218 @@
@extends('proyectos.brokers.base')
@section('brokers_content')
<table id="brokers" class="ui table">
<thead>
<tr>
<th>RUT</th>
<th>Nombre</th>
<th>Contacto</th>
<th>Contratos</th>
<th class="right aligned">
<button class="ui small tertiary green icon button" id="add_button">
<i class="plus icon"></i>
</button>
</th>
</tr>
</thead>
@foreach($brokers as $broker)
<tr>
<td>
<span
@if ($broker->data()?->legalName !== '')
data-tooltip="{{ $broker->data()?->legalName }}" data-position="right center"
@endif
>
{{$broker->rutFull()}}
</span>
</td>
<td>
<a href="{{ $urls->base }}/proyectos/broker/{{ $broker->rut }}">
{{$broker->name}}
</a>
</td>
<td>
<span
@if ($broker->data()?->representative?->email !== '' || $broker->data()?->representative?->phone !== '')
data-tooltip="{{ ($broker->data()?->representative?->email !== '') ? "Email: " . $broker->data()?->representative?->email : '' }}{{ ($broker->data()?->representative?->phone !== '') ? ' Teléfono: ' . $broker->data()?->representative?->phone : '' }}" data-position="right center"
@endif
>
{{ $broker->data()?->representative?->name }}
</span>
</td>
<td>
<div class="ui list">
@foreach($broker->contracts() as $contract)
<div class="item">
<a href="{{$urls->base}}/proyecto/{{$contract->project->id}}" data-tooltip="{{$contract->current()->date->format('d-m-Y')}}" data-position="right center">
{{$contract->project->descripcion}} ({{$format->percent($contract->commission, 2, true)}})
</a>
</div>
@endforeach
</div>
</td>
<td class="right aligned">
<button class="ui small tertiary icon button edit_button" data-index="{{$broker->rut}}">
<i class="edit icon"></i>
</button>
<button class="ui small tertiary red icon button remove_button" data-index="{{$broker->rut}}">
<i class="remove icon"></i>
</button>
</td>
</tr>
@endforeach
</table>
@include('proyectos.brokers.add_modal')
@include('proyectos.brokers.edit_modal')
@endsection
@push('page_scripts')
<script>
function storeBrokers() {
localStorage.setItem('brokers', '{!! json_encode(array_map(function($broker) {
$arr = json_decode(json_encode($broker), true);
array_walk_recursive($arr, function(&$val, $key) {
if ($val === null) {
$val = '';
}
});
$arr['contracts'] = $broker->contracts();
return $arr;
}, $brokers)) !!}')
}
const brokersHandler = {
ids: {
buttons: {
add: 'add_button',
edit: 'edit_button',
remove: 'remove_button'
},
modals: {
add: '',
edit: ''
},
forms: {
add: '',
edit: ''
}
},
modals: {
add: null,
edit: null
},
events() {
return {
add: clickEvent => {
clickEvent.preventDefault()
brokersHandler.actions().add()
},
edit: clickEvent => {
clickEvent.preventDefault()
const broker_rut = parseInt(clickEvent.currentTarget.dataset.index)
brokersHandler.actions().edit(broker_rut)
},
delete: clickEvent => {
clickEvent.preventDefault()
const broker_rut = clickEvent.currentTarget.dataset.index
brokersHandler.actions().delete(broker_rut)
}
}
},
buttonWatch() {
document.getElementById(brokersHandler.ids.buttons.add).addEventListener('click', brokersHandler.events().add)
Array.from(document.getElementsByClassName(brokersHandler.ids.buttons.edit)).forEach(button => {
button.addEventListener('click', brokersHandler.events().edit)
})
Array.from(document.getElementsByClassName(brokersHandler.ids.buttons.remove)).forEach(button => {
button.addEventListener('click', brokersHandler.events().delete)
})
},
actions() {
return {
add: () => {
this.modals.add.show()
},
edit: broker_rut => {
const localData = JSON.parse(localStorage.getItem('brokers'))
const broker = localData.find(broker => broker.rut === broker_rut)
const data = {
rut: broker_rut,
name: broker.name,
legal_name: broker.data?.legal_name || '',
contact: broker.data?.representative?.name || '',
email: broker.data?.representative?.email || '',
phone: broker.data?.representative?.phone || '',
address: broker.data?.representative?.address || '',
contracts: broker.contracts
}
this.modals.edit.load(data)
},
delete: broker_rut => {
brokersHandler.execute().delete(broker_rut)
}
}
},
execute() {
return {
add: data => {
const url = '{{$urls->api}}/proyectos/brokers/add'
const method = 'post'
const body = new FormData()
body.append('brokers[]', JSON.stringify(data))
return APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo agregar operador.')
return
}
window.location.reload()
})
},
edit: data => {
const url = '{{$urls->api}}/proyectos/brokers/edit'
const method = 'post'
const body = new FormData()
body.append('brokers[]', JSON.stringify(data))
return APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo editar operador.')
return
}
window.location.reload()
})
},
delete: broker_rut => {
const url = '{{$urls->api}}/proyectos/broker/' + broker_rut
const method = 'delete'
return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo eliminar operador.')
return
}
window.location.reload()
})
}
}
},
setup(ids) {
brokersHandler.ids = ids
brokersHandler.buttonWatch()
this.modals.add = new AddModal(brokersHandler)
this.modals.edit = new EditModal(brokersHandler)
}
}
$(document).ready(() => {
storeBrokers()
brokersHandler.setup({
buttons: {
add: 'add_button',
edit: 'edit_button',
remove: 'remove_button',
},
})
})
</script>
@endpush

View File

@ -0,0 +1,114 @@
<div class="ui modal" id="add_broker_modal">
<div class="header">
Agregar Operador
</div>
<div class="content">
<form class="ui form" id="add_broker_form">
<div class="fields">
<div class="field">
<label>RUT</label>
<div class="ui right labeled input">
<input type="text" name="rut" placeholder="RUT" maxlength="10" required />
<div class="ui basic label">-<span id="digit"></span></div>
</div>
</div>
</div>
<div class="fields">
<div class="field">
<label>Nombre</label>
<input type="text" name="name" placeholder="Nombre" required />
</div>
<div class="six wide field">
<label>Razón Social</label>
<input type="text" name="legal_name" placeholder="Razón Social" required />
</div>
</div>
<div class="fields">
<div class="field">
<label>Contacto</label>
<input type="text" name="contact" placeholder="Contacto" />
</div>
</div>
<div class="fields">
<div class="field">
<label>Correo</label>
<input type="email" name="email" placeholder="Correo" />
</div>
<div class="field">
<label>Teléfono</label>
<input type="text" name="phone" placeholder="Teléfono" />
</div>
</div>
</form>
</div>
<div class="actions">
<div class="ui deny button">
Cancelar
</div>
<div class="ui positive right labeled icon button">
Agregar
<i class="checkmark icon"></i>
</div>
</div>
</div>
@include('layout.body.scripts.rut')
@push('page_scripts')
<script>
class AddModal {
ids
modal
handler
constructor(handler) {
this.handler = handler
this.ids = {
modal: 'add_broker_modal',
form: 'add_broker_form',
digit: 'digit'
}
this.modal = $(`#${this.ids.modal}`)
this.modal.modal({
onApprove: () => {
const form = document.getElementById(this.ids.form)
const data = {
rut: form.querySelector('[name="rut"]').value.replace(/\D/g, ''),
digit: Rut.digitoVerificador(form.querySelector('[name="rut"]').value),
name: form.querySelector('[name="name"]').value,
legal_name: form.querySelector('[name="legal_name"]').value,
contact: form.querySelector('[name="contact"]').value || '',
email: form.querySelector('[name="email"]').value || '',
phone: form.querySelector('[name="phone"]').value || ''
}
this.handler.execute().add(data)
}
})
this.modal.modal('hide')
const value = document.querySelector(`#${this.ids.form} input[name="rut"]`).value
this.update().digit(value)
this.watch().rut()
}
update() {
return {
digit: value => {
if (value.length > 3) {
document.getElementById(this.ids.digit).textContent = Rut.digitoVerificador(value)
}
}
}
}
watch() {
return {
rut: () => {
document.querySelector(`#${this.ids.form} input[name="rut"]`).addEventListener('input', event => {
const value = event.currentTarget.value
this.update().digit(value)
})
}
}
}
show() {
this.modal.modal('show')
}
}
</script>
@endpush

View File

@ -0,0 +1,22 @@
@extends('layout.base')
@section('page_title')
@hasSection('brokers_title')
Operadores - @yield('brokers_title')
@else
Operadores
@endif
@endsection
@section('page_content')
<div class="ui container">
<h2 class="ui header">
@hasSection('brokers_header')
Operador - @yield('brokers_header')
@else
Operadores
@endif
</h2>
@yield('brokers_content')
</div>
@endsection

View File

@ -0,0 +1,236 @@
@extends('proyectos.brokers.base')
@section('brokers_title')
{{ $contract->broker->name }} - {{ $contract->project->descripcion }}
@endsection
@section('brokers_header')
{{ $contract->broker->name }} - {{ $contract->project->descripcion }}
@endsection
@include('layout.body.scripts.stats')
@prepend('page_scripts')
<script>
class TableHandler {
commission
constructor(commission) {
this.commission = commission
}
draw() {}
prices(units) {
const prices = []
units.forEach(unit => {
const price = unit.precio?.valor ?? 0
let amount = 1
unit.promotions?.forEach(promotion => {
amount /= 1/(1 - promotion.amount)
})
amount /= 1/(1 - this.commission)
amount = 1 - amount
prices.push({
id: unit.id,
base: price,
amount,
final: price / (1 - amount)
})
})
return prices
}
}
</script>
@endprepend
@section('brokers_content')
<div class="ui statistic">
<div class="value">{{ $format->percent($contract->commission, 2, true) }}</div>
<div class="label">
Comisión desde {{ $contract->current()->date->format('d/m/Y') }}
</div>
</div>
<br />
<div class="ui active inline loader"></div>
<div id="results">
<div class="ui top attached tabular menu">
<a class="item active" data-tab="tipos">Tipos</a>
<a class="item" data-tab="lineas">Líneas</a>
<a class="item" data-tab="unidades">Unidades</a>
</div>
<div class="ui bottom attached tab basic horizontally fitted segment active" data-tab="tipos">
@include('proyectos.brokers.contracts.show.tipo')
</div>
<div class="ui bottom attached tab basic horizontally fitted segment" data-tab="lineas">
@include('proyectos.brokers.contracts.show.linea')
</div>
<div class="ui bottom attached tab basic horizontally fitted segment" data-tab="unidades">
@include('proyectos.brokers.contracts.show.unidades')
</div>
</div>
@endsection
@include('layout.body.scripts.datatables')
@include('layout.body.scripts.datatables.searchbuilder')
@include('layout.body.scripts.datatables.buttons')
@push('page_scripts')
<script>
const units = {
ids: {
units: '',
loader: ''
},
data: {
project_id: {{ $contract->project->id }},
commission: {{ $contract->commission }},
units: []
},
formatters: {
ufs: new Intl.NumberFormat('es-CL', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 }),
percent: new Intl.NumberFormat('es-CL', { style: 'percent', minimumFractionDigits: 2 })
},
handlers: {
tipo: null,
linea: null,
unit: null
},
get() {
return {
units: () => {
const url = `{{ $urls->api }}/proyecto/${units.data.project_id}/unidades`
return APIClient.fetch(url).then(response => response.json()).then(json => {
if (json.unidades.length === 0) {
console.error(json.errors)
return
}
units.data.units = []
Object.entries(json.unidades).forEach(([tipo, unidades]) => {
units.data.units = [...units.data.units, ...unidades]
})
})
},
promotions: () => {
const chunkSize = 100
const chunks = []
for (let i = 0; i < units.data.units.length; i += chunkSize) {
chunks.push(units.data.units.slice(i, i + chunkSize).map(u => u.id))
}
const promises = []
chunks.forEach(chunk => {
const url = `{{ $urls->api }}/proyectos/broker/{{ $contract->broker->rut }}/contract/{{ $contract->id }}/promotions`
const method = 'post'
const body = new FormData()
chunk.forEach(id => body.append('unidad_ids[]', id))
promises.push(APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (json.unidades.length === 0) {
return
}
json.unidades.forEach(unidad => {
const idx = units.data.units.findIndex(u => u.id === parseInt(unidad.id))
units.data.units[idx].promotions = unidad.promotions
})
}))
})
return Promise.all(promises)
},
prices: () => {
const chunkSize = 100
const chunks = []
for (let i = 0; i < units.data.units.length; i += chunkSize) {
chunks.push(units.data.units.slice(i, i + chunkSize).map(u => u.id))
}
const promises = []
chunks.forEach(chunk => {
const url = `{{ $urls->api }}/proyecto/{{ $contract->project->id }}/unidades/precios`
const method = 'post'
const body = new FormData()
chunk.forEach(id => body.append('unidad_ids[]', id))
promises.push(APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (json.precios.length === 0) {
return
}
json.precios.forEach(unidad => {
const idx = units.data.units.findIndex(u => u.id === parseInt(unidad.id))
units.data.units[idx].precio = unidad.precio
})
}))
})
return Promise.all(promises)
},
sold: () => {
const chunkSize = 100
const chunks = []
for (let i = 0; i < units.data.units.length; i += chunkSize) {
chunks.push(units.data.units.slice(i, i + chunkSize).map(u => u.id))
}
const promises = []
chunks.forEach(chunk => {
const url = `{{ $urls->api }}/proyecto/{{ $contract->project->id }}/unidades/estados`
const method = 'post'
const body = new FormData()
chunk.forEach(id => body.append('unidad_ids[]', id))
promises.push(APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (json.estados.length === 0) {
return
}
json.estados.forEach(unidad => {
const idx = units.data.units.findIndex(u => u.id === parseInt(unidad.id))
units.data.units[idx].sold = unidad.sold
})
}))
})
return Promise.all(promises)
}
}
},
draw() {
return {
units: () => {
units.handlers.units.draw({units: units.data.units, formatters: units.formatters})
},
tipos: () => {
units.handlers.tipo.draw({units: units.data.units, formatters: units.formatters})
},
lineas: () => {
units.handlers.lineas.draw({units: units.data.units, formatters: units.formatters})
}
}
},
setup(ids) {
units.ids = ids
units.handlers.tipo = new TipoTable(units.data.commission)
units.handlers.lineas = new LineasTable(units.data.commission)
units.handlers.units = new UnitsTable(units.data.commission)
$(`#${units.ids.results}`).find('.tabular.menu .item').tab({
onVisible: function(tabPath) {
if (tabPath !== 'unidades') {
return
}
$(this.querySelector('table')).DataTable().columns.adjust().draw()
this.querySelector('table').style.width = ''
}
})
document.getElementById(units.ids.results).style.visibility = 'hidden'
units.get().units().then(() => {
units.get().prices().then(() => {
units.get().promotions().then(() => {
units.get().sold().then(() => {
$(units.ids.loader).hide()
document.getElementById(units.ids.results).style.visibility = 'visible'
units.draw().units()
units.draw().tipos()
units.draw().lineas()
})
})
})
})
}
}
$(document).ready(function () {
units.setup({results: 'results', loader: '.ui.loader'})
})
</script>
@endpush

View File

@ -0,0 +1,80 @@
<table class="ui table" id="lineas">
<thead>
<tr>
<th>Tipo</th>
<th class="center aligned">Línea</th>
<th class="center aligned">Orientación</th>
<th class="center aligned">Cantidad</th>
<th class="right aligned" style="text-decoration: overline">Precio Lista</th>
<th class="right aligned" style="text-decoration: overline">Porcentaje</th>
<th class="right aligned" style="text-decoration: overline">Precio Final</th>
</tr>
</thead>
<tbody></tbody>
</table>
@push('page_scripts')
<script>
class LineasTable extends TableHandler {
ids = {
lineas: 'lineas'
}
constructor(commission) {
super(commission)
}
draw({units, formatters}) {
const table = document.getElementById(this.ids.lineas)
const tbody = table.querySelector('tbody')
const lineas = Object.groupBy(units, unit => {
return [unit.proyecto_tipo_unidad.tipo_unidad.descripcion, unit.proyecto_tipo_unidad.nombre, unit.orientacion]
})
Object.entries(lineas).sort(([linea1, unidades1], [linea2, unidades2]) => {
const split1 = linea1.split(',')
const split2 = linea2.split(',')
const ct = unidades1[0].proyecto_tipo_unidad.tipo_unidad.orden - unidades2[0].proyecto_tipo_unidad.tipo_unidad.orden
if (ct === 0) {
const cl = split1[1].localeCompare(split2[1])
if (cl === 0) {
return split1[2].localeCompare(split2[2])
}
return cl
}
return ct
}).forEach(([linea, unidades]) => {
const parts = linea.split(',')
const tipo = parts[0]
const orientacion = parts[2]
const prices = this.prices(unidades)
const base_tooltip = [
`Min: UF ${formatters.ufs.format(Math.min(...prices.map(p => p.base)))}`,
`Max: UF ${formatters.ufs.format(Math.max(...prices.map(p => p.base)))}`,
`Desv: UF ${formatters.ufs.format(Stat.standardDeviation(prices.map(p => p.base)))}`
].join("\n").replaceAll(' ', '&nbsp;')
const amount_tooltip = [
`Min: ${formatters.percent.format(Math.min(...prices.map(p => p.amount)))}`,
`Max: ${formatters.percent.format(Math.max(...prices.map(p => p.amount)))}`,
`Desv: ${formatters.percent.format(Stat.standardDeviation(prices.map(p => p.amount)))}`
].join("\n").replaceAll(' ', '&nbsp;')
const final_tooltip = [
`Min: UF ${formatters.ufs.format(Math.min(...prices.map(p => p.final)))}`,
`Max: UF ${formatters.ufs.format(Math.max(...prices.map(p => p.final)))}`,
`Desv: UF ${formatters.ufs.format(Stat.standardDeviation(prices.map(p => p.final)))}`
].join("\n").replaceAll(' ', '&nbsp;')
tbody.innerHTML += [
`<tr>`,
`<td>${tipo.charAt(0).toUpperCase() + tipo.slice(1)}</td>`,
`<td class="center aligned"><span data-tooltip="${unidades[0].proyecto_tipo_unidad.tipologia}" data-position="right center">${parts[1]}</span></td>`,
`<td class="center aligned">${orientacion}</td>`,
`<td class="center aligned">${unidades.length}</td>`,
`<td class="right aligned"><span data-tooltip="${base_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(Stat.mean(prices.map(p => p.base)))}</span></td>`,
`<td class="right aligned"><span data-tooltip="${amount_tooltip}" data-position="right center" data-variation="wide multiline">${formatters.percent.format(Stat.mean(prices.map(p => p.amount)))}</span></td>`,
`<td class="right aligned"><span data-tooltip="${final_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(Stat.mean(prices.map(p => p.final)))}</span></td>`,
`</tr>`
].join("\n")
})
}
}
</script>
@endpush

View File

@ -0,0 +1,61 @@
<table class="ui table" id="tipos">
<thead>
<tr>
<th>Tipo</th>
<th class="center aligned">Cantidad</th>
<th class="right aligned" style="text-decoration: overline">Precio Base</th>
<th class="right aligned" style="text-decoration: overline">Porcentaje</th>
<th class="right aligned" style="text-decoration: overline">Precio Final</th>
</tr>
</thead>
<tbody></tbody>
</table>
@push('page_scripts')
<script>
class TipoTable extends TableHandler {
ids = {
tipos: 'tipos'
}
constructor(commission) {
super(commission)
}
draw({units, formatters}) {
const table = document.getElementById(this.ids.tipos)
const tbody = table.querySelector('tbody')
tbody.innerHTML = ''
const groups = Object.groupBy(units, unit => {
return unit.proyecto_tipo_unidad.tipo_unidad.descripcion
})
Object.entries(groups).forEach(([tipo, unidades]) => {
const prices = this.prices(unidades)
const base_tooltip = [
`Min: UF ${formatters.ufs.format(Math.min(...prices.map(p => p.base)))}`,
`Max: UF ${formatters.ufs.format(Math.max(...prices.map(p => p.base)))}`,
`Desv: UF ${formatters.ufs.format(Stat.standardDeviation(prices.map(p => p.base)))}`
].join("\n").replaceAll(' ', '&nbsp;')
const amount_tooltip = [
`Min: ${formatters.percent.format(Math.min(...prices.map(p => p.amount)))}`,
`Max: ${formatters.percent.format(Math.max(...prices.map(p => p.amount)))}`,
`Desv: ${formatters.percent.format(Stat.standardDeviation(prices.map(p => p.amount)))}`
].join("\n").replaceAll(' ', '&nbsp;')
const final_tooltip = [
`Min: UF ${formatters.ufs.format(Math.min(...prices.map(p => p.final)))}`,
`Max: UF ${formatters.ufs.format(Math.max(...prices.map(p => p.final)))}`,
`Desv: UF ${formatters.ufs.format(Stat.standardDeviation(prices.map(p => p.final)))}`
].join("\n").replaceAll(' ', '&nbsp;')
tbody.innerHTML += [
`<tr>`,
`<td>${tipo.charAt(0).toUpperCase() + tipo.slice(1)}</td>`,
`<td class="center aligned">${unidades.length}</td>`,
`<td class="right aligned"><span data-tooltip="${base_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(Stat.mean(prices.map(p => p.base)))}</span></td>`,
`<td class="right aligned"><span data-tooltip="${amount_tooltip}" data-position="right center" data-variation="wide multiline">${formatters.percent.format(Stat.mean(prices.map(p => p.amount)))}</span></td>`,
`<td class="right aligned"><span data-tooltip="${final_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(Stat.mean(prices.map(p => p.final)))}</span></td>`,
`</tr>`
].join("\n")
})
}
}
</script>
@endpush

View File

@ -0,0 +1,124 @@
<table class="ui table" id="unidades">
<thead>
<tr>
<th>Tipo</th>
<th>Tipo Order</th>
<th class="right aligned">Unidad</th>
<th>Unidad Orden</th>
<th>Estado</th>
<th class="right aligned">Precio Lista</th>
<th class="right aligned">Porcentaje</th>
<th class="right aligned">Precio Final</th>
<th>Fecha Inicio</th>
<th>Fecha Término</th>
</tr>
</thead>
<tbody></tbody>
</table>
@push('page_scripts')
<script>
class UnitsTable extends TableHandler {
ids = {
units: 'unidades',
}
constructor(commission) {
super(commission)
const dto = structuredClone(datatables_defaults)
dto.pageLength = 100
dto.columnDefs = [
{
target: [1, 3],
visible: false
},
{
target: 0,
orderData: 1
},
{
target: 2,
orderData: 3
},
{
target: [2, 5, 6, 7],
className: 'dt-right right aligned'
}
]
dto.order = [[1, 'asc'], [3, 'asc']]
dto.language.searchBuilder = searchBuilder
dto.layout = {
top1Start: {
searchBuilder: {
columns: [0, 2, 4, 5, 6, 7, 8, 9],
}
},
top1End: {
buttons: [
{
extend: 'excelHtml5',
className: 'green',
text: 'Exportar a Excel <i class="file excel icon"></i>',
title: 'Lista de Precios {{ $contract->broker->name }} {{ $contract->project->descripcion }} {{ (new DateTime())->format('Y-m-d') }}',
download: 'open',
exportOptions: {
columns: [0, 2, 4, 5, 6, 7],
/*format: {
body: (data, row, columnIdx, node) => {
const formats = this.columns.filter(columnDef => columnDef.format)
const match = formats.map(({title}) => title).indexOf(this.columns[columnIdx].title)
if (match > -1) {
return formats[match].format(data)
}
if (typeof data === 'string' && data.includes('<span data-tooltip')) {
return data.replace(/<span data-tooltip="(.*)">(.*)<\/span>/, '$2')
}
return data
}
}*/
},
customize: xlsx => {
const sheet = xlsx.xl.worksheets['sheet1.xml']
const columns = Object.values($('row[r="2"] t', sheet).map((idx, column) => column.textContent))
const columnStylesMap = {
Valor: '63',
Fecha: '15'
}
Object.entries(columnStylesMap).forEach((column, style) => {
const columnIndex = String.fromCharCode('A'.charCodeAt(0) + columns.indexOf(column))
$(`c[r^="${columnIndex}"]`, sheet).attr('s', style)
})
}
}
]
}
}
$(`#${this.ids.units}`).DataTable(dto)
}
draw({units, formatters}) {
const table = $(`#${this.ids.units}`).DataTable()
table.clear()
const tableData = []
const prices = this.prices(units)
units.forEach(unidad => {
const tipo = unidad.proyecto_tipo_unidad.tipo_unidad.descripcion
const price = prices.find(p => p.id === unidad.id)
tableData.push([
tipo.charAt(0).toUpperCase() + tipo.slice(1),
unidad.proyecto_tipo_unidad.tipo_unidad.orden,
unidad.descripcion,
unidad.descripcion.padStart(4, '0'),
unidad.sold ? 'Vendida' : 'Disponible',
'UF ' + formatters.ufs.format(price.base ?? 0),
formatters.percent.format(price.amount ?? 0),
'UF ' + formatters.ufs.format(price.final ?? 0),
unidad.promotion?.start_date ?? '',
unidad.promotion?.end_date ?? '',
])
})
table.rows.add(tableData)
table.draw()
}
}
</script>
@endpush

View File

@ -0,0 +1,113 @@
<div class="ui modal" id="edit_broker_modal">
<div class="header">
Editar Operador
</div>
<div class="content">
<form class="ui form" id="edit_broker_form">
<input type="hidden" name="broker_rut" value="" />
<div class="fields">
<div class="field">
<label>Rut</label>
<div class="ui right labeled input">
<input type="text" name="rut" placeholder="Rut" value="" disabled />
<div class="ui basic label">-<span id="edit_digit"></span></div>
</div>
</div>
</div>
<div class="fields">
<div class="field">
<label>Nombre</label>
<input type="text" name="name" placeholder="Nombre" value="" />
</div>
<div class="six wide field">
<label>Razón Social</label>
<input type="text" name="legal_name" placeholder="Razón Social" value="" />
</div>
</div>
<div class="fields">
<div class="field">
<label>Contacto</label>
<input type="text" name="contact" placeholder="Contacto" value="" />
</div>
</div>
<div class="fields">
<div class="field">
<label>Correo</label>
<input type="email" name="email" placeholder="Correo" value="" />
</div>
<div class="field">
<label>Teléfono</label>
<input type="text" name="phone" placeholder="Teléfono" value="" />
</div>
</div>
</form>
</div>
<div class="actions">
<div class="ui black deny button">
Cancelar
</div>
<div class="ui positive right labeled icon button">
Guardar
<i class="checkmark icon"></i>
</div>
</div>
</div>
@push('page_scripts')
<script>
class EditModal
{
ids
modal
handler
data
constructor(handler)
{
this.handler = handler
this.ids = {
modal: 'edit_broker_modal',
form: 'edit_broker_form',
digit: 'edit_digit',
}
this.modal = $(`#${this.ids.modal}`)
this.modal.modal({
onApprove: () => {
const form = document.getElementById(this.ids.form)
const broker_rut = form.querySelector('[name="broker_rut"]').value
const data = {
rut: form.querySelector('[name="rut"]').value.replace(/\D/g, ''),
name: form.querySelector('[name="name"]').value,
contact: form.querySelector('[name="contact"]').value || '',
legal_name: form.querySelector('[name="legal_name"]').value,
email: form.querySelector('[name="email"]').value || '',
phone: form.querySelector('[name="phone"]').value || ''
}
this.handler.execute().edit(data)
}
})
this.modal.modal('hide')
}
load(data) {
this.data = data
const form = document.getElementById(this.ids.form)
form.querySelector('input[name="broker_rut"]').value = data.rut
form.querySelector('input[name="rut"]').value = data.rut
form.querySelector('input[name="name"]').value = data.name
form.querySelector('input[name="legal_name"]').value = data.legal_name
form.querySelector('input[name="contact"]').value = data.contact
form.querySelector('input[name="email"]').value = data.email
form.querySelector('input[name="phone"]').value = data.phone
this.update().digit(data.rut)
this.modal.modal('show')
}
update() {
return {
digit: value => {
document.getElementById(this.ids.digit).textContent = Rut.digitoVerificador(value)
},
}
}
}
</script>
@endpush

View File

@ -0,0 +1,52 @@
<div class="ui top attached right aligned basic segment">
<button type="button" class="ui mini tertiary icon button" id="refresh_button">
<i class="sync alternate icon"></i>
</button>
<button type="button" class="ui mini tertiary icon button" id="up_button">
<i class="arrow up icon"></i>
</button>
</div>
<table class="ui table" id="projects">
<thead>
<tr>
<th>Proyecto</th>
</tr>
</thead>
<tbody>
@foreach($projects as $project)
<tr data-index="{{$project->id}}">
<td class="link" colspan="2">{{$project->descripcion}}</td>
</tr>
@endforeach
</tbody>
</table>
@push('page_scripts')
<script>
$(document).ready(function () {
document.querySelectorAll('#projects td.link').forEach(column => {
column.style.cursor = 'pointer'
column.addEventListener('click', () => {
const index = column.parentNode.dataset.index
if (typeof brokers.data.contracts[index] !== 'undefined') {
brokers.data.project_id = index
brokers.draw().brokers(index)
return
}
brokers.get().contracts(index)
})
})
document.getElementById('refresh_button').addEventListener('click', () => {
if (brokers.data.project_id === null) {
return
}
brokers.actions().refresh()
})
document.getElementById('up_button').addEventListener('click', () => {
brokers.actions().up()
})
})
</script>
@endpush

View File

@ -0,0 +1,169 @@
@extends('proyectos.brokers.base')
@section('brokers_title')
{{ $broker->name }}
@endsection
@section('brokers_header')
{{ $broker->name }}
@endsection
@section('brokers_content')
<div class="ui compact segment">
<b>RUT:</b> {{ $broker->rutFull() }} <br />
<b>Razón Social:</b> {{ $broker->data()?->legalName }}
</div>
@if ($broker->data()?->representative->name !== null)
<div class="ui card">
<div class="content">
<div class="header">
Contacto
</div>
<div class="description">
Nombre: {{ $broker->data()?->representative?->name }}<br />
Email: {{ $broker->data()?->representative?->email }}<br />
Teléfono: {{ $broker->data()?->representative?->phone }}<br />
Dirección: {{ $broker->data()?->representative?->address }}
</div>
</div>
</div>
@endif
<table class="ui table">
<thead>
<tr>
<th>Proyecto</th>
<th>Comisión</th>
<th>Fecha Inicio</th>
<th class="right aligned">
<button type="button" class="ui small tertiary green icon button" id="add_contract_button">
<i class="plus icon"></i>
</button>
</th>
</tr>
</thead>
<tbody id="contracts">
@foreach($broker->contracts() as $contract)
<tr>
<td>
<a href="{{ $urls->base }}/proyectos/broker/{{ $broker->rut }}/contract/{{ $contract->id }}">
{{ $contract->project->descripcion }}
</a>
</td>
<td>{{ $format->percent($contract->commission, 2, true) }}</td>
<td>{{ $contract->current()->date->format('d-m-Y') }}</td>
<td class="right aligned">
<button type="button" class="ui small tertiary red icon button remove_button" data-index="{{$contract->id}}">
<i class="remove icon"></i>
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
@include('proyectos.brokers.show.add_modal')
@endsection
@include('layout.body.scripts.datatables')
@push('page_scripts')
<script>
const brokerHandler = {
ids: {
buttons: {
add: '',
remove: ''
}
},
modals: {
add: null,
},
execute() {
return {
add: data => {
const url = '{{ $urls->api }}/proyectos/broker/{{ $broker->rut }}/contracts/add'
const method = 'post'
const body = new FormData()
body.set('contracts[]', JSON.stringify(data))
return APIClient.fetch(url, {method, body}).then(response => {
if (!response) {
console.error(response.errors)
alert('No se pudo agregar contrato.')
return
}
return response.json().then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo agregar contrato.')
return
}
window.location.reload()
})
})
},
remove: index => {
const url = `{{ $urls->api }}/proyectos/brokers/contract/${index}`
const method = 'delete'
return APIClient.fetch(url, {method}).then(response => {
if (!response) {
console.error(response.errors)
alert('No se pudo eliminar contrato.')
return
}
return response.json().then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo eliminar contrato.')
return
}
window.location.reload()
})
})
}
}
},
events() {
return {
add: clickEvent => {
clickEvent.preventDefault()
brokerHandler.modals.add.show()
},
remove: clickEvent => {
clickEvent.preventDefault()
const index = $(clickEvent.currentTarget).data('index')
brokerHandler.execute().remove(index)
}
}
},
buttonWatch() {
document.getElementById(brokerHandler.ids.buttons.add).addEventListener('click', brokerHandler.events().add)
Array.from(document.getElementsByClassName(brokerHandler.ids.buttons.remove)).forEach(button => {
button.addEventListener('click', brokerHandler.events().remove)
})
},
setup(ids) {
brokerHandler.ids = ids
brokerHandler.buttonWatch()
this.modals.add = new AddModal(brokerHandler)
const dto = structuredClone(datatables_defaults)
dto.order = [[0, 'asc']]
dto.columnDefs = [
{
targets: 3,
orderable: false
}
]
$('#contracts').parent().DataTable(dto)
}
}
$(document).ready(() => {
brokerHandler.setup({
buttons: {
add: 'add_contract_button',
remove: 'remove_button'
}
})
})
</script>
@endpush

View File

@ -0,0 +1,96 @@
<div class="ui modal" id="add_contract_modal">
<div class="header">
Agregar Contrato
</div>
<div class="content">
<form class="ui form" id="add_contract_form">
<input type="hidden" name="broker_rut" value="{{$broker->rut}}" />
<div class="fields">
<div class="six wide field">
<label>Proyecto</label>
<div class="ui search selection dropdown" id="project">
<input type="hidden" name="project_id" />
<i class="dropdown icon"></i>
<div class="default text">Proyecto</div>
<div class="menu">
@foreach($projects as $project)
<div class="item" data-value="{{ $project->id }}">{{ $project->descripcion }}</div>
@endforeach
</div>
</div>
</div>
<div class="field">
<label>Comisión</label>
<div class="ui right labeled input">
<input type="text" name="commission" placeholder="Comisión" />
<div class="ui basic label">%</div>
</div>
</div>
</div>
<div class="fields">
<div class="field">
<label>Fecha Inicio</label>
<div class="ui calendar" id="add_fecha_inicio">
<div class="ui icon input">
<i class="calendar icon"></i>
<input type="text" name="date" />
</div>
</div>
</div>
</div>
</form>
</div>
<div class="actions">
<div class="ui deny button">
Cancelar
</div>
<div class="ui positive right labeled icon button">
Agregar
<i class="checkmark icon"></i>
</div>
</div>
</div>
@push('page_scripts')
<script>
class AddModal {
ids
modal
handler
constructor(handler) {
this.handler = handler
this.ids = {
modal: 'add_contract_modal',
form: 'add_contract_form',
proyecto: 'project',
date: 'add_fecha_inicio'
}
$(`#${this.ids.proyecto}`).dropdown()
const cdo = structuredClone(calendar_date_options)
cdo['initialDate'] = new Date()
$(`#${this.ids.date}`).calendar(cdo)
this.modal = $(`#${this.ids.modal}`)
this.modal.modal({
onApprove: () => {
const form = document.getElementById(this.ids.form)
let commission = parseFloat(form.querySelector('[name="commission"]').value)
if (commission > 1) {
commission /= 100
}
const date = $(`#${this.ids.date}`).calendar('get date')
const data = {
broker_rut: form.querySelector('[name="broker_rut"]').value,
project_id: form.querySelector('[name="project_id"]').value,
commission: commission,
date: [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-')
}
this.handler.execute().add(data)
}
})
}
show() {
this.modal.modal('show')
}
}
</script>
@endpush

View File

@ -0,0 +1,50 @@
@extends('ventas.base')
@section('venta_subtitle')
Pie
@endsection
@section('venta_content')
<div class="ui basic compact segment">
Valor Promesa: {{ $format->ufs($venta->valor) }} <br />
10% {{ $format->ufs($venta->valor * 0.1) }}
</div>
<form class="ui form" id="add_pie">
<input type="hidden" name="venta" value="{{ $venta->id }}" />
<input type="hidden" name="fecha" value="{{ $venta->fecha->format('Y-m-d') }}" />
<div class="three wide field">
<label for="valor">Valor</label>
<div class="ui right labeled input">
<input type="text" name="valor" id="valor" value="{{ round($venta->valor * 0.1, 2) }}" />
<div class="ui basic label">UF</div>
</div>
</div>
<div class="three wide field">
<label for="cuotas"># Cuotas</label>
<input type="number" name="cuotas" id="cuotas" />
</div>
<button class="ui button">Agregar</button>
</form>
@endsection
@push('page_scripts')
<script>
$(document).ready(() => {
$('#add_pie').submit(event => {
event.preventDefault()
const data = new FormData(event.currentTarget)
return fetchAPI('{{ $urls->api }}/venta/{{ $venta->id }}/pie/add', {method: 'post', body: data}).then(response => {
if (response.ok) {
return response.json()
}
}).then(json => {
if (json.success) {
window.location = '{{$urls->base}}/venta/{{$venta->id}}'
return true
}
return false
})
})
})
</script>
@endpush

View File

@ -0,0 +1,172 @@
@extends('ventas.promotions.base')
@section('promotions_content')
<table class="ui table" id="promotions">
<thead>
<tr>
<th>Promoción</th>
<th>Tipo</th>
<th>Valor</th>
<th>Fecha Inicio</th>
<th>Fecha Término</th>
<th>Válido Hasta</th>
<th>Contratos</th>
<th class="right aligned">
<button type="button" class="ui small tertiary green icon button" id="add_button">
<i class="plus icon"></i>
</button>
</th>
</tr>
</thead>
<tbody>
@foreach($promotions as $promotion)
<tr>
<td>
<a href="{{ $urls->base }}/ventas/promotion/{{ $promotion->id }}">
{{ $promotion->description }}
</a>
</td>
<td>{{ ucwords($promotion->type->name()) }}</td>
<td>{{ ($promotion->type === Incoviba\Model\Venta\Promotion\Type::FIXED) ? $format->ufs($promotion->amount) : $format->percent($promotion->amount, 2, true) }}</td>
<td>{{ $promotion->startDate->format('d-m-Y') }}</td>
<td>{{ $promotion->endDate?->format('d-m-Y') }}</td>
<td>{{ $promotion->validUntil?->format('d-m-Y') }}</td>
<td>
Proyectos: {{ count(array_unique(array_map(function ($contract) { return $contract->project->descripcion; }, $promotion->contracts()))) }} <br />
Operadores: {{ count(array_unique(array_map(function ($contract) { return $contract->broker->name; }, $promotion->contracts()))) }}
</td>
<td class="right aligned">
<button type="button" class="ui small tertiary icon button edit_button" data-id="{{ $promotion->id }}">
<i class="edit icon"></i>
</button>
<button type="button" class="ui red small tertiary icon button remove_button" data-id="{{ $promotion->id }}">
<i class="trash icon"></i>
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
@include('ventas.promotions.add_modal')
@include('ventas.promotions.edit_modal')
@endsection
@push('page_scripts')
<script>
const promotions = {
ids: {
buttons: {
add: '',
edit: '',
remove: ''
},
},
handlers: {
add: null,
edit: null,
},
data: JSON.parse('{!! json_encode($promotions) !!}'),
execute() {
return {
add: data => {
const url = '{{$urls->api}}/ventas/promotions/add'
const method = 'post'
const body = new FormData()
body.set('promotions[]', JSON.stringify(data))
return APIClient.fetch(url, {method, body}).then(response => {
if (!response) {
console.error(response.errors)
alert('No se pudo agregar promoción.')
return
}
return response.json().then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo agregar promoción.')
return
}
window.location.reload()
})
})
},
edit: data => {
const url = '{{$urls->api}}/ventas/promotions/edit'
const method = 'post'
const body = new FormData()
body.set('promotions[]', JSON.stringify(data))
return APIClient.fetch(url, {method, body}).then(response => {
if (!response) {
console.error(response.errors)
alert('No se pudo editar promoción.')
return
}
return response.json().then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo editar promoción.')
return
}
window.location.reload()
})
})
},
remove: promotion_id => {
const url = `{{$urls->api}}/ventas/promotion/${promotion_id}/remove`
const method = 'delete'
return APIClient.fetch(url, {method}).then(response => {
if (!response) {
console.error(response.errors)
alert('No se pudo eliminar promoción.')
return
}
return response.json().then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo eliminar promoción.')
return
}
window.location.reload()
})
})
}
}
},
watch() {
document.getElementById(promotions.ids.buttons.add).addEventListener('click', clickEvent => {
clickEvent.preventDefault()
promotions.handlers.add.show()
})
Array.from(document.getElementsByClassName(promotions.ids.buttons.edit)).forEach(button => {
button.addEventListener('click', clickEvent => {
const id = clickEvent.currentTarget.dataset.id
promotions.handlers.edit.load(id)
})
})
Array.from(document.getElementsByClassName(promotions.ids.buttons.remove)).forEach(button => {
button.addEventListener('click', clickEvent => {
clickEvent.preventDefault()
const id = clickEvent.currentTarget.dataset.id
promotions.execute().remove(id)
})
})
},
setup(ids) {
promotions.ids = ids
promotions.handlers.add = new AddModal()
promotions.handlers.edit = new EditModal(promotions.data)
promotions.watch()
}
}
$(document).ready(() => {
promotions.setup({
buttons: {
add: 'add_button',
edit: 'edit_button',
remove: 'remove_button'
}
})
})
</script>
@endpush

View File

@ -0,0 +1,100 @@
<div class="ui modal" id="add_promotion_modal">
<div class="header">
Agregar Promoción
</div>
<div class="content">
<form class="ui form" id="add_promotion_form">
<div class="field">
<label for="description">Descripción</label>
<input type="text" id="description" name="description" placeholder="Descripción" required />
</div>
<div class="fields">
<div class="field">
<label for="type">Tipo</label>
<select id="type" name="type" class="ui select dropdown" required>
<option value="1">Valor Fijo</option>
<option value="2">Valor Variable</option>
</select>
</div>
<div class="field">
<label for="value">Valor</label>
<input type="text" id="value" name="value" placeholder="Valor" required />
</div>
</div>
<div class="fields">
<div class="field">
<label for="start_date">Fecha de Inicio</label>
<div class="ui calendar" id="start_date">
<div class="ui left icon input">
<i class="calendar icon"></i>
<input type="text" name="start_date" placeholder="Fecha de Inicio" required />
</div>
</div>
</div>
<div class="field">
<label for="end_date">Fecha de Término</label>
<div class="ui calendar" id="end_date">
<div class="ui left icon input">
<i class="calendar icon"></i>
<input type="text" name="end_date" placeholder="Fecha de Término" />
</div>
</div>
</div>
<div class="field">
<label for="valid_range">Válido por N Días Después del Término</label>
<input type="text" id="valid_range" name="valid_range" placeholder="Válido por N Días" value="7" required />
</div>
</div>
</form>
</div>
<div class="actions">
<div class="ui black deny button">
Cancelar
</div>
<div class="ui positive right labeled icon button">
Agregar
<i class="checkmark icon"></i>
</div>
</div>
@push('page_scripts')
<script>
class AddModal {
ids = {
modal: '#add_promotion_modal',
}
modal
constructor() {
this.modal = $(this.ids.modal)
this.modal.find('.ui.dropdown').dropdown()
this.modal.find('.ui.calendar').calendar(calendar_date_options)
this.modal.modal({
onApprove: () => {
const form = document.getElementById('add_promotion_form')
const type = $(form.querySelector('[name="type"]')).dropdown('get value')
const start_date = $(form.querySelector('#start_date')).calendar('get date')
const end_date = $(form.querySelector('#end_date')).calendar('get date')
let valid_until = null
if (end_date !== null) {
valid_until = new Date(end_date)
valid_until.setDate(valid_until.getDate() + parseInt(form.querySelector('[name="valid_range"]').value))
}
const data = {
description: form.querySelector('[name="description"]').value,
type,
value: form.querySelector('[name="value"]').value,
start_date: [start_date.getFullYear(), start_date.getMonth() + 1, start_date.getDate()].join('-'),
end_date: end_date === null ? null : [end_date.getFullYear(), end_date.getMonth() + 1, end_date.getDate()].join('-'),
valid_until: valid_until === null ? null : [valid_until.getFullYear(), valid_until.getMonth() + 1, valid_until.getDate()].join('-'),
}
promotions.execute().add(data)
}
})
}
show() {
this.modal.modal('show')
}
}
</script>
@endpush

View File

@ -0,0 +1,22 @@
@extends('layout.base')
@section('page_title')
@hasSection('promotions_title')
Promoción - @yield('promotions_title')
@else
Promociones
@endif
@endsection
@section('page_content')
<div class="ui container">
<h2 class="ui header">
@hasSection('promotions_header')
Promoción - @yield('promotions_header')
@else
Promociones
@endif
</h2>
@yield('promotions_content')
</div>
@endsection

View File

@ -0,0 +1,126 @@
<div class="ui modal" id="edit_promotion_modal">
<div class="header">
Editar Promoción - <span class="description"></span>
</div>
<div class="content">
<form class="ui form" id="edit_promotion_form">
<input type="hidden" name="id" />
<div class="field">
<label for="description">Descripción</label>
<input type="text" id="description" name="description" placeholder="Descripción" required />
</div>
<div class="fields">
<div class="field">
<label for="type">Tipo</label>
<select id="type" name="type" class="ui select dropdown" required>
<option value="1">Valor Fijo</option>
<option value="2">Valor Variable</option>
</select>
</div>
<div class="field">
<label for="value">Valor</label>
<input type="text" id="value" name="value" placeholder="Valor" required />
</div>
</div>
<div class="fields">
<div class="field">
<label for="edit_start_date">Fecha de Inicio</label>
<div class="ui calendar" id="edit_start_date">
<div class="ui left icon input">
<i class="calendar icon"></i>
<input type="text" name="edit_start_date" placeholder="Fecha de Inicio" required />
</div>
</div>
</div>
<div class="field">
<label for="edit_end_date">Fecha de Término</label>
<div class="ui calendar" id="edit_end_date">
<div class="ui left icon input">
<i class="calendar icon"></i>
<input type="text" name="edit_end_date" placeholder="Fecha de Término" />
</div>
</div>
</div>
<div class="field">
<label for="valid_range">Válido por N Días Después del Término</label>
<input type="text" id="valid_range" name="valid_range" placeholder="Válido por N Días" value="7" required />
</div>
</div>
</form>
</div>
<div class="actions">
<div class="ui black deny button">
Cancelar
</div>
<div class="ui positive right labeled icon button">
Editar
<i class="checkmark icon"></i>
</div>
</div>
@push('page_scripts')
<script>
class EditModal {
ids = {
modal: '#edit_promotion_modal',
}
modal
promotions
constructor(data) {
this.promotions = data
this.modal = $(this.ids.modal)
this.modal.find('.ui.dropdown').dropdown()
this.modal.find('.ui.calendar').calendar(calendar_date_options)
this.modal.modal({
onApprove: () => {
const form = document.getElementById('edit_promotion_form')
const type = $(form.querySelector('[name="type"]')).dropdown('get value')
const start_date = $(form.querySelector('#edit_start_date')).calendar('get date')
const end_date = $(form.querySelector('#edit_end_date')).calendar('get date')
let valid_until = null
if (end_date !== null) {
valid_until = new Date(end_date)
valid_until.setDate(valid_until.getDate() + parseInt(form.querySelector('[name="valid_range"]').value))
}
const data = {
id: form.querySelector('[name="id"]').value,
description: form.querySelector('[name="description"]').value,
type,
value: form.querySelector('[name="value"]').value,
start_date: [start_date.getFullYear(), start_date.getMonth() + 1, start_date.getDate()].join('-'),
end_date: end_date === null ? null : [end_date.getFullYear(), end_date.getMonth() + 1, end_date.getDate()].join('-'),
valid_until: valid_until === null ? null : [valid_until.getFullYear(), valid_until.getMonth() + 1, valid_until.getDate()].join('-'),
}
promotions.execute().edit(data)
}
})
}
load(promotion_id) {
const promotion = this.promotions.find(promotion => promotion.id === parseInt(promotion_id))
const form = document.getElementById('edit_promotion_form')
form.reset()
form.querySelector('[name="id"]').value = promotion.id
form.querySelector('[name="description"]').value = promotion.description
form.querySelector('[name="type"]').value = promotion.type
form.querySelector('[name="value"]').value = promotion.amount
const start_date_parts = promotion.start_date.split('-')
const start_date = new Date(start_date_parts[0], start_date_parts[1] - 1, start_date_parts[2])
$('#edit_start_date').calendar('set date', start_date)
if (promotion.end_date !== null) {
const end_date_parts = promotion.end_date.split('-')
const end_date = new Date(end_date_parts[0], end_date_parts[1] - 1, end_date_parts[2])
$('#edit_end_date').calendar('set date', end_date)
if (promotion.valid_until !== null) {
const valid_until_parts = promotion.valid_until.split('-')
const valid_until = new Date(valid_until_parts[0], valid_until_parts[1] - 1, valid_until_parts[2])
form.querySelector('[name="valid_range"]').value = valid_until.getDate() - end_date.getDate()
}
}
this.modal.modal('show')
}
}
</script>
@endpush

View File

@ -0,0 +1,84 @@
@extends('ventas.promotions.base')
@section('promotions_title')
{{ $promotion->description }}
@endsection
@section('promotions_header')
{{ $promotion->description }}
@endsection
@section('promotions_content')
<div class="ui card">
<div class="content">
<div class="description">
<p>
{{ ucwords($promotion->type->name()) }} {{ ($promotion->type === Incoviba\Model\Venta\Promotion\Type::FIXED) ? $format->ufs($promotion->amount) : $format->percent($promotion->amount, 2, true) }}
</p>
<p>
{{ $promotion->startDate->format('d-m-Y') }} -> {!! $promotion->endDate?->format('d-m-Y') ?? '&infin;' !!}
</p>
<p>Válido hasta: {!! $promotion->validUntil?->format('d-m-Y') ?? '&infin;' !!}</p>
</div>
</div>
</div>
<table class="ui table" id="contracts">
<thead>
<tr>
<th>Proyecto</th>
<th>Operador</th>
<th class="center aligned" colspan="2">Unidad</th>
<th class="right aligned">
<button class="ui tertiary green icon button" id="add_button">
<i class="plus icon"></i>
</button>
</th>
</tr>
<tr>
<th colspan="2"></th>
<th>Tipo</th>
<th></th>
</tr>
</thead>
<tbody>
@if (count($promotion->projects()) > 0)
@foreach ($promotion->projects() as $project)
<tr>
<td>{{ $project->descripcion }}</td>
<td>Todos los Operadores</td>
<td colspan="2">Todas las Unidades</td>
</tr>
@endforeach
@endif
@if (count($promotion->contracts()) > 0)
@foreach($promotion->contracts() as $contract)
<tr>
<td>{{ $contract->project->descripcion }}</td>
<td>{{ $contract->broker->name }}</td>
<td colspan="2">Todas las Unidades</td>
</tr>
@endforeach
@endif
@if (count($promotion->units()) > 0)
@foreach($promotion->units() as $unit)
<tr>
<td>{{ $unit->project->descripcion }}</td>
<td>Todos los Operadores</td>
<td>{{ $unit->proyectoTipoUnidad->tipoUnidad->descripcion }}</td>
<td>{{ $unit->descripcion }}</td>
</tr>
@endforeach
@endif
@if (count($promotion->contractUnits()) > 0)
@foreach($promotion->contractUnits() as $contractUnit)
<tr>
<td>{{ $contractUnit->contract->project->descripcion }}</td>
<td>{{ $contractUnit->contract->broker->name }}</td>
<td>{{ $contractUnit->unidad->proyectoTipoUnidad->tipoUnidad->descripcion }}</td>
<td>{{ $contractUnit->unidad->descripcion }}</td>
</tr>
@endforeach
@endif
</tbody>
</table>
@endsection

View File

@ -0,0 +1,2 @@
<div class="ui modal" id="add_connection_modal">
</div>

View File

@ -1,42 +1,52 @@
@if ($pie !== null)
<tr>
<td>
Pie
<sub>
<a href="{{$urls->base}}/venta/{{$venta->id}}/pie">
<i class="edit icon"></i>
</a>
</sub>
</td>
<td></td>
<td class="right aligned">{{$format->ufs($pie->valor)}}</td>
<td class="right aligned">{{$format->pesos($pie->valor * $pie->uf)}}</td>
<td class="right aligned">Cuotas</td>
<td>
<a href="{{$urls->base}}/venta/{{$venta->id}}/pie/cuotas">
<span data-tooltip="Pagadas">{{count($pie->cuotas(true, true))}}</span>/{{$pie->cuotas}}
</a>
@if (count($pie->cuotas(vigentes: true)) < $pie->cuotas)
<a href="{{$urls->base}}/ventas/pie/{{$pie->id}}/cuotas/add">
@if ($pie !== null)
<sub>
<a href="{{$urls->base}}/venta/{{$venta->id}}/pie">
<i class="edit icon"></i>
</a>
</sub>
@else
<a href="{{$urls->base}}/venta/{{$venta->id}}/pie/add">
<i class="plus icon"></i>
</a>
@endif
</td>
</tr>
<tr>
<td>Pagado</td>
<td></td>
<td class="right aligned">{{$format->ufs($pie->pagado())}}</td>
<td class="right aligned">{{$format->pesos($pie->pagado('pesos'))}}</td>
<td colspan="2"></td>
</tr>
@if ($pie->reajuste)
<tr>
<td>Reajuste</td>
<td></td>
<td class="right aligned">{{$format->ufs($pie->reajuste->valor())}}</td>
<td class="right aligned">{{$format->pesos($pie->reajuste->valor)}}</td>
<td colspan="2"></td>
@if ($pie !== null)
<td class="right aligned">{{$format->ufs($pie->valor)}}</td>
<td class="right aligned">{{$format->pesos($pie->valor * $pie->uf)}}</td>
<td class="right aligned">Cuotas</td>
<td>
<a href="{{$urls->base}}/venta/{{$venta->id}}/pie/cuotas">
<span data-tooltip="Pagadas">{{count($pie->cuotas(true, true))}}</span>/{{$pie->cuotas}}
</a>
@if (count($pie->cuotas(vigentes: true)) < $pie->cuotas)
<a href="{{$urls->base}}/ventas/pie/{{$pie->id}}/cuotas/add">
<i class="plus icon"></i>
</a>
@endif
</td>
@else
<td colspan="4"></td>
@endif
</tr>
@endif
@if ($pie !== null)
<tr>
<td>Pagado</td>
<td></td>
<td class="right aligned">{{$format->ufs($pie->pagado())}}</td>
<td class="right aligned">{{$format->pesos($pie->pagado('pesos'))}}</td>
<td colspan="2"></td>
</tr>
@if ($pie->reajuste)
<tr>
<td>Reajuste</td>
<td></td>
<td class="right aligned">{{$format->ufs($pie->reajuste->valor())}}</td>
<td class="right aligned">{{$format->pesos($pie->reajuste->valor)}}</td>
<td colspan="2"></td>
</tr>
@endif
@endif

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,21 @@ 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,106 @@
<?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 {
$data = json_decode($data, true);
$output['brokers'] []= [
'rut' => $data['rut'],
'broker' => $brokerService->edit($data),
'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,175 @@
<?php
namespace Incoviba\Controller\API\Proyectos\Brokers;
use DateTimeImmutable;
use DateMalformedStringException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement;
use Incoviba\Controller\API\withJson;
use Incoviba\Exception\ServiceAction;
use Incoviba\Repository;
use Incoviba\Service;
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);
}
public function promotions(ServerRequestInterface $request, ResponseInterface $response,
Service\Proyecto\Broker\Contract $contractService,
Repository\Venta\Unidad $unitRepository,
Repository\Venta\Promotion $promotionRepository,
int $contract_id): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'contract_id' => $contract_id,
'input' => $input,
'unidades' => [],
];
$unit_ids = $input['unidad_ids'];
if (is_string($unit_ids)) {
$unit_ids = json_decode($input['unidad_ids'], true);
}
foreach ($unit_ids as $unit_id) {
try {
$unit = $unitRepository->fetchById($unit_id);
$contractService->getById($contract_id);
$promotion = $promotionRepository->fetchByContractAndUnit($contract_id, $unit->id);
$output['unidades'] []= [
'id' => $unit->id,
'promotion' => $promotion
];
} catch (ServiceAction\Read | Implement\Exception\EmptyResult) {}
}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,85 @@
<?php
namespace Incoviba\Controller\API\Proyectos;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Controller\API\withJson;
use Incoviba\Controller\withRedis;
use Incoviba\Exception;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class Unidades extends Ideal\Controller
{
use withJson;
use withRedis;
public function precios(ServerRequestInterface $request, ResponseInterface $response,
Service\Proyecto $proyectoService,
Repository\Venta\Precio $precioRepository,
int $proyecto_id): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'proyecto_id' => $proyecto_id,
'input' => $input,
'precios' => []
];
$unidad_ids = $input['unidad_ids'];
if (is_string($unidad_ids)) {
$unidad_ids = json_decode($input['unidad_ids'], true);
}
try {
$proyecto = $proyectoService->getById($proyecto_id);
foreach ($unidad_ids as $unidad_id) {
try {
$output['precios'][] = [
'id' => $unidad_id,
'precio' => $precioRepository->fetchVigenteByUnidad((int) $unidad_id)
];
} catch (Implement\Exception\EmptyResult) {}
}
} catch (Implement\Exception\EmptyResult) {}
return $this->withJson($response, $output);
}
public function estados(ServerRequestInterface $request, ResponseInterface $response,
Service\Proyecto $proyectoService,
Repository\Venta\Unidad $unidadRepository,
int $proyecto_id): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'proyecto_id' => $proyecto_id,
'input' => $input,
'estados' => []
];
$unidad_ids = $input['unidad_ids'];
if (is_string($unidad_ids)) {
$unidad_ids = json_decode($input['unidad_ids'], true);
}
try {
$proyecto = $proyectoService->getById($proyecto_id);
foreach ($unidad_ids as $unidad_id) {
try {
$unidad = $unidadRepository->fetchById($unidad_id);
} catch (Implement\Exception\EmptyResult) {
try {
$output['estados'][] = [
'id' => $unidad_id,
'sold' => $unidadRepository->fetchSoldByUnidad((int) $unidad_id)
];
} catch (Implement\Exception\EmptyResult) {
$output['estados'][] = [
'id' => $unidad_id,
'sold' => false
];
}
}
}
} catch (Implement\Exception\EmptyResult) {}
return $this->withJson($response, $output);
}
}

View File

@ -5,7 +5,8 @@ use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Incoviba\Controller\API\{withJson, emptyBody};
use Incoviba\Controller\withRedis;
use Incoviba\Common\Implement\Exception\{EmptyRedis, EmptyResult};
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\{Create, Read, Update};
use Incoviba\Service;
class Pies
@ -27,4 +28,35 @@ class Pies
} catch (EmptyResult) {}
return $this->withJson($response, $output);
}
public function add(ServerRequestInterface $request, ResponseInterface $response, Service\Venta $ventaService,
Service\Venta\Pie $pieService, int $venta_id): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'venta_id' => $venta_id,
'input' => $input,
'pie' => null,
'success' => false
];
try {
$venta = $ventaService->getById($venta_id);
} catch (Read $exception) {
return $this->withError($response, $exception);
}
try {
$pie = $pieService->add($input);
} catch (Create $exception) {
return $this->withError($response, $exception);
}
try {
$ventaService->edit($venta, ['pie' => $pie->id]);
$output['pie'] = $pie;
$output['success'] = true;
} catch (Update $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,97 @@
<?php
namespace Incoviba\Controller\API\Ventas;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Incoviba\Controller\API\withJson;
use Incoviba\Exception\ServiceAction;
use Incoviba\Service;
class Promotions
{
use withJson;
public function add(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Promotion $promotionService): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'input' => $input,
'promotions' => [],
'success' => false,
'partial' => false,
'errors' => [],
];
if (is_string($input['promotions'])) {
$input['promotions'] = json_decode($input['promotions'], true);
}
foreach ($input['promotions'] as $promotion) {
try {
$promotionData = json_decode($promotion, true);
$promotion = $promotionService->add($promotionData);
$output['promotions'] []= [
'promotion' => $promotion,
'success' => true,
];
$output['partial'] = true;
} catch (ServiceAction\Create $exception) {
$output['errors'] []= $this->parseError($exception);
}
}
if (count($output['promotions']) == count($input['promotions'])) {
$output['success'] = true;
}
return $this->withJson($response, $output);
}
public function edit(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Promotion $promotionService): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'input' => $input,
'promotions' => [],
'success' => false,
'partial' => false,
'errors' => [],
];
if (is_string($input['promotions'])) {
$input['promotions'] = json_decode($input['promotions'], true);
}
foreach ($input['promotions'] as $promotion) {
try {
$promotionData = json_decode($promotion, true);
$promotion = $promotionService->getById($promotionData['id']);
unset($promotionData['id']);
$promotion = $promotionService->edit($promotion, $promotionData);
$output['promotions'] []= [
'promotion' => $promotion,
'success' => true,
];
$output['partial'] = true;
} catch (ServiceAction\Read | ServiceAction\Update $exception) {
$output['errors'] []= $this->parseError($exception);
}
}
if (count($output['promotions']) == count($input['promotions'])) {
$output['success'] = true;
}
return $this->withJson($response, $output);
}
public function remove(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Promotion $promotionService, int $promotion_id): ResponseInterface
{
$output = [
'promotion_id' => $promotion_id,
'promotion' => null,
'success' => false,
'errors' => [],
];
try {
$output['promotion'] = $promotionService->remove($promotion_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

@ -0,0 +1,46 @@
<?php
namespace Incoviba\Controller\Proyectos;
use Psr\Log\LoggerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository;
use Incoviba\Service;
class Brokers
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, LoggerInterface $logger,
Service\Proyecto\Broker $brokerService, Repository\Proyecto $proyectoRepository,
View $view): ResponseInterface
{
$projects = [];
try {
$projects = $proyectoRepository->fetchAll('descripcion');
} catch (EmptyResult $exception) {
$logger->error($exception);
}
$brokers = $brokerService->getAll();
return $view->render($response, 'proyectos.brokers', compact('brokers', 'projects'));
}
public function show(ServerRequestInterface $request, ResponseInterface $response, LoggerInterface $logger,
Service\Proyecto\Broker $brokerService, Repository\Proyecto $proyectoRepository,
View $view, int $broker_rut): ResponseInterface
{
$broker = null;
try {
$broker = $brokerService->get($broker_rut);
} catch (Read $exception) {
$logger->error($exception);
}
$projects = [];
try {
$projects = $proyectoRepository->fetchAll('descripcion');
} catch (EmptyResult $exception) {
$logger->error($exception);
}
return $view->render($response, 'proyectos.brokers.show', compact('broker', 'projects'));
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace Incoviba\Controller\Proyectos\Brokers;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Common\Ideal\Controller;
use Incoviba\Exception;
use Incoviba\Service;
class Contracts extends Controller
{
public function show(ServerRequestInterface $request, ResponseInterface $response, View $view,
Service\Proyecto\Broker\Contract $contractService,
int $broker_rut, int $contract_id): ResponseInterface
{
$contract = null;
try {
$contract = $contractService->getById($contract_id);
} catch (Exception\ServiceAction\Read) {}
return $view->render($response, 'proyectos.brokers.contracts.show', compact('contract'));
}
}

View File

@ -1,12 +1,12 @@
<?php
namespace Incoviba\Controller\Ventas;
use Incoviba\Common\Alias\View;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository;
use Incoviba\Service;
class Pies
{
@ -21,4 +21,13 @@ class Pies
$estados = $tipoEstadoPagoRepository->fetchAll('descripcion');
return $view->render($response, 'ventas.pies.cuotas', compact('pie', 'venta', 'bancos', 'estados', 'ventaRepository'));
}
public function add(ServerRequestInterface $request, ResponseInterface $response, Service\Venta $ventaService,
View $view, int $venta_id): ResponseInterface
{
$venta = null;
try {
$venta = $ventaService->getById($venta_id);
} catch (Read) {}
return $view->render($response, 'ventas.pies.add', compact('venta'));
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace Incoviba\Controller\Ventas;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Common\Ideal;
use Incoviba\Exception\ServiceAction;
use Incoviba\Service;
class Promotions extends Ideal\Controller
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view,
Service\Venta\Promotion $promotionService): ResponseInterface
{
$promotions = $promotionService->getAll('description');
return $view->render($response, 'ventas.promotions', ['promotions' => $promotions]);
}
public function show(ServerRequestInterface $request, ResponseInterface $response, View $view,
Service\Venta\Promotion $promotionService, int $promotion_id): ResponseInterface
{
$promotion = null;
try {
$promotion = $promotionService->getById($promotion_id);
} catch (ServiceAction\Read) {}
return $view->render($response, 'ventas.promotions.show', ['promotion' => $promotion]);
}
}

View File

@ -0,0 +1,45 @@
<?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;
public function data(): ?Broker\Data
{
if (!isset($this->data)) {
$this->data = $this->runFactory('data');
}
return $this->data;
}
protected array $contracts;
public function contracts(): ?array
{
if (!isset($this->contracts)) {
$this->contracts = $this->runFactory('contracts');
}
return $this->contracts;
}
public function rutFull(): string
{
return implode('-', [number_format($this->rut, 0, ',', '.'), $this->digit]);
}
public function jsonSerialize(): mixed
{
return [
'rut' => $this->rut,
'digit' => $this->digit,
'name' => $this->name,
'data' => $this->data(),
'rut_full' => $this->rutFull()
];
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace Incoviba\Model\Proyecto\Broker;
use Incoviba\Common\Ideal;
use Incoviba\Model\Direccion;
use Incoviba\Model\Proyecto\Broker;
class Contact extends Ideal\Model
{
public string $name;
public ?string $email = null;
public ?string $phone = null;
public ?Direccion $address = null;
protected function jsonComplement(): array
{
return [
'name' => $this->name,
'email' => $this->email,
'phone' => $this->phone,
'address' => $this->address
];
}
}

View File

@ -0,0 +1,54 @@
<?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 current(): ?Contract\State
{
if (!isset($this->current)) {
try {
$this->current = last($this->states());
} catch (\TypeError $error) {
$this->current = null;
}
}
return $this->current;
}
protected array $promotions = [];
public function promotions(): array
{
if (count($this->promotions) === 0) {
$this->promotions = $this->runFactory('promotions');
}
return $this->promotions;
}
protected function jsonComplement(): array
{
return [
'project_id' => $this->project->id,
'broker_rut' => $this->broker->rut,
'commission' => $this->commission,
'states' => $this->states(),
'current' => $this->current(),
];
}
}

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\Proyecto\Broker\Contact $representative = null;
public ?string $legalName = null;
protected function jsonComplement(): array
{
return [
'broker_rut' => $this->broker->rut,
'representative' => $this->representative,
'legal_name' => $this->legalName
];
}
}

View File

@ -24,8 +24,15 @@ class Pago extends Model
public function valor(string $moneda = Pago::UF): float
{
$uf = $this->uf ?? ($this->uf > 0.0 ? $this->uf : 1);
return $this->valor / (($moneda === Pago::UF) ? $uf : 1);
$multiplier = 1;
if ($moneda === Pago::UF) {
if ($this->uf === null or $this->uf === 0.0) {
return 0;
}
$uf = $this->uf;
$multiplier = 1 / $uf;
}
return $this->valor * $multiplier;
}
public function estado(?string $tipoEstado = null): ?EstadoPago

View File

@ -0,0 +1,79 @@
<?php
namespace Incoviba\Model\Venta;
use DateTimeInterface;
use Incoviba\Common;
use Incoviba\Model\Proyecto\Broker;
use Incoviba\Model\Venta\Promotion\State;
use Incoviba\Model\Venta\Promotion\Type;
class Promotion extends Common\Ideal\Model
{
public string $description;
public float $amount;
public DateTimeInterface $startDate;
public ?DateTimeInterface $endDate;
public ?DateTimeInterface $validUntil;
public Type $type;
public State $state = State::ACTIVE;
protected array $projects;
public function projects(): array
{
if (empty($this->projects)) {
$this->projects = $this->runFactory('projects');
}
return $this->projects;
}
protected array $contracts;
public function contracts(): array
{
if (empty($this->contracts)) {
$this->contracts = $this->runFactory('contracts');
}
return $this->contracts;
}
protected array $units;
public function units(): array
{
if (empty($this->units)) {
$this->units = $this->runFactory('units');
}
return $this->units;
}
protected array $contractUnits;
public function contractUnits(): array
{
if (empty($this->contractUnits)) {
$this->contractUnits = $this->runFactory('contractUnits');
}
return $this->contractUnits;
}
public function value(float $price): float
{
if ($this->type === Type::FIXED) {
return $price + $this->amount;
}
return $price / (1 - $this->amount);
}
protected function jsonComplement(): array
{
return [
'description' => $this->description,
'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'),
'type' => $this->type,
'state' => $this->state,
'projects' => $this->projects() ?? [],
'contracts' => $this->contracts() ?? [],
'units' => $this->units() ?? []
];
}
}

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,16 @@
<?php
namespace Incoviba\Model\Venta\Promotion;
enum Type: int
{
case FIXED = 1;
case VARIABLE = 2;
public function name(): string
{
return match ($this) {
self::FIXED => 'fijo',
self::VARIABLE => 'variable'
};
}
}

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

@ -45,6 +45,18 @@ class Unidad extends Ideal\Model
return $precio;
}
protected bool $sold;
public function sold(): bool
{
if (!isset($this->sold)) {
$this->sold = false;
try {
$this->sold = $this->runFactory('sold') ?? false;
} catch (EmptyResult) {}
}
return $this->sold;
}
public function jsonSerialize(): mixed
{
$output = array_merge(parent::jsonSerialize(), [
@ -59,6 +71,7 @@ class Unidad extends Ideal\Model
$output['precios'] = $this->precios;
$output['current_precio'] = $this->currentPrecio;
}
$output['sold'] = $this->sold() ?? false;
return $output;
}
}

View File

@ -34,6 +34,7 @@ class CentroCosto extends Ideal\Repository
->register('tipo_cuenta_id', (new Mapper())
->setProperty('tipoCuenta')
->setFunction(function(array $data) {
if (empty($data['tipo_cuenta_id'])) return null;
return $this->tipoCuentaRepository->fetchById($data['tipo_cuenta_id']);
})
->setDefault(null))
@ -54,6 +55,11 @@ class CentroCosto extends Ideal\Repository
return $this->update($model, ['tipo_centro_id', 'categoria_id', 'tipo_cuenta_id', 'cuenta_contable', 'descripcion'], $new_data);
}
/**
* @param string $descripcion
* @return Model\Contabilidad\CentroCosto
* @throws \Incoviba\Common\Implement\Exception\EmptyResult
*/
public function fetchByDescripcion(string $descripcion): Model\Contabilidad\CentroCosto
{
$query = $this->connection->getQueryBuilder()

View File

@ -164,6 +164,21 @@ class Proyecto extends Ideal\Repository
->where('inmobiliaria = ?');
return $this->fetchMany($query, [$inmobiliaria_rut]);
}
/**
* @param int $promotion_id
* @return array
* @throws Implement\Exception\EmptyResult
*/
public function fetchByPromotion(int $promotion_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_projects pp ON pp.project_id = a.id')
->where('pp.promotion_id = :promotion_id');
return $this->fetchMany($query, ['promotion_id' => $promotion_id]);
}
/*public function fetchSuperficieVendido(int $proyecto_id): float
{

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,60 @@
<?php
namespace Incoviba\Repository\Proyecto\Broker;
use Incoviba\Common;
use Incoviba\Common\Define;
use Incoviba\Repository;
use Incoviba\Model;
class Contact extends Common\Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Repository\Direccion $direccionRepository)
{
parent::__construct($connection);
$this->setTable('broker_contacts');
}
public function create(?array $data = null): Model\Proyecto\Broker\Contact
{
$map = (new Common\Implement\Repository\MapperParser(['name', 'email', 'phone']))
->register('address_id', (new Common\Implement\Repository\Mapper())
->setProperty('address')
->setDefault(null)
->setFunction(function($data) {
if ($data['address_id'] === null) return null;
try {
return $this->direccionRepository->fetchById($data['address_id']);
} catch (Common\Implement\Exception\EmptyResult) {
return null;
}
}));
return $this->parseData(new Model\Proyecto\Broker\Contact(), $data, $map);
}
public function save(Define\Model $model): Model\Proyecto\Broker\Contact
{
$model->id = $this->saveNew([
'name', 'email', 'phone', 'address_id'
], [
$model->name, $model->email, $model->phone, $model->address?->id
]);
return $model;
}
public function edit(Define\Model $model, array $new_data): Model\Proyecto\Broker\Contact
{
return $this->update($model, ['name', 'email', 'phone', 'address_id'], $new_data);
}
/**
* @param string $name
* @return Model\Proyecto\Broker\Contact
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByName(string $name): Model\Proyecto\Broker\Contact
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('name = :name');
return $this->fetchOne($query, ['name' => $name]);
}
}

View File

@ -0,0 +1,150 @@
<?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]);
}
/**
* @param int $promotion_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByPromotion(int $promotion_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_contracts pc ON pc.contract_id = a.id')
->where('pc.promotion_id = :promotion_id');
return $this->fetchMany($query, ['promotion_id' => $promotion_id]);
}
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\Proyecto\Broker\Contact $contactRepository)
{
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_id', (new Common\Implement\Repository\Mapper())
->setProperty('representative')
->setDefault(null)
->setFunction(function($data) {
if ($data['representative_id'] === null) return null;
try {
return $this->contactRepository->fetchById($data['representative_id']);
} 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_id', 'legal_name'],
[$model->broker->rut, $model->representative?->id, $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_id', '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,207 @@
<?php
namespace Incoviba\Repository\Venta;
use PDO;
use PDOException;
use Incoviba\Common;
use Incoviba\Model;
use Incoviba\Repository\Proyecto\Broker;
class Promotion extends Common\Ideal\Repository
{
public function __construct(Common\Define\Connection $connection, protected Broker\Contract $contractRepository, protected Precio $precioRepository)
{
parent::__construct($connection);
}
public function getTable(): string
{
return 'promotions';
}
public function create(?array $data = null): Model\Venta\Promotion
{
$map = (new Common\Implement\Repository\MapperParser(['description', 'amount']))
->register('type', (new Common\Implement\Repository\Mapper())
->setFunction(function($data) {
return Model\Venta\Promotion\Type::from($data['type']);
}))
->register('state', (new Common\Implement\Repository\Mapper())
->setFunction(function($data) {
return Model\Venta\Promotion\State::from($data['state']);
})
->setDefault(Model\Venta\Promotion\State::ACTIVE))
->register('start_date', new Common\Implement\Repository\Mapper\DateTime('start_date', 'startDate'))
->register('end_date', (new Common\Implement\Repository\Mapper\DateTime('end_date', 'endDate'))
->setDefault(null))
->register('valid_until', (new Common\Implement\Repository\Mapper\DateTime('valid_until', 'validUntil'))
->setDefault(null));
return $this->parseData(new Model\Venta\Promotion(), $data, $map);
}
public function save(Common\Define\Model $model): Model\Venta\Promotion
{
$model->id = $this->saveNew(
['description', 'amount', 'type', 'start_date', 'end_date', 'valid_until'],
[$model->description, $model->amount, $model->type->value, $model->startDate->format('Y-m-d'),
$model->endDate?->format('Y-m-d'), $model->validUntil?->format('Y-m-d')]
);
return $model;
}
public function edit(Common\Define\Model $model, array $new_data): Model\Venta\Promotion
{
return $this->update($model, ['description', 'amount', 'type', 'start_date', 'end_date', 'valid_until'], $new_data);
}
public function filterData(array $data): array
{
$filteredData = array_intersect_key($data, array_flip(['description', 'amount', 'type', 'start_date', 'end_date', 'valid_until']));
if (!isset($filteredData['amount']) and isset($data['value'])) {
$filteredData['amount'] = $data['value'];
}
$filteredData['type'] = (int) $filteredData['type'];
if ($filteredData['amount'] > 1 and $filteredData['type'] === Model\Venta\Promotion\Type::VARIABLE->value) {
$filteredData['amount'] = $filteredData['amount'] / 100;
}
return $filteredData;
}
/**
* @param int $contract_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByContract(int $contract_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_contracts pc ON pc.promotion_id = a.id')
->where('pc.contract_id = :contract_id');
return $this->fetchMany($query, ['contract_id' => $contract_id]);
}
/**
* @param int $contract_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActiveByContract(int $contract_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_contracts pc ON pc.promotion_id = a.id')
->where('pc.contract_id = :contract_id AND a.state = :state');
return $this->fetchMany($query, ['contract_id' => $contract_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
}
/**
* @param int $unit_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByUnit(int $unit_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_units pu ON pu.promotion_id = a.id')
->where('pu.unit_id = :unit_id');
return $this->fetchMany($query, ['unit_id' => $unit_id]);
}
/**
* @param int $unit_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActiveByUnit(int $unit_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_units pu ON pu.promotion_id = a.id')
->where('pu.unit_id = :unit_id AND a.state = :state');
return $this->fetchMany($query, ['unit_id' => $unit_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
}
/**
* @param int $project_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByProject(int $project_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_units pu ON pu.promotion_id = a.id')
->joined('INNER JOIN unidad ON unidad.id = pu.unit_id')
->joined('INNER JOIN proyecto_tipo_unidad ON proyecto_tipo_unidad.id = unidad.pt')
->joined('INNER JOIN proyecto ON proyecto.id = proyecto_tipo_unidad.proyecto')
->where('proyecto.id = :project_id');
return $this->fetchMany($query, ['project_id' => $project_id]);
}
/**
* @param int $project_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActiveByProject(int $project_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_units pu ON pu.promotion_id = a.id')
->joined('INNER JOIN unidad ON unidad.id = pu.unit_id')
->joined('INNER JOIN proyecto_tipo_unidad ON proyecto_tipo_unidad.id = unidad.pt')
->joined('INNER JOIN proyecto ON proyecto.id = proyecto_tipo_unidad.proyecto')
->where('proyecto.id = :project_id AND a.state = :state');
return $this->fetchMany($query, ['project_id' => $project_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
}
/**
* @param int $contract_id
* @param int $unit_id
* @return Model\Venta\Promotion
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByContractAndUnit(int $contract_id, int $unit_id): Model\Venta\Promotion
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_contracts pc ON pc.promotion_id = a.id')
->joined('INNER JOIN promotion_units pu ON pu.promotion_id = a.id')
->where('pc.contract_id = :contract_id AND pu.unit_id = :unit_id');
return $this->fetchOne($query, ['contract_id' => $contract_id, 'unit_id' => $unit_id]);
}
/**
* @param int $promotion_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchContractUnitsByPromotion(int $promotion_id): array
{
$query = $this->connection->getQueryBuilder()
->select('contracts.id, unidad.id')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_contract_units pcu ON pcu.promotion_id = a.id')
->joined('INNER JOIN unidad ON unidad.id = pcu.unit_id')
->joined('INNER JOIN contracts ON contracts.id = pcu.contract_id')
->where('a.id = :promotion_id');
try {
$result = $this->connection->execute($query, ['promotion_id' => $promotion_id])->fetchAll(PDO::FETCH_ASSOC);
if (empty($result)) {
throw new Common\Implement\Exception\EmptyResult($query);
}
return $result;
} catch (PDOException $exception) {
throw new Common\Implement\Exception\EmptyResult($query, $exception);
}
}
}

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

@ -172,6 +172,33 @@ class Unidad extends Ideal\Repository
->group('unidad.id');
return $this->connection->execute($query, [$unidad_id])->fetch(PDO::FETCH_ASSOC);
}
public function fetchSoldByUnidad(int $unidad_id): Model\Venta\Unidad
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN `propiedad_unidad` pu ON pu.`unidad` = a.`id`')
->joined('INNER JOIN `venta` ON `venta`.`propiedad` = `pu`.`propiedad`')
->joined('LEFT OUTER JOIN (SELECT ev1.* FROM `estado_venta` ev1 JOIN (SELECT MAX(`id`) as `id`, `venta` FROM `estado_venta`) ev0 ON ev0.`id` = ev1.`id`) ev ON ev.`venta` = `venta`.`id`')
->joined('LEFT OUTER JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`')
->where('a.id = :unidad_id AND tev.activa = 1');
return $this->fetchOne($query, ['unidad_id' => $unidad_id]);
}
/**
* @param int $promotion_id
* @return array
* @throws Implement\Exception\EmptyResult
*/
public function fetchByPromotion(int $promotion_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN `promotion_units` pu ON pu.`unit_id` = a.`id`')
->where('pu.`promotion_id` = :promotion_id');
return $this->fetchMany($query, ['promotion_id' => $promotion_id]);
}
protected function joinProrrateo(): string
{

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

@ -6,12 +6,12 @@ use IntlDateFormatter;
class Format
{
public function localDate(string $valor, string $format, bool $print = false): string
public function localDate(string $valor, ?string $format = null, bool $print = false): string
{
$date = new DateTimeImmutable($valor);
$formatter = new IntlDateFormatter('es_ES');
if ($format == null) {
$format = 'DD [de] MMMM [de] YYYY';
$format = "dd 'de' MMMM 'de' YYYY";
}
$formatter->setPattern($format);
return $formatter->format($date);
@ -21,9 +21,9 @@ class Format
{
return number_format($number, $decimal_places, ',', '.');
}
public function percent(float|string $number, int $decimal_places = 2): string
public function percent(float|string $number, int $decimal_places = 2, bool $multiply = false): string
{
return "{$this->number($number, $decimal_places)}%";
return "{$this->number(($multiply) ? $number * 100 : $number, $decimal_places)}%";
}
public function pesos(string $valor, int $decimal_places = 0): string
{

View File

@ -0,0 +1,209 @@
<?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 Repository\Proyecto\Broker\Contact $contactRepository,
protected Repository\Proyecto\Broker\Contract $contractRepository,
protected Service\Proyecto\Broker\Contract $contractService)
{
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['rut']);
} 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']))
->addFactory('contracts', (new Factory())
->setArgs(['broker_rut' => $broker->rut])
->setCallable([$this->contractService, 'getByBroker']));
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($data['contact'])) {
try {
$representative = $this->contactRepository->fetchByName($data['contact']);
$filteredData['representative_id'] = $representative->id;
} catch (EmptyResult) {
$representativeData = $this->contactRepository->filterData($data);
$representativeData['name'] = $data['contact'];
$representative = $this->contactRepository->create($representativeData);
try {
$representative = $this->contactRepository->save($representative);
$filteredData['representative_id'] = $representative->id;
} catch (PDOException) {
unset($representative);
}
}
}
if (isset($filteredData['representative_id'])) {
try {
$this->contactRepository->fetchById($filteredData['representative_id']);
} catch (EmptyResult) {
unset($filteredData['representative_id']);
}
}
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);
}
if (isset($data['contact'])) {
try {
$representative = $this->contactRepository->fetchByName($data['contact']);
$data['representative_id'] = $representative->id;
} catch (EmptyResult) {
$representativeData = $this->contactRepository->filterData($data);
$representativeData['name'] = $data['contact'];
try {
$representative = $this->contactRepository->create($representativeData);
$representative = $this->contactRepository->save($representative);
$data['representative_id'] = $representative->id;
} catch (PDOException) {
unset($representative);
unset($data['contact']);
}
}
}
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,154 @@
<?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,
protected Repository\Venta\Promotion $promotionRepository)
{
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);
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('promotions', (new Implement\Repository\Factory())
->setCallable([$this->promotionRepository, 'fetchByContract'])
->setArgs(['contract_id' => $contract->id]));
return $contract;
}
}

View File

@ -4,6 +4,7 @@ namespace Incoviba\Service;
use Exception;
use DateTimeImmutable;
use DateMalformedStringException;
use Incoviba\Exception\ServiceAction\{Read, Update};
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal\Service;
use Incoviba\Common\Implement;
@ -36,9 +37,18 @@ class Venta extends Service
parent::__construct($logger);
}
/**
* @param int $venta_id
* @return Model\Venta
* @throws Read
*/
public function getById(int $venta_id): Model\Venta
{
return $this->process($this->ventaRepository->fetchById($venta_id));
try {
return $this->process($this->ventaRepository->fetchById($venta_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new Read(__CLASS__, $exception);
}
}
public function getByProyecto(int $proyecto_id): array
{
@ -285,6 +295,22 @@ class Venta extends Service
return $this->formaPagoService->add($data);
}
/**
* @param Model\Venta $venta
* @param array $data
* @return Model\Venta
* @throws Update
*/
public function edit(Model\Venta $venta, array $data): Model\Venta
{
try {
$filteredData = $this->ventaRepository->filterData($data);
return $this->ventaRepository->edit($venta, $filteredData);
} catch (Implement\Exception\EmptyResult $exception) {
throw new Update(__CLASS__, $exception);
}
}
protected function addEstado(Model\Venta $venta, Model\Venta\TipoEstadoVenta $tipoEstadoVenta, array $data): void
{
try {

View File

@ -1,7 +1,6 @@
<?php
namespace Incoviba\Service\Venta;
use Exception;
use DateTimeInterface;
use DateTimeImmutable;
use DateMalformedStringException;
@ -218,11 +217,15 @@ class Pago
return $uf;
}
if ($uf !== 0.0) {
$this->pagoRepository->edit($pago, ['uf' => $uf]);
try {
$this->pagoRepository->edit($pago, ['uf' => $uf]);
} catch (EmptyResult) {}
return $uf;
}
} elseif ($pago->uf === 0.0) {
$this->pagoRepository->edit($pago, ['uf' => null]);
try {
$this->pagoRepository->edit($pago, ['uf' => null]);
} catch (EmptyResult) {}
return null;
}
return $pago->uf;

View File

@ -1,18 +1,22 @@
<?php
namespace Incoviba\Service\Venta;
use PDOException;
use DateTimeImmutable;
use DateMalformedStringException;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Common\Implement\Repository\Factory;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository;
use Incoviba\Exception\ServiceAction\{Create, Read};
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service\UF;
class Pie
{
public function __construct(
protected Repository\Venta\Pie $pieRepository,
protected Cuota $cuotaService,
protected Pago $pagoService
protected Pago $pagoService,
protected UF $ufService
) {}
public function getById(int $pie_id): Model\Venta\Pie
@ -28,11 +32,26 @@ class Pie
}
}
/**
* @param array $data
* @return Model\Venta\Pie
* @throws Create
*/
public function add(array $data): Model\Venta\Pie
{
$filteredData = $this->pieRepository->filterData($data);
$pie = $this->pieRepository->create($filteredData);
return $this->pieRepository->save($pie);
try {
$filteredData = $this->pieRepository->filterData($data);
if (!isset($filteredData['uf'])) {
try {
$date = new DateTimeImmutable($filteredData['fecha']);
$filteredData['uf'] = $this->ufService->get($date);
} catch (DateMalformedStringException) {}
}
$pie = $this->pieRepository->create($filteredData);
return $this->pieRepository->save($pie);
} catch (PDOException $exception) {
throw new Create(__CLASS__, $exception);
}
}
public function addCuota(array $data): Model\Venta\Cuota
{
@ -58,6 +77,12 @@ class Pie
if (isset($pie->asociado)) {
$pie->asociado = $this->getById($pie->asociado->id);
}
if (($pie->uf === null or $pie->uf === 0.0) and $pie->fecha <= new DateTimeImmutable()) {
$pie->uf = $this->ufService->get($pie->fecha);
try {
$this->pieRepository->edit($pie, ['uf' => $pie->uf]);
} catch (EmptyResult) {}
}
return $pie;
}
}

View File

@ -0,0 +1,186 @@
<?php
namespace Incoviba\Service\Venta;
use Incoviba\Controller\API\Ventas\Promotions;
use PDOException;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Exception;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class Promotion extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Promotion $promotionRepository,
protected Repository\Proyecto $projectRepository,
protected Repository\Proyecto\Broker\Contract $contractRepository,
protected Repository\Venta\Unidad $unidadRepository)
{
parent::__construct($logger);
}
public function getAll(null|string|array $order = null): array
{
try {
return array_map([$this, 'process'], $this->promotionRepository->fetchAll($order));
} catch (Implement\Exception\EmptyResult) {
return [];
}
}
/**
* @param int $promotion_id
* @return Model\Venta\Promotion
* @throws Exception\ServiceAction\Read
*/
public function getById(int $promotion_id): Model\Venta\Promotion
{
try {
return $this->process($this->promotionRepository->fetchById($promotion_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new Exception\ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $contract_id
* @return array
*/
public function getByContract(int $contract_id): array
{
try {
return array_map([$this, 'process'], $this->promotionRepository->fetchByContract($contract_id));
} catch (Implement\Exception\EmptyResult) {
try {
$contract = $this->contractRepository->fetchById($contract_id);
return array_map([$this, 'process'], $this->promotionRepository->fetchByProject($contract->project->id));
} catch (Implement\Exception\EmptyResult) {
return [];
}
}
}
/**
* @param int $contract_id
* @return array
*/
public function getActiveByContract(int $contract_id): array
{
try {
return array_map([$this, 'process'], $this->promotionRepository->fetchActiveByContract($contract_id));
} catch (Implement\Exception\EmptyResult) {
try {
$contract = $this->contractRepository->fetchById($contract_id);
return array_map([$this, 'process'], $this->promotionRepository->fetchActiveByProject($contract->project->id));
} catch (Implement\Exception\EmptyResult) {
return [];
}
}
}
/**
* @param array $data
* @return Model\Venta\Promotion
* @throws Exception\ServiceAction\Create
*/
public function add(array $data): Model\Venta\Promotion
{
try {
$filteredData = $this->promotionRepository->filterData($data);
#throw new \Exception(var_export($filteredData, true));
$promotion = $this->promotionRepository->create($filteredData);
#throw new \Exception(var_export($promotion, true));
$promotion = $this->promotionRepository->save($promotion);
return $this->process($promotion);
} catch (PDOException $exception) {
throw new Exception\ServiceAction\Create(__CLASS__, $exception);
}
}
/**
* @param Model\Venta\Promotion $promotion
* @param array $data
* @return Model\Venta\Promotion
* @throws Exception\ServiceAction\Update
*/
public function edit(Model\Venta\Promotion $promotion, array $data): Model\Venta\Promotion
{
try {
$filteredData = $this->promotionRepository->filterData($data);
$promotion = $this->promotionRepository->edit($promotion, $filteredData);
return $this->process($promotion);
} catch (PDOException | Implement\Exception\EmptyResult $exception) {
throw new Exception\ServiceAction\Update(__CLASS__, $exception);
}
}
/**
* @param int $promotion_id
* @return Model\Venta\Promotion
* @throws Exception\ServiceAction\Delete
*/
public function remove(int $promotion_id): Model\Venta\Promotion
{
try {
$promotion = $this->promotionRepository->fetchById($promotion_id);
$this->promotionRepository->remove($promotion);
return $promotion;
} catch (PDOException | Implement\Exception\EmptyResult $exception) {
throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
}
}
protected function process(Model\Venta\Promotion $model): Model\Venta\Promotion
{
$model->addFactory('projects', (new Implement\Repository\Factory())
->setCallable(function($promotion_id) {
try {
return $this->projectRepository->fetchByPromotion($promotion_id);
} catch (Implement\Exception\EmptyResult) {
return [];
}
})
->setArgs(['promotion_id' => $model->id]));
$model->addFactory('contracts', (new Implement\Repository\Factory())
->setCallable(function($promotion_id) {
try {
return $this->contractRepository->fetchByPromotion($promotion_id);
} catch (Implement\Exception\EmptyResult) {
return [];
}
})
->setArgs(['promotion_id' => $model->id]));
$model->addFactory('units', (new Implement\Repository\Factory())
->setCallable(function($promotion_id) {
try {
return $this->unidadRepository->fetchByPromotion($promotion_id);
} catch (Implement\Exception\EmptyResult) {
return [];
}
})
->setArgs(['promotion_id' => $model->id]));
$model->addFactory('contractUnits', (new Implement\Repository\Factory())
->setCallable(function($promotion_id) {
try {
$ids = $this->promotionRepository->fetchContractUnitsByPromotion($promotion_id);
$contractUnits = [];
foreach ($ids as $id) {
try {
$contract = $this->contractRepository->fetchById($id['contract_id']);
$unidad = $this->unidadRepository->fetchById($id['unidad_id']);
$contractUnits[]= (object) ['contract' => $contract, 'unit' => $unidad];
} catch (Implement\Exception\EmptyResult) {}
}
return $contractUnits;
} catch (Implement\Exception\EmptyResult) {
return [];
}
})
->setArgs(['promotion_id' => $model->id]));
return $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]);

Some files were not shown because too many files have changed in this diff Show More