Compare commits
159 Commits
feature/ma
...
878b02ee52
Author | SHA1 | Date | |
---|---|---|---|
878b02ee52 | |||
f3e15b34a8 | |||
3903551176 | |||
43eb8ec758 | |||
a405b15410 | |||
a2f2d94e64 | |||
0587b64d65 | |||
a6b81f1bff | |||
4239bafc26 | |||
6591e9f80e | |||
b57f32c86b | |||
0e903f99c4 | |||
186cd0f5b8 | |||
167d8e1ab7 | |||
46802507a7 | |||
aaf2ed7612 | |||
3ced9e40b1 | |||
594cb68b09 | |||
af68c4b8ec | |||
ea8f483dd5 | |||
5f53c77a1f | |||
b9adb9108b | |||
8be085222a | |||
d1e4314b35 | |||
7d04b406ab | |||
972e57b6f1 | |||
5f63bdbf4a | |||
a8325c3310 | |||
7e54b72587 | |||
ebe31a3d3d | |||
db6445bcf3 | |||
4e1901b7c8 | |||
c3316029c9 | |||
cbfc796685 | |||
da56192f97 | |||
b5d08620f9 | |||
c92b07ee6f | |||
ee6956d417 | |||
21d5e2d03b | |||
73a742c01e | |||
dd42c12d49 | |||
41ea5f5c15 | |||
eeb6f5bcd1 | |||
2680f51167 | |||
019d57a0b0 | |||
1a400d9a5c | |||
6276f87274 | |||
28c93a42bc | |||
4ff5d28522 | |||
a93642c55d | |||
87c0d8c8d9 | |||
dd1741a930 | |||
ad0fd82a9e | |||
bae5c1740d | |||
f5f1482b7a | |||
4bd5fe16df | |||
61845fbd05 | |||
f8ac0f14f0 | |||
acb7a1336d | |||
8af56137a8 | |||
c3247838b3 | |||
dd82ac6bb7 | |||
2acf0362fa | |||
e6892ee085 | |||
86b8d6b3c7 | |||
53115b085f | |||
c3b7427f60 | |||
5d939f970b | |||
4845801b27 | |||
d5bf9a7660 | |||
795dda868b | |||
53a3633dc7 | |||
0143fd11ac | |||
55745a8d0a | |||
2a1930c5f7 | |||
31f49dddb6 | |||
b4ca59fb6d | |||
d910f3eb69 | |||
555cdb7138 | |||
65088da2f5 | |||
966b341b65 | |||
90b05ca25c | |||
bb3a2fffa1 | |||
8a5e41a722 | |||
5736a346e7 | |||
4f4e69f0c3 | |||
00deebeaa8 | |||
aee0754b5a | |||
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 |
@ -1,11 +1,12 @@
|
||||
FROM php:8.2-fpm
|
||||
FROM php:8.4-fpm
|
||||
|
||||
ENV TZ=America/Santiago
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends libzip-dev libicu-dev git libpng-dev unzip tzdata \
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends libzip-dev libicu-dev git \
|
||||
libpng-dev unzip tzdata libxml2-dev \
|
||||
&& rm -r /var/lib/apt/lists/* \
|
||||
&& docker-php-ext-install pdo pdo_mysql zip intl gd bcmath \
|
||||
&& pecl install xdebug-3.3.2 \
|
||||
&& docker-php-ext-install pdo pdo_mysql zip intl gd bcmath dom \
|
||||
&& pecl install xdebug-3.4.2 \
|
||||
&& docker-php-ext-enable xdebug \
|
||||
&& echo $TZ > /etc/timezone
|
||||
|
||||
|
1
app/.gitignore
vendored
1
app/.gitignore
vendored
@ -1 +1,2 @@
|
||||
**/bin
|
||||
**/public/tests
|
||||
|
@ -10,5 +10,5 @@ notifications:
|
||||
failingTests: false
|
||||
hideManual: true
|
||||
phpunit:
|
||||
arguments: '--log-events-text /logs/output.txt --stop-on-failure'
|
||||
arguments: '--testsuite unit --log-events-text /logs/output.txt --stop-on-failure'
|
||||
timeout: 180
|
||||
|
3
app/bin/console
Normal file
3
app/bin/console
Normal file
@ -0,0 +1,3 @@
|
||||
#!/usr/bin/bash
|
||||
|
||||
php -d auto_prepend_file=test.bootstrap.php -a
|
3
app/bin/integration_tests
Normal file
3
app/bin/integration_tests
Normal file
@ -0,0 +1,3 @@
|
||||
#!/usr/bin/bash
|
||||
|
||||
bin/phpunit --testsuite acceptance $@
|
3
app/bin/performance_tests
Normal file
3
app/bin/performance_tests
Normal file
@ -0,0 +1,3 @@
|
||||
#!/usr/bin/bash
|
||||
|
||||
bin/phpunit --testsuite performance $@
|
3
app/bin/unit_tests
Normal file
3
app/bin/unit_tests
Normal file
@ -0,0 +1,3 @@
|
||||
#!/usr/bin/bash
|
||||
|
||||
./bin/phpunit --testsuite unit $@
|
@ -1,9 +1,6 @@
|
||||
<?php
|
||||
namespace Incoviba\Common\Alias;
|
||||
|
||||
use Illuminate\Events\Dispatcher;
|
||||
use Slim\Views\Blade;
|
||||
|
||||
class View extends Blade
|
||||
{
|
||||
}
|
||||
class View extends Blade {}
|
||||
|
@ -8,9 +8,9 @@ interface Provider
|
||||
{
|
||||
/**
|
||||
* @param string $money_symbol
|
||||
* @param DateTimeInterface $dateTime
|
||||
* @param ?DateTimeInterface $dateTime = null
|
||||
* @return float
|
||||
* @throws EmptyResponse
|
||||
*/
|
||||
public function get(string $money_symbol, DateTimeInterface $dateTime): float;
|
||||
public function get(string $money_symbol, ?DateTimeInterface $dateTime = null): float;
|
||||
}
|
||||
|
@ -24,6 +24,11 @@ abstract class Repository implements Define\Repository
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getConnection(): Define\Connection
|
||||
{
|
||||
return $this->connection;
|
||||
}
|
||||
|
||||
public function load(array $data_row): Define\Model
|
||||
{
|
||||
$model = $this->create($data_row);
|
||||
@ -189,7 +194,7 @@ abstract class Repository implements Define\Repository
|
||||
try {
|
||||
$this->connection->execute($query, $values);
|
||||
} catch (PDOException $exception) {
|
||||
throw new EmptyResult($query, $exception);
|
||||
throw new EmptyResult($query, $exception, $data);
|
||||
}
|
||||
return $this->fetchById($this->getIndex($model));
|
||||
}
|
||||
@ -205,10 +210,10 @@ abstract class Repository implements Define\Repository
|
||||
try {
|
||||
$result = $this->connection->execute($query, $data)->fetch(PDO::FETCH_ASSOC);
|
||||
if ($result === false) {
|
||||
throw new EmptyResult($query);
|
||||
throw new EmptyResult($query, null, $data);
|
||||
}
|
||||
} catch (PDOException $exception) {
|
||||
throw new EmptyResult($query, $exception);
|
||||
throw new EmptyResult($query, $exception, $data);
|
||||
}
|
||||
return $this->load($result);
|
||||
}
|
||||
@ -224,7 +229,7 @@ abstract class Repository implements Define\Repository
|
||||
try {
|
||||
$results = $this->connection->execute($query, $data)->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $exception) {
|
||||
throw new EmptyResult($query, $exception);
|
||||
throw new EmptyResult($query, $exception, $data);
|
||||
}
|
||||
return array_map([$this, 'load'], $results);
|
||||
}
|
||||
@ -240,7 +245,7 @@ abstract class Repository implements Define\Repository
|
||||
try {
|
||||
$results = $this->connection->execute($query, $data)->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $exception) {
|
||||
throw new EmptyResult($query, $exception);
|
||||
throw new EmptyResult($query, $exception, $data);
|
||||
}
|
||||
return $results;
|
||||
}
|
||||
|
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)) . ')';
|
||||
}
|
||||
|
@ -6,10 +6,15 @@ use Throwable;
|
||||
|
||||
class EmptyResult extends Exception
|
||||
{
|
||||
public function __construct(public string $query, ?Throwable $previous = null)
|
||||
public function __construct(public string $query, ?Throwable $previous = null, protected ?array $data = null)
|
||||
{
|
||||
$message = "Empty results for {$query}";
|
||||
$code = 700;
|
||||
parent::__construct($message, $code, $previous);
|
||||
}
|
||||
|
||||
public function getData(): ?array
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
}
|
||||
|
@ -13,7 +13,7 @@ class PDOFormatter extends JsonFormatter
|
||||
|
||||
public function format(LogRecord $record): string
|
||||
{
|
||||
$normalized = $this->normalize($record);
|
||||
$normalized = $this->normalize($record, $this->maxNormalizeDepth);
|
||||
return $normalized['message'];
|
||||
}
|
||||
}
|
||||
|
@ -4,6 +4,7 @@
|
||||
"type": "project",
|
||||
"require": {
|
||||
"ext-curl": "*",
|
||||
"ext-dom": "*",
|
||||
"ext-gd": "*",
|
||||
"ext-openssl": "*",
|
||||
"ext-pdo": "*",
|
||||
@ -18,7 +19,8 @@
|
||||
"predis/predis": "^2",
|
||||
"robmorgan/phinx": "^0.16",
|
||||
"slim/slim": "^4",
|
||||
"symfony/string": "^7.2"
|
||||
"symfony/string": "^7.2",
|
||||
"tedivm/jshrink": "^1.7"
|
||||
},
|
||||
"require-dev": {
|
||||
"fakerphp/faker": "^1",
|
||||
|
@ -28,16 +28,15 @@
|
||||
<directory>common</directory>
|
||||
</include>
|
||||
</source>
|
||||
<coverage pathCoverage="false" ignoreDeprecatedCodeUnits="true" disableCodeCoverageIgnore="true">
|
||||
<!--<coverage pathCoverage="false" ignoreDeprecatedCodeUnits="true" disableCodeCoverageIgnore="true">
|
||||
<report>
|
||||
<html outputDirectory="/code/public/coverage/html"/>
|
||||
<php outputFile="/code/public/coverage/coverage.php"/>
|
||||
</report>
|
||||
</coverage>
|
||||
</coverage>-->
|
||||
<logging>
|
||||
<junit outputFile="/code/cache/tests/junit.xml"/>
|
||||
<teamcity outputFile="/code/cache/tests/teamcity.txt"/>
|
||||
<testdoxHtml outputFile="/code/cache/tests/testdox.html"/>
|
||||
<!--<testdoxHtml outputFile="/code/public/tests/testdox.html"/>-->
|
||||
<testdoxText outputFile="/code/cache/tests/testdox.txt"/>
|
||||
</logging>
|
||||
</phpunit>
|
||||
|
@ -13,3 +13,10 @@ try {
|
||||
$app->getContainer()->get(Psr\Log\LoggerInterface::class)->notice($exception);
|
||||
header('Location: /construccion');
|
||||
}
|
||||
register_shutdown_function(function() {
|
||||
$error = error_get_last();
|
||||
|
||||
if ($error !== null) {
|
||||
error_log(json_encode($error).PHP_EOL,3, '/logs/fatal.log');
|
||||
}
|
||||
});
|
||||
|
@ -18,7 +18,7 @@ class CreateAgente extends Phinx\Migration\AbstractMigration
|
||||
->addColumn('telefono', 'integer', ['length' => 11, 'default' => null, 'null' => true])
|
||||
->addColumn('correo', 'string', ['length' => 50, 'default' => null, 'null' => true])
|
||||
->addColumn('direccion', 'integer', ['length' => 11, 'default' => null, 'null' => true])
|
||||
->addColumn('giro', 'mediumtext', ['default' => null, 'null' => true])
|
||||
->addColumn('giro', 'text', ['default' => null, 'null' => true])
|
||||
->addColumn('abreviacion', 'string', ['length' => 20, 'default' => null, 'null' => true])
|
||||
->create();
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
|
@ -13,9 +13,9 @@ class CreateCartolas extends Phinx\Migration\AbstractMigration
|
||||
$this->table('cartolas')
|
||||
->addColumn('cuenta_id', 'integer', ['length' => 10, 'null' => false, 'signed' => false])
|
||||
->addColumn('fecha', 'date', ['null' => false])
|
||||
->addColumn('cargos', 'bigint', ['length' => 20, 'default' => 0, 'null' => false, 'signed' => false])
|
||||
->addColumn('abonos', 'bigint', ['length' => 20, 'default' => 0, 'null' => false, 'signed' => false])
|
||||
->addColumn('saldo', 'bigint', ['length' => 20, 'default' => 0, 'null' => false])
|
||||
->addColumn('cargos', 'biginteger', ['length' => 20, 'default' => 0, 'null' => false, 'signed' => false])
|
||||
->addColumn('abonos', 'biginteger', ['length' => 20, 'default' => 0, 'null' => false, 'signed' => false])
|
||||
->addColumn('saldo', 'biginteger', ['length' => 20, 'default' => 0, 'null' => false])
|
||||
->addForeignKey('cuenta_id', 'cuenta', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
|
||||
->create();
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
|
@ -15,7 +15,7 @@ class CreateCentrosCostos extends Phinx\Migration\AbstractMigration
|
||||
->addColumn('categoria_id', 'integer', ['length' => 10, 'null' => false, 'signed' => false])
|
||||
->addColumn('tipo_cuenta_id', 'integer', ['length' => 10, 'default' => null, 'null' => true, 'signed' => false])
|
||||
->addColumn('cuenta_contable', 'string', ['length' => 100, 'null' => false])
|
||||
->addColumn('descripcion', 'mediumtext', ['null' => false])
|
||||
->addColumn('descripcion', 'text', ['null' => false, 'limit' => MysqlAdapter::TEXT_MEDIUM])
|
||||
->addForeignKey('tipo_centro_id', 'tipos_centros_costos', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
|
||||
->addForeignKey('categoria_id', 'categorias_centros_costos', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
|
||||
->create();
|
||||
|
@ -19,7 +19,7 @@ class CreateCobro extends Phinx\Migration\AbstractMigration
|
||||
->addColumn('iva', 'float', ['default' => 0])
|
||||
->addColumn('uf', 'float', ['default' => null, 'null' => true])
|
||||
->addColumn('identificador', 'string', ['length' => 50, 'default' => null, 'null' => true])
|
||||
->addColumn('glosa', 'mediumtext', ['default' => null, 'null' => true])
|
||||
->addColumn('glosa', 'text', ['default' => null, 'null' => true, 'limit' => MysqlAdapter::TEXT_MEDIUM])
|
||||
->create();
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
|
@ -11,7 +11,7 @@ class CreateEscritura extends Phinx\Migration\AbstractMigration
|
||||
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
|
||||
|
||||
$this->table('escritura')
|
||||
->addColumn('valor', 'bigint', ['length' => 20, 'null' => false])
|
||||
->addColumn('valor', 'biginteger', ['length' => 20, 'null' => false])
|
||||
->addColumn('fecha', 'date', ['null' => false])
|
||||
->addColumn('uf', 'float', ['default' => null, 'null' => true])
|
||||
->addColumn('abonado', 'integer', ['length' => 11, 'default' => 0])
|
||||
|
@ -13,7 +13,7 @@ class CreateEstadoProblema extends Phinx\Migration\AbstractMigration
|
||||
$this->table('estado_problema')
|
||||
->addColumn('problema', 'integer', ['length' => 11, 'default' => null, 'null' => true])
|
||||
->addColumn('fecha', 'date', ['default' => null, 'null' => true])
|
||||
->addColumn('estado', 'enum', ['length' => 'ingreso','revision','correccion','ok', 'default' => null, 'null' => true])
|
||||
->addColumn('estado', 'enum', ['values' => ['ingreso','revision','correccion','ok'], 'default' => null, 'null' => true])
|
||||
->create();
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
|
@ -15,7 +15,7 @@ class CreateInmobiliariasNubox extends Phinx\Migration\AbstractMigration
|
||||
->addColumn('alias', 'string', ['length' => 100, 'null' => false])
|
||||
->addColumn('usuario', 'string', ['length' => 100, 'null' => false])
|
||||
->addColumn('contraseña', 'string', ['length' => 100, 'null' => false])
|
||||
->addForeignKey('inmobiliaria_rut', 'inmobiliaria', 'rut', ['delete' => 'cascade', 'update' => 'cascade'])
|
||||
#->addForeignKey('inmobiliaria_rut', 'inmobiliaria', 'rut', ['delete' => 'cascade', 'update' => 'cascade'])
|
||||
->create();
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
|
@ -15,9 +15,9 @@ class CreateMovimientos extends Phinx\Migration\AbstractMigration
|
||||
->addColumn('fecha', 'date', ['null' => false])
|
||||
->addColumn('glosa', 'text', ['null' => false])
|
||||
->addColumn('documento', 'string', ['length' => 50, 'null' => false])
|
||||
->addColumn('cargo', 'bigint', ['length' => 20, 'default' => 0, 'null' => false, 'signed' => false])
|
||||
->addColumn('abono', 'bigint', ['length' => 20, 'default' => 0, 'null' => false, 'signed' => false])
|
||||
->addColumn('saldo', 'bigint', ['length' => 20, 'default' => 0, 'null' => false])
|
||||
->addColumn('cargo', 'biginteger', ['length' => 20, 'default' => 0, 'null' => false, 'signed' => false])
|
||||
->addColumn('abono', 'biginteger', ['length' => 20, 'default' => 0, 'null' => false, 'signed' => false])
|
||||
->addColumn('saldo', 'biginteger', ['length' => 20, 'default' => 0, 'null' => false])
|
||||
->addForeignKey('cuenta_id', 'cuenta', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
|
||||
->create();
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
|
@ -12,7 +12,7 @@ class CreateProblema extends Phinx\Migration\AbstractMigration
|
||||
|
||||
$this->table('problema')
|
||||
->addColumn('venta', 'integer', ['length' => 11, 'default' => null, 'null' => true])
|
||||
->addColumn('descripcion', 'mediumtext', ['default' => null, 'null' => true])
|
||||
->addColumn('descripcion', 'text', ['default' => null, 'null' => true, 'limit' => MysqlAdapter::TEXT_MEDIUM])
|
||||
->create();
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
|
@ -12,7 +12,7 @@ class CreateProyecto extends Phinx\Migration\AbstractMigration
|
||||
|
||||
$this->table('proyecto')
|
||||
->addColumn('inmobiliaria', 'integer', ['length' => 10, 'default' => null, 'null' => true, 'signed' => false])
|
||||
->addColumn('descripcion', 'mediumtext', ['null' => false])
|
||||
->addColumn('descripcion', 'text', ['null' => false, 'limit' => MysqlAdapter::TEXT_MEDIUM])
|
||||
->addColumn('direccion', 'integer', ['length' => 10, 'null' => false, 'signed' => false])
|
||||
->addColumn('superficie_terreno', 'float', ['default' => 0, 'null' => false, 'signed' => false])
|
||||
->addColumn('valor_terreno', 'float', ['default' => 0, 'null' => false, 'signed' => false])
|
||||
|
@ -18,7 +18,7 @@ class CreateProyectoTipoUnidad extends Phinx\Migration\AbstractMigration
|
||||
->addColumn('m2', 'float', ['default' => null, 'null' => true])
|
||||
->addColumn('logia', 'float', ['default' => 0])
|
||||
->addColumn('terraza', 'float', ['default' => 0])
|
||||
->addColumn('descripcion', 'mediumtext', ['default' => null, 'null' => true])
|
||||
->addColumn('descripcion', 'text', ['default' => null, 'null' => true, 'limit' => MysqlAdapter::TEXT_MEDIUM])
|
||||
->addForeignKey('proyecto', 'proyecto', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
|
||||
->create();
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
|
@ -33,7 +33,7 @@ class CreateVenta extends Phinx\Migration\AbstractMigration
|
||||
->addColumn('resciliacion', 'integer', ['length' => 10, 'default' => null, 'null' => true, 'signed' => false])
|
||||
->addColumn('devolucion', 'integer', ['length' => 10, 'default' => null, 'null' => true, 'signed' => false])
|
||||
->addForeignKey('propiedad', 'propiedad', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
|
||||
->addForeignKey('propietario', 'propietario', 'rut', ['delete' => 'cascade', 'update' => 'cascade'])
|
||||
#->addForeignKey('propietario', 'propietario', 'rut', ['delete' => 'cascade', 'update' => 'cascade'])
|
||||
->create();
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
|
@ -1,22 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Phinx\Db\Adapter\MysqlAdapter;
|
||||
|
||||
class CreateVentaAbonoCuotas extends Phinx\Migration\AbstractMigration
|
||||
{
|
||||
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('venta_abono_cuotas')
|
||||
->addColumn('venta_id', 'integer', ['length' => 11, 'null' => false, 'signed' => false])
|
||||
->addColumn('pago_id', 'integer', ['length' => 11, 'null' => false, 'signed' => false])
|
||||
->addColumn('numero', 'integer', ['length' => 11, 'default' => 1, 'null' => false, 'signed' => false])
|
||||
->addForeignKey('venta_id', 'venta', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
|
||||
->addForeignKey('pago_id', 'pago', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
|
||||
->create();
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
}
|
@ -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
|
||||
@ -33,6 +34,7 @@
|
||||
{{--<a class="item" href="{{$urls->base}}/ventas/precios/importar">Importar Precios</a>--}}
|
||||
{{--<a class="item" href="{{$urls->base}}/ventas/cierres/evaluar">Evaluar Cierre</a>--}}
|
||||
<a class="item" href="{{$urls->base}}/ventas/facturacion">Facturación</a>
|
||||
<div class="divider"></div>
|
||||
<a class="item" href="{{$urls->base}}/ventas/add">
|
||||
Nueva Venta
|
||||
<i class="plus icon"></i>
|
||||
|
@ -1,33 +1,9 @@
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js" integrity="sha512-3gJwYpMe3QewGELv8k/BX9vcqhryRdzRMxVfq6ngyWXwo03GFEzjsUm8Q7RZcHPHksttq7/GFoxjCVUjkjvPdw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.9.3/semantic.min.js" integrity="sha512-gnoBksrDbaMnlE0rhhkcx3iwzvgBGz6mOEj4/Y5ZY09n55dYddx6+WYc72A55qEesV8VX2iMomteIwobeGK1BQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
|
||||
|
||||
<script type="text/javascript">
|
||||
class APIClient {
|
||||
static fetch(url, options=null, showErrors=false) {
|
||||
return fetchAPI(url, options, showErrors)
|
||||
}
|
||||
}
|
||||
function fetchAPI(url, options=null, showErrors=false) {
|
||||
if (options === null) {
|
||||
options = {}
|
||||
}
|
||||
if (!Object.hasOwn(options, 'headers')) {
|
||||
options['headers'] = {}
|
||||
}
|
||||
if (!Object.hasOwn(options['headers'], 'Authorization')) {
|
||||
options['headers']['Authorization'] = 'Bearer {{md5($API_KEY)}}{{($login->isIn()) ? $login->getSeparator() . $login->getToken() : ''}}'
|
||||
}
|
||||
return fetch(url, options).then(response => {
|
||||
if (response.ok) {
|
||||
return response
|
||||
}
|
||||
throw new Error(JSON.stringify({code: response.status, message: response.statusText, url}))
|
||||
}).catch(error => {
|
||||
if (showErrors) {
|
||||
console.error(error)
|
||||
}
|
||||
})
|
||||
}
|
||||
@include('layout.body.scripts.api')
|
||||
|
||||
<script>
|
||||
const datatables_defaults = {
|
||||
language: {
|
||||
emptyTable: 'No hay datos disponibles',
|
||||
|
28
app/resources/views/layout/body/scripts/api.blade.php
Normal file
28
app/resources/views/layout/body/scripts/api.blade.php
Normal file
@ -0,0 +1,28 @@
|
||||
<script>
|
||||
class APIClient {
|
||||
static fetch(url, options=null, showErrors=false) {
|
||||
return fetchAPI(url, options, showErrors)
|
||||
}
|
||||
}
|
||||
function fetchAPI(url, options=null, showErrors=false) {
|
||||
if (options === null) {
|
||||
options = {}
|
||||
}
|
||||
if (!Object.hasOwn(options, 'headers')) {
|
||||
options['headers'] = {}
|
||||
}
|
||||
if (!Object.hasOwn(options['headers'], 'Authorization')) {
|
||||
options['headers']['Authorization'] = 'Bearer {{md5($API_KEY)}}{{($login->isIn()) ? $login->getSeparator() . $login->getToken() : ''}}'
|
||||
}
|
||||
return fetch(url, options).then(response => {
|
||||
if (response.ok) {
|
||||
return response
|
||||
}
|
||||
throw new Error(JSON.stringify({code: response.status, message: response.statusText, url}))
|
||||
}).catch(error => {
|
||||
if (showErrors) {
|
||||
console.error(error)
|
||||
}
|
||||
})
|
||||
}
|
||||
</script>
|
@ -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
|
||||
|
@ -0,0 +1,45 @@
|
||||
@push('page_scripts')
|
||||
<script>
|
||||
Intl.NumberFormat.prototype.parse = function(valueString) {
|
||||
const format = new Intl.NumberFormat(this.resolvedOptions().locale);
|
||||
const parts = format.formatToParts(-12345.6);
|
||||
const numerals = Array.from({ length: 10 }).map((_, i) => format.format(i));
|
||||
const index = new Map(numerals.map((d, i) => [d, i]));
|
||||
_minusSign = new RegExp(`[${parts.find(d => d.type === 'minusSign').value}]`);
|
||||
_group = new RegExp(`[${parts.find(d => d.type === 'group').value}]`, 'g');
|
||||
_decimal = new RegExp(`[${parts.find(d => d.type === 'decimal').value}]`);
|
||||
_numeral = new RegExp(`[${numerals.join('')}]`, 'g');
|
||||
_index = d => index.get(d);
|
||||
|
||||
const DIRECTION_MARK = /\u061c|\u200e/g
|
||||
return +(
|
||||
valueString.trim()
|
||||
.replace(DIRECTION_MARK, '')
|
||||
.replace(_group, '')
|
||||
.replace(_decimal, '.')
|
||||
.replace(_numeral, _index)
|
||||
.replace(_minusSign, '-')
|
||||
)
|
||||
}
|
||||
Intl.NumberFormat.prototype.isLocale = function(stringValue) {
|
||||
const format = new Intl.NumberFormat(this.resolvedOptions().locale);
|
||||
const parts = format.formatToParts(-12345.6);
|
||||
const group = parts.find(d => d.type === 'group').value;
|
||||
const decimal = parts.find(d => d.type === 'decimal').value;
|
||||
|
||||
if (stringValue.includes(group)) {
|
||||
if (stringValue.includes(decimal)) {
|
||||
return stringValue.indexOf(group) < stringValue.indexOf(decimal)
|
||||
}
|
||||
if (stringValue.split(group).map(d => d.length).filter(d => d > 3).length > 0) {
|
||||
return false
|
||||
}
|
||||
return stringValue.split(group).length > 2;
|
||||
}
|
||||
if (stringValue.includes(decimal)) {
|
||||
return stringValue.split(decimal).length <= 2;
|
||||
}
|
||||
return false
|
||||
}
|
||||
</script>
|
||||
@endpush
|
@ -0,0 +1,76 @@
|
||||
@push('page_scripts')
|
||||
<script>
|
||||
if (typeof Intl.NumberFormat.isLocale === 'undefined' || typeof Intl.NumberFormat.isLocale !== 'function') {
|
||||
// Load Intl.NumberFormat custom methods
|
||||
@include('layout.body.scripts.number_format')
|
||||
}
|
||||
class NumberInput {
|
||||
input
|
||||
isRational
|
||||
outputLocale
|
||||
currentValue
|
||||
formatters
|
||||
|
||||
constructor({input, isRational, outputLocale}) {
|
||||
this.input = input
|
||||
this.isRational = isRational
|
||||
this.outputLocale = outputLocale || 'es-CL'
|
||||
|
||||
this.formatters = {}
|
||||
const locales = ['es-CL', 'en-US']
|
||||
locales.forEach(locale => {
|
||||
this.formatters[locale] = {
|
||||
rational: new Intl.NumberFormat(locale, {minimumFractionDigits: 2, maximumFractionDigits: 2}),
|
||||
integer: new Intl.NumberFormat(locale)
|
||||
}
|
||||
})
|
||||
|
||||
if (this.input.value !== '') {
|
||||
this.currentValue = this.process(this.input.value)
|
||||
this.input.value = this.format(this.currentValue)
|
||||
}
|
||||
}
|
||||
watch() {
|
||||
this.input.addEventListener('change', event => {
|
||||
this.currentValue = this.process(event.currentTarget.value)
|
||||
this.input.value = this.format(this.currentValue)
|
||||
})
|
||||
}
|
||||
process(stringValue) {
|
||||
if (stringValue === '') {
|
||||
return ''
|
||||
}
|
||||
if (typeof stringValue !== 'string') {
|
||||
return stringValue
|
||||
}
|
||||
return this.formatters[this.detectLocale(stringValue)][this.isRational ? 'rational' : 'integer'].parse(stringValue)
|
||||
}
|
||||
detectLocale(stringValue) {
|
||||
if (stringValue === '') {
|
||||
return ''
|
||||
}
|
||||
if (typeof stringValue !== 'string') {
|
||||
return stringValue
|
||||
}
|
||||
const outputFormat = this.formatters[this.outputLocale][this.isRational ? 'rational' : 'integer'].isLocale(stringValue)
|
||||
const otherFormats = Object.entries(this.formatters).filter(formatter => formatter[0] !== this.outputLocale).map(formatter => {
|
||||
return {
|
||||
locale: formatter[0],
|
||||
value: formatter[1][this.isRational ? 'rational' : 'integer'].isLocale(stringValue)
|
||||
}
|
||||
}).filter(formatter => formatter.value)
|
||||
|
||||
if (outputFormat) {
|
||||
return this.outputLocale
|
||||
}
|
||||
if (otherFormats.length > 0) {
|
||||
return otherFormats[0].locale
|
||||
}
|
||||
return 'en-US'
|
||||
}
|
||||
format(value) {
|
||||
return this.formatters[this.outputLocale][this.isRational ? 'rational' : 'integer'].format(value)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@endpush
|
@ -28,7 +28,7 @@
|
||||
if (!(typeof digito === 'string' || digito instanceof String)) {
|
||||
digito = digito.toString()
|
||||
}
|
||||
return Rut.digitoVerificador(rut) === digito
|
||||
return Rut.digitoVerificador(rut).toString().toUpperCase() === digito.toUpperCase()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
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')
|
||||
|
14
app/resources/views/not_allowed.blade.php
Normal file
14
app/resources/views/not_allowed.blade.php
Normal file
@ -0,0 +1,14 @@
|
||||
@extends('layout.base')
|
||||
|
||||
@section('page_title')
|
||||
405 - Método No Permitido
|
||||
@endsection
|
||||
|
||||
@section('page_content')
|
||||
<div class="ui container">
|
||||
<div class="ui message">
|
||||
<i class="exclamation triangle icon"></i>
|
||||
No se ha encontrado la página solicitada para el método solicitado.
|
||||
</div>
|
||||
</div>
|
||||
@endsection
|
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
|
115
app/resources/views/proyectos/brokers/add_modal.blade.php
Normal file
115
app/resources/views/proyectos/brokers/add_modal.blade.php
Normal file
@ -0,0 +1,115 @@
|
||||
<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
|
489
app/resources/views/proyectos/brokers/contracts/show.blade.php
Normal file
489
app/resources/views/proyectos/brokers/contracts/show.blade.php
Normal file
@ -0,0 +1,489 @@
|
||||
@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) {
|
||||
return units.map(unit => {
|
||||
let price = unit.valor ?? (unit.precio?.valor ?? 0)
|
||||
const broker = price / (1 - this.commission)
|
||||
const promotions = unit.promotions?.map(promotion => {
|
||||
if (promotion.type === 1) {
|
||||
return {
|
||||
name: promotion.description,
|
||||
type: promotion.type,
|
||||
amount: promotion.amount,
|
||||
final: broker + promotion.amount
|
||||
}
|
||||
}
|
||||
return {
|
||||
name: promotion.description,
|
||||
type: promotion.type,
|
||||
amount: promotion.amount,
|
||||
final: broker / (1 - promotion.amount)
|
||||
}
|
||||
}) ?? []
|
||||
return {
|
||||
id: unit.id,
|
||||
base: price,
|
||||
commission: this.commission,
|
||||
broker,
|
||||
promotions
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
class GroupedTableHandler extends TableHandler {
|
||||
promotions = {
|
||||
names: new Set(),
|
||||
values: []
|
||||
}
|
||||
process() {
|
||||
return {
|
||||
prices: prices => {
|
||||
let promotions = {}
|
||||
prices.map(price => price.promotions).forEach(promotionArray => {
|
||||
promotionArray.forEach(p => {
|
||||
if (!Object.hasOwn(promotions, p.name)) {
|
||||
promotions[p.name] = {
|
||||
name: p.name,
|
||||
type: p.type,
|
||||
amount: [],
|
||||
final: []
|
||||
}
|
||||
}
|
||||
promotions[p.name].amount.push(p.amount)
|
||||
promotions[p.name].final.push(p.final)
|
||||
})
|
||||
})
|
||||
return promotions
|
||||
},
|
||||
promotions: () => {
|
||||
return {
|
||||
names: promotions => {
|
||||
Object.keys(promotions).forEach(name => {
|
||||
this.add().promotion().name(name)
|
||||
})
|
||||
},
|
||||
values: ({promotions, formatters}) => {
|
||||
const temp = Object.values(promotions)
|
||||
if (temp.length > 0) {
|
||||
const data = temp.map(p => {
|
||||
return {
|
||||
name: p.name,
|
||||
type: p.type,
|
||||
amount: {
|
||||
min: Math.min(...p.amount),
|
||||
max: Math.max(...p.amount),
|
||||
desv: Stat.standardDeviation(p.amount),
|
||||
mean: Stat.mean(p.amount)
|
||||
},
|
||||
final: {
|
||||
min: Math.min(...p.final),
|
||||
max: Math.max(...p.final),
|
||||
desv: Stat.standardDeviation(p.final),
|
||||
mean: Stat.mean(p.final)
|
||||
}
|
||||
}
|
||||
})
|
||||
this.add().promotion().values({promotions: data, formatters})
|
||||
return
|
||||
}
|
||||
this.promotions.values.push([])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
add() {
|
||||
return {
|
||||
promotion: () => {
|
||||
return {
|
||||
name: name => {
|
||||
this.promotions.names.add(name)
|
||||
},
|
||||
values: ({promotions, formatters}) => {
|
||||
this.promotions.values.push(promotions.map(promotion => {
|
||||
const amount_tooltip = [
|
||||
`Min: ${promotion.type === 1 ? 'UF ' + formatters.ufs.format(promotion.amount.min) : formatters.percent.format(promotion.amount.min)}`,
|
||||
`Max: ${promotion.type === 1 ? 'UF ' + formatters.ufs.format(promotion.amount.max) : formatters.percent.format(promotion.amount.max)}`,
|
||||
`Desv: ${promotion.type === 1 ? 'UF ' + formatters.ufs.format(promotion.amount.desv) : formatters.percent.format(promotion.amount.desv)}`
|
||||
].join("\n").replaceAll(' ', ' ')
|
||||
const final_tooltip = [
|
||||
`Min: UF ${formatters.ufs.format(promotion.final.min)}`,
|
||||
`Max: UF ${formatters.ufs.format(promotion.final.max)}`,
|
||||
`Desv: UF ${formatters.ufs.format(promotion.final.desv)}`
|
||||
].join("\n").replaceAll(' ', ' ')
|
||||
return {
|
||||
name: promotion.name,
|
||||
value: [
|
||||
`<td class="right aligned"><span data-tooltip="${amount_tooltip}" data-position="right center" data-variation="wide multiline">${promotion.type === 1 ? formatters.ufs.format(promotion.amount.mean) : formatters.percent.format(promotion.amount.mean)}</td>`,
|
||||
`<td class="right aligned"><span data-tooltip="${final_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(promotion.final.mean)}</td></td>`,
|
||||
].join("\n")
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
build() {
|
||||
return {
|
||||
promotions: (table, tbody) => {
|
||||
if (this.promotions.names.size > 0) {
|
||||
const title = document.getElementById(this.ids.promotions)
|
||||
title.innerHTML = this.promotions.names.size > 0 ? Array.from(this.promotions.names)[0] : ''
|
||||
title.setAttribute('colspan', '2')
|
||||
if (this.promotions.names.size > 1) {
|
||||
const thead = table.querySelector('thead')
|
||||
Array.from(this.promotions.names).slice(1).forEach(name => {
|
||||
thead.insertAdjacentHTML('beforeend', `<th class="right aligned" style="text-decoration: overline" colspan="2">${name}</th>`)
|
||||
})
|
||||
}
|
||||
const trs = tbody.querySelectorAll('tr')
|
||||
this.promotions.values.forEach((row, i) => {
|
||||
const tr = trs[i]
|
||||
const td = tr.querySelector('td.promotions')
|
||||
if (row.length === 0) {
|
||||
td.setAttribute('colspan', 2 * this.promotions.names.size)
|
||||
return
|
||||
}
|
||||
td.remove()
|
||||
this.promotions.names.forEach(name => {
|
||||
const index = row.findIndex(r => r.name === name)
|
||||
if (index === -1) {
|
||||
tr.insertAdjacentHTML('beforeend', '<td colspan="2"></td>')
|
||||
return
|
||||
}
|
||||
tr.insertAdjacentHTML('beforeend', row[index].value)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@endprepend
|
||||
|
||||
@section('brokers_content')
|
||||
<div class="ui statistic">
|
||||
<div class="value">{{ $format->percent($contract->commission ?? 0, 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">
|
||||
@if (count($contract->promotions()) === 0)
|
||||
- Ninguna
|
||||
@else
|
||||
<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>
|
||||
@endif
|
||||
</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 < 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/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 => {
|
||||
const idx = units.data.units.findIndex(unit => unit.id === departamento.id)
|
||||
return units.data.units[idx].precio
|
||||
}).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.precio
|
||||
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 * 3 })
|
||||
|
||||
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,91 @@
|
||||
<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">Precio Operador</th>
|
||||
<th class="center aligned" style="text-decoration: overline" id="linea_promociones">Promociones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
|
||||
@push('page_scripts')
|
||||
<script>
|
||||
class LineasTable extends GroupedTableHandler {
|
||||
ids = {
|
||||
lineas: 'lineas',
|
||||
promotions: 'linea_promociones'
|
||||
}
|
||||
constructor(commission) {
|
||||
super(commission)
|
||||
}
|
||||
draw({units, formatters}) {
|
||||
const table = document.getElementById(this.ids.lineas)
|
||||
const tbody = table.querySelector('tbody')
|
||||
tbody.innerHTML = ''
|
||||
const lineas = Object.groupBy(units, unit => {
|
||||
return [unit.proyecto_tipo_unidad.tipo_unidad.descripcion, unit.proyecto_tipo_unidad.nombre, unit.orientacion]
|
||||
})
|
||||
this.promotions.names = new Set()
|
||||
this.promotions.values = []
|
||||
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 promotions = this.process().prices(prices)
|
||||
this.process().promotions().names(promotions)
|
||||
this.process().promotions().values({promotions, formatters})
|
||||
|
||||
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 promotions"></td>`,
|
||||
`</tr>`
|
||||
].join("\n")
|
||||
})
|
||||
this.build().promotions(table, tbody)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@endpush
|
@ -0,0 +1,71 @@
|
||||
<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="center aligned" style="text-decoration: overline" id="tipo_promociones">Promociones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
|
||||
@push('page_scripts')
|
||||
<script>
|
||||
class TipoTable extends GroupedTableHandler {
|
||||
ids = {
|
||||
tipos: 'tipos',
|
||||
promotions: 'tipo_promociones'
|
||||
}
|
||||
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
|
||||
})
|
||||
this.promotions.names = new Set()
|
||||
this.promotions.values = []
|
||||
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 promotions = this.process().prices(prices)
|
||||
this.process().promotions().names(promotions)
|
||||
this.process().promotions().values({promotions, formatters})
|
||||
|
||||
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 promotions"></td>`,
|
||||
`</tr>`
|
||||
].join("\n")
|
||||
})
|
||||
this.build().promotions(table, tbody)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@endpush
|
@ -0,0 +1,254 @@
|
||||
<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² Interior</th>
|
||||
<th>m² Terraza</th>
|
||||
<th>m² Vendibles</th>
|
||||
<th>m² Total</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="center aligned" id="unit_promotions">Promociones</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_interior',
|
||||
'metros_terraza',
|
||||
'metros',
|
||||
'metros_total',
|
||||
'precio_base',
|
||||
'commission',
|
||||
'precio_operador',
|
||||
'UF/m²',
|
||||
'promociones',
|
||||
]
|
||||
set = {
|
||||
table: false,
|
||||
titles: false
|
||||
}
|
||||
table
|
||||
constructor(commission) {
|
||||
super(commission)
|
||||
}
|
||||
setup() {
|
||||
return {
|
||||
titles: promotions_names => {
|
||||
if (this.set.titles || promotions_names.size === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const nameArray = Array.from(promotions_names)
|
||||
|
||||
this.columns.pop()
|
||||
this.columns.push(`${nameArray[0].toLowerCase().replaceAll(' ', '_')}.amount`)
|
||||
this.columns.push(`${nameArray[0].toLowerCase().replaceAll(' ', '_')}.final`)
|
||||
|
||||
const table = document.getElementById(this.ids.units)
|
||||
const thead = table.querySelector('thead')
|
||||
const tr = thead.querySelector('tr')
|
||||
const th = tr.querySelector('th#unit_promotions')
|
||||
th.innerHTML = `${nameArray[0]}<br />Porcentaje`
|
||||
tr.insertAdjacentHTML('beforeend', `<th class="right aligned">${nameArray[0]}<br />Precio Final</th>`)
|
||||
|
||||
if (promotions_names.size > 1) {
|
||||
nameArray.slice(1).forEach(name => {
|
||||
this.columns.push(`${name.toLowerCase().replaceAll(' ', '_')}.amount`)
|
||||
this.columns.push(`${name.toLowerCase().replaceAll(' ', '_')}.final`)
|
||||
|
||||
tr.insertAdjacentHTML('beforeend', `<th class="right aligned">${name}<br />Porcentaje</th>`)
|
||||
tr.insertAdjacentHTML('beforeend', `<th class="right aligned">${name}<br />Precio Final</th>`)
|
||||
})
|
||||
}
|
||||
this.set.titles = true
|
||||
},
|
||||
table: () => {
|
||||
if (typeof this.table !== 'undefined' || this.set.table) {
|
||||
return
|
||||
}
|
||||
|
||||
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
|
||||
const exportColumns = ['tipo', 'unidad', 'tipologia', 'piso', 'orientacion', 'metros_interior', 'metros_terraza', 'metros', 'metros_total', 'precio_operador', 'promociones']
|
||||
if (typeof this.columns['promotions'] === 'undefined') {
|
||||
exportColumns.pop()
|
||||
this.columns.slice(this.columns.indexOf('UF/m²')+1).forEach(name => {
|
||||
exportColumns.push(name)
|
||||
})
|
||||
}
|
||||
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: exportColumns
|
||||
.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 (typeof data === 'string' && data.includes('UF ')) {
|
||||
return data.replace('UF ', '').replaceAll('.', '').replaceAll(',', '.')
|
||||
}
|
||||
const formatColumns = ['metros', 'metros_interior', 'metros_terraza', 'metros_total']
|
||||
if (this.set.titles) {
|
||||
this.columns.filter(column => column.includes('.amount') || column.includes('.final')).forEach(name => {
|
||||
formatColumns.push(name)
|
||||
})
|
||||
}
|
||||
if (formatColumns.map(column => this.columns.indexOf(column)).includes(columnIdx)) {
|
||||
return data.replaceAll('.', '').replaceAll(',', '.')
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
this.table = $(`#${this.ids.units}`).DataTable(dto)
|
||||
|
||||
this.set.table = true
|
||||
}
|
||||
}
|
||||
}
|
||||
draw({units, formatters}) {
|
||||
const prices = this.prices(units)
|
||||
|
||||
const promotions_names = new Set()
|
||||
const tableData = []
|
||||
units.forEach(unidad => {
|
||||
const tipo = unidad.proyecto_tipo_unidad.tipo_unidad.descripcion
|
||||
const price = prices.find(p => p.id === unidad.id)
|
||||
|
||||
let promotions = []
|
||||
price.promotions.forEach(p => {
|
||||
if (Object.hasOwn(promotions, p.name)) {
|
||||
return
|
||||
}
|
||||
promotions[p.name] = {
|
||||
name: p.name,
|
||||
type: p.type,
|
||||
amount: p.type === 1 ? 'UF ' + formatters.ufs.format(p.amount) : formatters.percent.format(p.amount),
|
||||
final: `UF ${formatters.ufs.format(p.final)}`
|
||||
}
|
||||
})
|
||||
|
||||
Object.keys(promotions).forEach(name => {
|
||||
promotions_names.add(name)
|
||||
})
|
||||
const temp = Object.values(promotions)
|
||||
|
||||
const data = [
|
||||
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.util) ?? 0,
|
||||
formatters.ufs.format(unidad.proyecto_tipo_unidad.terraza) ?? 0,
|
||||
formatters.ufs.format(unidad.proyecto_tipo_unidad.vendible) ?? 0,
|
||||
formatters.ufs.format(unidad.proyecto_tipo_unidad.superficie) ?? 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),
|
||||
''
|
||||
]
|
||||
|
||||
if (temp.length > 0) {
|
||||
data.pop()
|
||||
temp.forEach((p, i) => {
|
||||
data.push(p.amount)
|
||||
data.push(p.final)
|
||||
})
|
||||
} else {
|
||||
if (promotions_names.size > 0) {
|
||||
Array.from(promotions_names).forEach(name => {
|
||||
data.push('')
|
||||
data.push('')
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
tableData.push(data)
|
||||
})
|
||||
|
||||
this.setup().titles(promotions_names)
|
||||
this.setup().table()
|
||||
|
||||
const table = this.table
|
||||
table.clear()
|
||||
|
||||
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
|
@ -150,6 +150,8 @@
|
||||
</div>
|
||||
@endsection
|
||||
|
||||
@include('layout.body.scripts.rut')
|
||||
|
||||
@push('page_scripts')
|
||||
<script type="text/javascript">
|
||||
const regiones = [
|
||||
@ -158,7 +160,7 @@
|
||||
@endforeach
|
||||
]
|
||||
|
||||
class Rut {
|
||||
class RutHandler {
|
||||
ids
|
||||
patterns
|
||||
valid
|
||||
@ -222,7 +224,7 @@
|
||||
if (!this.is().like(rut) || (not_suspicious && this.is().suspicious(rut))) {
|
||||
return false
|
||||
}
|
||||
return this.get().verifier(rut).toLowerCase() === this.calculate().verifier(this.get().digits(rut))
|
||||
return Rut.validar(this.get().digits(rut), this.get().verifier(rut))
|
||||
}
|
||||
verify(event) {
|
||||
this.alert().valid()
|
||||
@ -407,7 +409,7 @@
|
||||
return lines.join("\n")
|
||||
}
|
||||
activate() {
|
||||
new Rut({id: '#rut', alert_id: '#alert_rut', valid: this.valid})
|
||||
new RutHandler({id: '#rut', alert_id: '#alert_rut', valid: this.valid})
|
||||
const comuna = new Comuna('#comuna')
|
||||
new Region({id: '#region', comuna})
|
||||
}
|
||||
@ -469,7 +471,7 @@
|
||||
return [lines.join("\n"), this.persona.draw()].join("\n")
|
||||
}
|
||||
activate() {
|
||||
new Rut({id: '#rut_sociedad', alert_id: '#alert_rut_sociedad'})
|
||||
new RutHandler({id: '#rut_sociedad', alert_id: '#alert_rut_sociedad'})
|
||||
const comuna = new Comuna('#comuna_sociedad')
|
||||
new Region({id: '#region_sociedad', comuna})
|
||||
this.persona.activate()
|
||||
@ -542,7 +544,7 @@
|
||||
}
|
||||
activate() {
|
||||
this.persona.activate()
|
||||
new Rut({id: '#rut_otro', alert_id: '#alert_rut_otro'})
|
||||
new RutHandler({id: '#rut_otro', alert_id: '#alert_rut_otro'})
|
||||
const comuna = new Comuna('#comuna_otro')
|
||||
new Region({id: '#region_otro', comuna})
|
||||
}
|
||||
@ -783,7 +785,9 @@
|
||||
}
|
||||
|
||||
$(document).ready(() => {
|
||||
$('#fecha_venta_calendar').calendar(calendar_date_options)
|
||||
const cdo = structuredClone(calendar_date_options)
|
||||
cdo['maxDate'] = new Date()
|
||||
$('#fecha_venta_calendar').calendar(cdo)
|
||||
new Propietario({id: '#propietario', id_tipo: 'persona_propietario', id_cantidad: 'cantidad_propietario'})
|
||||
new Proyecto({unidades_id: '#unidades', proyecto_id: '#proyecto'})
|
||||
|
||||
|
@ -52,8 +52,12 @@
|
||||
draw(formatter, dateFormatter) {
|
||||
const tipo = this.estado.tipo_estado_venta.descripcion
|
||||
const date = new Date(this.fecha)
|
||||
let unidad = this.propiedad.unidades[0]
|
||||
if (this.propiedad.departamentos.length > 0) {
|
||||
unidad = this.propiedad.departamentos[0]
|
||||
}
|
||||
return $('<tr></tr>').append(
|
||||
$('<td></td>').attr('data-order', this.propiedad.departamentos[0].descripcion).append(
|
||||
$('<td></td>').attr('data-order', unidad.descripcion).append(
|
||||
$('<a></a>').attr('href', '{{$urls->base}}/venta/' + this.id).html(this.propiedad.summary)
|
||||
)
|
||||
).append(
|
||||
@ -63,9 +67,9 @@
|
||||
).append(
|
||||
$('<td></td>').html(formatter.format(this.valor) + ' UF')
|
||||
).append(
|
||||
$('<td></td>').html(this.propiedad.departamentos[0].proyecto_tipo_unidad.abreviacion + ' (' + formatter.format(this.propiedad.departamentos[0].proyecto_tipo_unidad.vendible) + ' m²)')
|
||||
$('<td></td>').html(unidad.proyecto_tipo_unidad.abreviacion + ' (' + formatter.format(unidad.proyecto_tipo_unidad.vendible) + ' m²)')
|
||||
).append(
|
||||
$('<td></td>').html(formatter.format(this.valor / this.propiedad.departamentos[0].proyecto_tipo_unidad.vendible) + ' UF/m²')
|
||||
$('<td></td>').html(formatter.format(this.valor / unidad.proyecto_tipo_unidad.vendible) + ' UF/m²')
|
||||
).append(
|
||||
$('<td></td>').attr('data-order', this.fecha).html(dateFormatter.format(date))
|
||||
).append(
|
||||
@ -237,7 +241,12 @@
|
||||
|
||||
const tbody = $('<tbody></tbody>')
|
||||
this.data.ventas.forEach(venta => {
|
||||
tbody.append(venta.draw(this.formatters.number, this.formatters.date))
|
||||
try {
|
||||
tbody.append(venta.draw(this.formatters.number, this.formatters.date))
|
||||
} catch (error) {
|
||||
console.debug(venta)
|
||||
console.error(error)
|
||||
}
|
||||
})
|
||||
table.append(this.draw().header()).append(tbody)
|
||||
table.show()
|
||||
|
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
|
@ -33,6 +33,8 @@
|
||||
</form>
|
||||
@endsection
|
||||
|
||||
@include('layout.body.scripts.number_input')
|
||||
|
||||
@push('page_scripts')
|
||||
<script>
|
||||
$(document).ready(() => {
|
||||
@ -40,13 +42,17 @@
|
||||
fecha.calendar(calendar_date_options)
|
||||
fecha.calendar('set date', new Date({{$venta->formaPago()->bonoPie->pago->fecha->format('Y, m-1, j')}}))
|
||||
|
||||
const numberInput = new NumberInput({input: document.querySelector('input[name="valor"]'), isRational: true})
|
||||
numberInput.watch()
|
||||
|
||||
$('#add_bono').submit(submitEvent => {
|
||||
submitEvent.preventDefault()
|
||||
const url = '{{$urls->api}}/venta/{{$venta->id}}/bono_pie/edit'
|
||||
const data = new FormData()
|
||||
data.set('fecha', $('#fecha').calendar('get date').toISOString())
|
||||
data.set('valor', $('#valor').val())
|
||||
return APIClient.fetch(url, {method: 'post', body: data}).then(response => {
|
||||
const method = 'post'
|
||||
const body = new FormData()
|
||||
body.set('fecha', $('#fecha').calendar('get date').toISOString())
|
||||
body.set('valor', numberInput.currentValue)
|
||||
return APIClient.fetch(url, {method, body}).then(response => {
|
||||
if (response.ok) {
|
||||
return response.json()
|
||||
}
|
||||
|
@ -61,6 +61,9 @@
|
||||
<tbody>@php
|
||||
$now = new DateTimeImmutable();
|
||||
$uf_venta = $venta->uf === 0.0 ? $UF->get($venta->currentEstado()->fecha) : $venta->uf;
|
||||
if ($uf_venta === 0.0) {
|
||||
$uf_venta = $UF->get();
|
||||
}
|
||||
@endphp
|
||||
@foreach ($venta->formaPago()->pie->cuotas() as $cuota)
|
||||
<tr data-pago="{{$cuota->pago->id}}"
|
||||
|
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
|
@ -63,6 +63,8 @@ Editar Propietario
|
||||
</div>
|
||||
@endsection
|
||||
|
||||
@include('layout.body.scripts.rut')
|
||||
|
||||
@push('page_scripts')
|
||||
<script type="text/javascript">
|
||||
class Propietario {
|
||||
@ -90,7 +92,7 @@ Editar Propietario
|
||||
return {
|
||||
rut: rut => {
|
||||
this.props.rut = rut
|
||||
this.update().digito(Rut.digito(this.props.rut))
|
||||
this.update().digito(Rut.digitoVerificador(this.props.rut))
|
||||
},
|
||||
digito: digito => {
|
||||
this.props.digito = digito
|
||||
@ -187,7 +189,7 @@ Editar Propietario
|
||||
return
|
||||
}
|
||||
if ('rut' in data) {
|
||||
data['dv'] = Rut.digito(data['rut'])
|
||||
data['dv'] = Rut.digitoVerificador(data['rut'])
|
||||
}
|
||||
return fetchAPI(uri,
|
||||
{method: 'put', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)}
|
||||
@ -360,22 +362,7 @@ Editar Propietario
|
||||
}
|
||||
}
|
||||
}
|
||||
class Rut {
|
||||
static format(rut) {
|
||||
return Intl.NumberFormat('es-CL', {maximumFractionDigits: 0}).format(rut)
|
||||
}
|
||||
static digito(rut) {
|
||||
const cleanRut = rut.replace(/\D/g, ''); // Removes non-digit characters more efficiently
|
||||
let sum = 0;
|
||||
const factors = [2, 3, 4, 5, 6, 7, 2, 3, 4, 5];
|
||||
for (let i = 0; i < cleanRut.length; i++) {
|
||||
const digit = parseInt(cleanRut[cleanRut.length - 1 - i], 10);
|
||||
sum += digit * factors[i % factors.length];
|
||||
}
|
||||
const dv = 11 - (sum % 11);
|
||||
return dv === 10 ? 'K' : dv === 11 ? '0' : dv.toString();
|
||||
}
|
||||
}
|
||||
|
||||
const propietario = {
|
||||
props: {
|
||||
ids: {},
|
||||
|
@ -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
|
||||
|
@ -22,8 +22,12 @@ return [
|
||||
$ine = new Incoviba\Service\Money\Ine(new GuzzleHttp\Client([
|
||||
'base_uri' => 'https://api-calculadora.ine.cl/ServiciosCalculadoraVariacion'
|
||||
]));
|
||||
$sii = new Incoviba\Service\Money\SII(new GuzzleHttp\Client([
|
||||
'base_uri' => 'https://www.sii.cl/valores_y_fechas/'
|
||||
]), $container->get(Incoviba\Repository\UF::class));
|
||||
return (new Incoviba\Service\Money($container->get(Psr\Log\LoggerInterface::class)))
|
||||
->register('uf', $mindicador)
|
||||
->register('uf', $sii)
|
||||
->register('usd', $mindicador)
|
||||
->register('ipc', $ine);
|
||||
},
|
||||
|
@ -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;
|
||||
@ -93,7 +94,7 @@ class Ventas extends Controller
|
||||
$venta = $service->getById($venta_id);
|
||||
$output['ventas'] []= $venta;
|
||||
$this->saveRedis($redisService, $redisKey, $venta);
|
||||
} catch (EmptyResult $exception) {
|
||||
} catch (Read $exception) {
|
||||
$this->logger->notice($exception);
|
||||
}
|
||||
}
|
||||
@ -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);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user