Compare commits
71 Commits
develop
...
eabdab23c3
Author | SHA1 | Date | |
---|---|---|---|
eabdab23c3 | |||
5147450ed6 | |||
ed96f25475 | |||
d5a3512852 | |||
d6730cd020 | |||
c7dddc818c | |||
33b4182bd3 | |||
fc776e6cec | |||
5d79ea83c3 | |||
c34048a53a | |||
f7af93b815 | |||
993e4ff3b8 | |||
bc49ba7629 | |||
3c2b486083 | |||
76f69f3bda | |||
8ba3c456b6 | |||
98b18fab3e | |||
12a4831887 | |||
da46914de4 | |||
596bc71cf8 | |||
7f8e4ea943 | |||
5456485f71 | |||
836503a71b | |||
4df0cca675 | |||
00a0adb4ac | |||
037fcd60f3 | |||
7a97fc9dfe | |||
7b2df74e4d | |||
b5d6d0acb9 | |||
8a1e6a7761 | |||
ced673e452 | |||
8a7a1d4e64 | |||
9be20ab1cd | |||
1c40f18624 | |||
db36549699 | |||
4ce83fb270 | |||
b191a01313 | |||
d3b0026ca4 | |||
2b3f476df7 | |||
39c148b7b3 | |||
bae0f1f555 | |||
2e49e2c947 | |||
68aebdb4fe | |||
346001db8e | |||
8b04eb262f | |||
7c7c8315e2 | |||
510e05e5ca | |||
5055d2703c | |||
2bc30ab9e8 | |||
c7ee440e03 | |||
18dd8c4ec0 | |||
8ea4995f6b | |||
aeeca65d94 | |||
5f69069aa0 | |||
095a65a643 | |||
928d2e57be | |||
2a0335f834 | |||
9ccf53fa4e | |||
ef54c36edc | |||
4aa88d5164 | |||
8ea13c3efd | |||
12e3d7ed3b | |||
a7fc89ac29 | |||
a71df4e70d | |||
f17b7a758a | |||
7fb28cd44c | |||
a44bd610ad | |||
28bba8a438 | |||
0ec6ebdafe | |||
3ebe256a66 | |||
9d135e2c26 |
56
app/common/Ideal/Service/API.php
Normal file
56
app/common/Ideal/Service/API.php
Normal 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;
|
||||
}
|
@ -81,6 +81,9 @@ class Insert extends Ideal\Query implements Define\Query\Insert
|
||||
if ($value === (int) $value) {
|
||||
return $value;
|
||||
}
|
||||
if (str_starts_with($value, ':')) {
|
||||
return $value;
|
||||
}
|
||||
return "'{$value}'";
|
||||
}, $this->values)) . ')';
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
@ -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;');
|
||||
}
|
||||
}
|
@ -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;');
|
||||
}
|
||||
}
|
@ -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;');
|
||||
}
|
||||
}
|
@ -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;');
|
||||
}
|
||||
}
|
@ -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;');
|
||||
}
|
||||
}
|
@ -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;');
|
||||
}
|
||||
}
|
@ -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;');
|
||||
}
|
||||
}
|
@ -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;');
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
<?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 up(): void
|
||||
{
|
||||
if ($this->table('promotions')->hasColumn('price_id')) {
|
||||
$this->table('promotions')
|
||||
->dropForeignKey('price_id')
|
||||
->removeColumn('price_id')
|
||||
->update();
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void {}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
<?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 up(): void
|
||||
{
|
||||
$this->table('promotions')
|
||||
->changeColumn('end_date', 'date', ['null' => true])
|
||||
->changeColumn('valid_until', 'date', ['null' => true])
|
||||
->update();
|
||||
}
|
||||
public function down(): void {}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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_projects')
|
||||
->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();
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Phinx\Migration\AbstractMigration;
|
||||
|
||||
final class CreatePromotionBrokers 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_brokers')
|
||||
->addColumn('promotion_id', 'integer', ['signed' => false, 'null' => false])
|
||||
->addColumn('broker_rut', 'integer', ['signed' => false, 'null' => false])
|
||||
->addForeignKey('promotion_id', 'promotions', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
|
||||
->addForeignKey('broker_rut', 'brokers', 'rut', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
|
||||
->create();
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Phinx\Migration\AbstractMigration;
|
||||
|
||||
final class CreatePromotionUnitLines 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_unit_lines')
|
||||
->addColumn('promotion_id', 'integer', ['signed' => false, 'null' => false])
|
||||
->addColumn('unit_line_id', 'integer', ['signed' => false, 'null' => false])
|
||||
->addForeignKey('promotion_id', 'promotions', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
|
||||
->addForeignKey('unit_line_id', 'proyecto_tipo_unidad', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
|
||||
->create();
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Phinx\Migration\AbstractMigration;
|
||||
|
||||
final class CreatePromotionUnitTypes 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_unit_types')
|
||||
->addColumn('promotion_id', 'integer', ['signed' => false, 'null' => false])
|
||||
->addColumn('project_id', 'integer', ['signed' => false, 'null' => false])
|
||||
->addColumn('unit_type_id', 'integer', ['signed' => false, 'null' => false])
|
||||
->addForeignKey('promotion_id', 'promotions', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
|
||||
->addForeignKey('project_id', 'proyecto', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
|
||||
->addForeignKey('unit_type_id', 'tipo_unidad', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
|
||||
->create();
|
||||
}
|
||||
}
|
@ -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));
|
||||
|
@ -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']);
|
||||
});
|
||||
|
@ -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']);
|
||||
});
|
||||
|
30
app/resources/routes/api/proyectos/brokers.php
Normal file
30
app/resources/routes/api/proyectos/brokers.php
Normal 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']);
|
||||
});
|
@ -21,6 +21,7 @@ $app->group('/ventas', function($app) {
|
||||
});
|
||||
$app->group('/by', function($app) {
|
||||
$app->get('/unidad/{unidad_id}', [Ventas::class, 'unidad']);
|
||||
$app->post('/unidades[/]', [Ventas::class, 'byUnidades']);
|
||||
});
|
||||
$app->post('/get[/]', [Ventas::class, 'getMany']);
|
||||
$app->post('[/]', [Ventas::class, 'proyecto']);
|
||||
@ -55,6 +56,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']);
|
||||
});
|
||||
|
28
app/resources/routes/api/ventas/promotions.php
Normal file
28
app/resources/routes/api/ventas/promotions.php
Normal file
@ -0,0 +1,28 @@
|
||||
<?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']);
|
||||
$app->group('/connections', function($app) {
|
||||
$app->post('/add[/]', [Promotions::class, 'addConnections']);
|
||||
$app->group('/project/{project_id}', function($app) {
|
||||
$app->delete('[/]', [Promotions::class, 'removeProject']);
|
||||
$app->group('/unit-type/{unit_type_id}', function($app) {
|
||||
$app->delete('[/]', [Promotions::class, 'removeUnitType']);
|
||||
});
|
||||
});
|
||||
$app->group('/broker/{broker_rut}', function($app) {
|
||||
$app->delete('[/]', [Promotions::class, 'removeBroker']);
|
||||
});
|
||||
$app->group('/unit-line/{unit_line_id}', function($app) {
|
||||
$app->delete('[/]', [Promotions::class, 'removeUnitLine']);
|
||||
});
|
||||
$app->group('/unit/{unit_id}', function($app) {
|
||||
$app->delete('[/]', [Promotions::class, 'removeUnit']);
|
||||
});
|
||||
});
|
||||
});
|
12
app/resources/routes/api/ventas/reservations.php
Normal file
12
app/resources/routes/api/ventas/reservations.php
Normal 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']);
|
||||
});
|
12
app/resources/routes/proyectos/brokers.php
Normal file
12
app/resources/routes/proyectos/brokers.php
Normal 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']);
|
||||
});
|
9
app/resources/routes/ventas/promotions.php
Normal file
9
app/resources/routes/ventas/promotions.php
Normal 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']);
|
||||
});
|
@ -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: {
|
||||
|
@ -3,5 +3,6 @@
|
||||
<i class="dropdown icon"></i>
|
||||
<div class="menu">
|
||||
<a class="item" href="{{$urls->base}}/proyectos/unidades">Unidades</a>
|
||||
<a class="item" href="{{ $urls->base }}/proyectos/brokers">Operadores</a>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -3,6 +3,7 @@
|
||||
<i class="dropdown icon"></i>
|
||||
<div class="menu">
|
||||
<a class="item" href="{{$urls->base}}/ventas/precios">Precios</a>
|
||||
<a class="item" href="{{ $urls->base }}/ventas/promotions">Promociones</a>
|
||||
<a class="item" href="{{$urls->base}}/ventas/cierres">Cierres</a>
|
||||
<div class="item">
|
||||
Cuotas
|
||||
|
@ -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
|
||||
|
6
app/resources/views/layout/body/scripts/stats.blade.php
Normal file
6
app/resources/views/layout/body/scripts/stats.blade.php
Normal 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
|
@ -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')
|
||||
|
219
app/resources/views/proyectos/brokers.blade.php
Normal file
219
app/resources/views/proyectos/brokers.blade.php
Normal file
@ -0,0 +1,219 @@
|
||||
@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 class="top aligned">
|
||||
<span
|
||||
@if ($broker->data()?->legalName !== '')
|
||||
data-tooltip="{{ $broker->data()?->legalName }}" data-position="right center"
|
||||
@endif
|
||||
>
|
||||
{{$broker->rutFull()}}
|
||||
</span>
|
||||
</td>
|
||||
<td class="top aligned">
|
||||
<a href="{{ $urls->base }}/proyectos/broker/{{ $broker->rut }}">
|
||||
{{$broker->name}}
|
||||
<i class="angle right icon"></i>
|
||||
</a>
|
||||
</td>
|
||||
<td class="top aligned">
|
||||
<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 class="top aligned">
|
||||
<div class="ui list">
|
||||
@foreach($broker->contracts() as $contract)
|
||||
<div class="item">
|
||||
<a href="{{$urls->base}}/proyectos/broker/{{$broker->rut}}/contract/{{$contract->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="top aligned 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
|
114
app/resources/views/proyectos/brokers/add_modal.blade.php
Normal file
114
app/resources/views/proyectos/brokers/add_modal.blade.php
Normal 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
|
22
app/resources/views/proyectos/brokers/base.blade.php
Normal file
22
app/resources/views/proyectos/brokers/base.blade.php
Normal 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
|
350
app/resources/views/proyectos/brokers/contracts/show.blade.php
Normal file
350
app/resources/views/proyectos/brokers/contracts/show.blade.php
Normal file
@ -0,0 +1,350 @@
|
||||
@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 => {
|
||||
let price = unit.valor ?? (unit.precio?.valor ?? 0)
|
||||
let amount = 1
|
||||
let diff = 0
|
||||
unit.promotions?.forEach(promotion => {
|
||||
if (promotion.type === 1) {
|
||||
diff += promotion.amount
|
||||
return
|
||||
}
|
||||
amount /= 1/(1 - promotion.amount)
|
||||
})
|
||||
amount = 1 - amount
|
||||
price += diff
|
||||
prices.push({
|
||||
id: unit.id,
|
||||
base: price,
|
||||
commission: this.commission,
|
||||
broker: price / (1 - this.commission),
|
||||
amount,
|
||||
final: price / (1 - this.commission) / (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 card">
|
||||
<div class="content">
|
||||
<div class="header">
|
||||
Promociones Aplicadas
|
||||
</div>
|
||||
<div class="description">
|
||||
<div class="ui list">
|
||||
@foreach ($contract->promotions() as $promotion)
|
||||
<div class="item">
|
||||
{{ $promotion->description }} {{ $format->percent($promotion->amount, 2, true) }} {{ ucwords($promotion->type->name()) }}
|
||||
</div>
|
||||
@endforeach
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ui very basic segment">
|
||||
<div class="ui active inline loader" id="loader"></div>
|
||||
<div class="ui indicating progress" id="load_progress">
|
||||
<div class="bar">
|
||||
<div class="progress"></div>
|
||||
</div>
|
||||
</div>
|
||||
</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 top attached indicating progress" id="values_progress">
|
||||
<div class="bar"></div>
|
||||
</div>
|
||||
<div class="ui bottom attached tab basic fitted segment active" data-tab="tipos">
|
||||
@include('proyectos.brokers.contracts.show.tipo')
|
||||
</div>
|
||||
<div class="ui bottom attached tab basic fitted segment" data-tab="lineas">
|
||||
@include('proyectos.brokers.contracts.show.linea')
|
||||
</div>
|
||||
<div class="ui bottom attached tab basic 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: '',
|
||||
progress: '',
|
||||
load_progress: ''
|
||||
},
|
||||
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: progress_bar => {
|
||||
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 = []
|
||||
const url = `{{ $urls->api }}/proyectos/broker/{{ $contract->broker->rut }}/contract/{{ $contract->id }}/promotions`
|
||||
const method = 'post'
|
||||
chunks.forEach(chunk => {
|
||||
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 => {
|
||||
progress_bar.progress('increment', json.input.unidad_ids.length)
|
||||
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: progress_bar => {
|
||||
const unsold = [...units.data.units.filter(unit => !unit.sold), ...units.data.units.filter(unit => unit.sold && unit.proyecto_tipo_unidad.tipo_unidad.descripcion !== 'departamento')]
|
||||
const current_total = progress_bar.progress('get total')
|
||||
progress_bar.progress('set total', current_total + unsold.length)
|
||||
|
||||
const chunkSize = 100
|
||||
const chunks = []
|
||||
for (let i = 0; i < unsold.length; i += chunkSize) {
|
||||
chunks.push(unsold.slice(i, i + chunkSize).map(u => u.id))
|
||||
}
|
||||
const promises = []
|
||||
const url = `{{ $urls->api }}/proyecto/{{ $contract->project->id }}/unidades/precios`
|
||||
const method = 'post'
|
||||
chunks.forEach(chunk => {
|
||||
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 => {
|
||||
progress_bar.progress('increment', json.input.unidad_ids.length)
|
||||
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)
|
||||
},
|
||||
values: progress_bar => {
|
||||
const sold = units.data.units.filter(unit => unit.sold && unit.proyecto_tipo_unidad.tipo_unidad.descripcion === 'departamento')
|
||||
progress_bar.progress('set total', sold.length)
|
||||
|
||||
const chunkSize = 10
|
||||
const chunks = []
|
||||
for (let i = 0; i < sold.length; i += chunkSize) {
|
||||
chunks.push(sold.slice(i, i + chunkSize).map(u => u.id))
|
||||
}
|
||||
const promises = []
|
||||
const url = `{{ $urls->api }}/ventas/by/unidades`
|
||||
const method = 'post'
|
||||
chunks.forEach(chunk => {
|
||||
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 => {
|
||||
progress_bar.progress('increment', json.input.unidad_ids.length)
|
||||
if (json.ventas.length === 0) {
|
||||
return
|
||||
}
|
||||
json.ventas.forEach(({unidad_id, venta}) => {
|
||||
const unidades = venta.propiedad.unidades
|
||||
const otras_unidades = unidades.filter(unit => unit.id !== parseInt(unidad_id) && unit.proyecto_tipo_unidad.tipo_unidad.descripcion !== 'departamento')
|
||||
const departamentos = unidades.filter(unit => unit.proyecto_tipo_unidad.tipo_unidad.descripcion === 'departamento' && unit.id !== parseInt(unidad_id))
|
||||
const precios = otras_unidades.map(unit => {
|
||||
const idx = units.data.units.findIndex(u => u.id === unit.id)
|
||||
return units.data.units[idx].precio?.valor ?? 0
|
||||
}).reduce((sum, precio) => sum + precio, 0)
|
||||
if (departamentos.length === 0) {
|
||||
const idx = units.data.units.findIndex(unit => unit.id === parseInt(unidad_id))
|
||||
units.data.units[idx].valor = venta.valor - precios
|
||||
units.data.units[idx].venta = venta
|
||||
return
|
||||
}
|
||||
const sum_precios = departamentos.map(departamento => {
|
||||
return departamento.current_precio.valor
|
||||
}).reduce((sum, precio) => sum + precio, 0)
|
||||
departamentos.forEach(departamento => {
|
||||
const idx = units.data.units.findIndex(unit => unit.id === departamento.id)
|
||||
const saldo = venta.valor - precios
|
||||
units.data.units[idx].valor = saldo / sum_precios * departamento.current_precio.valor
|
||||
units.data.units[idx].venta = venta
|
||||
})
|
||||
})
|
||||
}))
|
||||
})
|
||||
return Promise.all(promises)
|
||||
},
|
||||
sold: progress_bar => {
|
||||
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 = []
|
||||
const url = `{{ $urls->api }}/proyecto/{{ $contract->project->id }}/unidades/estados`
|
||||
const method = 'post'
|
||||
chunks.forEach(chunk => {
|
||||
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 => {
|
||||
progress_bar.progress('increment', json.input.unidad_ids.length)
|
||||
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'
|
||||
document.getElementById(units.ids.progress).style.visibility = 'hidden'
|
||||
document.getElementById(units.ids.load_progress).style.visibility = 'hidden'
|
||||
|
||||
const loader = $(`#${units.ids.loader}`)
|
||||
|
||||
units.get().units().then(() => {
|
||||
document.getElementById(units.ids.load_progress).style.visibility = 'visible'
|
||||
|
||||
const units_length = units.data.units.length
|
||||
const progress_bar = $(`#${units.ids.load_progress}`)
|
||||
progress_bar.progress({ total: units_length * 2 })
|
||||
|
||||
loader.hide()
|
||||
|
||||
units.get().promotions(progress_bar).then(() => {
|
||||
units.get().sold(progress_bar).then(() => {
|
||||
units.get().prices(progress_bar).then(() => {
|
||||
document.getElementById(units.ids.results).style.visibility = 'visible'
|
||||
|
||||
loader.parent().remove()
|
||||
|
||||
units.draw().units()
|
||||
units.draw().tipos()
|
||||
units.draw().lineas()
|
||||
|
||||
document.getElementById(units.ids.progress).style.visibility = 'visible'
|
||||
const progress_bar = $(`#${units.ids.progress}`)
|
||||
progress_bar.progress()
|
||||
|
||||
units.get().values(progress_bar).then(() => {
|
||||
document.getElementById(units.ids.progress).remove()
|
||||
|
||||
units.draw().units()
|
||||
units.draw().tipos()
|
||||
units.draw().lineas()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
$(document).ready(function () {
|
||||
units.setup({results: 'results', loader: 'loader', progress: 'values_progress', load_progress: 'load_progress'})
|
||||
})
|
||||
</script>
|
||||
@endpush
|
@ -0,0 +1,94 @@
|
||||
<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 Base</th>
|
||||
<th class="right aligned" style="text-decoration: overline">Comisión</th>
|
||||
<th class="right aligned" style="text-decoration: overline">Porcentaje</th>
|
||||
<th class="right aligned" style="text-decoration: overline">Precio Operador</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(' ', ' ')
|
||||
const commission_tooltip = [
|
||||
`Min: ${formatters.percent.format(Math.min(...prices.map(p => p.commission)))}`,
|
||||
`Max: ${formatters.percent.format(Math.max(...prices.map(p => p.commission)))}`,
|
||||
`Desv: ${formatters.percent.format(Stat.standardDeviation(prices.map(p => p.commission)))}`
|
||||
].join("\n").replaceAll(' ', ' ')
|
||||
const broker_tooltip = [
|
||||
`Min: ${formatters.ufs.format(Math.min(...prices.map(p => p.broker)))}`,
|
||||
`Max: ${formatters.ufs.format(Math.max(...prices.map(p => p.broker)))}`,
|
||||
`Desv: ${formatters.ufs.format(Stat.standardDeviation(prices.map(p => p.broker)))}`
|
||||
].join("\n").replaceAll(' ', ' ')
|
||||
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(' ', ' ')
|
||||
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(' ', ' ')
|
||||
|
||||
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="${commission_tooltip}" data-position="right center" data-variation="wide multiline">${formatters.percent.format(Stat.mean(prices.map(p => p.commission)))}</span></td>`,
|
||||
`<td class="right aligned"><span data-tooltip="${broker_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(Stat.mean(prices.map(p => p.broker)))}</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
|
@ -0,0 +1,75 @@
|
||||
<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">Comisión</th>
|
||||
<th class="right aligned" style="text-decoration: overline">Precio Operador</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(' ', ' ')
|
||||
const commission_tooltip = [
|
||||
`Min: ${formatters.percent.format(Math.min(...prices.map(p => p.commission)))}`,
|
||||
`Max: ${formatters.percent.format(Math.max(...prices.map(p => p.commission)))}`,
|
||||
`Desv: ${formatters.percent.format(Stat.standardDeviation(prices.map(p => p.commission)))}`
|
||||
].join("\n").replaceAll(' ', ' ')
|
||||
const broker_tooltip = [
|
||||
`Min: ${formatters.ufs.format(Math.min(...prices.map(p => p.broker)))}`,
|
||||
`Max: ${formatters.ufs.format(Math.max(...prices.map(p => p.broker)))}`,
|
||||
`Desv: ${formatters.ufs.format(Stat.standardDeviation(prices.map(p => p.broker)))}`
|
||||
].join("\n").replaceAll(' ', ' ')
|
||||
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(' ', ' ')
|
||||
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(' ', ' ')
|
||||
|
||||
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="${commission_tooltip}" data-position="right center" data-variation="wide multiline">${formatters.percent.format(Stat.mean(prices.map(p => p.commission)))}</span></td>`,
|
||||
`<td class="right aligned"><span data-tooltip="${broker_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(Stat.mean(prices.map(p => p.broker)))}</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
|
@ -0,0 +1,145 @@
|
||||
<table class="ui table" id="unidades">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Estado</th>
|
||||
<th>Tipo</th>
|
||||
<th>Tipo Order</th>
|
||||
<th class="right aligned">Unidad</th>
|
||||
<th>Unidad Orden</th>
|
||||
<th>Tipología</th>
|
||||
<th>Piso</th>
|
||||
<th>Orientación</th>
|
||||
<th>m²</th>
|
||||
<th class="right aligned">Precio Base</th>
|
||||
<th class="right aligned">Comisión</th>
|
||||
<th class="right aligned">Precio Operador</th>
|
||||
<th class="right aligned">UF/m²</th>
|
||||
<th class="right aligned">Porcentaje</th>
|
||||
<th class="right aligned">Precio Final</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
|
||||
@push('page_scripts')
|
||||
<script>
|
||||
class UnitsTable extends TableHandler {
|
||||
ids = {
|
||||
units: 'unidades',
|
||||
}
|
||||
columns = [
|
||||
'estado',
|
||||
'tipo',
|
||||
'tipo_order',
|
||||
'unidad',
|
||||
'unidad_order',
|
||||
'tipologia',
|
||||
'piso',
|
||||
'orientacion',
|
||||
'metros',
|
||||
'precio_base',
|
||||
'commission',
|
||||
'precio_operador',
|
||||
'UF/m²',
|
||||
'porcentaje',
|
||||
'precio_final',
|
||||
]
|
||||
constructor(commission) {
|
||||
super(commission)
|
||||
|
||||
const dto = structuredClone(datatables_defaults)
|
||||
dto.pageLength = 100
|
||||
dto.columnDefs = [
|
||||
{
|
||||
target: ['tipo_order', 'unidad_order', 'tipologia', 'piso', 'orientacion', 'metros'].map(column => this.columns.indexOf(column)),
|
||||
visible: false
|
||||
},
|
||||
{
|
||||
target: ['tipo'].map(column => this.columns.indexOf(column)),
|
||||
orderData: ['tipo_order'].map(column => this.columns.indexOf(column)),
|
||||
},
|
||||
{
|
||||
target: ['unidad'].map(column => this.columns.indexOf(column)),
|
||||
orderData: ['unidad_order'].map(column => this.columns.indexOf(column)),
|
||||
},
|
||||
{
|
||||
target: ['unidad', 'precio_base', 'commission', 'precio_operador', 'UF/m²', 'porcentaje', 'precio_final']
|
||||
.map(column => this.columns.indexOf(column)),
|
||||
className: 'dt-right right aligned'
|
||||
}
|
||||
]
|
||||
dto.order = ['tipo_order', 'unidad_order'].map(column => [this.columns.indexOf(column), 'asc'])
|
||||
dto.language.searchBuilder = searchBuilder
|
||||
dto.layout = {
|
||||
top1Start: {
|
||||
searchBuilder: {
|
||||
columns: this.columns.filter(column => !['tipo_order', 'unidad_order'].includes(column))
|
||||
.map(column => this.columns.indexOf(column)),
|
||||
}
|
||||
},
|
||||
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: ['tipo', 'unidad', 'tipologia', 'piso', 'orientacion', 'metros', 'commission', 'precio_operador', 'porcentaje', 'precio_final']
|
||||
.map(column => this.columns.indexOf(column)),
|
||||
rows: (idx, data, node) => {
|
||||
return data[this.columns.indexOf('estado')] === 'Libre'
|
||||
},
|
||||
format: {
|
||||
body: (data, row, columnIdx, node) => {
|
||||
if (typeof data === 'string' && data.includes('<span')) {
|
||||
return data.replace(/<span.*>(.*)<\/span>/, '$1')
|
||||
}
|
||||
if (['metros'].map(column => this.columns.indexOf(column)).includes(columnIdx)) {
|
||||
return data.replaceAll('.', '').replaceAll(',', '.')
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
$(`#${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([
|
||||
unidad.sold ? `<span class="ui yellow text">Vendida</span>` : 'Libre',
|
||||
tipo.charAt(0).toUpperCase() + tipo.slice(1),
|
||||
unidad.proyecto_tipo_unidad.tipo_unidad.orden,
|
||||
unidad.sold && unidad.venta ? `<a href="{{ $urls->base }}/venta/${unidad.venta?.id }" data-tooltip="Valor Promesa: UF ${formatters.ufs.format(unidad.venta?.valor ?? 0)}" data-position="left center">${unidad.descripcion}</a>` : unidad.descripcion,
|
||||
unidad.descripcion.padStart(4, '0'),
|
||||
unidad.proyecto_tipo_unidad.tipologia,
|
||||
unidad.piso,
|
||||
unidad.orientacion,
|
||||
formatters.ufs.format(unidad.proyecto_tipo_unidad.vendible) ?? 0,
|
||||
'UF ' + formatters.ufs.format(price.base ?? 0),
|
||||
formatters.percent.format(price.commission ?? 0),
|
||||
'UF ' + formatters.ufs.format(price.broker ?? 0),
|
||||
formatters.ufs.format(price.broker / unidad.proyecto_tipo_unidad.vendible),
|
||||
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
|
113
app/resources/views/proyectos/brokers/edit_modal.blade.php
Normal file
113
app/resources/views/proyectos/brokers/edit_modal.blade.php
Normal 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
|
52
app/resources/views/proyectos/brokers/proyectos.blade.php
Normal file
52
app/resources/views/proyectos/brokers/proyectos.blade.php
Normal 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
|
170
app/resources/views/proyectos/brokers/show.blade.php
Normal file
170
app/resources/views/proyectos/brokers/show.blade.php
Normal file
@ -0,0 +1,170 @@
|
||||
@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 }}
|
||||
<i class="angle right icon"></i>
|
||||
</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
|
@ -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
|
50
app/resources/views/ventas/pies/add.blade.php
Normal file
50
app/resources/views/ventas/pies/add.blade.php
Normal 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
|
176
app/resources/views/ventas/promotions.blade.php
Normal file
176
app/resources/views/ventas/promotions.blade.php
Normal file
@ -0,0 +1,176 @@
|
||||
@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 }}
|
||||
<i class="angle right icon"></i>
|
||||
</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($promotion->projects()) +
|
||||
count(array_unique(array_map(function($unitType) {return $unitType->project;},$promotion->unitTypes()))) +
|
||||
count(array_unique(array_map(function($unitLine) {return $unitLine->proyecto;},$promotion->unitLines()))) +
|
||||
count($promotion->units()) }} <br />
|
||||
Operadores: {{ count($promotion->brokers()) }}
|
||||
</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
|
100
app/resources/views/ventas/promotions/add_modal.blade.php
Normal file
100
app/resources/views/ventas/promotions/add_modal.blade.php
Normal 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
|
22
app/resources/views/ventas/promotions/base.blade.php
Normal file
22
app/resources/views/ventas/promotions/base.blade.php
Normal 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
|
126
app/resources/views/ventas/promotions/edit_modal.blade.php
Normal file
126
app/resources/views/ventas/promotions/edit_modal.blade.php
Normal 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
|
310
app/resources/views/ventas/promotions/show.blade.php
Normal file
310
app/resources/views/ventas/promotions/show.blade.php
Normal file
@ -0,0 +1,310 @@
|
||||
@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') ?? '∞' !!}
|
||||
</p>
|
||||
<p>Válido hasta: {!! $promotion->validUntil?->format('d-m-Y') ?? '∅' !!}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ui right aligned basic segment">
|
||||
<button class="ui green tertiary icon button" id="add_button">
|
||||
<i class="plus icon"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="ui top attached tabular menu" id="tables_tab_menu">
|
||||
<div class="active item" data-tab="projects_table">Proyectos</div>
|
||||
<div class="item" data-tab="brokers_table">Operadores</div>
|
||||
<div class="item" data-tab="unit-types_table">Tipos</div>
|
||||
<div class="item" data-tab="unit-lines_table">Líneas</div>
|
||||
<div class="item" data-tab="units_table">Unidades</div>
|
||||
</div>
|
||||
<div class="ui bottom attached tab fitted segment" data-tab="projects_table"></div>
|
||||
<div class="ui bottom attached tab fitted segment" data-tab="brokers_table"></div>
|
||||
<div class="ui bottom attached tab fitted segment" data-tab="unit-types_table"></div>
|
||||
<div class="ui bottom attached tab fitted segment" data-tab="unit-lines_table"></div>
|
||||
<div class="ui bottom attached tab fitted segment" data-tab="units_table"></div>
|
||||
@include('ventas.promotions.show.add_modal')
|
||||
@endsection
|
||||
|
||||
@push('page_scripts')
|
||||
<script>
|
||||
class ConnectionTable {
|
||||
table
|
||||
constructor(tab) {
|
||||
const parent = document.querySelector(`.ui.tab.segment[data-tab="${tab}"]`)
|
||||
this.table = document.createElement('table')
|
||||
this.table.className = 'ui table'
|
||||
this.table.innerHTML = [
|
||||
'<thead>',
|
||||
'<tr>',
|
||||
'<th>Proyecto</th>',
|
||||
'<th>Operador</th>',
|
||||
'<th class="center aligned" colspan="3">Unidad</th>',
|
||||
'</tr>',
|
||||
'<tr>',
|
||||
'<th colspan="2"></th>',
|
||||
'<th>Tipo</th>',
|
||||
'<th>Línea</th>',
|
||||
'<th>#</th>',
|
||||
'<th></th>',
|
||||
'</tr>',
|
||||
'</thead>',
|
||||
'<tbody></tbody>'
|
||||
].join("\n")
|
||||
parent.appendChild(this.table)
|
||||
}
|
||||
static fromProjects(data) {
|
||||
const table = new ConnectionTable('projects_table')
|
||||
data.forEach(project => {
|
||||
const row = document.createElement('tr')
|
||||
row.innerHTML = [
|
||||
`<td>${project.descripcion}</td>`,
|
||||
'<td>Todos los Operadores</td>',
|
||||
'<td colspan="3">Todas las Unidades</td>',
|
||||
`<td class="right aligned">`,
|
||||
`<button class="ui red icon button remove_button project" data-id="${project.id}">`,
|
||||
'<i class="plus icon"></i>',
|
||||
'</button>',
|
||||
`</td>`
|
||||
].join("\n")
|
||||
table.table.querySelector('tbody').appendChild(row)
|
||||
})
|
||||
document.querySelectorAll('.remove_button.project').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
const project_id = button.dataset.id
|
||||
promotion.remove().project(project_id)
|
||||
})
|
||||
})
|
||||
}
|
||||
static fromBrokers(data) {
|
||||
const table = new ConnectionTable('brokers_table')
|
||||
data.forEach(broker => {
|
||||
const row = document.createElement('tr')
|
||||
row.innerHTML = [
|
||||
`<td>Todos los Proyectos</td>`,
|
||||
`<td>${broker.name}</td>`,
|
||||
'<td colspan="3">Todas las Unidades</td>',
|
||||
`<td class="right aligned">`,
|
||||
`<button class="ui red icon button remove_button broker" data-id="${broker.rut}">`,
|
||||
'<i class="plus icon"></i>',
|
||||
'</button>',
|
||||
`</td>`
|
||||
].join("\n")
|
||||
table.table.querySelector('tbody').appendChild(row)
|
||||
})
|
||||
document.querySelectorAll('.remove_button.broker').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
const broker_rut = button.dataset.id
|
||||
promotion.remove().broker(broker_rut)
|
||||
})
|
||||
})
|
||||
}
|
||||
static fromUnitTypes(data) {
|
||||
const table = new ConnectionTable('unit-types_table')
|
||||
data.forEach(unitType => {
|
||||
const row = document.createElement('tr')
|
||||
const tipo = unitType.unitType.descripcion
|
||||
row.innerHTML = [
|
||||
`<td>${unitType.project.descripcion}</td>`,
|
||||
'<td>Todos los Operadores</td>',
|
||||
`<td colspan="3">Todos l@s ${tipo.charAt(0).toUpperCase() + tipo.slice(1)}s</td>`,
|
||||
`<td class="right aligned">`,
|
||||
`<button class="ui red icon button remove_button unit-type" data-project="${unitType.project.id}" data-id="${unitType.unitType.id}">`,
|
||||
'<i class="plus icon"></i>',
|
||||
'</button>',
|
||||
`</td>`
|
||||
].join("\n")
|
||||
table.table.querySelector('tbody').appendChild(row)
|
||||
})
|
||||
document.querySelectorAll('.remove_button.unit-type').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
const project_id = button.dataset.project
|
||||
const unit_type_id = button.dataset.id
|
||||
promotion.remove().unitType(project_id, unit_type_id)
|
||||
})
|
||||
})
|
||||
}
|
||||
static fromUnitLines(data) {
|
||||
const table = new ConnectionTable('unit-lines_table')
|
||||
data.forEach(unitLine => {
|
||||
const row = document.createElement('tr')
|
||||
const tipo = unitLine.tipo_unidad.descripcion
|
||||
row.innerHTML = [
|
||||
`<td>${unitLine.proyecto.descripcion}</td>`,
|
||||
'<td>Todos los Operadores</td>',
|
||||
`<td>${tipo.charAt(0).toUpperCase() + tipo.slice(1)}</td>`,
|
||||
`<td colspan="2">Todas las unidades de la línea ${unitLine.nombre} - ${unitLine.tipologia}</td>`,
|
||||
`<td class="right aligned">`,
|
||||
`<button class="ui red icon button remove_button unit-line" data-id="${unitLine.id}">`,
|
||||
'<i class="plus icon"></i>',
|
||||
'</button>',
|
||||
`</td>`
|
||||
].join("\n")
|
||||
table.table.querySelector('tbody').appendChild(row)
|
||||
})
|
||||
document.querySelectorAll('.remove_button.unit-line').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
const unit_line_id = button.dataset.id
|
||||
promotion.remove().unitLine(unit_line_id)
|
||||
})
|
||||
})
|
||||
}
|
||||
static fromUnits(data) {
|
||||
const table = new ConnectionTable('units_table')
|
||||
data.forEach(unit => {
|
||||
const row = document.createElement('tr')
|
||||
const tipo = unit.proyecto_tipo_unidad.tipo_unidad.descripcion
|
||||
row.innerHTML = [
|
||||
`<td>${unit.proyecto_tipo_unidad.proyecto.descripcion}</td>`,
|
||||
`<td>Todos los Operadores</td>`,
|
||||
`<td>${tipo.charAt(0).toUpperCase() + tipo.slice(1)}</td>`,
|
||||
`<td>${unit.proyecto_tipo_unidad.nombre} - ${unit.proyecto_tipo_unidad.tipologia}</td>`,
|
||||
`<td>${unit.descripcion}</td>`,
|
||||
`<td class="right aligned">`,
|
||||
`<button class="ui red icon button remove_button unit" data-id="${unit.id}">`,
|
||||
'<i class="plus icon"></i>',
|
||||
'</button>',
|
||||
`</td>`
|
||||
].join("\n")
|
||||
table.table.querySelector('tbody').appendChild(row)
|
||||
})
|
||||
document.querySelectorAll('.remove_button.unit').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
const unit_id = button.dataset.id
|
||||
promotion.remove().unit(unit_id)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
const promotion = {
|
||||
ids: {
|
||||
table: '',
|
||||
button: {
|
||||
add: ''
|
||||
}
|
||||
},
|
||||
handlers: {
|
||||
add: null
|
||||
},
|
||||
watch() {
|
||||
return {
|
||||
add: () => {
|
||||
document.getElementById(promotion.ids.button.add).addEventListener('click', clickEvent => {
|
||||
clickEvent.preventDefault()
|
||||
promotion.handlers.add.show()
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
remove() {
|
||||
return {
|
||||
project: project_id => {
|
||||
const url = `{{$urls->api}}/ventas/promotion/{{ $promotion->id }}/connections/project/${project_id}`
|
||||
const method = 'delete'
|
||||
return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
|
||||
if (json.success) {
|
||||
window.location.reload()
|
||||
}
|
||||
})
|
||||
},
|
||||
broker: broker_rut => {
|
||||
const url = `{{$urls->api}}/ventas/promotion/{{ $promotion->id }}/connections/broker/${broker_rut}`
|
||||
const method = 'delete'
|
||||
return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
|
||||
if (json.success) {
|
||||
window.location.reload()
|
||||
}
|
||||
})
|
||||
},
|
||||
unitType: (project_id, unit_type_id) => {
|
||||
const url = `{{$urls->api}}/ventas/promotion/{{ $promotion->id }}/connections/unit-type/${project_id}/${unit_type_id}`
|
||||
const method = 'delete'
|
||||
return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
|
||||
if (json.success) {
|
||||
window.location.reload()
|
||||
}
|
||||
})
|
||||
},
|
||||
unitLine: unit_line_id => {
|
||||
const url = `{{$urls->api}}/ventas/promotion/{{ $promotion->id }}/connections/unit-line/${unit_line_id}`
|
||||
const method = 'delete'
|
||||
return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
|
||||
if (json.success) {
|
||||
window.location.reload()
|
||||
}
|
||||
})
|
||||
},
|
||||
unit: unit_id => {
|
||||
const url = `{{$urls->api}}/ventas/promotion/{{ $promotion->id }}/connections/unit/${unit_id}`
|
||||
const method = 'delete'
|
||||
return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
|
||||
if (json.success) {
|
||||
window.location.reload()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
execute() {},
|
||||
setup(ids) {
|
||||
this.ids = ids
|
||||
|
||||
this.handlers.add = new AddModal()
|
||||
$(`#${this.ids.menu} .item`).tab()
|
||||
|
||||
this.watch().add()
|
||||
|
||||
@if (count($promotion->projects()) > 0)
|
||||
ConnectionTable.fromProjects({!! json_encode($promotion->projects()) !!})
|
||||
@else
|
||||
ConnectionTable.fromProjects([])
|
||||
@endif
|
||||
@if (count($promotion->brokers()) > 0)
|
||||
ConnectionTable.fromBrokers({!! json_encode($promotion->brokers()) !!})
|
||||
@else
|
||||
ConnectionTable.fromBrokers([])
|
||||
@endif
|
||||
@if (count($promotion->unitTypes()) > 0)
|
||||
ConnectionTable.fromUnitTypes({!! json_encode($promotion->unitTypes()) !!})
|
||||
@else
|
||||
ConnectionTable.fromUnitTypes([])
|
||||
@endif
|
||||
@if (count($promotion->unitLines()) > 0)
|
||||
ConnectionTable.fromUnitLines({!! json_encode($promotion->unitLines()) !!})
|
||||
@else
|
||||
ConnectionTable.fromUnitLines([])
|
||||
@endif
|
||||
@if (count($promotion->units()) > 0)
|
||||
ConnectionTable.fromUnits({!! json_encode($promotion->units()) !!})
|
||||
@else
|
||||
ConnectionTable.fromUnits([])
|
||||
@endif
|
||||
}
|
||||
}
|
||||
$(document).ready(() => {
|
||||
promotion.setup({
|
||||
menu: 'tables_tab_menu',
|
||||
table: 'connections',
|
||||
button: {
|
||||
add: 'add_button'
|
||||
}
|
||||
})
|
||||
})
|
||||
</script>
|
||||
@endpush
|
288
app/resources/views/ventas/promotions/show/add_modal.blade.php
Normal file
288
app/resources/views/ventas/promotions/show/add_modal.blade.php
Normal file
@ -0,0 +1,288 @@
|
||||
<div class="ui modal" id="add_connection_modal">
|
||||
<div class="header">
|
||||
Agregar
|
||||
</div>
|
||||
<div class="content">
|
||||
<form class="ui form" id="add_connection_form">
|
||||
<input type="hidden" name="promotion_id" value="{{$promotion->id}}" />
|
||||
<div class="field" id="type">
|
||||
<label>Tipo</label>
|
||||
@foreach (['Proyecto' => 'project', 'Operador' => 'broker', 'Tipo' => 'type', 'Línea' => 'line', 'Unidad' => 'unit'] as $type => $value)
|
||||
<div class="ui radio checkbox type" data-tab="{{ $value }}">
|
||||
<input type="radio" name="type" value="{{$value}}" @if ($value === 'project') checked="checked"@endif />
|
||||
<label>{{$type}}</label>
|
||||
</div>
|
||||
@endforeach
|
||||
</div>
|
||||
<div class="ui active tab segment" data-tab="project">
|
||||
<div class="field">
|
||||
<label>Proyecto</label>
|
||||
<div class="ui search multiple selection dropdown" id="project">
|
||||
<input type="hidden" name="project[]" />
|
||||
<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>
|
||||
<div class="ui tab segment" data-tab="broker">
|
||||
<div class="field">
|
||||
<label>Operador</label>
|
||||
<div class="ui search multiple selection dropdown" id="broker">
|
||||
<input type="hidden" name="broker[]" />
|
||||
<i class="dropdown icon"></i>
|
||||
<div class="default text">Operador</div>
|
||||
<div class="menu">
|
||||
@foreach ($brokers as $broker)
|
||||
<div class="item" data-value="{{$broker->rut}}">{{$broker->name}}</div>
|
||||
@endforeach
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ui tab segment" data-tab="type">
|
||||
<div class="fields">
|
||||
<div class="six wide field">
|
||||
<label>Proyecto</label>
|
||||
<div class="ui search selection dropdown" id="type_project">
|
||||
<input type="hidden" name="type_project" />
|
||||
<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="six wide field">
|
||||
<label>Tipo</label>
|
||||
<div class="ui search multiple selection dropdown" id="unit_type">
|
||||
<input type="hidden" name="unit_type[]" />
|
||||
<i class="dropdown icon"></i>
|
||||
<div class="default text">Tipo</div>
|
||||
<div class="menu"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ui tab segment" data-tab="line">
|
||||
<div class="fields">
|
||||
<div class="six wide field">
|
||||
<label>Proyecto</label>
|
||||
<div class="ui search selection dropdown" id="line_project">
|
||||
<input type="hidden" name="line_project" />
|
||||
<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="six wide field">
|
||||
<label>Línea</label>
|
||||
<div class="ui search multiple selection dropdown" id="line">
|
||||
<input type="hidden" name="line[]" />
|
||||
<i class="dropdown icon"></i>
|
||||
<div class="default text">Línea</div>
|
||||
<div class="menu"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ui tab segment" data-tab="unit">
|
||||
<div class="fields">
|
||||
<div class="six wide field">
|
||||
<label>Proyecto</label>
|
||||
<div class="ui search selection dropdown" id="unit_project">
|
||||
<input type="hidden" name="unit_project" />
|
||||
<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="six wide field">
|
||||
<label>Unidad</label>
|
||||
<div class="ui search multiple selection dropdown" id="unit">
|
||||
<input type="hidden" name="unit[]" />
|
||||
<i class="dropdown icon"></i>
|
||||
<div class="default text">Unidad</div>
|
||||
<div class="menu"></div>
|
||||
</div>
|
||||
</div>
|
||||
</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 AddModal {
|
||||
ids
|
||||
modal
|
||||
units = []
|
||||
constructor() {
|
||||
this.ids = {
|
||||
form: 'add_connection_form',
|
||||
modal: 'add_connection_modal',
|
||||
radios: '#type .ui.radio.checkbox.type',
|
||||
type_project: 'type_project',
|
||||
unit_type: 'unit_type',
|
||||
line_project: 'line_project',
|
||||
line: 'line',
|
||||
unit_project: 'unit_project',
|
||||
unit: 'unit',
|
||||
broker: 'broker'
|
||||
}
|
||||
this.modal = $(`#${this.ids.modal}`).modal({
|
||||
onApprove: () => {
|
||||
const form = document.getElementById(this.ids.form)
|
||||
const body = new FormData(form)
|
||||
const url = `{{$urls->api}}/ventas/promotion/{{$promotion->id}}/connections/add`
|
||||
const method = 'post'
|
||||
return APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
|
||||
if (json.success) {
|
||||
window.location.reload()
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
$(`#${this.ids.form} ${this.ids.radios}`).checkbox({
|
||||
fireOnInit: true,
|
||||
onChecked: () => {
|
||||
$(`#${this.ids.form} ${this.ids.radios}`).each((index, radio) => {
|
||||
if ($(radio).checkbox('is checked')) {
|
||||
const tab = radio.dataset.tab
|
||||
$.tab('change tab', tab)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
$('.ui.dropdown').dropdown()
|
||||
|
||||
const typeProject = $(`#${this.ids.type_project}`)
|
||||
typeProject.dropdown('clear', false)
|
||||
typeProject.dropdown({
|
||||
onChange: (value, text, $choice) => {
|
||||
this.draw().types(value)
|
||||
}
|
||||
})
|
||||
const lineProject = $(`#${this.ids.line_project}`)
|
||||
lineProject.dropdown('clear', false)
|
||||
lineProject.dropdown({
|
||||
onChange: (value, text, $choice) => {
|
||||
this.draw().lines(value)
|
||||
}
|
||||
})
|
||||
const unitProject = $(`#${this.ids.unit_project}`)
|
||||
unitProject.dropdown('clear', false)
|
||||
unitProject.dropdown({
|
||||
onChange: (value, text, $choice) => {
|
||||
this.draw().units(value)
|
||||
}
|
||||
})
|
||||
}
|
||||
show() {
|
||||
this.modal.modal('show')
|
||||
}
|
||||
draw() {
|
||||
return {
|
||||
types: project_id => {
|
||||
this.load().units(project_id).then(() => {
|
||||
const values = []
|
||||
this.units[project_id].forEach(unit => {
|
||||
const tipo = unit.proyecto_tipo_unidad.tipo_unidad
|
||||
if (values.find(value => value.value === tipo.id)) return
|
||||
const label = `${tipo.descripcion.charAt(0).toUpperCase() + tipo.descripcion.slice(1)}`
|
||||
values.push( {
|
||||
value: tipo.id,
|
||||
text: label,
|
||||
name: label
|
||||
} )
|
||||
})
|
||||
$(`#${this.ids.unit_type}`).dropdown('change values', values)
|
||||
})
|
||||
},
|
||||
lines: project_id => {
|
||||
this.load().units(project_id).then(() => {
|
||||
const values = []
|
||||
this.units[project_id].forEach(unit => {
|
||||
const tipo = unit.proyecto_tipo_unidad.tipo_unidad
|
||||
const linea = unit.proyecto_tipo_unidad
|
||||
if (values.find(value => value.value === linea.id)) return
|
||||
let name = linea.nombre
|
||||
if (!linea.nombre.includes(tipo.descripcion.charAt(0).toUpperCase() + tipo.descripcion.slice(1))) {
|
||||
name = `${tipo.descripcion.charAt(0).toUpperCase() + tipo.descripcion.slice(1)} ${name}`
|
||||
}
|
||||
const label = `${name} - ${linea.tipologia}`
|
||||
values.push( {
|
||||
value: linea.id,
|
||||
text: label,
|
||||
name: label
|
||||
} )
|
||||
})
|
||||
$(`#${this.ids.line}`).dropdown('change values', values)
|
||||
})
|
||||
},
|
||||
units: project_id => {
|
||||
this.load().units(project_id).then(() => {
|
||||
const values = this.units[project_id].map(unit => {
|
||||
const tipo = unit.proyecto_tipo_unidad.tipo_unidad.descripcion
|
||||
const label = `${tipo.charAt(0).toUpperCase() + tipo.slice(1)} - ${unit.descripcion}`
|
||||
return {
|
||||
value: unit.id,
|
||||
text: label,
|
||||
name: label
|
||||
}
|
||||
})
|
||||
$(`#${this.ids.unit}`).dropdown('change values', values)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
load() {
|
||||
return {
|
||||
units: project_id => {
|
||||
if (typeof this.units[project_id] !== 'undefined' && this.units[project_id].length > 0) {
|
||||
return new Promise( resolve => resolve(this.units[project_id]) )
|
||||
}
|
||||
const url = `{{ $urls->api }}/proyecto/${project_id}/unidades`
|
||||
return APIClient.fetch(url).then(response => response.json()).then(json => {
|
||||
if (json.unidades.length === 0) {
|
||||
throw new Error('No se encontraron unidades')
|
||||
}
|
||||
const units = []
|
||||
Object.values(json.unidades).forEach(unidades => {
|
||||
unidades.forEach(unit => {
|
||||
units.push(unit)
|
||||
})
|
||||
})
|
||||
this.units[project_id] = units
|
||||
return units
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@endpush
|
@ -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>{{ $format->percent($pie->valor / $venta->valor, 2, true) }}</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>
|
||||
@if ($pie !== null)
|
||||
<td>{{ $format->percent($pie->valor / $venta->valor, 2, true) }}</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">
|
||||
<i class="plus icon"></i>
|
||||
</a>
|
||||
@endif
|
||||
</td>
|
||||
@else
|
||||
<td colspan="4"></td>
|
||||
@endif
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Pagado</td>
|
||||
<td>{{$format->percent($pie->pagado() / $venta->valor, 2, true)}}</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
|
||||
@if ($pie !== null)
|
||||
<tr>
|
||||
<td>Pagado</td>
|
||||
<td>{{$format->percent($pie->pagado() / $venta->valor, 2, true)}}</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
|
||||
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
106
app/src/Controller/API/Proyectos/Brokers.php
Normal file
106
app/src/Controller/API/Proyectos/Brokers.php
Normal 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);
|
||||
}
|
||||
}
|
178
app/src/Controller/API/Proyectos/Brokers/Contracts.php
Normal file
178
app/src/Controller/API/Proyectos/Brokers/Contracts.php
Normal file
@ -0,0 +1,178 @@
|
||||
<?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;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
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,
|
||||
LoggerInterface $logger,
|
||||
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);
|
||||
}
|
||||
try {
|
||||
$output['unidades'] = $promotionRepository->fetchByContractAndUnits($contract_id, $unit_ids);
|
||||
} catch (Implement\Exception\EmptyResult $exception) {
|
||||
$logger->debug($exception);
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
62
app/src/Controller/API/Proyectos/Unidades.php
Normal file
62
app/src/Controller/API/Proyectos/Unidades.php
Normal file
@ -0,0 +1,62 @@
|
||||
<?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);
|
||||
$output['precios'] = $precioRepository->fetchVigentesByUnidades($unidad_ids);
|
||||
} 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);
|
||||
$output['estados'] = $unidadRepository->fetchSoldByUnidades($unidad_ids);
|
||||
} catch (Implement\Exception\EmptyResult) {}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
@ -9,6 +9,7 @@ use Incoviba\Common\Ideal\Controller;
|
||||
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;
|
||||
@ -368,4 +369,17 @@ class Ventas extends Controller
|
||||
} catch (EmptyResult) {}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function byUnidades(ServerRequestInterface $request, ResponseInterface $response,
|
||||
Service\Venta $ventaService, Service\Venta\Unidad $unidadService): ResponseInterface
|
||||
{
|
||||
$input = $request->getParsedBody();
|
||||
$output = [
|
||||
'input' => $input,
|
||||
'ventas' => []
|
||||
];
|
||||
try {
|
||||
$output['ventas'] = $ventaService->getActiveByUnidadIds($input['unidad_ids']);
|
||||
} catch (Read) {}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
287
app/src/Controller/API/Ventas/Promotions.php
Normal file
287
app/src/Controller/API/Ventas/Promotions.php
Normal file
@ -0,0 +1,287 @@
|
||||
<?php
|
||||
namespace Incoviba\Controller\API\Ventas;
|
||||
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
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);
|
||||
}
|
||||
public function addConnections(ServerRequestInterface $request, ResponseInterface $response,
|
||||
LoggerInterface $logger,
|
||||
Service\Venta\Promotion $promotionService, int $promotion_id): ResponseInterface
|
||||
{
|
||||
$input = $request->getParsedBody();
|
||||
$output = [
|
||||
'promotion_id' => $promotion_id,
|
||||
'input' => $input,
|
||||
'connections' => [],
|
||||
'success' => false,
|
||||
'partial' => false
|
||||
];
|
||||
$total = 0;
|
||||
if (count($input['project']) > 0 and $input['project'][0] !== '') {
|
||||
$project_ids = array_filter($input['project'], function($project_id) { return $project_id !== ''; });
|
||||
$total += count($project_ids);
|
||||
foreach ($project_ids as $project_id) {
|
||||
try {
|
||||
$promotionService->addProject($promotion_id, $project_id);
|
||||
$output['connections'] []= [
|
||||
'project_id' => $project_id,
|
||||
'success' => true,
|
||||
];
|
||||
$output['partial'] = true;
|
||||
} catch (ServiceAction\Create $exception) {
|
||||
$logger->error($exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (count($input['broker']) > 0 and $input['broker'][0] !== '') {
|
||||
$broker_ruts = array_filter($input['broker'], function($broker_rut) { return $broker_rut !== ''; });
|
||||
$total += count($broker_ruts);
|
||||
foreach ($broker_ruts as $broker_rut) {
|
||||
try {
|
||||
$promotionService->addBroker($promotion_id, $broker_rut);
|
||||
$output['connections'] []= [
|
||||
'broker_rut' => $broker_rut,
|
||||
'success' => true,
|
||||
];
|
||||
$output['partial'] = true;
|
||||
} catch (ServiceAction\Create $exception) {
|
||||
$logger->error($exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (count($input['unit_type']) > 0 and $input['unit_type'][0] !== '') {
|
||||
$unit_type_ids = array_filter($input['unit_type'], function($unit_type_id) { return $unit_type_id !== ''; });
|
||||
$total += count($unit_type_ids);
|
||||
foreach ($unit_type_ids as $unit_type_id) {
|
||||
try {
|
||||
$promotionService->addUnitType($promotion_id, $input['type_project'], $unit_type_id);
|
||||
$output['connections'] []= [
|
||||
'unit_type_id' => $unit_type_id,
|
||||
'success' => true,
|
||||
];
|
||||
$output['partial'] = true;
|
||||
} catch (ServiceAction\Create $exception) {
|
||||
$logger->error($exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (count($input['line']) > 0 and $input['line'][0] !== '') {
|
||||
$line_ids = array_filter($input['line'], function($line_id) { return $line_id !== ''; });
|
||||
$total += count($line_ids);
|
||||
foreach ($line_ids as $line_id) {
|
||||
try {
|
||||
$promotionService->addUnitLine($promotion_id, $line_id);
|
||||
$output['connections'] []= [
|
||||
'line_id' => $line_id,
|
||||
'success' => true,
|
||||
];
|
||||
$output['partial'] = true;
|
||||
} catch (ServiceAction\Create $exception) {
|
||||
$logger->error($exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (count($input['unit']) > 0 and $input['unit'][0] !== '') {
|
||||
$unit_ids = array_filter($input['unit'], function($unit_id) { return $unit_id !== ''; });
|
||||
$total += count($unit_ids);
|
||||
foreach ($unit_ids as $unit_id) {
|
||||
try {
|
||||
$promotionService->addUnit($promotion_id, $unit_id);
|
||||
$output['connections'] []= [
|
||||
'unit_id' => $unit_id,
|
||||
'success' => true,
|
||||
];
|
||||
$output['partial'] = true;
|
||||
} catch (ServiceAction\Create $exception) {
|
||||
$logger->error($exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (count($output['connections']) === $total) {
|
||||
$output['success'] = true;
|
||||
}
|
||||
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function removeProject(ServerRequestInterface $request, ResponseInterface $response,
|
||||
Service\Venta\Promotion $promotionService,
|
||||
int $promotion_id, int $project_id): ResponseInterface
|
||||
{
|
||||
$output = [
|
||||
'promotion_id' => $promotion_id,
|
||||
'project_id' => $project_id,
|
||||
'success' => false,
|
||||
];
|
||||
try {
|
||||
$promotionService->removeProject($promotion_id, $project_id);
|
||||
$output['success'] = true;
|
||||
} catch (ServiceAction\Delete $exception) {
|
||||
return $this->withError($response, $exception);
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function removeBroker(ServerRequestInterface $request, ResponseInterface $response,
|
||||
Service\Venta\Promotion $promotionService,
|
||||
int $promotion_id, string $broker_rut): ResponseInterface
|
||||
{
|
||||
$output = [
|
||||
'promotion_id' => $promotion_id,
|
||||
'broker_rut' => $broker_rut,
|
||||
'success' => false,
|
||||
];
|
||||
try {
|
||||
$promotionService->removeBroker($promotion_id, $broker_rut);
|
||||
$output['success'] = true;
|
||||
} catch (ServiceAction\Delete $exception) {
|
||||
return $this->withError($response, $exception);
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function removeUnitType(ServerRequestInterface $request, ResponseInterface $response,
|
||||
Service\Venta\Promotion $promotionService,
|
||||
int $promotion_id, int $project_id, int $unit_type_id): ResponseInterface
|
||||
{
|
||||
$output = [
|
||||
'promotion_id' => $promotion_id,
|
||||
'project_id' => $project_id,
|
||||
'unit_type_id' => $unit_type_id,
|
||||
'success' => false,
|
||||
];
|
||||
try {
|
||||
$promotionService->removeUnitType($promotion_id, $project_id, $unit_type_id);
|
||||
$output['success'] = true;
|
||||
} catch (ServiceAction\Delete $exception) {
|
||||
return $this->withError($response, $exception);
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function removeUnitLine(ServerRequestInterface $request, ResponseInterface $response,
|
||||
Service\Venta\Promotion $promotionService,
|
||||
int $promotion_id, int $unit_line_id): ResponseInterface
|
||||
{
|
||||
$output = [
|
||||
'promotion_id' => $promotion_id,
|
||||
'unit_line_id' => $unit_line_id,
|
||||
'success' => false,
|
||||
];
|
||||
try {
|
||||
$promotionService->removeUnitLine($promotion_id, $unit_line_id);
|
||||
$output['success'] = true;
|
||||
} catch (ServiceAction\Delete $exception) {
|
||||
return $this->withError($response, $exception);
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function removeUnit(ServerRequestInterface $request, ResponseInterface $response,
|
||||
Service\Venta\Promotion $promotionService,
|
||||
int $promotion_id, int $unit_id): ResponseInterface
|
||||
{
|
||||
$output = [
|
||||
'promotion_id' => $promotion_id,
|
||||
'unit_id' => $unit_id,
|
||||
'success' => false,
|
||||
];
|
||||
try {
|
||||
$promotionService->removeUnit($promotion_id, $unit_id);
|
||||
$output['success'] = true;
|
||||
} catch (ServiceAction\Delete $exception) {
|
||||
return $this->withError($response, $exception);
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
@ -4,9 +4,11 @@ namespace Incoviba\Controller\API\Ventas;
|
||||
use PDOException;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Controller\API\{withJson, emptyBody};
|
||||
use Incoviba\Controller\withRedis;
|
||||
use Incoviba\Common\Implement\Exception\{EmptyResult,EmptyRedis};
|
||||
use Incoviba\Exception\ServiceAction\{Read, Create, Update};
|
||||
use Incoviba\Repository;
|
||||
use Incoviba\Service;
|
||||
|
||||
@ -14,7 +16,9 @@ class PropiedadesUnidades
|
||||
{
|
||||
use emptyBody, withJson, withRedis;
|
||||
|
||||
public function add(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\PropiedadUnidad $propiedadUnidadService): ResponseInterface
|
||||
public function add(ServerRequestInterface $request, ResponseInterface $response,
|
||||
LoggerInterface $logger,
|
||||
Service\Venta\PropiedadUnidad $propiedadUnidadService): ResponseInterface
|
||||
{
|
||||
$body = $request->getParsedBody();
|
||||
$output = [
|
||||
@ -26,8 +30,8 @@ class PropiedadesUnidades
|
||||
$pu = $propiedadUnidadService->add($body);
|
||||
$output['propiedad_unidad'] = $pu;
|
||||
$output['added'] = true;
|
||||
} catch (EmptyResult $exception) {
|
||||
error_log($exception);
|
||||
} catch (Read | Create $exception) {
|
||||
$logger->notice($exception);
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
@ -44,7 +48,7 @@ class PropiedadesUnidades
|
||||
$pu = $propiedadUnidadService->getById($pu_id);
|
||||
$propiedadUnidadService->edit($pu, (array) $body);
|
||||
$output['edited'] = true;
|
||||
} catch (PDOException | EmptyResult) {}
|
||||
} catch (PDOException | Read | EmptyResult | Update) {}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function remove(ServerRequestInterface $request, ResponseInterface $response,
|
||||
@ -58,7 +62,7 @@ class PropiedadesUnidades
|
||||
$pu = $propiedadUnidadRepository->fetchById($pu_id);
|
||||
$propiedadUnidadRepository->remove($pu);
|
||||
$output['removed'] = true;
|
||||
} catch (EmptyResult) {}
|
||||
} catch (PDOException | EmptyResult) {}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
||||
|
103
app/src/Controller/API/Ventas/Reservations.php
Normal file
103
app/src/Controller/API/Ventas/Reservations.php
Normal 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);
|
||||
}
|
||||
}
|
46
app/src/Controller/Proyectos/Brokers.php
Normal file
46
app/src/Controller/Proyectos/Brokers.php
Normal 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'));
|
||||
}
|
||||
}
|
24
app/src/Controller/Proyectos/Brokers/Contracts.php
Normal file
24
app/src/Controller/Proyectos/Brokers/Contracts.php
Normal 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'));
|
||||
}
|
||||
}
|
@ -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'));
|
||||
}
|
||||
}
|
||||
|
34
app/src/Controller/Ventas/Promotions.php
Normal file
34
app/src/Controller/Ventas/Promotions.php
Normal file
@ -0,0 +1,34 @@
|
||||
<?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, Service\Proyecto $proyectoService,
|
||||
Service\Proyecto\Broker $brokerService,
|
||||
int $promotion_id): ResponseInterface
|
||||
{
|
||||
$promotion = null;
|
||||
try {
|
||||
$promotion = $promotionService->getById($promotion_id);
|
||||
} catch (ServiceAction\Read) {}
|
||||
$projects = $proyectoService->getVendibles('descripcion');
|
||||
$brokers = $brokerService->getAll('name');
|
||||
return $view->render($response, 'ventas.promotions.show', ['promotion' => $promotion,
|
||||
'projects' => $projects, 'brokers' => $brokers]);
|
||||
}
|
||||
}
|
22
app/src/Exception/AggregateException.php
Normal file
22
app/src/Exception/AggregateException.php
Normal file
@ -0,0 +1,22 @@
|
||||
<?php
|
||||
namespace Incoviba\Exception;
|
||||
|
||||
use Exception;
|
||||
use Throwable;
|
||||
|
||||
class AggregateException extends Exception
|
||||
{
|
||||
public function __construct(array $exceptions, ?Throwable $previous = null)
|
||||
{
|
||||
$code = count($exceptions);
|
||||
$temp_arr = array_reverse($exceptions);
|
||||
$current = array_shift($temp_arr);
|
||||
$current->previous = $previous;
|
||||
foreach ($temp_arr as $exception) {
|
||||
$exception->previous = $current;
|
||||
$current = $exception;
|
||||
}
|
||||
$message = "Aggregate Exception";
|
||||
parent::__construct($message, $code, $current);
|
||||
}
|
||||
}
|
45
app/src/Model/Proyecto/Broker.php
Normal file
45
app/src/Model/Proyecto/Broker.php
Normal 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()
|
||||
];
|
||||
}
|
||||
}
|
24
app/src/Model/Proyecto/Broker/Contact.php
Normal file
24
app/src/Model/Proyecto/Broker/Contact.php
Normal 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
|
||||
];
|
||||
}
|
||||
}
|
54
app/src/Model/Proyecto/Broker/Contract.php
Normal file
54
app/src/Model/Proyecto/Broker/Contract.php
Normal 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(),
|
||||
];
|
||||
}
|
||||
}
|
25
app/src/Model/Proyecto/Broker/Contract/State.php
Normal file
25
app/src/Model/Proyecto/Broker/Contract/State.php
Normal 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
|
||||
]
|
||||
];
|
||||
}
|
||||
}
|
17
app/src/Model/Proyecto/Broker/Contract/State/Type.php
Normal file
17
app/src/Model/Proyecto/Broker/Contract/State/Type.php
Normal 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')
|
||||
};
|
||||
}
|
||||
}
|
21
app/src/Model/Proyecto/Broker/Data.php
Normal file
21
app/src/Model/Proyecto/Broker/Data.php
Normal 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
|
||||
];
|
||||
}
|
||||
}
|
@ -43,6 +43,15 @@ class ProyectoTipoUnidad extends Ideal\Model
|
||||
return $this->abreviacion;
|
||||
}
|
||||
|
||||
protected array $unidades;
|
||||
public function unidades(): array
|
||||
{
|
||||
if (!isset($this->unidades)) {
|
||||
$this->unidades = $this->runFactory('unidades');
|
||||
}
|
||||
return $this->unidades;
|
||||
}
|
||||
|
||||
public function jsonSerialize(): mixed
|
||||
{
|
||||
return array_merge(parent::jsonSerialize(), [
|
||||
|
87
app/src/Model/Venta/Promotion.php
Normal file
87
app/src/Model/Venta/Promotion.php
Normal file
@ -0,0 +1,87 @@
|
||||
<?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 $brokers;
|
||||
public function brokers(): array
|
||||
{
|
||||
if (empty($this->brokers)) {
|
||||
$this->brokers = $this->runFactory('brokers') ?? [];
|
||||
}
|
||||
return $this->brokers;
|
||||
}
|
||||
|
||||
protected array $unitTypes;
|
||||
public function unitTypes(): array
|
||||
{
|
||||
if (empty($this->unitTypes)) {
|
||||
$this->unitTypes = $this->runFactory('unitTypes') ?? [];
|
||||
}
|
||||
return $this->unitTypes;
|
||||
}
|
||||
protected array $unitLines;
|
||||
public function unitLines(): array
|
||||
{
|
||||
if (empty($this->unitLines)) {
|
||||
$this->unitLines = $this->runFactory('unitLines') ?? [];
|
||||
}
|
||||
return $this->unitLines;
|
||||
}
|
||||
|
||||
protected array $units;
|
||||
public function units(): array
|
||||
{
|
||||
if (empty($this->units)) {
|
||||
$this->units = $this->runFactory('units') ?? [];
|
||||
}
|
||||
return $this->units;
|
||||
}
|
||||
|
||||
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->brokers() ?? [],
|
||||
'units' => $this->units() ?? []
|
||||
];
|
||||
}
|
||||
}
|
17
app/src/Model/Venta/Promotion/State.php
Normal file
17
app/src/Model/Venta/Promotion/State.php
Normal 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')
|
||||
};
|
||||
}
|
||||
}
|
16
app/src/Model/Venta/Promotion/Type.php
Normal file
16
app/src/Model/Venta/Promotion/Type.php
Normal 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'
|
||||
};
|
||||
}
|
||||
}
|
83
app/src/Model/Venta/Reservation.php
Normal file
83
app/src/Model/Venta/Reservation.php
Normal 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,
|
||||
];
|
||||
}
|
||||
}
|
25
app/src/Model/Venta/Reservation/State.php
Normal file
25
app/src/Model/Venta/Reservation/State.php
Normal 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)
|
||||
]
|
||||
];
|
||||
}
|
||||
}
|
19
app/src/Model/Venta/Reservation/State/Type.php
Normal file
19
app/src/Model/Venta/Reservation/State/Type.php
Normal 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')
|
||||
};
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
@ -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()
|
||||
|
@ -94,7 +94,7 @@ class Proyecto extends Ideal\Repository
|
||||
->where("a.descripcion LIKE ?");
|
||||
return $this->fetchOne($query, ["%{$name}%"]);
|
||||
}
|
||||
public function fetchAllActive(): array
|
||||
public function fetchAllActive(null|string|array $orderBy = null): array
|
||||
{
|
||||
$etapaProyecto = $this->etapaRepository->fetchByDescripcion('Proyecto');
|
||||
$etapaTerminado = $this->etapaRepository->fetchByDescripcion('Terminado');
|
||||
@ -103,8 +103,12 @@ class Proyecto extends Ideal\Repository
|
||||
->from("{$this->getTable()} a")
|
||||
->joined($this->joinTerreno())
|
||||
->joined($this->joinEstado())
|
||||
->where("et.orden BETWEEN {$etapaProyecto->orden} AND ({$etapaTerminado->orden} - 1)")
|
||||
->order('a.descripcion');
|
||||
->where("et.orden BETWEEN {$etapaProyecto->orden} AND ({$etapaTerminado->orden} - 1)");
|
||||
if ($orderBy === null) {
|
||||
$query = $query->order('a.descripcion');
|
||||
} else {
|
||||
$query = $query->order($orderBy);
|
||||
}
|
||||
return $this->fetchMany($query);
|
||||
}
|
||||
public function fetchAllEscriturando(): array
|
||||
@ -164,6 +168,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
|
||||
{
|
||||
|
||||
|
78
app/src/Repository/Proyecto/Broker.php
Normal file
78
app/src/Repository/Proyecto/Broker.php
Normal file
@ -0,0 +1,78 @@
|
||||
<?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]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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_brokers pb ON pb.broker_rut = a.rut')
|
||||
->where('pb.promotion_id = :promotion_id');
|
||||
return $this->fetchMany($query, ['promotion_id' => $promotion_id]);
|
||||
}
|
||||
}
|
60
app/src/Repository/Proyecto/Broker/Contact.php
Normal file
60
app/src/Repository/Proyecto/Broker/Contact.php
Normal 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]);
|
||||
}
|
||||
}
|
135
app/src/Repository/Proyecto/Broker/Contract.php
Normal file
135
app/src/Repository/Proyecto/Broker/Contract.php
Normal file
@ -0,0 +1,135 @@
|
||||
<?php
|
||||
namespace Incoviba\Repository\Proyecto\Broker;
|
||||
|
||||
use Incoviba\Common;
|
||||
use Incoviba\Repository;
|
||||
use Incoviba\Model;
|
||||
|
||||
class Contract extends Common\Ideal\Repository
|
||||
{
|
||||
public function __construct(Common\Define\Connection $connection, protected Repository\Proyecto\Broker $brokerRepository,
|
||||
protected Repository\Proyecto $proyectoRepository)
|
||||
{
|
||||
parent::__construct($connection);
|
||||
}
|
||||
|
||||
public function getTable(): string
|
||||
{
|
||||
return 'broker_contracts';
|
||||
}
|
||||
|
||||
public function create(?array $data = null): Model\Proyecto\Broker\Contract
|
||||
{
|
||||
$map = (new Common\Implement\Repository\MapperParser(['commission']))
|
||||
->register('broker_rut', (new Common\Implement\Repository\Mapper())
|
||||
->setProperty('broker')
|
||||
->setFunction(function($data) {
|
||||
return $this->brokerRepository->fetchById($data['broker_rut']);
|
||||
})
|
||||
)
|
||||
->register('project_id', (new Common\Implement\Repository\Mapper())
|
||||
->setProperty('project')
|
||||
->setFunction(function($data) {
|
||||
return $this->proyectoRepository->fetchById($data['project_id']);
|
||||
})
|
||||
);
|
||||
return $this->parseData(new Model\Proyecto\Broker\Contract(), $data, $map);
|
||||
}
|
||||
public function save(Common\Define\Model $model): Model\Proyecto\Broker\Contract
|
||||
{
|
||||
$model->id = $this->saveNew(
|
||||
['broker_rut', 'project_id', 'commission'],
|
||||
[$model->broker->rut, $model->project->id, $model->commission]);
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Common\Define\Model $model
|
||||
* @param array $new_data
|
||||
* @return Model\Proyecto\Broker\Contract
|
||||
* @throws Common\Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function edit(Common\Define\Model $model, array $new_data): Model\Proyecto\Broker\Contract
|
||||
{
|
||||
return $this->update($model, ['broker_rut', 'project_id', 'commission'], $new_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $brokerRut
|
||||
* @return array
|
||||
* @throws Common\Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchByBroker(int $brokerRut): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select()
|
||||
->from($this->getTable())
|
||||
->where('broker_rut = :broker_rut');
|
||||
return $this->fetchMany($query, ['broker_rut' => $brokerRut]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $projectId
|
||||
* @return array
|
||||
* @throws Common\Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchByProject(int $projectId): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select()
|
||||
->from($this->getTable())
|
||||
->where('project_id = :project_id');
|
||||
return $this->fetchMany($query, ['project_id' => $projectId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $brokerRut
|
||||
* @return array
|
||||
* @throws Common\Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchActiveByBroker(int $brokerRut): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined($this->statusJoin())
|
||||
->where('a.broker_rut = :broker_rut AND bcs.state = :state');
|
||||
return $this->fetchMany($query, ['broker_rut' => $brokerRut, 'state' => Model\Proyecto\Broker\Contract\Type::ACTIVE]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $projectId
|
||||
* @return array
|
||||
* @throws Common\Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchActiveByProject(int $projectId): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined($this->statusJoin())
|
||||
->where('a.proyecto_id = :proyecto_id AND bcs.state = :state');
|
||||
return $this->fetchMany($query, ['proyecto_id' => $projectId, 'state' => Model\Proyecto\Broker\Contract\State\Type::ACTIVE->value]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $projectId
|
||||
* @param int $brokerRut
|
||||
* @return Model\Proyecto\Broker\Contract
|
||||
* @throws Common\Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchActiveByProjectAndBroker(int $projectId, int $brokerRut): Model\Proyecto\Broker\Contract
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined($this->statusJoin())
|
||||
->where('a.project_id = :project_id AND a.broker_rut = :broker_rut AND bcs.type = :state');
|
||||
return $this->fetchOne($query, ['project_id' => $projectId, 'broker_rut' => $brokerRut, 'state' => Model\Proyecto\Broker\Contract\State\Type::ACTIVE->value]);
|
||||
}
|
||||
|
||||
protected function statusJoin(): string
|
||||
{
|
||||
return 'INNER JOIN (SELECT bcs1.* FROM broker_contract_states bcs1 INNER JOIN (SELECT MAX(id) AS id, contract_id FROM broker_contract_states GROUP BY contract_id) bcs0 ON bcs0.id = bcs1.id) bcs ON bcs.contract_id = a.id';
|
||||
}
|
||||
}
|
72
app/src/Repository/Proyecto/Broker/Contract/State.php
Normal file
72
app/src/Repository/Proyecto/Broker/Contract/State.php
Normal 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]);
|
||||
}
|
||||
}
|
78
app/src/Repository/Proyecto/Broker/Data.php
Normal file
78
app/src/Repository/Proyecto/Broker/Data.php
Normal 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]);
|
||||
}
|
||||
}
|
@ -43,4 +43,20 @@ class ProyectoTipoUnidad extends Ideal\Repository
|
||||
{
|
||||
return $this->update($model, ['proyecto', 'tipo', 'nombre', 'abreviacion', 'util', 'logia', 'terraza', 'descripcion'], $new_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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_unit_lines pul ON pul.unit_line_id = a.id')
|
||||
->where('pul.`promotion_id` = :promotion_id')
|
||||
->group('a.id');
|
||||
return $this->fetchMany($query, ['promotion_id' => $promotion_id]);
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,8 @@
|
||||
<?php
|
||||
namespace Incoviba\Repository\Proyecto;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Incoviba\Common\Define;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Implement;
|
||||
@ -32,6 +34,11 @@ class TipoUnidad extends Ideal\Repository
|
||||
return $this->update($model, ['descripcion', 'orden'], $new_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $proyecto_id
|
||||
* @return array
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchByProyecto(int $proyecto_id): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
@ -43,6 +50,29 @@ class TipoUnidad extends Ideal\Repository
|
||||
->order('a.orden');
|
||||
return $this->fetchMany($query, [$proyecto_id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $promotion_id
|
||||
* @return array
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchByPromotion(int $promotion_id): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('a.id, put.project_id')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined('INNER JOIN promotion_unit_types put ON put.`unit_type_id` = a.`id`')
|
||||
->where('put.`promotion_id` = :promotion_id')
|
||||
->group('a.id');
|
||||
try {
|
||||
$result = $this->connection->execute($query, ['promotion_id' => $promotion_id])->fetchAll(PDO::FETCH_ASSOC);
|
||||
if (empty($result)) {
|
||||
throw new Implement\Exception\EmptyResult($query);
|
||||
}
|
||||
return $result;
|
||||
} catch (PDOException $exception) {
|
||||
throw new Implement\Exception\EmptyResult($query, $exception);
|
||||
}
|
||||
return $this->fetchMany($query, ['promotion_id' => $promotion_id]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -296,16 +296,65 @@ class Venta extends Ideal\Repository
|
||||
* @return Model\Venta
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchByUnidadId(int $unidad_id): Model\Venta
|
||||
public function fetchActiveByUnidadId(int $unidad_id): Model\Venta
|
||||
{
|
||||
$subSubQuery = $this->connection->getQueryBuilder()
|
||||
->select('MAX(`id`) AS `id`, `venta`')
|
||||
->from('`estado_venta`')
|
||||
->group('`venta`');
|
||||
$subQuery = $this->connection->getQueryBuilder()
|
||||
->select('e1.*')
|
||||
->from('`estado_venta` e1')
|
||||
->joined("INNER JOIN ({$subSubQuery}) e0 ON e0.`id` = e1.`id`");
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined('JOIN propiedad_unidad pu ON pu.propiedad = a.propiedad')
|
||||
->where('pu.unidad = ?');
|
||||
->joined('INNER JOIN propiedad_unidad pu ON pu.propiedad = a.propiedad')
|
||||
->joined("INNER JOIN ({$subQuery}) ev ON ev.`venta` = a.`id`")
|
||||
->joined('INNER JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`')
|
||||
->where('pu.unidad = ? AND tev.activa = 1');
|
||||
return $this->fetchOne($query, [$unidad_id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $unidad_ids
|
||||
* @return array
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchActiveArrayByUnidadIds(array $unidad_ids): array
|
||||
{
|
||||
$subSubQuery = $this->connection->getQueryBuilder()
|
||||
->select('MAX(`id`) AS `id`, `venta`')
|
||||
->from('`estado_venta`')
|
||||
->group('`venta`');
|
||||
$subQuery = $this->connection->getQueryBuilder()
|
||||
->select('e1.*')
|
||||
->from('`estado_venta` e1')
|
||||
->joined("INNER JOIN ({$subSubQuery}) e0 ON e0.`id` = e1.`id`");
|
||||
$interrogations = implode(',', array_fill(0, count($unidad_ids), '?'));
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('a.*, pu.unidad')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined('INNER JOIN propiedad_unidad pu ON pu.propiedad = a.propiedad')
|
||||
->joined("INNER JOIN ({$subQuery}) ev ON ev.`venta` = a.`id`")
|
||||
->joined('INNER JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`')
|
||||
->where("pu.unidad IN ({$interrogations}) AND tev.activa = 1");
|
||||
try {
|
||||
$results = $this->connection->execute($query, $unidad_ids)->fetchAll(PDO::FETCH_ASSOC);
|
||||
if (empty($results)) {
|
||||
throw new Implement\Exception\EmptyResult($query);
|
||||
}
|
||||
return array_map(function($result) {
|
||||
return [
|
||||
'unidad_id' => $result['unidad'],
|
||||
'venta' => $result
|
||||
];
|
||||
}, $results);
|
||||
} catch (PDOException $exception) {
|
||||
throw new Implement\Exception\EmptyResult($query, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $unidad
|
||||
* @param string $tipo
|
||||
@ -575,7 +624,11 @@ class Venta extends Ideal\Repository
|
||||
protected function fetchId(string $query, ?array $data = null): array
|
||||
{
|
||||
try {
|
||||
return $this->connection->execute($query, $data)->fetch(PDO::FETCH_ASSOC);
|
||||
$result = $this->connection->execute($query, $data)->fetch(PDO::FETCH_ASSOC);
|
||||
if ($result === false) {
|
||||
throw new Implement\Exception\EmptyResult($query);
|
||||
}
|
||||
return $result;
|
||||
} catch (PDOException $exception) {
|
||||
throw new Implement\Exception\EmptyResult($query, $exception);
|
||||
}
|
||||
|
@ -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()
|
||||
|
@ -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()
|
||||
|
@ -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()
|
||||
|
@ -1,6 +1,8 @@
|
||||
<?php
|
||||
namespace Incoviba\Repository\Venta;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Define;
|
||||
use Incoviba\Common\Implement;
|
||||
@ -51,15 +53,16 @@ class Precio extends Ideal\Repository
|
||||
*/
|
||||
public function fetchByProyecto(int $proyecto_id): array
|
||||
{
|
||||
$query = "SELECT a.*
|
||||
FROM `{$this->getTable()}` a
|
||||
JOIN (SELECT e1.* FROM `estado_precio` e1 JOIN (SELECT MAX(`id`) AS 'id', `precio` FROM `estado_precio` GROUP BY `precio`) e0 ON e0.`id` = e1.`id`) ep ON ep.`precio` = a.`id`
|
||||
JOIN `tipo_estado_precio` tep ON tep.`id` = ep.`estado`
|
||||
JOIN `unidad` ON `unidad`.`id` = a.`unidad`
|
||||
JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt`
|
||||
JOIN `tipo_unidad` tu ON tu.`id` = ptu.`tipo`
|
||||
WHERE ptu.`proyecto` = ? AND tep.`descripcion` = 'vigente'
|
||||
ORDER BY tu.`orden`, ptu.`nombre`, `unidad`.`subtipo`, LPAD(`unidad`.`descripcion`, 4, '0')";
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined($this->joinEstado())
|
||||
->joined('INNER JOIN `tipo_estado_precio` tep ON tep.`id` = ep.`estado`')
|
||||
->joined('INNER JOIN `unidad` ON `unidad`.`id` = a.`unidad`')
|
||||
->joined('INNER JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt`')
|
||||
->joined('INNER JOIN `tipo_unidad` tu ON tu.`id` = ptu.`tipo`')
|
||||
->where('ptu.`proyecto` = ? AND tep.`descripcion` = "vigente"')
|
||||
->order('tu.`orden`, ptu.`nombre`, `unidad`.`subtipo`, LPAD(`unidad`.`descripcion`, 4, "0")');
|
||||
return $this->fetchMany($query, [$proyecto_id]);
|
||||
}
|
||||
|
||||
@ -70,11 +73,12 @@ ORDER BY tu.`orden`, ptu.`nombre`, `unidad`.`subtipo`, LPAD(`unidad`.`descripcio
|
||||
*/
|
||||
public function fetchByUnidad(int $unidad_id): array
|
||||
{
|
||||
$query = "SELECT a.*
|
||||
FROM `{$this->getTable()}` a
|
||||
JOIN (SELECT e1.* FROM `estado_precio` e1 JOIN (SELECT MAX(`id`) AS 'id', `precio` FROM `estado_precio` GROUP BY `precio`) e0 ON e0.`id` = e1.`id`) ep ON ep.`precio` = a.`id`
|
||||
JOIN `tipo_estado_precio` tep ON tep.`id` = ep.`estado`
|
||||
WHERE `unidad` = ?";
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined($this->joinEstado())
|
||||
->joined('INNER JOIN tipo_estado_precio tep ON tep.`id` = ep.`estado`')
|
||||
->where('`unidad` = ?');
|
||||
return $this->fetchMany($query, [$unidad_id]);
|
||||
}
|
||||
|
||||
@ -85,14 +89,45 @@ WHERE `unidad` = ?";
|
||||
*/
|
||||
public function fetchVigenteByUnidad(int $unidad_id): Define\Model
|
||||
{
|
||||
$query = "SELECT a.*
|
||||
FROM `{$this->getTable()}` a
|
||||
JOIN (SELECT e1.* FROM `estado_precio` e1 JOIN (SELECT MAX(`id`) AS 'id', `precio` FROM `estado_precio` GROUP BY `precio`) e0 ON e0.`id` = e1.`id`) ep ON ep.`precio` = a.`id`
|
||||
JOIN `tipo_estado_precio` tep ON tep.`id` = ep.`estado`
|
||||
WHERE `unidad` = ? AND tep.`descripcion` = 'vigente'";
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined($this->joinEstado())
|
||||
->joined('INNER JOIN tipo_estado_precio tep ON tep.`id` = ep.`estado`')
|
||||
->where('`unidad` = ? AND tep.`descripcion` = "vigente"');
|
||||
return $this->fetchOne($query, [$unidad_id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $unidad_ids
|
||||
* @return array
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchVigentesByUnidades(array $unidad_ids): array
|
||||
{
|
||||
$interrogations = implode(',', array_fill(0, count($unidad_ids), '?'));
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('a.*, unidad')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined($this->joinEstado())
|
||||
->joined('INNER JOIN tipo_estado_precio tep ON tep.`id` = ep.`estado`')
|
||||
->where("`unidad` IN ({$interrogations}) AND tep.`descripcion` = \"vigente\"");
|
||||
try {
|
||||
$results = $this->connection->execute($query, $unidad_ids)->fetchAll(PDO::FETCH_ASSOC);
|
||||
if (empty($results)) {
|
||||
throw new Implement\Exception\EmptyResult($query);
|
||||
}
|
||||
return array_map(function($result) {
|
||||
return [
|
||||
'id' => $result['unidad'],
|
||||
'precio' => $this->load($result)
|
||||
];
|
||||
}, $results);
|
||||
} catch (PDOException $exception) {
|
||||
throw new Implement\Exception\EmptyResult($query, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $unidad_id
|
||||
* @param string $date_time
|
||||
@ -101,11 +136,25 @@ WHERE `unidad` = ? AND tep.`descripcion` = 'vigente'";
|
||||
*/
|
||||
public function fetchByUnidadAndDate(int $unidad_id, string $date_time): Define\Model
|
||||
{
|
||||
$query = "SELECT a.*
|
||||
FROM `{$this->getTable()}` a
|
||||
JOIN (SELECT e1.* FROM `estado_precio` e1 JOIN (SELECT MAX(`id`) AS 'id', `precio` FROM `estado_precio` GROUP BY `precio`) e0 ON e0.`id` = e1.`id`) ep ON ep.`precio` = a.`id`
|
||||
JOIN `tipo_estado_precio` tep ON tep.`id` = ep.`estado`
|
||||
WHERE `unidad` = ? AND ep.`fecha` <= ? AND tep.`descripcion` = 'vigente'";
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined($this->joinEstado())
|
||||
->joined('INNER JOIN `tipo_estado_precio` tep ON tep.`id` = ep.`estado`')
|
||||
->where('`unidad` = ? AND ep.`fecha` <= ? AND tep.`descripcion` = "vigente"');
|
||||
return $this->fetchOne($query, [$unidad_id, $date_time]);
|
||||
}
|
||||
|
||||
protected function joinEstado(): string
|
||||
{
|
||||
$subSubQuery = $this->connection->getQueryBuilder()
|
||||
->select('MAX(id) AS id, precio')
|
||||
->from('estado_precio')
|
||||
->group('precio');
|
||||
$subQuery = $this->connection->getQueryBuilder()
|
||||
->select('e1.*')
|
||||
->from('estado_precio e1')
|
||||
->joined("INNER JOIN ($subSubQuery) e0 ON e0.id = e1.id");
|
||||
return "JOIN ($subQuery) ep ON ep.precio = a.id";
|
||||
}
|
||||
}
|
||||
|
431
app/src/Repository/Venta/Promotion.php
Normal file
431
app/src/Repository/Venta/Promotion.php
Normal file
@ -0,0 +1,431 @@
|
||||
<?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('DISTINCT a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined('LEFT OUTER JOIN promotion_brokers pb ON pb.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN broker_contracts bc ON bc.broker_rut = pb.broker_rut')
|
||||
->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN broker_contracts bc2 ON bc2.project_id = pp.project_id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN broker_contracts bc3 ON bc3.project_id = put.project_id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu ON ptu.id = pul.unit_line_id')
|
||||
->joined('LEFT OUTER JOIN broker_contracts bc4 ON bc4.project_id = ptu.proyecto')
|
||||
->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN unidad ON unidad.id = pu.unit_id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu2 ON ptu2.id = unidad.pt')
|
||||
->joined('LEFT OUTER JOIN broker_contracts bc5 ON bc5.project_id = ptu2.proyecto')
|
||||
->where('bc.id = :contract_id OR bc2.id = :contract_id OR bc3.id = :contract_id OR bc4.id = :contract_id OR bc5.id = :contract_id')
|
||||
->group('a.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('DISTINCT a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined('LEFT OUTER JOIN promotion_broker pb ON pb.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN broker_contracts bc ON bc.id = pb.contract_id')
|
||||
->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN broker_contracts bc2 ON bc2.project_id = pp.project_id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN broker_contracts bc3 ON bc3.project_id = put.project_id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu ON ptu.id = pul.unit_line_id')
|
||||
->joined('LEFT OUTER JOIN broker_contracts bc4 ON bc4.project_id = btu.proyecto')
|
||||
->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN unidad ON unidad.id = pu.unit_id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu2 ON ptu2.id = unidad.pt')
|
||||
->joined('LEFT OUTER JOIN broker_contracts bc5 ON bc5.project_id = ptu2.proyecto')
|
||||
->where('(bc.id = :contract_id OR bc2.id = :contract_id OR bc3.id = :contract_id OR bc4.id = :contract_id OR bc5.id = :contract_id) AND a.state = :state')
|
||||
->group('a.id');
|
||||
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('DISTINCT a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu1 ON ptu1.proyecto = pp.project_id')
|
||||
->joined('LEFT OUTER JOIN unidad u1 ON u1.pt = ptu1.id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu2 ON ptu2.tipo = put.unit_type_id AND ptu2.proyecto = put.project_id')
|
||||
->joined('LEFT OUTER JOIN unidad u2 ON u2.pt = ptu2.id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN unidad u3 ON u3.pt = pul.unit_line_id')
|
||||
->where('pu.unit_id = :unit_id OR u1.id = :unit_id OR u2.id = :unit_id OR u3.id = :unit_id')
|
||||
->group('a.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('DISTINCT a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu1 ON ptu1.proyecto = pp.project_id')
|
||||
->joined('LEFT OUTER JOIN unidad u1 ON u1.pt = ptu1.id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu2 ON ptu2.tipo = put.unit_type_id AND ptu2.proyecto = put.project_id')
|
||||
->joined('LEFT OUTER JOIN unidad u2 ON u2.pt = ptu2.id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN unidad u3 ON u3.pt = pul.unit_line_id')
|
||||
->where('(pu.unit_id = :unit_id OR u1.id = :unit_id OR u2.id = :unit_id OR u3.id = :unit_id) AND a.state = :state')
|
||||
->group('a.id');
|
||||
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('DISTINCT a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu ON ptu.id = pul.unit_line_id')
|
||||
->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN unidad ON unidad.id = pu.unit_id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu1 ON ptu.id = unidad.pt')
|
||||
->where('pp.project_id = :project_id OR put.project_id = :project_id OR ptu.proyecto = :project_id OR ptu1.proyecto = :project_id')
|
||||
->group('a.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('DISTINCT a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu ON ptu.id = pul.unit_line_id')
|
||||
->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN unidad ON unidad.id = pu.unit_id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu1 ON ptu.id = unidad.pt')
|
||||
->where('(pp.project_id = :project_id OR put.project_id = :project_id OR ptu.proyecto = :project_id OR ptu1.proyecto = :project_id) AND a.state = :state')
|
||||
->group('a.id');
|
||||
return $this->fetchMany($query, ['project_id' => $project_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $contract_id
|
||||
* @param int $unit_id
|
||||
* @return array
|
||||
* @throws Common\Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchByContractAndUnit(int $contract_id, int $unit_id): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('DISTINCT a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined('LEFT OUTER JOIN promotion_brokers pb ON pb.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN broker_contracts bc ON bc.broker_rut = pb.broker_rut')
|
||||
->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu1 ON ptu1.proyecto = pp.project_id')
|
||||
->joined('LEFT OUTER JOIN unidad u1 ON u1.pt = ptu1.id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu2 ON ptu2.tipo = put.unit_type_id AND ptu2.proyecto = put.project_id')
|
||||
->joined('LEFT OUTER JOIN unidad u2 ON u2.pt = ptu2.id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu3 ON ptu3.id = pul.unit_line_id')
|
||||
->joined('LEFT OUTER JOIN unidad u3 ON u3.pt = ptu3.id')
|
||||
->where('bc.id = :contract_id OR pu.unit_id = :unit_id OR u1.id = :unit_id OR u2.id = :unit_id OR u3.id = :unit_id')
|
||||
->group('a.id');
|
||||
return $this->fetchMany($query, ['contract_id' => $contract_id, 'unit_id' => $unit_id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $contract_id
|
||||
* @param array $unit_ids
|
||||
* @return array
|
||||
* @throws Common\Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchByContractAndUnits(int $contract_id, array $unit_ids): array
|
||||
{
|
||||
$interrogations = implode(',', array_map(fn($k) => ":id{$k}", array_keys($unit_ids)));
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('DISTINCT a.*, GROUP_CONCAT(COALESCE(pu.unit_id, u1.id, u2.id, u3.id) SEPARATOR "|") as unit_id')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined('LEFT OUTER JOIN promotion_brokers pb ON pb.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN broker_contracts bc ON bc.broker_rut = pb.broker_rut')
|
||||
->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu1 ON ptu1.proyecto = pp.project_id')
|
||||
->joined('LEFT OUTER JOIN unidad u1 ON u1.pt = ptu1.id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu2 ON ptu2.tipo = put.unit_type_id AND ptu2.proyecto = put.project_id')
|
||||
->joined('LEFT OUTER JOIN unidad u2 ON u2.pt = ptu2.id')
|
||||
->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
|
||||
->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu3 ON ptu3.id = pul.unit_line_id')
|
||||
->joined('LEFT OUTER JOIN unidad u3 ON u3.pt = ptu3.id')
|
||||
->where("bc.id = :contract_id OR pu.unit_id IN ({$interrogations}) OR u1.id IN ({$interrogations}) OR u2.id IN ({$interrogations}) OR u3.id IN ({$interrogations})")
|
||||
->group('a.id');
|
||||
$unitParams = array_combine(array_map(fn($k) => "id{$k}", array_keys($unit_ids)), $unit_ids);
|
||||
try {
|
||||
$results = $this->connection->execute($query, array_merge(['contract_id' => $contract_id], $unitParams))->fetchAll(PDO::FETCH_ASSOC);
|
||||
if (empty($results)) {
|
||||
throw new Common\Implement\Exception\EmptyResult($query);
|
||||
}
|
||||
$temp = new class()
|
||||
{
|
||||
protected array $promotions = [];
|
||||
public function addItem(int $id, Model\Venta\Promotion $promotion): void
|
||||
{
|
||||
if (!array_key_exists($id, $this->promotions)) {
|
||||
$this->promotions[$id] = [
|
||||
'id' => $id,
|
||||
'promotions' => []
|
||||
];
|
||||
}
|
||||
$this->promotions[$id]['promotions'] []= $promotion;
|
||||
}
|
||||
public function toArray(): array
|
||||
{
|
||||
return array_values($this->promotions);
|
||||
}
|
||||
};
|
||||
foreach ($results as $result) {
|
||||
if (str_contains($result['unit_id'], '|')) {
|
||||
$ids = explode('|', $result['unit_id']);
|
||||
foreach ($ids as $id) {
|
||||
$temp->addItem((int) $id, $this->load($result));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$temp->addItem((int) $result['unit_id'], $this->load($result));
|
||||
}
|
||||
return $temp->toArray();
|
||||
} catch (PDOException $exception) {
|
||||
throw new Common\Implement\Exception\EmptyResult($query, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Model\Venta\Promotion $promotion
|
||||
* @param int $project_id
|
||||
* @return void
|
||||
* @throws PDOException
|
||||
*/
|
||||
public function insertProjectForPromotion(Model\Venta\Promotion $promotion, int $project_id): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->insert()
|
||||
->into('promotion_projects')
|
||||
->columns(['promotion_id', 'project_id'])
|
||||
->values([':promotion_id', ':project_id']);
|
||||
$this->connection->execute($query, ['promotion_id' => $promotion->id, 'project_id' => $project_id]);
|
||||
}
|
||||
public function removeProjectForPromotion(Model\Venta\Promotion $promotion, int $project_id): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->delete()
|
||||
->from('promotion_projects')
|
||||
->where('promotion_id = :promotion_id AND project_id = :project_id');
|
||||
$this->connection->execute($query, ['promotion_id' => $promotion->id, 'project_id' => $project_id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Model\Venta\Promotion $promotion
|
||||
* @param int $broker_rut
|
||||
* @return void
|
||||
* @throws PDOException
|
||||
*/
|
||||
public function insertBrokerForPromotion(Model\Venta\Promotion $promotion, int $broker_rut): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->insert()
|
||||
->into('promotion_brokers')
|
||||
->columns(['promotion_id', 'broker_rut'])
|
||||
->values([':promotion_id', ':broker_rut']);
|
||||
$this->connection->execute($query, ['promotion_id' => $promotion->id, 'broker_rut' => $broker_rut]);
|
||||
}
|
||||
public function removeBrokerForPromotion(Model\Venta\Promotion $promotion, int $broker_rut): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->delete()
|
||||
->from('promotion_brokers')
|
||||
->where('promotion_id = :promotion_id AND broker_rut = :broker_rut');
|
||||
$this->connection->execute($query, ['promotion_id' => $promotion->id, 'broker_rut' => $broker_rut]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Model\Venta\Promotion $promotion
|
||||
* @param int $project_id
|
||||
* @param int $unit_type_id
|
||||
* @return void
|
||||
*/
|
||||
public function insertUnitTypeForPromotion(Model\Venta\Promotion $promotion, int $project_id, int $unit_type_id): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->insert()
|
||||
->into('promotion_unit_types')
|
||||
->columns(['promotion_id', 'project_id', 'unit_type_id'])
|
||||
->values([':promotion_id', ':project_id', ':unit_type_id']);
|
||||
$this->connection->execute($query,
|
||||
['promotion_id' => $promotion->id, 'project_id' => $project_id, 'unit_type_id' => $unit_type_id]);
|
||||
}
|
||||
public function removeUnitTypeForPromotion(Model\Venta\Promotion $promotion, int $project_id, int $unit_type_id): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->delete()
|
||||
->from('promotion_unit_types')
|
||||
->where('promotion_id = :promotion_id AND project_id = :project_id AND unit_type_id = :unit_type_id');
|
||||
$this->connection->execute($query,
|
||||
['promotion_id' => $promotion->id, 'project_id' => $project_id, 'unit_type_id' => $unit_type_id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Model\Venta\Promotion $promotion
|
||||
* @param int $unit_line_id
|
||||
* @return void
|
||||
*/
|
||||
public function insertUnitLineForPromotion(Model\Venta\Promotion $promotion, int $unit_line_id): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->insert()
|
||||
->into('promotion_unit_lines')
|
||||
->columns(['promotion_id', 'unit_line_id'])
|
||||
->values([':promotion_id', ':unit_line_id']);
|
||||
$this->connection->execute($query, ['promotion_id' => $promotion->id, 'unit_line_id' => $unit_line_id]);
|
||||
}
|
||||
public function removeUnitLineForPromotion(Model\Venta\Promotion $promotion, int $unit_line_id): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->delete()
|
||||
->from('promotion_unit_lines')
|
||||
->where('promotion_id = :promotion_id AND unit_line_id = :unit_line_id');
|
||||
$this->connection->execute($query, ['promotion_id' => $promotion->id, 'unit_line_id' => $unit_line_id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Model\Venta\Promotion $promotion
|
||||
* @param int $unit_id
|
||||
* @return void
|
||||
*/
|
||||
public function insertUnitForPromotion(Model\Venta\Promotion $promotion, int $unit_id): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->insert()
|
||||
->into('promotion_units')
|
||||
->columns(['promotion_id', 'unit_id'])
|
||||
->values([':promotion_id', ':unit_id']);
|
||||
$this->connection->execute($query, ['promotion_id' => $promotion->id, 'unit_id' => $unit_id]);
|
||||
}
|
||||
public function removeUnitForPromotion(Model\Venta\Promotion $promotion, int $unit_id): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->delete()
|
||||
->from('promotion_units')
|
||||
->where('promotion_id = :promotion_id AND unit_id = :unit_id');
|
||||
$this->connection->execute($query, ['promotion_id' => $promotion->id, 'unit_id' => $unit_id]);
|
||||
}
|
||||
}
|
@ -1,6 +1,8 @@
|
||||
<?php
|
||||
namespace Incoviba\Repository\Venta;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Define;
|
||||
use Incoviba\Common\Implement;
|
||||
@ -17,14 +19,7 @@ class Propiedad extends Ideal\Repository
|
||||
|
||||
public function create(?array $data = null): Model\Venta\Propiedad
|
||||
{
|
||||
$map = (new Implement\Repository\MapperParser())
|
||||
->register('unidad_principal', (new Implement\Repository\Mapper())
|
||||
->setProperty('unidades')
|
||||
->setDefault([])
|
||||
->setFunction(function($data) {
|
||||
return [$this->unidadService->getById($data['unidad_principal'])];
|
||||
})
|
||||
)
|
||||
$map = (new Implement\Repository\MapperParser(['unidad_principal', 'estacionamientos', 'bodegas', 'estado']))
|
||||
->register('estado', new Implement\Repository\Mapper\Boolean('estado'));
|
||||
return $this->parseData(new Model\Venta\Propiedad(), $data, $map);
|
||||
}
|
||||
@ -67,7 +62,10 @@ class Propiedad extends Ideal\Repository
|
||||
*/
|
||||
public function fetchVigenteByUnidad(int $unidad_id): Model\Venta\Propiedad
|
||||
{
|
||||
$query = "SELECT * FROM `{$this->getTable()}` WHERE `unidad_principal` = ?";
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select()
|
||||
->from($this->getTable())
|
||||
->where('`unidad_principal` = ? AND `estado` = 1');
|
||||
return $this->fetchOne($query, [$unidad_id]);
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
<?php
|
||||
namespace Incoviba\Repository\Venta;
|
||||
|
||||
use PDOException;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Define;
|
||||
use Incoviba\Common\Implement;
|
||||
@ -57,7 +58,12 @@ class PropiedadUnidad extends Ideal\Repository
|
||||
return $this->update($model, ['propiedad', 'unidad', 'valor'], $new_data);
|
||||
}
|
||||
|
||||
public function fetchById(int $id): Define\Model
|
||||
/**
|
||||
* @param int $id
|
||||
* @return Model\Venta\PropiedadUnidad
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchById(int $id): Model\Venta\PropiedadUnidad
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select()
|
||||
@ -66,16 +72,27 @@ class PropiedadUnidad extends Ideal\Repository
|
||||
return $this->fetchOne($query, [$id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $venta_id
|
||||
* @return array
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchByVenta(int $venta_id): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('a.*')
|
||||
->from("{$this->getTable()} a")
|
||||
->joined('JOIN unidad ON a.unidad = unidad.id
|
||||
JOIN venta ON venta.propiedad = a.propiedad')
|
||||
->joined('INNER JOIN unidad ON a.unidad = unidad.id')
|
||||
->joined('INNER JOIN venta ON venta.propiedad = a.propiedad')
|
||||
->where('venta.id = ?');
|
||||
return $this->fetchMany($query, [$venta_id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $propiedad_id
|
||||
* @return array
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchByPropiedad(int $propiedad_id): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
@ -86,6 +103,12 @@ class PropiedadUnidad extends Ideal\Repository
|
||||
->group('`unidad`.`id`');
|
||||
return $this->fetchMany($query, [$propiedad_id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Define\Model $model
|
||||
* @return void
|
||||
* @throws PDOException
|
||||
*/
|
||||
public function remove(Define\Model $model): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
@ -94,7 +117,15 @@ class PropiedadUnidad extends Ideal\Repository
|
||||
$this->connection->execute($query, [$model->pu_id]);
|
||||
}
|
||||
|
||||
protected function update(Define\Model $model, array $columns, array $data): Define\Model
|
||||
/**
|
||||
* @param Define\Model $model
|
||||
* @param array $columns
|
||||
* @param array $data
|
||||
* @return Model\Venta\PropiedadUnidad
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
* @throws PDOException
|
||||
*/
|
||||
protected function update(Define\Model $model, array $columns, array $data): Model\Venta\PropiedadUnidad
|
||||
{
|
||||
$changes = [];
|
||||
$values = [];
|
||||
|
230
app/src/Repository/Venta/Reservation.php
Normal file
230
app/src/Repository/Venta/Reservation.php
Normal 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;
|
||||
}
|
||||
}
|
60
app/src/Repository/Venta/Reservation/State.php
Normal file
60
app/src/Repository/Venta/Reservation/State.php
Normal 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]);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user