Compare commits
334 Commits
develop
...
dc0ae2746b
Author | SHA1 | Date | |
---|---|---|---|
dc0ae2746b | |||
eb402b1b71 | |||
c5188a1feb | |||
1c3052219c | |||
9e8a388653 | |||
cbee830f7a | |||
d5b8c7f877 | |||
b668844fea | |||
f2169c9536 | |||
48bcb33bad | |||
92ae0b4ac2 | |||
44540d0dc3 | |||
d9a2f63691 | |||
b10accf602 | |||
981858f251 | |||
8c0bd450ef | |||
8996765cb4 | |||
ec2451cb69 | |||
37d30d2aec | |||
afb6e2526f | |||
a9b6f2a87b | |||
9aeb6906f6 | |||
879d365baf | |||
1d03b262ae | |||
2c175c8171 | |||
a750bdbfaa | |||
7f6d0232c0 | |||
37cff67a1c | |||
bc3d739af9 | |||
46efbb57c1 | |||
d71333b334 | |||
688b500f1e | |||
d4b1a66a9e | |||
e796d91d95 | |||
2a442417ce | |||
3c161ed4e9 | |||
3c8822e531 | |||
b3b91d3f8f | |||
6e34a76a3f | |||
ed29dfb984 | |||
7f37dc76e3 | |||
a62293e509 | |||
fbfc2cb8ae | |||
02665ac6bd | |||
300d966f3f | |||
27031035ed | |||
18fc9a76fd | |||
cb6fa73a21 | |||
8796762cfe | |||
99c9952c93 | |||
9895fd6a70 | |||
c1149d89be | |||
7d8e2249de | |||
a54586e870 | |||
734f258382 | |||
f728ed0b55 | |||
6144accb8e | |||
f399eb8d47 | |||
b4159d1417 | |||
2a792a947d | |||
25710d616a | |||
3197802264 | |||
6c53127c2f | |||
b7391a77d3 | |||
5b499aee75 | |||
4505531c5f | |||
3f8adc753c | |||
ace205798f | |||
6e0e1fc75e | |||
026474c63c | |||
f32204df97 | |||
2852816eae | |||
892cdf324f | |||
a9a10e012d | |||
b7089f7a1c | |||
aed26cfcd8 | |||
896dded6eb | |||
3b03c4b64b | |||
f34ed03b84 | |||
ce75ec1548 | |||
312baa34f6 | |||
b7c5e4ebc3 | |||
105179b4ed | |||
16cd29635d | |||
2bdb2a0ed0 | |||
8ce7d2570d | |||
8ba54fd3ad | |||
f47f86dd2b | |||
8ca68bf7e8 | |||
8965354528 | |||
8d32aecd09 | |||
c8f79e076e | |||
9e0d604d79 | |||
331d004040 | |||
03317b3aa5 | |||
e33edc4d7b | |||
bb459a2ff5 | |||
5e2d2e861f | |||
e9b2fe9963 | |||
2f481ef8a9 | |||
386fe452af | |||
91ad1e39f8 | |||
a3a5b58cfb | |||
1d77d65af2 | |||
0f0c81e283 | |||
ac278ca690 | |||
97d34f9ad6 | |||
134588c96d | |||
8b6516241d | |||
d6e60efcaf | |||
3e937ab748 | |||
fa6881d0a9 | |||
f07c1f1cbd | |||
148d08089d | |||
45b6ee710e | |||
c84277fdc4 | |||
c0024a4a63 | |||
308a84a448 | |||
91c74bf113 | |||
024a6eae54 | |||
d536342425 | |||
e7f3b33850 | |||
c47d94d475 | |||
ee74fc7588 | |||
5ac324de6a | |||
dfb0ff7aea | |||
6d1a1c914a | |||
b45d03aa7e | |||
4e0b611bcf | |||
20ea5d021d | |||
32dc24a783 | |||
95a6aa96e9 | |||
f14cdd2730 | |||
3006adb0f7 | |||
d22480dcb8 | |||
425b85e40d | |||
2c21e48562 | |||
8d3ce99be7 | |||
35386724b3 | |||
1597657f0e | |||
c6bbaf3404 | |||
9e2d7277b0 | |||
abe37227ce | |||
32130f0bc2 | |||
d78bdaa7f5 | |||
1266c3859d | |||
c5466b2c4d | |||
6d8e8a9068 | |||
4d5b657b92 | |||
4ca1616dfc | |||
fb7177fd65 | |||
1486d6cf38 | |||
8b2de31e02 | |||
61324f159b | |||
c95e74d574 | |||
59ecb6cc79 | |||
db84187461 | |||
c2f98c8b0d | |||
8d73987ac3 | |||
400b2754bf | |||
418becaeda | |||
679b401101 | |||
26b6862955 | |||
e239669839 | |||
adc0e52c1e | |||
d1905194bd | |||
a5c1d60819 | |||
5ad4fc4038 | |||
ca5354a3ee | |||
c1ebac6c0c | |||
f742c7ddd0 | |||
5d5f9866bb | |||
0866292d84 | |||
e02ed4684f | |||
8be5f94b7c | |||
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 |
@ -2,15 +2,15 @@ FROM php:8.4-cli
|
||||
|
||||
ENV TZ "${TZ}"
|
||||
ENV APP_NAME "${APP_NAME}"
|
||||
ENV API_URL "${API_URL}"
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cron rsyslog nano beanstalkd \
|
||||
&& rm -r /var/lib/apt/lists/*
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cron rsyslog nano && rm -r /var/lib/apt/lists/*
|
||||
|
||||
RUN pecl install xdebug-3.4.2 \
|
||||
&& docker-php-ext-enable xdebug \
|
||||
&& echo $TZ > /etc/timezone
|
||||
|
||||
COPY --chmod=550 ./cli/start_command /root/start_command
|
||||
COPY --chmod=550 ./cli/entrypoint /root/entrypoint
|
||||
|
||||
COPY ./php-errors.ini /usr/local/etc/php/conf.d/docker-php-errors.ini
|
||||
COPY ./php-timezone.ini /usr/local/etc/php/conf.d/docker-php-timezone.ini
|
||||
@ -19,4 +19,4 @@ WORKDIR /code/bin
|
||||
|
||||
COPY --chmod=644 ./cli/crontab /var/spool/cron/crontabs/root
|
||||
|
||||
CMD [ "/root/start_command" ]
|
||||
CMD [ "/root/entrypoint" ]
|
||||
|
@ -3,7 +3,7 @@ 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 libxml2-dev beanstalkd \
|
||||
libpng-dev unzip tzdata libxml2-dev \
|
||||
&& rm -r /var/lib/apt/lists/* \
|
||||
&& docker-php-ext-install pdo pdo_mysql zip intl gd bcmath dom \
|
||||
&& pecl install xdebug-3.4.2 \
|
||||
|
0
app/bin/console
Executable file → Normal file
0
app/bin/console
Executable file → Normal file
0
app/bin/integration_tests
Executable file → Normal file
0
app/bin/integration_tests
Executable file → Normal file
0
app/bin/performance_tests
Executable file → Normal file
0
app/bin/performance_tests
Executable file → Normal file
0
app/bin/unit_tests
Executable file → Normal file
0
app/bin/unit_tests
Executable file → Normal file
@ -6,7 +6,7 @@ use Psr\Log\LoggerInterface;
|
||||
|
||||
abstract class LoggerEnabled implements LoggerAwareInterface
|
||||
{
|
||||
public LoggerInterface $logger;
|
||||
protected LoggerInterface $logger;
|
||||
public function setLogger(LoggerInterface $logger): void
|
||||
{
|
||||
$this->logger = $logger;
|
||||
|
@ -1,10 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Common\Ideal\Service;
|
||||
|
||||
use Incoviba\Common\Define;
|
||||
use Incoviba\Common\Ideal;
|
||||
|
||||
abstract class Repository extends Ideal\Service
|
||||
{
|
||||
abstract public function getRepository(): Define\Repository;
|
||||
}
|
@ -64,10 +64,10 @@ class Select extends Ideal\Query implements Define\Query\Select
|
||||
public function having(array|string $conditions): Select
|
||||
{
|
||||
if (is_string($conditions)) {
|
||||
return $this->addHaving($conditions);
|
||||
return $this->addCondition($conditions);
|
||||
}
|
||||
foreach ($conditions as $condition) {
|
||||
$this->addHaving($condition);
|
||||
$this->addCondition($condition);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
@ -1,13 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Common\Implement\Exception;
|
||||
|
||||
use Throwable;
|
||||
use Exception;
|
||||
|
||||
class HttpException extends Exception
|
||||
{
|
||||
public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
|
||||
{
|
||||
parent::__construct($message, $code, $previous);
|
||||
}
|
||||
}
|
@ -1,7 +1,6 @@
|
||||
<?php
|
||||
namespace Incoviba\Common\Implement\Log\Formatter;
|
||||
|
||||
use Throwable;
|
||||
use Monolog\Formatter\JsonFormatter;
|
||||
use Monolog\LogRecord;
|
||||
|
||||
@ -14,35 +13,7 @@ class PDO extends JsonFormatter
|
||||
|
||||
public function format(LogRecord $record): string
|
||||
{
|
||||
if (is_a($record->message, Throwable::class)) {
|
||||
$exception = $record->message;
|
||||
$message = $this->normalizeException($exception);
|
||||
$context = $record->context;
|
||||
$context['exception'] = $exception;
|
||||
if ($exception->getPrevious()) {
|
||||
$context['previous'] = $this->walkException($exception);
|
||||
}
|
||||
$new_record = new LogRecord(
|
||||
$record->datetime,
|
||||
$record->channel,
|
||||
$record->level,
|
||||
json_encode($message),
|
||||
$context,
|
||||
$record->extra
|
||||
);
|
||||
$record = $new_record;
|
||||
}
|
||||
$normalized = $this->normalize($record, $this->maxNormalizeDepth);
|
||||
return $normalized['message'];
|
||||
}
|
||||
|
||||
protected function walkException(Throwable $exception, int $depth = 0): array
|
||||
{
|
||||
$output = [];
|
||||
$currentDepth = $depth;
|
||||
while ($previous = $exception->getPrevious() and $currentDepth < $this->maxNormalizeDepth) {
|
||||
$output []= $this->normalizeException($previous);
|
||||
}
|
||||
return $output;
|
||||
}
|
||||
}
|
||||
|
@ -1,139 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Common\Implement\Log\Processor;
|
||||
|
||||
use DateInvalidTimeZoneException;
|
||||
use DateMalformedStringException;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use Psr\Container\ContainerExceptionInterface;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Container\NotFoundExceptionInterface;
|
||||
use Monolog\Formatter;
|
||||
use Monolog\Handler;
|
||||
use Monolog\Level;
|
||||
use Predis;
|
||||
use Incoviba;
|
||||
use Throwable;
|
||||
|
||||
class ArrayBuilder
|
||||
{
|
||||
public function __construct(protected ContainerInterface $container) {}
|
||||
|
||||
public function build(array $data): array
|
||||
{
|
||||
$handlers = [];
|
||||
foreach ($data as $handlerData) {
|
||||
if (in_array($handlerData['handler'], [Handler\StreamHandler::class, Handler\RotatingFileHandler::class,])) {
|
||||
$params = [
|
||||
"/logs/{$handlerData['filename']}",
|
||||
];
|
||||
if ($handlerData['handler'] === Handler\RotatingFileHandler::class) {
|
||||
$params []= 10;
|
||||
}
|
||||
try {
|
||||
$formatter = Formatter\LineFormatter::class;
|
||||
if (array_key_exists('formatter', $handlerData)) {
|
||||
$formatter = $handlerData['formatter'];
|
||||
}
|
||||
$handler = new $handlerData['handler'](...$params)
|
||||
->setFormatter($this->container->get($formatter));
|
||||
} catch (NotFoundExceptionInterface | ContainerExceptionInterface $exception) {
|
||||
$this->log($exception, ['handlerData' => $handlerData]);
|
||||
continue;
|
||||
}
|
||||
} elseif ($handlerData['handler'] === Incoviba\Common\Implement\Log\Handler\MySQL::class) {
|
||||
try {
|
||||
$params = [
|
||||
$this->container->get(Incoviba\Common\Define\Connection::class)
|
||||
];
|
||||
$formatter = Incoviba\Common\Implement\Log\Formatter\PDO::class;
|
||||
if (array_key_exists('formatter', $handlerData)) {
|
||||
$formatter = $handlerData['formatter'];
|
||||
}
|
||||
$handler = new $handlerData['handler'](...$params)
|
||||
->setFormatter($this->container->get($formatter));
|
||||
} catch (NotFoundExceptionInterface | ContainerExceptionInterface $exception) {
|
||||
$this->log($exception, ['handlerData' => $handlerData]);
|
||||
continue;
|
||||
}
|
||||
} elseif ($handlerData['handler'] === Handler\RedisHandler::class) {
|
||||
try {
|
||||
$params = [
|
||||
$this->container->get(Predis\ClientInterface::class),
|
||||
"logs:{$handlerData['name']}"
|
||||
];
|
||||
} catch (NotFoundExceptionInterface | ContainerExceptionInterface $exception) {
|
||||
$this->log($exception, ['handlerData' => $handlerData]);
|
||||
continue;
|
||||
}
|
||||
$handler = new $handlerData['handler'](...$params);
|
||||
}
|
||||
if (!isset($handler)) {
|
||||
$this->log("Invalid handler", ['handlerData' => $handlerData]);
|
||||
continue;
|
||||
}
|
||||
$params = [
|
||||
$handler,
|
||||
];
|
||||
if (is_array($handlerData['levels'])) {
|
||||
foreach ($handlerData['levels'] as $level) {
|
||||
$params []= $level;
|
||||
}
|
||||
} else {
|
||||
$params []= $handlerData['levels'];
|
||||
$params []= Level::Emergency;
|
||||
}
|
||||
$params []= false;
|
||||
$handlers []= new Handler\FilterHandler(...$params);
|
||||
}
|
||||
return $handlers;
|
||||
}
|
||||
|
||||
protected function log(string|Throwable $message, array $context = []): void
|
||||
{
|
||||
try {
|
||||
$dateTime = new DateTimeImmutable('now', new DateTimeZone($_ENV['TZ'] ?? 'America/Santiago'));
|
||||
} catch (DateMalformedStringException | DateInvalidTimeZoneException $exception) {
|
||||
$dateTime = new DateTimeImmutable();
|
||||
}
|
||||
if (is_a($message, Throwable::class)) {
|
||||
$exception = $message;
|
||||
$message = $exception->getMessage();
|
||||
}
|
||||
$context = json_encode($context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
if ($context === false) {
|
||||
$context = '[]';
|
||||
}
|
||||
$extra = [];
|
||||
$extra['from'] = __FILE__;
|
||||
if (isset($exception)) {
|
||||
$extra['file'] = $exception->getFile();
|
||||
$extra['line'] = $exception->getLine();
|
||||
$extra['trace'] = $exception->getTrace();
|
||||
}
|
||||
$extra = json_encode($extra, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
$code = 0;
|
||||
if (isset($exception)) {
|
||||
$code = $exception->getCode();
|
||||
}
|
||||
if ($extra === false) {
|
||||
$extra = '[]';
|
||||
}
|
||||
$output = "[{$dateTime->format('Y-m-d H:i:s P')}] [{$code}] {$message} {$context} {$extra}";
|
||||
$filename = '/logs/error.json';
|
||||
$fileContents = [];
|
||||
if (file_exists($filename)) {
|
||||
$fileContents = file_get_contents($filename);
|
||||
$fileContents = json_decode($fileContents, true);
|
||||
if ($fileContents === false) {
|
||||
$fileContents = [];
|
||||
}
|
||||
}
|
||||
$fileContents[$dateTime->getTimestamp()] = $output;
|
||||
$fileContents = json_encode($fileContents, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
if ($fileContents === false) {
|
||||
$fileContents = '[]';
|
||||
}
|
||||
file_put_contents($filename, $fileContents);
|
||||
}
|
||||
}
|
@ -8,13 +8,11 @@
|
||||
"ext-gd": "*",
|
||||
"ext-openssl": "*",
|
||||
"ext-pdo": "*",
|
||||
"ext-sockets": "*",
|
||||
"berrnd/slim-blade-view": "^1",
|
||||
"guzzlehttp/guzzle": "^7",
|
||||
"monolog/monolog": "^3",
|
||||
"nyholm/psr7": "^1",
|
||||
"nyholm/psr7-server": "^1",
|
||||
"pda/pheanstalk": "^7.0",
|
||||
"php-di/php-di": "^7",
|
||||
"php-di/slim-bridge": "^3",
|
||||
"phpoffice/phpspreadsheet": "^3",
|
||||
|
496
app/fcgi.conf
496
app/fcgi.conf
@ -1,496 +0,0 @@
|
||||
; Start a new pool named 'www'.
|
||||
; the variable $pool can be used in any directive and will be replaced by the
|
||||
; pool name ('www' here)
|
||||
[fcgi]
|
||||
|
||||
; Per pool prefix
|
||||
; It only applies on the following directives:
|
||||
; - 'access.log'
|
||||
; - 'slowlog'
|
||||
; - 'listen' (unixsocket)
|
||||
; - 'chroot'
|
||||
; - 'chdir'
|
||||
; - 'php_values'
|
||||
; - 'php_admin_values'
|
||||
; When not set, the global prefix (or NONE) applies instead.
|
||||
; Note: This directive can also be relative to the global prefix.
|
||||
; Default Value: none
|
||||
;prefix = /path/to/pools/$pool
|
||||
|
||||
; Unix user/group of the child processes. This can be used only if the master
|
||||
; process running user is root. It is set after the child process is created.
|
||||
; The user and group can be specified either by their name or by their numeric
|
||||
; IDs.
|
||||
; Note: If the user is root, the executable needs to be started with
|
||||
; --allow-to-run-as-root option to work.
|
||||
; Default Values: The user is set to master process running user by default.
|
||||
; If the group is not set, the user's group is used.
|
||||
user = www-data
|
||||
group = www-data
|
||||
|
||||
; The address on which to accept FastCGI requests.
|
||||
; Valid syntaxes are:
|
||||
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on
|
||||
; a specific port;
|
||||
; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
|
||||
; a specific port;
|
||||
; 'port' - to listen on a TCP socket to all addresses
|
||||
; (IPv6 and IPv4-mapped) on a specific port;
|
||||
; '/path/to/unix/socket' - to listen on a unix socket.
|
||||
; Note: This value is mandatory.
|
||||
;listen = 127.0.0.1:9000
|
||||
listen = 9090
|
||||
|
||||
; Set listen(2) backlog.
|
||||
; Default Value: 511 (-1 on Linux, FreeBSD and OpenBSD)
|
||||
;listen.backlog = 511
|
||||
|
||||
; Set permissions for unix socket, if one is used. In Linux, read/write
|
||||
; permissions must be set in order to allow connections from a web server. Many
|
||||
; BSD-derived systems allow connections regardless of permissions. The owner
|
||||
; and group can be specified either by name or by their numeric IDs.
|
||||
; Default Values: Owner is set to the master process running user. If the group
|
||||
; is not set, the owner's group is used. Mode is set to 0660.
|
||||
;listen.owner = www-data
|
||||
;listen.group = www-data
|
||||
;listen.mode = 0660
|
||||
|
||||
; When POSIX Access Control Lists are supported you can set them using
|
||||
; these options, value is a comma separated list of user/group names.
|
||||
; When set, listen.owner and listen.group are ignored
|
||||
;listen.acl_users =
|
||||
;listen.acl_groups =
|
||||
|
||||
; List of addresses (IPv4/IPv6) of FastCGI clients which are allowed to connect.
|
||||
; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
|
||||
; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
|
||||
; must be separated by a comma. If this value is left blank, connections will be
|
||||
; accepted from any ip address.
|
||||
; Default Value: any
|
||||
;listen.allowed_clients = 127.0.0.1
|
||||
|
||||
; Set the associated the route table (FIB). FreeBSD only
|
||||
; Default Value: -1
|
||||
;listen.setfib = 1
|
||||
|
||||
; Specify the nice(2) priority to apply to the pool processes (only if set)
|
||||
; The value can vary from -19 (highest priority) to 20 (lower priority)
|
||||
; Note: - It will only work if the FPM master process is launched as root
|
||||
; - The pool processes will inherit the master process priority
|
||||
; unless it specified otherwise
|
||||
; Default Value: no set
|
||||
; process.priority = -19
|
||||
|
||||
; Set the process dumpable flag (PR_SET_DUMPABLE prctl for Linux or
|
||||
; PROC_TRACE_CTL procctl for FreeBSD) even if the process user
|
||||
; or group is different than the master process user. It allows to create process
|
||||
; core dump and ptrace the process for the pool user.
|
||||
; Default Value: no
|
||||
; process.dumpable = yes
|
||||
|
||||
; Choose how the process manager will control the number of child processes.
|
||||
; Possible Values:
|
||||
; static - a fixed number (pm.max_children) of child processes;
|
||||
; dynamic - the number of child processes are set dynamically based on the
|
||||
; following directives. With this process management, there will be
|
||||
; always at least 1 children.
|
||||
; pm.max_children - the maximum number of children that can
|
||||
; be alive at the same time.
|
||||
; pm.start_servers - the number of children created on startup.
|
||||
; pm.min_spare_servers - the minimum number of children in 'idle'
|
||||
; state (waiting to process). If the number
|
||||
; of 'idle' processes is less than this
|
||||
; number then some children will be created.
|
||||
; pm.max_spare_servers - the maximum number of children in 'idle'
|
||||
; state (waiting to process). If the number
|
||||
; of 'idle' processes is greater than this
|
||||
; number then some children will be killed.
|
||||
; pm.max_spawn_rate - the maximum number of rate to spawn child
|
||||
; processes at once.
|
||||
; ondemand - no children are created at startup. Children will be forked when
|
||||
; new requests will connect. The following parameter are used:
|
||||
; pm.max_children - the maximum number of children that
|
||||
; can be alive at the same time.
|
||||
; pm.process_idle_timeout - The number of seconds after which
|
||||
; an idle process will be killed.
|
||||
; Note: This value is mandatory.
|
||||
pm = ondemand
|
||||
|
||||
; The number of child processes to be created when pm is set to 'static' and the
|
||||
; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
|
||||
; This value sets the limit on the number of simultaneous requests that will be
|
||||
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
|
||||
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
|
||||
; CGI. The below defaults are based on a server without much resources. Don't
|
||||
; forget to tweak pm.* to fit your needs.
|
||||
; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand'
|
||||
; Note: This value is mandatory.
|
||||
pm.max_children = 2
|
||||
|
||||
; The number of child processes created on startup.
|
||||
; Note: Used only when pm is set to 'dynamic'
|
||||
; Default Value: (min_spare_servers + max_spare_servers) / 2
|
||||
;pm.start_servers = 2
|
||||
|
||||
; The desired minimum number of idle server processes.
|
||||
; Note: Used only when pm is set to 'dynamic'
|
||||
; Note: Mandatory when pm is set to 'dynamic'
|
||||
;pm.min_spare_servers = 1
|
||||
|
||||
; The desired maximum number of idle server processes.
|
||||
; Note: Used only when pm is set to 'dynamic'
|
||||
; Note: Mandatory when pm is set to 'dynamic'
|
||||
;pm.max_spare_servers = 3
|
||||
|
||||
; The number of rate to spawn child processes at once.
|
||||
; Note: Used only when pm is set to 'dynamic'
|
||||
; Note: Mandatory when pm is set to 'dynamic'
|
||||
; Default Value: 32
|
||||
;pm.max_spawn_rate = 32
|
||||
|
||||
; The number of seconds after which an idle process will be killed.
|
||||
; Note: Used only when pm is set to 'ondemand'
|
||||
; Default Value: 10s
|
||||
;pm.process_idle_timeout = 10s;
|
||||
pm.process_idle_timeout = 10s
|
||||
|
||||
; The number of requests each child process should execute before respawning.
|
||||
; This can be useful to work around memory leaks in 3rd party libraries. For
|
||||
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
|
||||
; Default Value: 0
|
||||
;pm.max_requests = 500
|
||||
|
||||
; The URI to view the FPM status page. If this value is not set, no URI will be
|
||||
; recognized as a status page. It shows the following information:
|
||||
; pool - the name of the pool;
|
||||
; process manager - static, dynamic or ondemand;
|
||||
; start time - the date and time FPM has started;
|
||||
; start since - number of seconds since FPM has started;
|
||||
; accepted conn - the number of request accepted by the pool;
|
||||
; listen queue - the number of request in the queue of pending
|
||||
; connections (see backlog in listen(2));
|
||||
; max listen queue - the maximum number of requests in the queue
|
||||
; of pending connections since FPM has started;
|
||||
; listen queue len - the size of the socket queue of pending connections;
|
||||
; idle processes - the number of idle processes;
|
||||
; active processes - the number of active processes;
|
||||
; total processes - the number of idle + active processes;
|
||||
; max active processes - the maximum number of active processes since FPM
|
||||
; has started;
|
||||
; max children reached - number of times, the process limit has been reached,
|
||||
; when pm tries to start more children (works only for
|
||||
; pm 'dynamic' and 'ondemand');
|
||||
; Value are updated in real time.
|
||||
; Example output:
|
||||
; pool: www
|
||||
; process manager: static
|
||||
; start time: 01/Jul/2011:17:53:49 +0200
|
||||
; start since: 62636
|
||||
; accepted conn: 190460
|
||||
; listen queue: 0
|
||||
; max listen queue: 1
|
||||
; listen queue len: 42
|
||||
; idle processes: 4
|
||||
; active processes: 11
|
||||
; total processes: 15
|
||||
; max active processes: 12
|
||||
; max children reached: 0
|
||||
;
|
||||
; By default the status page output is formatted as text/plain. Passing either
|
||||
; 'html', 'xml' or 'json' in the query string will return the corresponding
|
||||
; output syntax. Example:
|
||||
; http://www.foo.bar/status
|
||||
; http://www.foo.bar/status?json
|
||||
; http://www.foo.bar/status?html
|
||||
; http://www.foo.bar/status?xml
|
||||
;
|
||||
; By default the status page only outputs short status. Passing 'full' in the
|
||||
; query string will also return status for each pool process.
|
||||
; Example:
|
||||
; http://www.foo.bar/status?full
|
||||
; http://www.foo.bar/status?json&full
|
||||
; http://www.foo.bar/status?html&full
|
||||
; http://www.foo.bar/status?xml&full
|
||||
; The Full status returns for each process:
|
||||
; pid - the PID of the process;
|
||||
; state - the state of the process (Idle, Running, ...);
|
||||
; start time - the date and time the process has started;
|
||||
; start since - the number of seconds since the process has started;
|
||||
; requests - the number of requests the process has served;
|
||||
; request duration - the duration in µs of the requests;
|
||||
; request method - the request method (GET, POST, ...);
|
||||
; request URI - the request URI with the query string;
|
||||
; content length - the content length of the request (only with POST);
|
||||
; user - the user (PHP_AUTH_USER) (or '-' if not set);
|
||||
; script - the main script called (or '-' if not set);
|
||||
; last request cpu - the %cpu the last request consumed
|
||||
; it's always 0 if the process is not in Idle state
|
||||
; because CPU calculation is done when the request
|
||||
; processing has terminated;
|
||||
; last request memory - the max amount of memory the last request consumed
|
||||
; it's always 0 if the process is not in Idle state
|
||||
; because memory calculation is done when the request
|
||||
; processing has terminated;
|
||||
; If the process is in Idle state, then information is related to the
|
||||
; last request the process has served. Otherwise information is related to
|
||||
; the current request being served.
|
||||
; Example output:
|
||||
; ************************
|
||||
; pid: 31330
|
||||
; state: Running
|
||||
; start time: 01/Jul/2011:17:53:49 +0200
|
||||
; start since: 63087
|
||||
; requests: 12808
|
||||
; request duration: 1250261
|
||||
; request method: GET
|
||||
; request URI: /test_mem.php?N=10000
|
||||
; content length: 0
|
||||
; user: -
|
||||
; script: /home/fat/web/docs/php/test_mem.php
|
||||
; last request cpu: 0.00
|
||||
; last request memory: 0
|
||||
;
|
||||
; Note: There is a real-time FPM status monitoring sample web page available
|
||||
; It's available in: /usr/local/share/php/fpm/status.html
|
||||
;
|
||||
; Note: The value must start with a leading slash (/). The value can be
|
||||
; anything, but it may not be a good idea to use the .php extension or it
|
||||
; may conflict with a real PHP file.
|
||||
; Default Value: not set
|
||||
;pm.status_path = /status
|
||||
|
||||
; The address on which to accept FastCGI status request. This creates a new
|
||||
; invisible pool that can handle requests independently. This is useful
|
||||
; if the main pool is busy with long running requests because it is still possible
|
||||
; to get the status before finishing the long running requests.
|
||||
;
|
||||
; Valid syntaxes are:
|
||||
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on
|
||||
; a specific port;
|
||||
; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
|
||||
; a specific port;
|
||||
; 'port' - to listen on a TCP socket to all addresses
|
||||
; (IPv6 and IPv4-mapped) on a specific port;
|
||||
; '/path/to/unix/socket' - to listen on a unix socket.
|
||||
; Default Value: value of the listen option
|
||||
;pm.status_listen = 127.0.0.1:9001
|
||||
|
||||
; The ping URI to call the monitoring page of FPM. If this value is not set, no
|
||||
; URI will be recognized as a ping page. This could be used to test from outside
|
||||
; that FPM is alive and responding, or to
|
||||
; - create a graph of FPM availability (rrd or such);
|
||||
; - remove a server from a group if it is not responding (load balancing);
|
||||
; - trigger alerts for the operating team (24/7).
|
||||
; Note: The value must start with a leading slash (/). The value can be
|
||||
; anything, but it may not be a good idea to use the .php extension or it
|
||||
; may conflict with a real PHP file.
|
||||
; Default Value: not set
|
||||
;ping.path = /ping
|
||||
|
||||
; This directive may be used to customize the response of a ping request. The
|
||||
; response is formatted as text/plain with a 200 response code.
|
||||
; Default Value: pong
|
||||
;ping.response = pong
|
||||
|
||||
; The access log file
|
||||
; Default: not set
|
||||
;access.log = log/$pool.access.log
|
||||
access.log = /proc/self/fd/2
|
||||
|
||||
; The access log format.
|
||||
; The following syntax is allowed
|
||||
; %%: the '%' character
|
||||
; %C: %CPU used by the request
|
||||
; it can accept the following format:
|
||||
; - %{user}C for user CPU only
|
||||
; - %{system}C for system CPU only
|
||||
; - %{total}C for user + system CPU (default)
|
||||
; %d: time taken to serve the request
|
||||
; it can accept the following format:
|
||||
; - %{seconds}d (default)
|
||||
; - %{milliseconds}d
|
||||
; - %{milli}d
|
||||
; - %{microseconds}d
|
||||
; - %{micro}d
|
||||
; %e: an environment variable (same as $_ENV or $_SERVER)
|
||||
; it must be associated with embraces to specify the name of the env
|
||||
; variable. Some examples:
|
||||
; - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e
|
||||
; - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e
|
||||
; %f: script filename
|
||||
; %l: content-length of the request (for POST request only)
|
||||
; %m: request method
|
||||
; %M: peak of memory allocated by PHP
|
||||
; it can accept the following format:
|
||||
; - %{bytes}M (default)
|
||||
; - %{kilobytes}M
|
||||
; - %{kilo}M
|
||||
; - %{megabytes}M
|
||||
; - %{mega}M
|
||||
; %n: pool name
|
||||
; %o: output header
|
||||
; it must be associated with embraces to specify the name of the header:
|
||||
; - %{Content-Type}o
|
||||
; - %{X-Powered-By}o
|
||||
; - %{Transfert-Encoding}o
|
||||
; - ....
|
||||
; %p: PID of the child that serviced the request
|
||||
; %P: PID of the parent of the child that serviced the request
|
||||
; %q: the query string
|
||||
; %Q: the '?' character if query string exists
|
||||
; %r: the request URI (without the query string, see %q and %Q)
|
||||
; %R: remote IP address
|
||||
; %s: status (response code)
|
||||
; %t: server time the request was received
|
||||
; it can accept a strftime(3) format:
|
||||
; %d/%b/%Y:%H:%M:%S %z (default)
|
||||
; The strftime(3) format must be encapsulated in a %{<strftime_format>}t tag
|
||||
; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
|
||||
; %T: time the log has been written (the request has finished)
|
||||
; it can accept a strftime(3) format:
|
||||
; %d/%b/%Y:%H:%M:%S %z (default)
|
||||
; The strftime(3) format must be encapsulated in a %{<strftime_format>}t tag
|
||||
; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
|
||||
; %u: basic auth user if specified in Authorization header
|
||||
;
|
||||
; Default: "%R - %u %t \"%m %r\" %s"
|
||||
;access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{milli}d %{kilo}M %C%%"
|
||||
|
||||
; A list of request_uri values which should be filtered from the access log.
|
||||
;
|
||||
; As a security precaution, this setting will be ignored if:
|
||||
; - the request method is not GET or HEAD; or
|
||||
; - there is a request body; or
|
||||
; - there are query parameters; or
|
||||
; - the response code is outwith the successful range of 200 to 299
|
||||
;
|
||||
; Note: The paths are matched against the output of the access.format tag "%r".
|
||||
; On common configurations, this may look more like SCRIPT_NAME than the
|
||||
; expected pre-rewrite URI.
|
||||
;
|
||||
; Default Value: not set
|
||||
;access.suppress_path[] = /ping
|
||||
;access.suppress_path[] = /health_check.php
|
||||
|
||||
; The log file for slow requests
|
||||
; Default Value: not set
|
||||
; Note: slowlog is mandatory if request_slowlog_timeout is set
|
||||
;slowlog = log/$pool.log.slow
|
||||
|
||||
; The timeout for serving a single request after which a PHP backtrace will be
|
||||
; dumped to the 'slowlog' file. A value of '0s' means 'off'.
|
||||
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
|
||||
; Default Value: 0
|
||||
;request_slowlog_timeout = 0
|
||||
|
||||
; Depth of slow log stack trace.
|
||||
; Default Value: 20
|
||||
;request_slowlog_trace_depth = 20
|
||||
|
||||
; The timeout for serving a single request after which the worker process will
|
||||
; be killed. This option should be used when the 'max_execution_time' ini option
|
||||
; does not stop script execution for some reason. A value of '0' means 'off'.
|
||||
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
|
||||
; Default Value: 0
|
||||
;request_terminate_timeout = 0
|
||||
|
||||
; The timeout set by 'request_terminate_timeout' ini option is not engaged after
|
||||
; application calls 'fastcgi_finish_request' or when application has finished and
|
||||
; shutdown functions are being called (registered via register_shutdown_function).
|
||||
; This option will enable timeout limit to be applied unconditionally
|
||||
; even in such cases.
|
||||
; Default Value: no
|
||||
;request_terminate_timeout_track_finished = no
|
||||
|
||||
; Set open file descriptor rlimit.
|
||||
; Default Value: system defined value
|
||||
;rlimit_files = 1024
|
||||
|
||||
; Set max core size rlimit.
|
||||
; Possible Values: 'unlimited' or an integer greater or equal to 0
|
||||
; Default Value: system defined value
|
||||
;rlimit_core = 0
|
||||
|
||||
; Chroot to this directory at the start. This value must be defined as an
|
||||
; absolute path. When this value is not set, chroot is not used.
|
||||
; Note: you can prefix with '$prefix' to chroot to the pool prefix or one
|
||||
; of its subdirectories. If the pool prefix is not set, the global prefix
|
||||
; will be used instead.
|
||||
; Note: chrooting is a great security feature and should be used whenever
|
||||
; possible. However, all PHP paths will be relative to the chroot
|
||||
; (error_log, sessions.save_path, ...).
|
||||
; Default Value: not set
|
||||
;chroot =
|
||||
|
||||
; Chdir to this directory at the start.
|
||||
; Note: relative path can be used.
|
||||
; Default Value: current directory or / when chroot
|
||||
;chdir = /var/www
|
||||
|
||||
; Redirect worker stdout and stderr into main error log. If not set, stdout and
|
||||
; stderr will be redirected to /dev/null according to FastCGI specs.
|
||||
; Note: on highloaded environment, this can cause some delay in the page
|
||||
; process time (several ms).
|
||||
; Default Value: no
|
||||
;catch_workers_output = yes
|
||||
catch_workers_output = yes
|
||||
|
||||
; Decorate worker output with prefix and suffix containing information about
|
||||
; the child that writes to the log and if stdout or stderr is used as well as
|
||||
; log level and time. This options is used only if catch_workers_output is yes.
|
||||
; Settings to "no" will output data as written to the stdout or stderr.
|
||||
; Default value: yes
|
||||
;decorate_workers_output = no
|
||||
decorate_workers_output = no
|
||||
|
||||
; Clear environment in FPM workers
|
||||
; Prevents arbitrary environment variables from reaching FPM worker processes
|
||||
; by clearing the environment in workers before env vars specified in this
|
||||
; pool configuration are added.
|
||||
; Setting to "no" will make all environment variables available to PHP code
|
||||
; via getenv(), $_ENV and $_SERVER.
|
||||
; Default Value: yes
|
||||
;clear_env = no
|
||||
clear_env = no
|
||||
|
||||
; Limits the extensions of the main script FPM will allow to parse. This can
|
||||
; prevent configuration mistakes on the web server side. You should only limit
|
||||
; FPM to .php extensions to prevent malicious users to use other extensions to
|
||||
; execute php code.
|
||||
; Note: set an empty value to allow all extensions.
|
||||
; Default Value: .php
|
||||
;security.limit_extensions = .php .php3 .php4 .php5 .php7
|
||||
|
||||
; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
|
||||
; the current environment.
|
||||
; Default Value: clean env
|
||||
;env[HOSTNAME] = $HOSTNAME
|
||||
;env[PATH] = /usr/local/bin:/usr/bin:/bin
|
||||
;env[TMP] = /tmp
|
||||
;env[TMPDIR] = /tmp
|
||||
;env[TEMP] = /tmp
|
||||
|
||||
; Additional php.ini defines, specific to this pool of workers. These settings
|
||||
; overwrite the values previously defined in the php.ini. The directives are the
|
||||
; same as the PHP SAPI:
|
||||
; php_value/php_flag - you can set classic ini defines which can
|
||||
; be overwritten from PHP call 'ini_set'.
|
||||
; php_admin_value/php_admin_flag - these directives won't be overwritten by
|
||||
; PHP call 'ini_set'
|
||||
; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.
|
||||
|
||||
; Defining 'extension' will load the corresponding shared extension from
|
||||
; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
|
||||
; overwrite previously defined php.ini values, but will append the new value
|
||||
; instead.
|
||||
|
||||
; Note: path INI options can be relative and will be expanded with the prefix
|
||||
; (pool, global or /usr/local)
|
||||
|
||||
; Default Value: nothing is defined by default except the values in php.ini and
|
||||
; specified at startup with the -d argument
|
||||
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
|
||||
;php_flag[display_errors] = off
|
||||
;php_admin_value[error_log] = /var/log/fpm-php.www.log
|
||||
;php_admin_flag[log_errors] = on
|
||||
;php_admin_value[memory_limit] = 32M
|
@ -10,8 +10,7 @@ class CreateTipoEstadoPago extends Phinx\Migration\AbstractMigration
|
||||
$this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
|
||||
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
|
||||
|
||||
$this->table('tipo_estado_pago', ['id' => false, 'primary_key' => 'id'])
|
||||
->addColumn('id', 'integer', ['signed' => true])
|
||||
$this->table('tipo_estado_pago')
|
||||
->addColumn('descripcion', 'string', ['length' => 20, 'default' => null, 'null' => true])
|
||||
->addColumn('active', 'integer', ['length' => 1, 'default' => 0])
|
||||
->create();
|
||||
|
@ -1,36 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Phinx\Migration\AbstractMigration;
|
||||
|
||||
final class CreateTokuAccounts 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->table('toku_accounts')
|
||||
->addColumn('sociedad_rut', 'integer', ['limit' => 8, 'signed' => false, 'null' => false])
|
||||
->addColumn('toku_id', 'string', ['length' => 255, 'null' => false])
|
||||
->addColumn('account_key', 'string', ['length' => 255, 'null' => false])
|
||||
->addColumn('enabled', 'boolean', ['default' => true])
|
||||
->addTimestamps()
|
||||
#->addForeignKey('sociedad_rut', 'inmobiliaria', 'rut', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
|
||||
->addIndex(['toku_id'], ['unique' => true])
|
||||
->create();
|
||||
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Phinx\Migration\AbstractMigration;
|
||||
|
||||
final class ChangeTelefonoSizeInPropietario 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('propietario')
|
||||
->changeColumn('telefono', 'biginteger', ['null' => true, 'signed' => false, 'default' => null])
|
||||
->update();
|
||||
}
|
||||
}
|
@ -1,52 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class Comuna extends AbstractSeed
|
||||
{
|
||||
public function getDependencies(): array
|
||||
{
|
||||
return [
|
||||
'Provincia',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Run Method.
|
||||
*
|
||||
* Write your database seeder using this method.
|
||||
*
|
||||
* More information on writing seeders is available here:
|
||||
* https://book.cakephp.org/phinx/0/en/seeding.html
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
$this->execute('SET unique_checks=0; SET foreign_key_checks=0;');
|
||||
|
||||
$table = $this->table('comuna');
|
||||
$table->truncate();
|
||||
|
||||
$filename = implode(DIRECTORY_SEPARATOR, [getcwd(), 'resources', 'database', 'seeds', 'comuna.csv']);
|
||||
$dataRows = explode(PHP_EOL, trim(file_get_contents($filename)));
|
||||
$data = array_map(fn($row) => explode(';', $row), $dataRows);
|
||||
$columns = array_shift($data);
|
||||
$columns = array_map(function($column) {
|
||||
if (str_contains($column, 'id')) {
|
||||
return 'id';
|
||||
}
|
||||
if (str_contains($column, 'provincia')) {
|
||||
return 'provincia';
|
||||
}
|
||||
return $column;
|
||||
}, $columns);
|
||||
$data = array_map(function ($row) use ($columns) {
|
||||
return array_combine($columns, $row);
|
||||
}, $data);
|
||||
|
||||
$table->insert($data)->save();
|
||||
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
}
|
@ -1,52 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class Provincia extends AbstractSeed
|
||||
{
|
||||
public function getDependencies(): array
|
||||
{
|
||||
return [
|
||||
'Region',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Run Method.
|
||||
*
|
||||
* Write your database seeder using this method.
|
||||
*
|
||||
* More information on writing seeders is available here:
|
||||
* https://book.cakephp.org/phinx/0/en/seeding.html
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
$this->execute('SET unique_checks=0; SET foreign_key_checks=0;');
|
||||
|
||||
$table = $this->table('provincia');
|
||||
$table->truncate();
|
||||
|
||||
$filename = implode(DIRECTORY_SEPARATOR, [getcwd(), 'resources', 'database', 'seeds', 'provincia.csv']);
|
||||
$dataRows = explode(PHP_EOL, trim(file_get_contents($filename)));
|
||||
$data = array_map(fn($row) => explode(';', $row), $dataRows);
|
||||
$columns = array_shift($data);
|
||||
$columns = array_map(function($column) {
|
||||
if (str_contains($column, 'id')) {
|
||||
return 'id';
|
||||
}
|
||||
if (str_contains($column, 'region')) {
|
||||
return 'region';
|
||||
}
|
||||
return $column;
|
||||
}, $columns);
|
||||
$data = array_map(function ($row) use ($columns) {
|
||||
return array_combine($columns, $row);
|
||||
}, $data);
|
||||
|
||||
$table->insert($data)->save();
|
||||
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class Region extends AbstractSeed
|
||||
{
|
||||
/**
|
||||
* Run Method.
|
||||
*
|
||||
* Write your database seeder using this method.
|
||||
*
|
||||
* More information on writing seeders is available here:
|
||||
* https://book.cakephp.org/phinx/0/en/seeding.html
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
$this->execute('SET unique_checks=0; SET foreign_key_checks=0;');
|
||||
|
||||
$table = $this->table('region');
|
||||
$table->truncate();
|
||||
|
||||
$filename = implode(DIRECTORY_SEPARATOR, [getcwd(), 'resources', 'database', 'seeds', 'region.csv']);
|
||||
$dataRows = explode(PHP_EOL, trim(file_get_contents($filename)));
|
||||
$data = array_map(fn($row) => explode(';', $row), $dataRows);
|
||||
$columns = array_shift($data);
|
||||
$columns = array_map(function($column) {
|
||||
if (str_contains($column, 'id')) {
|
||||
return 'id';
|
||||
}
|
||||
if (str_contains($column, 'numeracion')) {
|
||||
return 'numeracion';
|
||||
}
|
||||
return $column;
|
||||
}, $columns);
|
||||
$data = array_map(function ($row) use ($columns) {
|
||||
return array_combine($columns, $row);
|
||||
}, $data);
|
||||
|
||||
$table->insert($data)->save();
|
||||
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class TipoEstadoPago extends AbstractSeed
|
||||
{
|
||||
/**
|
||||
* Run Method.
|
||||
*
|
||||
* Write your database seeder using this method.
|
||||
*
|
||||
* More information on writing seeders is available here:
|
||||
* https://book.cakephp.org/phinx/0/en/seeding.html
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
$this->execute('SET unique_checks=0; SET foreign_key_checks=0;');
|
||||
|
||||
$table = $this->table('tipo_estado_pago');
|
||||
$table->truncate();
|
||||
|
||||
$data = [
|
||||
['id' => -3, 'descripcion' => 'anulado'],
|
||||
['id' => -2, 'descripcion' => 'reemplazado'],
|
||||
['id' => -1, 'descripcion' => 'devuelto'],
|
||||
['id' => 0, 'descripcion' => 'no pagado', 'active' => 1],
|
||||
['id' => 1, 'descripcion' => 'depositado', 'active' => 1],
|
||||
['id' => 2, 'descripcion' => 'abonado', 'active' => 1],
|
||||
];
|
||||
$table->insert($data)->saveData();
|
||||
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
}
|
@ -1,52 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class TipoPago extends AbstractSeed
|
||||
{
|
||||
/**
|
||||
* Run Method.
|
||||
*
|
||||
* Write your database seeder using this method.
|
||||
*
|
||||
* More information on writing seeders is available here:
|
||||
* https://book.cakephp.org/phinx/0/en/seeding.html
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
$table = $this->table('tipo_pago');
|
||||
$data = [
|
||||
[
|
||||
'descripcion' => 'cheque',
|
||||
],
|
||||
[
|
||||
'descripcion' => 'carta de resguardo',
|
||||
],
|
||||
[
|
||||
'descripcion' => 'vale vista'
|
||||
],
|
||||
[
|
||||
'descripcion' => 'deposito',
|
||||
],
|
||||
[
|
||||
'descripcion' => 'efectivo',
|
||||
],
|
||||
[
|
||||
'descripcion' => 'tarjeta de credito',
|
||||
],
|
||||
[
|
||||
'descripcion' => 'transferencia electronica',
|
||||
],
|
||||
[
|
||||
'descripcion' => 'virtual',
|
||||
]
|
||||
];
|
||||
|
||||
$table->truncate();
|
||||
$table
|
||||
->insert($data)
|
||||
->saveData();
|
||||
}
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class TipoSociedad extends AbstractSeed
|
||||
{
|
||||
/**
|
||||
* Run Method.
|
||||
*
|
||||
* Write your database seeder using this method.
|
||||
*
|
||||
* More information on writing seeders is available here:
|
||||
* https://book.cakephp.org/phinx/0/en/seeding.html
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
$this->execute('SET unique_checks=0; SET foreign_key_checks=0;');
|
||||
|
||||
$table = $this->table('tipo_sociedad');
|
||||
$table->truncate();
|
||||
|
||||
$data = [
|
||||
[
|
||||
'descripcion' => 'Limitada',
|
||||
'abreviacion' => 'Ltda',
|
||||
],
|
||||
[
|
||||
'descripcion' => 'Sociedad Anónima',
|
||||
'abreviacion' => 'SA',
|
||||
],
|
||||
[
|
||||
'descripcion' => 'Sociedad por Acciones',
|
||||
'abreviacion' => 'SpA',
|
||||
]
|
||||
];
|
||||
|
||||
$table->insert($data)->saveData();
|
||||
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class TipoUnidad extends AbstractSeed
|
||||
{
|
||||
/**
|
||||
* Run Method.
|
||||
*
|
||||
* Write your database seeder using this method.
|
||||
*
|
||||
* More information on writing seeders is available here:
|
||||
* https://book.cakephp.org/phinx/0/en/seeding.html
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
$this->execute('SET unique_checks=0; SET foreign_key_checks=0;');
|
||||
|
||||
$table = $this->table('tipo_unidad');
|
||||
$table->truncate();
|
||||
|
||||
$data = [
|
||||
[
|
||||
'descripcion' => 'departamento',
|
||||
'orden' => 0,
|
||||
],
|
||||
[
|
||||
'descripcion' => 'estacionamiento',
|
||||
'orden' => 1,
|
||||
],
|
||||
[
|
||||
'descripcion' => 'bodega',
|
||||
'orden' => 2,
|
||||
]
|
||||
];
|
||||
|
||||
$table->insert($data)->saveData();
|
||||
|
||||
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||
}
|
||||
}
|
@ -1,347 +0,0 @@
|
||||
id;descripcion;provincia
|
||||
1101;Iquique;11
|
||||
1107;Alto Hospicio;11
|
||||
1401;Pozo Almonte;14
|
||||
1402;Camiña;14
|
||||
1403;Colchane;14
|
||||
1404;Huara;14
|
||||
1405;Pica;14
|
||||
2101;Antofagasta;21
|
||||
2102;Mejillones;21
|
||||
2103;Sierra Gorda;21
|
||||
2104;Taltal;21
|
||||
2201;Calama;22
|
||||
2202;Ollagüe;22
|
||||
2203;San Pedro de Atacama;22
|
||||
2301;Tocopilla;23
|
||||
2302;María Elena;23
|
||||
3101;Copiapó;31
|
||||
3102;Caldera;31
|
||||
3103;Tierra Amarilla;31
|
||||
3201;Chañaral;32
|
||||
3202;Diego de Almagro;32
|
||||
3301;Vallenar;33
|
||||
3302;Alto del Carmen;33
|
||||
3303;Freirina;33
|
||||
3304;Huasco;33
|
||||
4101;La Serena;41
|
||||
4102;Coquimbo;41
|
||||
4103;Andacollo;41
|
||||
4104;La Higuera;41
|
||||
4105;Paiguano;41
|
||||
4106;Vicuña;41
|
||||
4201;Illapel;42
|
||||
4202;Canela;42
|
||||
4203;Los Vilos;42
|
||||
4204;Salamanca;42
|
||||
4301;Ovalle;43
|
||||
4302;Combarbalá;43
|
||||
4303;Monte Patria;43
|
||||
4304;Punitaqui;43
|
||||
4305;Río Hurtado;43
|
||||
5101;Valparaíso;51
|
||||
5102;Casablanca;51
|
||||
5103;Concón;51
|
||||
5104;Juan Fernández;51
|
||||
5105;Puchuncaví;51
|
||||
5107;Quintero;51
|
||||
5109;Viña del Mar;51
|
||||
5201;Isla de Pascua;52
|
||||
5301;Los Andes;53
|
||||
5302;Calle Larga;53
|
||||
5303;Rinconada;53
|
||||
5304;San Esteban;53
|
||||
5401;La Ligua;54
|
||||
5402;Cabildo;54
|
||||
5403;Papudo;54
|
||||
5404;Petorca;54
|
||||
5405;Zapallar;54
|
||||
5501;Quillota;55
|
||||
5502;Calera;55
|
||||
5503;Hijuelas;55
|
||||
5504;La Cruz;55
|
||||
5506;Nogales;55
|
||||
5601;San Antonio;56
|
||||
5602;Algarrobo;56
|
||||
5603;Cartagena;56
|
||||
5604;El Quisco;56
|
||||
5605;El Tabo;56
|
||||
5606;Santo Domingo;56
|
||||
5701;San Felipe;57
|
||||
5702;Catemu;57
|
||||
5703;Llaillay;57
|
||||
5704;Panquehue;57
|
||||
5705;Putaendo;57
|
||||
5706;Santa María;57
|
||||
5801;Quilpué;58
|
||||
5802;Limache;58
|
||||
5803;Olmué;58
|
||||
5804;Villa Alemana;58
|
||||
6101;Rancagua;61
|
||||
6102;Codegua;61
|
||||
6103;Coinco;61
|
||||
6104;Coltauco;61
|
||||
6105;Doñihue;61
|
||||
6106;Graneros;61
|
||||
6107;Las Cabras;61
|
||||
6108;Machalí;61
|
||||
6109;Malloa;61
|
||||
6110;Mostazal;61
|
||||
6111;Olivar;61
|
||||
6112;Peumo;61
|
||||
6113;Pichidegua;61
|
||||
6114;Quinta de Tilcoco;61
|
||||
6115;Rengo;61
|
||||
6116;Requínoa;61
|
||||
6117;San Vicente;61
|
||||
6201;Pichilemu;62
|
||||
6202;La Estrella;62
|
||||
6203;Litueche;62
|
||||
6204;Marchihue;62
|
||||
6205;Navidad;62
|
||||
6206;Paredones;62
|
||||
6301;San Fernando;63
|
||||
6302;Chépica;63
|
||||
6303;Chimbarongo;63
|
||||
6304;Lolol;63
|
||||
6305;Nancagua;63
|
||||
6306;Palmilla;63
|
||||
6307;Peralillo;63
|
||||
6308;Placilla;63
|
||||
6309;Pumanque;63
|
||||
6310;Santa Cruz;63
|
||||
7101;Talca;71
|
||||
7102;Constitución;71
|
||||
7103;Curepto;71
|
||||
7104;Empedrado;71
|
||||
7105;Maule;71
|
||||
7106;Pelarco;71
|
||||
7107;Pencahue;71
|
||||
7108;Río Claro;71
|
||||
7109;San Clemente;71
|
||||
7110;San Rafael;71
|
||||
7201;Cauquenes;72
|
||||
7202;Chanco;72
|
||||
7203;Pelluhue;72
|
||||
7301;Curicó;73
|
||||
7302;Hualañé;73
|
||||
7303;Licantén;73
|
||||
7304;Molina;73
|
||||
7305;Rauco;73
|
||||
7306;Romeral;73
|
||||
7307;Sagrada Familia;73
|
||||
7308;Teno;73
|
||||
7309;Vichuquén;73
|
||||
7401;Linares;74
|
||||
7402;Colbún;74
|
||||
7403;Longaví;74
|
||||
7404;Parral;74
|
||||
7405;Retiro;74
|
||||
7406;San Javier;74
|
||||
7407;Villa Alegre;74
|
||||
7408;Yerbas Buenas;74
|
||||
8101;Concepción;81
|
||||
8102;Coronel;81
|
||||
8103;Chiguayante;81
|
||||
8104;Florida;81
|
||||
8105;Hualqui;81
|
||||
8106;Lota;81
|
||||
8107;Penco;81
|
||||
8108;San Pedro de la Paz;81
|
||||
8109;Santa Juana;81
|
||||
8110;Talcahuano;81
|
||||
8111;Tomé;81
|
||||
8112;Hualpén;81
|
||||
8201;Lebu;82
|
||||
8202;Arauco;82
|
||||
8203;Cañete;82
|
||||
8204;Contulmo;82
|
||||
8205;Curanilahue;82
|
||||
8206;Los Álamos;82
|
||||
8207;Tirúa;82
|
||||
8301;Los Ángeles;83
|
||||
8302;Antuco;83
|
||||
8303;Cabrero;83
|
||||
8304;Laja;83
|
||||
8305;Mulchén;83
|
||||
8306;Nacimiento;83
|
||||
8307;Negrete;83
|
||||
8308;Quilaco;83
|
||||
8309;Quilleco;83
|
||||
8310;San Rosendo;83
|
||||
8311;Santa Bárbara;83
|
||||
8312;Tucapel;83
|
||||
8313;Yumbel;83
|
||||
8314;Alto Biobío;83
|
||||
8401;Chillán;84
|
||||
8402;Bulnes;84
|
||||
8403;Cobquecura;84
|
||||
8404;Coelemu;84
|
||||
8405;Coihueco;84
|
||||
8406;Chillán Viejo;84
|
||||
8407;El Carmen;84
|
||||
8408;Ninhue;84
|
||||
8409;Ñiquén;84
|
||||
8410;Pemuco;84
|
||||
8411;Pinto;84
|
||||
8412;Portezuelo;84
|
||||
8413;Quillón;84
|
||||
8414;Quirihue;84
|
||||
8415;Ránquil;84
|
||||
8416;San Carlos;84
|
||||
8417;San Fabián;84
|
||||
8418;San Ignacio;84
|
||||
8419;San Nicolás;84
|
||||
8420;Treguaco;84
|
||||
8421;Yungay;84
|
||||
9101;Temuco;91
|
||||
9102;Carahue;91
|
||||
9103;Cunco;91
|
||||
9104;Curarrehue;91
|
||||
9105;Freire;91
|
||||
9106;Galvarino;91
|
||||
9107;Gorbea;91
|
||||
9108;Lautaro;91
|
||||
9109;Loncoche;91
|
||||
9110;Melipeuco;91
|
||||
9111;Nueva Imperial;91
|
||||
9112;Padre las Casas;91
|
||||
9113;Perquenco;91
|
||||
9114;Pitrufquén;91
|
||||
9115;Pucón;91
|
||||
9116;Saavedra;91
|
||||
9117;Teodoro Schmidt;91
|
||||
9118;Toltén;91
|
||||
9119;Vilcún;91
|
||||
9120;Villarrica;91
|
||||
9121;Cholchol;91
|
||||
9201;Angol;92
|
||||
9202;Collipulli;92
|
||||
9203;Curacautín;92
|
||||
9204;Ercilla;92
|
||||
9205;Lonquimay;92
|
||||
9206;Los Sauces;92
|
||||
9207;Lumaco;92
|
||||
9208;Purén;92
|
||||
9209;Renaico;92
|
||||
9210;Traiguén;92
|
||||
9211;Victoria;92
|
||||
10101;Puerto Montt;101
|
||||
10102;Calbuco;101
|
||||
10103;Cochamó;101
|
||||
10104;Fresia;101
|
||||
10105;Frutillar;101
|
||||
10106;Los Muermos;101
|
||||
10107;Llanquihue;101
|
||||
10108;Maullín;101
|
||||
10109;Puerto Varas;101
|
||||
10201;Castro;102
|
||||
10202;Ancud;102
|
||||
10203;Chonchi;102
|
||||
10204;Curaco de Vélez;102
|
||||
10205;Dalcahue;102
|
||||
10206;Puqueldón;102
|
||||
10207;Queilén;102
|
||||
10208;Quellón;102
|
||||
10209;Quemchi;102
|
||||
10210;Quinchao;102
|
||||
10301;Osorno;103
|
||||
10302;Puerto Octay;103
|
||||
10303;Purranque;103
|
||||
10304;Puyehue;103
|
||||
10305;Río Negro;103
|
||||
10306;San Juan de la Costa;103
|
||||
10307;San Pablo;103
|
||||
10401;Chaitén;104
|
||||
10402;Futaleufú;104
|
||||
10403;Hualaihué;104
|
||||
10404;Palena;104
|
||||
11101;Coihaique;111
|
||||
11102;Lago Verde;111
|
||||
11201;Aisén;112
|
||||
11202;Cisnes;112
|
||||
11203;Guaitecas;112
|
||||
11301;Cochrane;113
|
||||
11302;O’Higgins;113
|
||||
11303;Tortel;113
|
||||
11401;Chile Chico;114
|
||||
11402;Río Ibáñez;114
|
||||
12101;Punta Arenas;121
|
||||
12102;Laguna Blanca;121
|
||||
12103;Río Verde;121
|
||||
12104;San Gregorio;121
|
||||
12201;Cabo de Hornos (Ex Navarino);122
|
||||
12202;Antártica;122
|
||||
12301;Porvenir;123
|
||||
12302;Primavera;123
|
||||
12303;Timaukel;123
|
||||
12401;Natales;124
|
||||
12402;Torres del Paine;124
|
||||
13101;Santiago;131
|
||||
13102;Cerrillos;131
|
||||
13103;Cerro Navia;131
|
||||
13104;Conchalí;131
|
||||
13105;El Bosque;131
|
||||
13106;Estación Central;131
|
||||
13107;Huechuraba;131
|
||||
13108;Independencia;131
|
||||
13109;La Cisterna;131
|
||||
13110;La Florida;131
|
||||
13111;La Granja;131
|
||||
13112;La Pintana;131
|
||||
13113;La Reina;131
|
||||
13114;Las Condes;131
|
||||
13115;Lo Barnechea;131
|
||||
13116;Lo Espejo;131
|
||||
13117;Lo Prado;131
|
||||
13118;Macul;131
|
||||
13119;Maipú;131
|
||||
13120;Ñuñoa;131
|
||||
13121;Pedro Aguirre Cerda;131
|
||||
13122;Peñalolén;131
|
||||
13123;Providencia;131
|
||||
13124;Pudahuel;131
|
||||
13125;Quilicura;131
|
||||
13126;Quinta Normal;131
|
||||
13127;Recoleta;131
|
||||
13128;Renca;131
|
||||
13129;San Joaquín;131
|
||||
13130;San Miguel;131
|
||||
13131;San Ramón;131
|
||||
13132;Vitacura;131
|
||||
13201;Puente Alto;132
|
||||
13202;Pirque;132
|
||||
13203;San José de Maipo;132
|
||||
13301;Colina;133
|
||||
13302;Lampa;133
|
||||
13303;Tiltil;133
|
||||
13401;San Bernardo;134
|
||||
13402;Buin;134
|
||||
13403;Calera de Tango;134
|
||||
13404;Paine;134
|
||||
13501;Melipilla;135
|
||||
13502;Alhué;135
|
||||
13503;Curacaví;135
|
||||
13504;María Pinto;135
|
||||
13505;San Pedro;135
|
||||
13601;Talagante;136
|
||||
13602;El Monte;136
|
||||
13603;Isla de Maipo;136
|
||||
13604;Padre Hurtado;136
|
||||
13605;Peñaflor;136
|
||||
14101;Valdivia;141
|
||||
14102;Corral;141
|
||||
14103;Lanco;141
|
||||
14104;Los Lagos;141
|
||||
14105;Máfil;141
|
||||
14106;Mariquina;141
|
||||
14107;Paillaco;141
|
||||
14108;Panguipulli;141
|
||||
14201;La Unión;142
|
||||
14202;Futrono;142
|
||||
14203;Lago Ranco;142
|
||||
14204;Río Bueno;142
|
||||
15101;Arica;151
|
||||
15102;Camarones;151
|
||||
15201;Putre;152
|
||||
15202;General Lagos;152
|
|
@ -1,55 +0,0 @@
|
||||
id;descripcion;region
|
||||
11;Iquique;1
|
||||
14;Tamarugal;1
|
||||
21;Antofagasta;2
|
||||
22;El Loa;2
|
||||
23;Tocopilla;2
|
||||
31;Copiap;3
|
||||
32;Chañaral;3
|
||||
33;Huasco;3
|
||||
41;Elqui;4
|
||||
42;Choapa;4
|
||||
43;Limari;4
|
||||
51;Valparaíso;5
|
||||
52;Isla de Pascua;5
|
||||
53;Los Andes;5
|
||||
54;Petorca;5
|
||||
55;Quillota;5
|
||||
56;San Antonio;5
|
||||
57;San Felipe;5
|
||||
58;Marga Marga;5
|
||||
61;Cachapoal;6
|
||||
62;Cardenal Caro;6
|
||||
63;Colchagua;6
|
||||
71;Talca;7
|
||||
72;Cauquenes;7
|
||||
73;Curico;7
|
||||
74;Linares;7
|
||||
81;Concepci;8
|
||||
82;Arauco;8
|
||||
83;Bío- Bío;8
|
||||
84;Ñuble;8
|
||||
91;Cautín;9
|
||||
92;Malleco;9
|
||||
101;Llanquihue;10
|
||||
102;Chiloe;10
|
||||
103;Osorno;10
|
||||
104;Palena;10
|
||||
111;Coihaique;11
|
||||
112;Aisén;11
|
||||
113;Capitan Prat;11
|
||||
114;General Carrera;11
|
||||
121;Magallanes;12
|
||||
122;Antártica Chilena;12
|
||||
123;Tierra del Fuego;12
|
||||
124;Ultima Esperanza;12
|
||||
131;Santiago;13
|
||||
132;Cordillera;13
|
||||
133;Chacabuco;13
|
||||
134;Maipo;13
|
||||
135;Melipilla;13
|
||||
136;Talagante;13
|
||||
141;Valdivia;14
|
||||
142;Ranco;14
|
||||
151;Arica;15
|
||||
152;Parinacota;15
|
|
@ -1,16 +0,0 @@
|
||||
id;descripcion;numeral;numeracion
|
||||
1;Región de Tarapacá;I;1
|
||||
2;Región de Antofagasta;II;2
|
||||
3;Región de Atacama;III;3
|
||||
4;Región de Coquimbo;IV;4
|
||||
5;Región de Valparaíso;V;5
|
||||
6;Región del Libertador Gral. Bernardo O’Higgins;VI;6
|
||||
7;Región del Maule;VII;7
|
||||
8;Región del Biobío;VIII;8
|
||||
9;Región de la Araucanía;IX;9
|
||||
10;Región de Los Lagos;X;10
|
||||
11;Región Aisén del Gral. Carlos Ibáñez del Campo;XI;11
|
||||
12;Región de Magallanes y de la Antártica Chilena;XII;12
|
||||
13;Región Metropolitana de Santiago;RM;13
|
||||
14;Región de Los Ríos;XIV;14
|
||||
15;Región de Arica y Parinacota;XV;15
|
|
1
app/resources/routes/api/external/toku.php
vendored
1
app/resources/routes/api/external/toku.php
vendored
@ -7,5 +7,4 @@ $app->group('/toku', function($app) {
|
||||
$app->get('/test[/]', [Toku::class, 'test']);
|
||||
$app->delete('/reset[/]', [Toku::class, 'reset']);
|
||||
$app->post('/enqueue[/]', [Toku::class, 'enqueue']);
|
||||
$app->post('/update[/{type}[/]]', [Toku::class, 'update']);
|
||||
});
|
||||
|
@ -2,9 +2,9 @@
|
||||
use Incoviba\Controller\API\Queues;
|
||||
|
||||
$app->group('/queue', function($app) {
|
||||
#$app->get('/jobs[/]', [Queues::class, 'jobs']);
|
||||
$app->get('/jobs[/]', [Queues::class, 'jobs']);
|
||||
$app->group('/run', function($app) {
|
||||
#$app->get('/{job_id:[0-9]+}[/]', [Queues::class, 'run']);
|
||||
$app->get('/{job_id:[0-9]+}[/]', [Queues::class, 'run']);
|
||||
$app->get('[/]', Queues::class);
|
||||
});
|
||||
});
|
||||
|
@ -2,7 +2,6 @@
|
||||
use Incoviba\Controller\API\Ventas\Precios;
|
||||
|
||||
$app->group('/precios', function($app) {
|
||||
$app->post('/import[/]', [Precios::class, 'import']);
|
||||
$app->post('[/]', [Precios::class, 'proyecto']);
|
||||
});
|
||||
$app->group('/precio', function($app) {
|
||||
|
@ -2,5 +2,5 @@
|
||||
use Incoviba\Controller\Ventas\Precios;
|
||||
|
||||
$app->group('/precios', function($app) {
|
||||
$app->get('[/{project_id}[/]]', Precios::class);
|
||||
$app->get('[/]', Precios::class);
|
||||
});
|
||||
|
@ -156,7 +156,7 @@
|
||||
<script>
|
||||
const regiones = [
|
||||
@foreach ($regiones as $region)
|
||||
'<div class="item" data-value="{{$region->id}}">{{$region->numeral}} - {{$region->descripcion}}</div>',
|
||||
'<div class="item" data-value="{{$region->id}}">{{$region->descripcion}}</div>',
|
||||
@endforeach
|
||||
]
|
||||
|
||||
|
@ -54,23 +54,22 @@
|
||||
}
|
||||
$(document).ready(() => {
|
||||
const url = '{{$urls->api}}/ventas/pago/{{$venta->resciliacion()->id}}'
|
||||
let old = new Date(Date.parse('{{$venta->resciliacion()?->fecha->format('Y-m-d') ?? $venta->currentEstado()->fecha->format('Y-m-d') ?? $venta->fecha->format('Y-m-d')}}') + 24 * 60 * 60 * 1000)
|
||||
let old = new Date({{$venta->resciliacion()?->fecha->format('Y') ?? date('Y')}},
|
||||
{{$venta->resciliacion()?->fecha->format('n') ?? date('n')}}-1, {{$venta->resciliacion()?->fecha->format('j') ?? date('j')}})
|
||||
calendar_date_options['initialDate'] = old
|
||||
calendar_date_options['onChange'] = function(date, text, mode) {
|
||||
if (date.getTime() === old.getTime()) {
|
||||
return
|
||||
}
|
||||
const body = new FormData()
|
||||
const fecha = new Date(date.getTime())
|
||||
fecha.setDate(fecha.getDate() - 1)
|
||||
body.set('fecha', fecha.toISOString())
|
||||
body.set('fecha', date.toISOString())
|
||||
$('#loading-spinner-fecha').show()
|
||||
APIClient.fetch(url, {method: 'post', body}).then(response => {
|
||||
$('#loading-spinner-fecha').hide()
|
||||
if (!response) {
|
||||
return
|
||||
}
|
||||
old = new Date(date.getTime())
|
||||
old = date
|
||||
alertResponse('Fecha cambiada correctamente.')
|
||||
})
|
||||
}
|
||||
|
@ -6,26 +6,15 @@
|
||||
|
||||
@section('venta_content')
|
||||
<div class="ui list">
|
||||
@if (isset($venta->formaPago()->pie))
|
||||
<div class="item">
|
||||
<div class="header">Valor Pagado</div>
|
||||
<div class="content">
|
||||
{{$format->pesos($venta->formaPago()->pie->pagado('pesos'))}}
|
||||
<div class="ui left pointing small label">
|
||||
{{$format->number($venta->formaPago()->pie->pagado() / $venta->valor * 100)}}% de la venta
|
||||
</div>
|
||||
<div class="item">
|
||||
<div class="header">Valor Pagado</div>
|
||||
<div class="content">
|
||||
{{$format->pesos($venta->formaPago()->pie->pagado('pesos'))}}
|
||||
<div class="ui left pointing small label">
|
||||
{{$format->number($venta->formaPago()->pie->pagado() / $venta->valor * 100)}}% de la venta
|
||||
</div>
|
||||
</div>
|
||||
@else
|
||||
<div class="item">
|
||||
<div class="ui compact warning message">
|
||||
<div class="content">
|
||||
<i class="exclamation triangle icon"></i>
|
||||
No tiene valor pagado
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
<div class="item">
|
||||
<div class="header">
|
||||
Multa Estandar
|
||||
|
@ -40,7 +40,7 @@
|
||||
const url = '{{$urls->api}}/ventas/unidad/' + this.props.id + '/prorrateo'
|
||||
const method = 'post'
|
||||
const body = new FormData()
|
||||
body.set('prorrateo', (parseFloat(newValue) / 100).toFixed(8))
|
||||
body.set('prorrateo', newValue)
|
||||
return fetchAPI(url, {method, body}).then(response => {
|
||||
if (!response) {
|
||||
return
|
||||
|
@ -24,9 +24,6 @@
|
||||
<button class="ui tiny green icon button" id="add_button">
|
||||
<i class="plus icon"></i>
|
||||
</button>
|
||||
<button class="ui tiny green icon button" id="import_button">
|
||||
<i class="upload icon"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</h4>
|
||||
@ -34,7 +31,6 @@
|
||||
<table class="ui table" id="list_data"></table>
|
||||
</div>
|
||||
</div>
|
||||
@include('ventas.precios.modal.import')
|
||||
<div class="ui modal" id="list_modal">
|
||||
<div class="header">
|
||||
Actualizar <span id="modal_title"></span>
|
||||
@ -101,8 +97,7 @@
|
||||
return this.precio / this.superficie
|
||||
}
|
||||
draw(formatter) {
|
||||
const dateParts = this.fecha.split('-')
|
||||
const date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2])
|
||||
const date = new Date(this.fecha)
|
||||
const dateFormatter = new Intl.DateTimeFormat('es-CL')
|
||||
return $('<tr></tr>').addClass('unidad').attr('data-linea', this.linea).append(
|
||||
$('<td></td>').html(this.nombre)
|
||||
@ -322,8 +317,7 @@
|
||||
buttons: {
|
||||
add: '',
|
||||
up: '',
|
||||
refresh: '',
|
||||
import: ''
|
||||
refresh: ''
|
||||
}
|
||||
},
|
||||
data: {
|
||||
@ -336,11 +330,6 @@
|
||||
loading: {
|
||||
precios: false
|
||||
},
|
||||
components: {
|
||||
modals: {
|
||||
import: null
|
||||
}
|
||||
},
|
||||
get: function() {
|
||||
return {
|
||||
proyectos: () => {
|
||||
@ -389,24 +378,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
url() {
|
||||
return {
|
||||
proyectos: () => {
|
||||
const currentUrl = window.location.href
|
||||
const newUrl = `{{ $urls->base }}/ventas/precios`
|
||||
if (newUrl !== currentUrl) {
|
||||
window.history.replaceState(null, null, newUrl)
|
||||
}
|
||||
},
|
||||
precios: proyecto_id => {
|
||||
const currentUrl = window.location.href
|
||||
const newUrl = `{{ $urls->base }}/ventas/precios/${proyecto_id}`
|
||||
if (newUrl !== currentUrl) {
|
||||
window.history.replaceState(null, null, newUrl)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
add: function() {
|
||||
return {
|
||||
precio: data => {
|
||||
@ -429,7 +400,6 @@
|
||||
draw: function() {
|
||||
return {
|
||||
proyectos: () => {
|
||||
this.url().proyectos()
|
||||
const parent = $(this.ids.list)
|
||||
const header = parent.find('#list_title')
|
||||
const list = parent.find('.list')
|
||||
@ -438,7 +408,6 @@
|
||||
$(this.ids.buttons.add).hide()
|
||||
$(this.ids.buttons.add).attr('data-id', '')
|
||||
$(this.ids.buttons.add).attr('data-proyecto', '')
|
||||
$(`#${this.ids.buttons.import}`).hide()
|
||||
|
||||
header.html('Proyectos')
|
||||
table.hide()
|
||||
@ -446,8 +415,7 @@
|
||||
|
||||
this.data.proyectos.forEach(proyecto => {
|
||||
list.append(
|
||||
$('<div></div>').addClass('item proyecto').attr('data-proyecto', proyecto.id)
|
||||
.html(proyecto.descripcion).css('cursor', 'pointer')
|
||||
$('<div></div>').addClass('item proyecto').attr('data-proyecto', proyecto.id).html(proyecto.descripcion).css('cursor', 'pointer')
|
||||
)
|
||||
})
|
||||
list.show()
|
||||
@ -463,7 +431,6 @@
|
||||
})
|
||||
},
|
||||
precios: () => {
|
||||
this.url().precios(this.data.id)
|
||||
const parent = $(this.ids.list)
|
||||
const header = parent.find('#list_title')
|
||||
const list = parent.find('.list')
|
||||
@ -473,8 +440,6 @@
|
||||
$(this.ids.buttons.add).attr('data-proyecto', this.data.proyecto)
|
||||
$(this.ids.buttons.add).show()
|
||||
|
||||
$(`#${this.ids.buttons.import}`).show()
|
||||
|
||||
header.html('Precios de ' + this.data.proyecto)
|
||||
list.hide()
|
||||
table.html('')
|
||||
@ -616,27 +581,18 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
import: event => {
|
||||
event.preventDefault()
|
||||
precios.components.modals.import.show(this.data.id)
|
||||
return false
|
||||
}
|
||||
}
|
||||
},
|
||||
setup: function({list, proyectos, buttons_up, buttons_refresh, buttons_add, buttons_import}) {
|
||||
setup: function({list, proyectos, buttons_up, buttons_refresh, buttons_add}) {
|
||||
this.ids.list = list
|
||||
this.ids.proyectos = proyectos
|
||||
this.ids.buttons.up = buttons_up
|
||||
this.ids.buttons.refresh = buttons_refresh
|
||||
this.ids.buttons.add = buttons_add
|
||||
this.ids.buttons.import = buttons_import
|
||||
|
||||
$(this.ids.buttons.up).click(this.actions().up)
|
||||
$(this.ids.buttons.refresh).click(this.actions().refresh)
|
||||
$(this.ids.buttons.add).click(this.actions().add().list)
|
||||
document.getElementById(this.ids.buttons.import).addEventListener('click', this.actions().import)
|
||||
|
||||
this.components.modals.import = new ImportModal()
|
||||
|
||||
this.draw().proyectos()
|
||||
}
|
||||
@ -718,10 +674,6 @@
|
||||
$(this.ids.button).click(this.actions().send)
|
||||
}
|
||||
}
|
||||
function selectProject(projectId) {
|
||||
const $project = $(`.item.proyecto[data-proyecto="${projectId}"]`)
|
||||
$project.click()
|
||||
}
|
||||
|
||||
$(document).ready(() => {
|
||||
precios.setup({
|
||||
@ -729,8 +681,7 @@
|
||||
proyectos: '#proyectos',
|
||||
buttons_up: '#up_button',
|
||||
buttons_refresh: '#refresh_button',
|
||||
buttons_add: '#add_button',
|
||||
buttons_import: 'import_button'
|
||||
buttons_add: '#add_button'
|
||||
})
|
||||
list_modal.setup({
|
||||
modal: '#list_modal',
|
||||
@ -741,10 +692,6 @@
|
||||
fields_valor: '#valor',
|
||||
button: '#send'
|
||||
})
|
||||
|
||||
@if (isset($project_id))
|
||||
selectProject({{$project_id}})
|
||||
@endif
|
||||
})
|
||||
</script>
|
||||
@endpush
|
||||
|
@ -1,120 +0,0 @@
|
||||
<div class="ui modal" id="import_modal">
|
||||
<div class="header">
|
||||
Importar Precios
|
||||
</div>
|
||||
<div class="content">
|
||||
<div class="ui form">
|
||||
<input type="hidden" id="import_project_id" name="import_project_id" value="" />
|
||||
<div class="three wide field">
|
||||
<div class="ui calendar" id="import_date">
|
||||
<div class="ui left icon input">
|
||||
<i class="calendar icon"></i>
|
||||
<input type="text" name="fecha" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<input class="ui invisible file input" type="file" id="import_file" name="file" />
|
||||
<label class="ui placeholder segment" for="import_file">
|
||||
<div class="ui icon header">
|
||||
<i class="upload icon"></i>
|
||||
Archivo de Precios
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<div class="ui red cancel icon button">
|
||||
<i class="remove icon"></i>
|
||||
</div>
|
||||
<div class="ui green ok icon button">
|
||||
<i class="checkmark icon"></i>
|
||||
Importar
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@push('page_scripts')
|
||||
<script>
|
||||
class ImportModal {
|
||||
ids = {
|
||||
modal: '',
|
||||
project: '',
|
||||
calendar: '',
|
||||
file: ''
|
||||
}
|
||||
components = {
|
||||
$modal: null,
|
||||
form: null,
|
||||
project: null,
|
||||
$calendar: null,
|
||||
file: null,
|
||||
$file: null
|
||||
}
|
||||
constructor() {
|
||||
this.ids.modal = 'import_modal'
|
||||
this.ids.project = 'import_project_id'
|
||||
this.ids.calendar = 'import_date'
|
||||
this.ids.file = 'import_file'
|
||||
|
||||
this.setup()
|
||||
}
|
||||
show(project_id) {
|
||||
this.components.project.value = project_id
|
||||
this.components.$modal.modal('show')
|
||||
}
|
||||
dragDrop(event) {
|
||||
event.preventDefault()
|
||||
|
||||
if (event.originalEvent.dataTransfer && event.originalEvent.dataTransfer.files.length > 0) {
|
||||
this.components.file.files = event.originalEvent.dataTransfer.files
|
||||
}
|
||||
}
|
||||
import() {
|
||||
const url = '{{ $urls->api }}/ventas/precios/import'
|
||||
const method = 'post'
|
||||
const body = new FormData()
|
||||
body.set('project_id', this.components.project.value)
|
||||
const date = this.components.$calendar.calendar('get date')
|
||||
body.set('date', [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-'))
|
||||
body.set('file', this.components.file.files[0])
|
||||
APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
|
||||
if (json.status === true) {
|
||||
window.location.reload()
|
||||
return
|
||||
}
|
||||
console.debug(json)
|
||||
})
|
||||
}
|
||||
setup() {
|
||||
this.components.$modal = $(`#${this.ids.modal}`)
|
||||
this.components.$modal.modal({
|
||||
onApprove: () => {
|
||||
this.import()
|
||||
}
|
||||
})
|
||||
this.components.form = this.components.$modal.find('form')
|
||||
this.components.form.submit(event => {
|
||||
event.preventDefault()
|
||||
this.import()
|
||||
return false
|
||||
})
|
||||
this.components.project = document.getElementById(this.ids.project)
|
||||
this.components.$calendar = $(`#${this.ids.calendar}`)
|
||||
const cdo = structuredClone(calendar_date_options)
|
||||
cdo['maxDate'] = new Date()
|
||||
this.components.$calendar.calendar(cdo)
|
||||
this.components.file = document.getElementById(this.ids.file)
|
||||
this.components.$file = $(this.components.file.parentNode.querySelector('label'))
|
||||
this.components.$file.css('cursor', 'pointer')
|
||||
this.components.$file.on('dragover', event => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
})
|
||||
this.components.$file.on('dragenter', event => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
})
|
||||
this.components.$file.on('drop', this.dragDrop.bind(this))
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@endpush
|
@ -5,8 +5,28 @@ use DI\Bridge\Slim\Bridge;
|
||||
require_once 'composer.php';
|
||||
|
||||
function buildApp() {
|
||||
require_once 'container.php';
|
||||
$app = Bridge::create(buildContainer());
|
||||
$builder = new ContainerBuilder();
|
||||
$folders = [
|
||||
'settings',
|
||||
'setups'
|
||||
];
|
||||
foreach ($folders as $folder_name) {
|
||||
$folder = implode(DIRECTORY_SEPARATOR, [
|
||||
__DIR__,
|
||||
$folder_name
|
||||
]);
|
||||
if (!file_exists($folder)) {
|
||||
continue;
|
||||
}
|
||||
$files = new FilesystemIterator($folder);
|
||||
foreach ($files as $file) {
|
||||
if ($file->isDir()) {
|
||||
continue;
|
||||
}
|
||||
$builder->addDefinitions($file->getRealPath());
|
||||
}
|
||||
}
|
||||
$app = Bridge::create($builder->build());
|
||||
$folder = implode(DIRECTORY_SEPARATOR, [
|
||||
__DIR__,
|
||||
'middlewares'
|
||||
|
@ -1,33 +0,0 @@
|
||||
<?php
|
||||
use Psr\Container\ContainerInterface;
|
||||
use DI\ContainerBuilder;
|
||||
|
||||
/**
|
||||
* @return ContainerInterface
|
||||
* @throws Exception
|
||||
*/
|
||||
function buildContainer(): ContainerInterface
|
||||
{
|
||||
$builder = new ContainerBuilder();
|
||||
$folders = [
|
||||
'settings',
|
||||
'setups'
|
||||
];
|
||||
foreach ($folders as $folder_name) {
|
||||
$folder = implode(DIRECTORY_SEPARATOR, [
|
||||
__DIR__,
|
||||
$folder_name
|
||||
]);
|
||||
if (!file_exists($folder)) {
|
||||
continue;
|
||||
}
|
||||
$files = new FilesystemIterator($folder);
|
||||
foreach ($files as $file) {
|
||||
if ($file->isDir()) {
|
||||
continue;
|
||||
}
|
||||
$builder->addDefinitions($file->getRealPath());
|
||||
}
|
||||
}
|
||||
return $builder->build();
|
||||
}
|
@ -27,8 +27,8 @@ return [
|
||||
$container->get(Monolog\Processor\UidProcessor::class),
|
||||
];
|
||||
},
|
||||
'baseDefaultHandlers' => function(ContainerInterface $container) {
|
||||
return [
|
||||
'defaultMonologHandlers' => function(ContainerInterface $container) {
|
||||
$baseHandlers = [
|
||||
'critical' => [
|
||||
'handler' => Monolog\Handler\RotatingFileHandler::class,
|
||||
'filename' => 'critical.log',
|
||||
@ -49,28 +49,56 @@ return [
|
||||
'levels' => [Monolog\Level::Debug, Monolog\Level::Info]
|
||||
],
|
||||
];
|
||||
},
|
||||
'developmentHandlers' => function(ContainerInterface $container) {
|
||||
$baseHandlers = $container->get('baseDefaultHandlers');
|
||||
$baseHandlers['critical']['handler'] = Monolog\Handler\StreamHandler::class;
|
||||
$baseHandlers['error']['handler'] = Monolog\Handler\StreamHandler::class;
|
||||
$baseHandlers['notices']['handler'] = Monolog\Handler\StreamHandler::class;
|
||||
$baseHandlers['notices']['filename'] = 'notices.log';
|
||||
$baseHandlers['debug']['handler'] = Monolog\Handler\StreamHandler::class;
|
||||
$baseHandlers['debug']['filename'] = 'debug.log';
|
||||
return $baseHandlers;
|
||||
},
|
||||
'defaultMonologHandlers' => function(ContainerInterface $container) {
|
||||
$key = 'baseDefault';
|
||||
if ($container->has('ENVIRONMENT') and $container->get('ENVIRONMENT') === 'development') {
|
||||
$key = 'development';
|
||||
if (!$container->has("{$key}Handlers")) {
|
||||
$key = 'baseDefault';
|
||||
}
|
||||
$baseHandlers['critical']['handler'] = Monolog\Handler\StreamHandler::class;
|
||||
$baseHandlers['error']['handler'] = Monolog\Handler\StreamHandler::class;
|
||||
$baseHandlers['notices']['handler'] = Monolog\Handler\StreamHandler::class;
|
||||
$baseHandlers['notices']['filename'] = 'notices.log';
|
||||
$baseHandlers['debug']['handler'] = Monolog\Handler\StreamHandler::class;
|
||||
$baseHandlers['debug']['filename'] = 'debug.log';
|
||||
}
|
||||
$baseHandlers = $container->get("{$key}Handlers");
|
||||
$builder = $container->get(Incoviba\Common\Implement\Log\Processor\ArrayBuilder::class);
|
||||
return $builder->build($baseHandlers);
|
||||
$handlers = [];
|
||||
foreach ($baseHandlers as $handlerData) {
|
||||
if (in_array($handlerData['handler'], [
|
||||
Monolog\Handler\StreamHandler::class,
|
||||
Monolog\Handler\RotatingFileHandler::class,
|
||||
])) {
|
||||
$params = [
|
||||
"/logs/{$handlerData['filename']}",
|
||||
];
|
||||
if ($handlerData['handler'] === Monolog\Handler\RotatingFileHandler::class) {
|
||||
$params []= 10;
|
||||
}
|
||||
$handler = new $handlerData['handler'](...$params)
|
||||
->setFormatter($container->get(Monolog\Formatter\LineFormatter::class));
|
||||
} elseif ($handlerData['handler'] === Incoviba\Common\Implement\Log\Handler\MySQL::class) {
|
||||
$params = [
|
||||
$container->get(Incoviba\Common\Define\Connection::class)
|
||||
];
|
||||
$handler = new $handlerData['handler'](...$params)
|
||||
->setFormatter(new \Incoviba\Common\Implement\Log\Formatter\PDO());
|
||||
} elseif ($handlerData['handler'] === Monolog\Handler\RedisHandler::class) {
|
||||
$params = [
|
||||
$container->get(Predis\ClientInterface::class),
|
||||
"logs:{$handlerData['name']}"
|
||||
];
|
||||
$handler = new $handlerData['handler'](...$params);
|
||||
}
|
||||
$params = [
|
||||
$handler,
|
||||
];
|
||||
if (is_array($handlerData['levels'])) {
|
||||
foreach ($handlerData['levels'] as $level) {
|
||||
$params []= $level;
|
||||
}
|
||||
} else {
|
||||
$params []= $handlerData['levels'];
|
||||
$params []= Monolog\Level::Emergency;
|
||||
}
|
||||
$params []= false;
|
||||
$handlers []= new Monolog\Handler\FilterHandler(...$params);
|
||||
}
|
||||
return $handlers;
|
||||
},
|
||||
Psr\Log\LoggerInterface::class => function(ContainerInterface $container) {
|
||||
return new Monolog\Logger('incoviba',
|
||||
@ -80,26 +108,6 @@ return [
|
||||
$container->get(DateTimeZone::class)
|
||||
);
|
||||
},
|
||||
'jsonHandlers' => function(ContainerInterface $container) {
|
||||
$baseHandlers = $container->get('baseDefaultHandlers');
|
||||
$baseHandlers['debug']['handler'] = Monolog\Handler\RotatingFileHandler::class;
|
||||
$baseHandlers['debug']['filename'] = 'info.json';
|
||||
$baseHandlers['debug']['formatter'] = Monolog\Formatter\JsonFormatter::class;
|
||||
$baseHandlers['notices']['handler'] = Monolog\Handler\RotatingFileHandler::class;
|
||||
$baseHandlers['notices']['filename'] = 'notices.json';
|
||||
$baseHandlers['notices']['formatter'] = Monolog\Formatter\JsonFormatter::class;
|
||||
return $baseHandlers;
|
||||
},
|
||||
'jsonLogger' => function(ContainerInterface $container) {
|
||||
$builder = $container->get(Incoviba\Common\Implement\Log\Processor\ArrayBuilder::class);
|
||||
$handlers = $builder->build($container->get('jsonHandlers'));
|
||||
return new Monolog\Logger('json',
|
||||
$handlers,
|
||||
[$container->get(Incoviba\Common\Implement\Log\Processor\User::class)]
|
||||
+ $container->get('baseMonologProcessors'),
|
||||
$container->get(DateTimeZone::class)
|
||||
);
|
||||
},
|
||||
'loginLogger' => function(ContainerInterface $container) {
|
||||
return new Monolog\Logger('login',
|
||||
[
|
||||
@ -118,35 +126,11 @@ return [
|
||||
$container->get(DateTimeZone::class)
|
||||
);
|
||||
},
|
||||
'externalHandlers' => function(ContainerInterface $container) {
|
||||
return [
|
||||
'critical' => [
|
||||
'handler' => Monolog\Handler\RedisHandler::class,
|
||||
'name' => 'external:critical',
|
||||
'levels' => Monolog\Level::Critical
|
||||
],
|
||||
'error' => [
|
||||
'handler' => Monolog\Handler\RedisHandler::class,
|
||||
'name' => 'external:error',
|
||||
'levels' => [Monolog\Level::Error, Monolog\Level::Error],
|
||||
],
|
||||
'notices' => [
|
||||
'handler' => Monolog\Handler\RedisHandler::class,
|
||||
'name' => 'external:notices',
|
||||
'levels' => [Monolog\Level::Notice, Monolog\Level::Warning],
|
||||
],
|
||||
'debug' => [
|
||||
'handler' => Monolog\Handler\RedisHandler::class,
|
||||
'name' => 'external:debug',
|
||||
'levels' => [Monolog\Level::Debug, Monolog\Level::Info],
|
||||
],
|
||||
];
|
||||
},
|
||||
'externalLogger' => function(ContainerInterface $container) {
|
||||
$builder = $container->get(Incoviba\Common\Implement\Log\Processor\ArrayBuilder::class);
|
||||
$handlers = $builder->build($container->get('externalHandlers'));
|
||||
return new Monolog\Logger('external',
|
||||
$handlers,
|
||||
[
|
||||
new Monolog\Handler\RedisHandler($container->get(Predis\ClientInterface::class), 'logs:external'),
|
||||
],
|
||||
$container->get('baseMonologProcessors'),
|
||||
$container->get(DateTimeZone::class)
|
||||
);
|
||||
|
@ -116,18 +116,7 @@ return [
|
||||
->registerSub($container->get(Incoviba\Service\Contabilidad\Cartola\BCI\Mes::class));
|
||||
},
|
||||
'TokuClient' => function(ContainerInterface $container) {
|
||||
$logger = $container->get('externalLogger');
|
||||
$stack = GuzzleHttp\HandlerStack::create();
|
||||
$stack->push(GuzzleHttp\Middleware::mapRequest(function(Psr\Http\Message\RequestInterface $request) use ($logger) {
|
||||
$logger->info('Toku Request', [
|
||||
'method' => $request->getMethod(),
|
||||
'uri' => (string) $request->getUri(),
|
||||
'headers' => $request->getHeaders(),
|
||||
'body' => $request->getBody()->getContents(),
|
||||
]);
|
||||
}));
|
||||
return new GuzzleHttp\Client([
|
||||
'handler' => $stack,
|
||||
'base_uri' => $container->get('TOKU_URL'),
|
||||
'headers' => [
|
||||
'x-api-key' => $container->get('TOKU_TOKEN'),
|
||||
@ -160,37 +149,25 @@ return [
|
||||
$container->get(Incoviba\Service\UF::class)
|
||||
);
|
||||
$service->setLogger($container->get('externalLogger'));
|
||||
$service->setAltLogger($container->get('jsonLogger'));
|
||||
return $service;
|
||||
},
|
||||
Incoviba\Service\Venta\MediosPago\Toku::class => function(ContainerInterface $container) {
|
||||
return new Incoviba\Service\Venta\MediosPago\Toku(
|
||||
return (new Incoviba\Service\Venta\MediosPago\Toku(
|
||||
$container->get('externalLogger'),
|
||||
$container->get(Incoviba\Common\Define\Connection::class),
|
||||
$container->get(Incoviba\Service\HMAC::class)
|
||||
)
|
||||
))
|
||||
->register('customer', $container->get(Incoviba\Service\Venta\MediosPago\Toku\Customer::class))
|
||||
->register('subscription', $container->get(Incoviba\Service\Venta\MediosPago\Toku\Subscription::class))
|
||||
->register('invoice', $container->get(Incoviba\Service\Venta\MediosPago\Toku\Invoice::class));
|
||||
},
|
||||
Pheanstalk\Pheanstalk::class => function(ContainerInterface $container) {
|
||||
return Pheanstalk\Pheanstalk::create(
|
||||
$container->get('BEANSTALKD_HOST'),
|
||||
$container->has('BEANSTALKD_PORT') ? $container->get('BEANSTALKD_PORT') : 11300
|
||||
);
|
||||
},
|
||||
Incoviba\Service\MQTT::class => function(ContainerInterface $container) {
|
||||
return new Incoviba\Service\MQTT()
|
||||
->register('default', $container->get(Incoviba\Service\MQTT\Pheanstalk::class));
|
||||
},
|
||||
Incoviba\Service\Queue::class => function(ContainerInterface $container) {
|
||||
return new Incoviba\Service\Queue(
|
||||
return (new Incoviba\Service\Queue(
|
||||
$container->get(Psr\Log\LoggerInterface::class),
|
||||
$container->get(Incoviba\Service\Job::class),
|
||||
$container->get(Incoviba\Service\Worker\Request::class)
|
||||
)
|
||||
))
|
||||
->register('request', $container->get(Incoviba\Service\Worker\Request::class))
|
||||
->register('service', $container->get(Incoviba\Service\Worker\Service::class))
|
||||
->register('dummy', $container->get(Incoviba\Service\Worker\Dummy::class))
|
||||
->register('checkExternal', $container->get(Incoviba\Service\Worker\CheckExternal::class));
|
||||
},
|
||||
@ -219,14 +196,10 @@ return [
|
||||
);
|
||||
},
|
||||
Incoviba\Service\External::class => function(ContainerInterface $container) {
|
||||
return new Incoviba\Service\External(
|
||||
return (new Incoviba\Service\External(
|
||||
$container->get('externalLogger'),
|
||||
$container->get(Incoviba\Service\Queue::class)
|
||||
)
|
||||
))
|
||||
->register($container->get(Incoviba\Service\Venta\MediosPago\Toku::class));
|
||||
},
|
||||
Incoviba\Service\FileUpload::class => function(ContainerInterface $container) {
|
||||
return new Incoviba\Service\FileUpload($container->get(Psr\Log\LoggerInterface::class))
|
||||
->register($container->get(Incoviba\Service\FileUpload\ExcelBase::class));
|
||||
}
|
||||
];
|
||||
|
@ -22,4 +22,20 @@ class Queues extends Ideal\Controller
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function jobs(ServerRequestInterface $request, ResponseInterface $response,
|
||||
Service\Queue $queueService): ResponseInterface
|
||||
{
|
||||
$output = [
|
||||
'jobs' => array_column($queueService->getPendingJobs(), 'id')
|
||||
];
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function run(ServerRequestInterface $request, ResponseInterface $response, Service\Queue $queueService,
|
||||
int $job_id): ResponseInterface
|
||||
{
|
||||
if ($queueService->runJob($job_id, $request)) {
|
||||
return $response->withStatus(200);
|
||||
}
|
||||
return $response->withStatus(422);
|
||||
}
|
||||
}
|
||||
|
@ -49,11 +49,8 @@ class Toku extends Controller
|
||||
ResponseFactoryInterface $responseFactory,
|
||||
Service\Venta\MediosPago\Toku $tokuService): ResponseInterface
|
||||
{
|
||||
$input = $request->getParsedBody();
|
||||
if ($input === null) {
|
||||
$body = $request->getBody()->getContents();
|
||||
$input = json_decode($body, true);
|
||||
}
|
||||
$body = $request->getBody()->getContents();
|
||||
$input = json_decode($body, true);
|
||||
$this->logger->info('Toku payment success', ['input' => $input]);
|
||||
try {
|
||||
if ($tokuService->successEvent($input)) {
|
||||
@ -114,7 +111,6 @@ class Toku extends Controller
|
||||
if (!$container->has('TOKU_ENV') or strtolower($container->get('TOKU_ENV')) !== 'sandbox') {
|
||||
return $this->withJson($response, ['success' => false], 409);
|
||||
}
|
||||
$this->logger->info('Toku reset');
|
||||
$input = $request->getParsedBody();
|
||||
$output = [
|
||||
'input' => $input,
|
||||
@ -123,9 +119,7 @@ class Toku extends Controller
|
||||
try {
|
||||
$tokuService->reset($input['skips'] ?? []);
|
||||
$output['success'] = true;
|
||||
} catch (Exception $exception) {
|
||||
$this->logger->error($exception);
|
||||
}
|
||||
} catch (Exception $exception) {}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function enqueue(ServerRequestInterface $request, ResponseInterface $response,
|
||||
@ -146,25 +140,4 @@ class Toku extends Controller
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
|
||||
public function update(ServerRequestInterface $request, ResponseInterface $response,
|
||||
Service\Venta\MediosPago\Toku $tokuService, ?string $type = null): ResponseInterface
|
||||
{
|
||||
$body = $request->getBody()->getContents();
|
||||
$input = json_decode($body, true);
|
||||
$output = [
|
||||
'type' => $type,
|
||||
'input' => $input,
|
||||
'output' => [],
|
||||
'success' => false
|
||||
];
|
||||
try {
|
||||
$output['output'] = $tokuService->update($input, $type);
|
||||
$output['success'] = true;
|
||||
} catch (Exception $exception) {
|
||||
$this->logger->error($exception);
|
||||
}
|
||||
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
||||
|
@ -1,16 +1,13 @@
|
||||
<?php
|
||||
namespace Incoviba\Controller\API\Ventas;
|
||||
|
||||
use DateTime;
|
||||
use Exception;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Incoviba\Common\Implement\Exception\{EmptyRedis,EmptyResult};
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Common\Implement\Exception\EmptyRedis;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use Incoviba\Controller\API\{withJson,emptyBody};
|
||||
use Incoviba\Controller\withRedis;
|
||||
use Incoviba\Exception\ServiceAction\Create;
|
||||
use Incoviba\Service;
|
||||
use Incoviba\Controller\withRedis;
|
||||
|
||||
class Precios
|
||||
{
|
||||
@ -54,29 +51,4 @@ class Precios
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function import(ServerRequestInterface $request, ResponseInterface $response,
|
||||
LoggerInterface $logger,
|
||||
Service\Venta\Precio $precioService): ResponseInterface
|
||||
{
|
||||
$body = $request->getParsedBody();
|
||||
$projectId = $body['project_id'];
|
||||
$date = $body['date'];
|
||||
$file = $request->getUploadedFiles()['file'];
|
||||
$output = [
|
||||
'input' => $body,
|
||||
'total' => 0,
|
||||
'precios' => [],
|
||||
'status' => false
|
||||
];
|
||||
$date = DateTime::createFromFormat('Y-m-d', $date);
|
||||
try {
|
||||
$output['precios'] = $precioService->import($projectId, $date, $file);
|
||||
$output['total'] = count($output['precios']);
|
||||
$output['status'] = true;
|
||||
} catch (Create | Exception $exception) {
|
||||
$logger->warning($exception);
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
||||
|
@ -4,9 +4,6 @@ namespace Incoviba\Controller;
|
||||
use Incoviba\Common\Alias\View;
|
||||
use Incoviba\Common\Implement\Exception\EmptyRedis;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use Incoviba\Exception\ServiceAction\Create;
|
||||
use Incoviba\Exception\ServiceAction\Read;
|
||||
use Incoviba\Exception\ServiceAction\Update;
|
||||
use Incoviba\Model;
|
||||
use Incoviba\Repository;
|
||||
use Incoviba\Service;
|
||||
@ -145,24 +142,9 @@ class Ventas
|
||||
return $view->render($response, 'ventas.desistir', compact('venta'));
|
||||
}
|
||||
public function desistida(ServerRequestInterface $request, ResponseInterface $response, Service\Venta $ventaService,
|
||||
Service\Venta\Pago $pagoService,
|
||||
View $view, int $venta_id): ResponseInterface
|
||||
{
|
||||
try {
|
||||
$venta = $ventaService->getById($venta_id);
|
||||
} catch (Read) {
|
||||
return $view->render($response->withStatus(404), 'not_found');
|
||||
}
|
||||
if ($venta->resciliacion() === null) {
|
||||
$pagoData = [
|
||||
'fecha' => $venta->currentEstado()->fecha->format('Y-m-d'),
|
||||
'valor' => 0
|
||||
];
|
||||
try {
|
||||
$pago = $pagoService->add($pagoData);
|
||||
$venta = $ventaService->edit($venta, ['resciliacion' => $pago->id]);
|
||||
} catch (Create | Update) {}
|
||||
}
|
||||
$venta = $ventaService->getById($venta_id);
|
||||
return $view->render($response, 'ventas.desistida', compact('venta'));
|
||||
}
|
||||
}
|
||||
|
@ -9,9 +9,9 @@ use Incoviba\Model;
|
||||
|
||||
class Precios
|
||||
{
|
||||
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view, Service\Proyecto $proyectoService, ?int $project_id = null): ResponseInterface
|
||||
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view, Service\Proyecto $proyectoService): ResponseInterface
|
||||
{
|
||||
$proyectos = array_map(function(Model\Proyecto $proyecto) {return ['id' => $proyecto->id, 'descripcion' => $proyecto->descripcion];}, $proyectoService->getVendibles());
|
||||
return $view->render($response, 'ventas.precios.list', compact('proyectos', 'project_id'));
|
||||
return $view->render($response, 'ventas.precios.list', compact('proyectos'));
|
||||
}
|
||||
}
|
||||
|
@ -1,18 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Exception;
|
||||
|
||||
use Throwable;
|
||||
use Exception;
|
||||
|
||||
abstract class MQTT extends Exception
|
||||
{
|
||||
public function __construct($message = "", $code = 0, ?Throwable $previous = null)
|
||||
{
|
||||
$baseCode = 700;
|
||||
$code = $baseCode + $code;
|
||||
if ($message == "") {
|
||||
$message = "MQTT Exception";
|
||||
}
|
||||
parent::__construct($message, $code, $previous);
|
||||
}
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Exception\MQTT;
|
||||
|
||||
use Throwable;
|
||||
use Incoviba\Exception\MQTT;
|
||||
|
||||
class MissingClient extends MQTT
|
||||
{
|
||||
public function __construct(string $host = '', ?Throwable $previous = null)
|
||||
{
|
||||
$message = 'Missing MQTT client';
|
||||
if ($host !== '') {
|
||||
$message = "{$message} for host {$host}";
|
||||
}
|
||||
$code = 1;
|
||||
parent::__construct($message, $code, $previous);
|
||||
}
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Exception\MQTT;
|
||||
|
||||
use Throwable;
|
||||
use Incoviba\Exception\MQTT;
|
||||
|
||||
class MissingJob extends MQTT
|
||||
{
|
||||
public function __construct(?Throwable $previous = null)
|
||||
{
|
||||
$message = 'Missing MQTT job';
|
||||
$code = 10;
|
||||
parent::__construct($message, $code, $previous);
|
||||
}
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Exception\MQTT;
|
||||
|
||||
use Throwable;
|
||||
use Incoviba\Exception\MQTT;
|
||||
|
||||
class RemoveJob extends MQTT
|
||||
{
|
||||
public function __construct(int $jobId, ?Throwable $previous = null)
|
||||
{
|
||||
$message = "Could not remove job {$jobId}";
|
||||
$code = 13;
|
||||
parent::__construct($message, $code, $previous);
|
||||
}
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Exception\MQTT;
|
||||
|
||||
use Throwable;
|
||||
use Incoviba\Exception\MQTT;
|
||||
|
||||
class SetJob extends MQTT
|
||||
{
|
||||
public function __construct(string $payload, ?Throwable $previous = null)
|
||||
{
|
||||
$message = "Could not set job with {$payload}";
|
||||
$code = 11;
|
||||
parent::__construct($message, $code, $previous);
|
||||
}
|
||||
}
|
@ -7,11 +7,11 @@ use Incoviba\Model\Inmobiliaria\TipoSociedad;
|
||||
class Inmobiliaria extends Model
|
||||
{
|
||||
public int $rut;
|
||||
public ?string $dv = null;
|
||||
public ?string $razon = null;
|
||||
public ?string $abreviacion = null;
|
||||
public ?TipoSociedad $tipoSociedad = null;
|
||||
public ?string $sigla = null;
|
||||
public ?string $dv;
|
||||
public ?string $razon;
|
||||
public ?string $abreviacion;
|
||||
public ?TipoSociedad $tipoSociedad;
|
||||
public string $sigla;
|
||||
|
||||
public function rut(): string
|
||||
{
|
||||
@ -37,7 +37,7 @@ class Inmobiliaria extends Model
|
||||
'razon' => $this->razon ?? '',
|
||||
'abreviacion' => $this->abreviacion ?? '',
|
||||
'tipo_sociedad' => $this->tipoSociedad ?? '',
|
||||
'sigla' => $this->sigla ?? '',
|
||||
'sigla' => $this->sigla,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
@ -7,14 +7,12 @@ class Job extends Ideal\Model
|
||||
{
|
||||
public array $configuration;
|
||||
public bool $executed = false;
|
||||
public int $retries = 0;
|
||||
|
||||
protected function jsonComplement(): array
|
||||
{
|
||||
return [
|
||||
'configuration' => $this->configuration,
|
||||
'executed' => $this->executed,
|
||||
'retries' => $this->retries
|
||||
'executed' => $this->executed
|
||||
];
|
||||
}
|
||||
}
|
||||
|
@ -6,12 +6,12 @@ use Incoviba\Model\Direccion;
|
||||
|
||||
class Datos
|
||||
{
|
||||
public ?string $sexo = null;
|
||||
public ?string $estado_civil = null;
|
||||
public ?string $profesion = null;
|
||||
public ?Direccion $direccion = null;
|
||||
public ?int $telefono = null;
|
||||
public ?string $email = null;
|
||||
public ?string $sexo;
|
||||
public ?string $estado_civil;
|
||||
public ?string $profesion;
|
||||
public ?Direccion $direccion;
|
||||
public ?int $telefono;
|
||||
public ?string $email;
|
||||
|
||||
public function jsonSerialize(): mixed
|
||||
{
|
||||
|
@ -9,7 +9,7 @@ class Propiedad extends Ideal\Model
|
||||
public array $unidades = [];
|
||||
public bool $estado;
|
||||
|
||||
public function principal(): ?Unidad
|
||||
public function principal(): Unidad
|
||||
{
|
||||
if (count($this->departamentos()) > 0) {
|
||||
return $this->departamentos()[0];
|
||||
|
@ -11,8 +11,8 @@ class Propietario extends Model
|
||||
public string $nombres;
|
||||
public array $apellidos;
|
||||
public Datos $datos;
|
||||
public ?Propietario $representante = null;
|
||||
public ?bool $otro = null;
|
||||
public ?Propietario $representante;
|
||||
public ?bool $otro;
|
||||
|
||||
public function rut(): string
|
||||
{
|
||||
|
@ -22,7 +22,7 @@ class Inmobiliaria extends Ideal\Repository
|
||||
|
||||
public function create(?array $data = null): Model\Inmobiliaria
|
||||
{
|
||||
$map = (new Implement\Repository\MapperParser(['rut', 'dv', 'razon', 'abreviacion', 'sigla']))
|
||||
$map = (new Implement\Repository\MapperParser(['dv', 'razon', 'abreviacion', 'sigla']))
|
||||
->register('sociedad', (new Implement\Repository\Mapper())
|
||||
->setProperty('tipoSociedad')
|
||||
->setFunction(function($data) {
|
||||
@ -32,9 +32,9 @@ class Inmobiliaria extends Ideal\Repository
|
||||
}
|
||||
public function save(Define\Model $model): Model\Inmobiliaria
|
||||
{
|
||||
$this->saveNew(
|
||||
['rut', 'dv', 'razon', 'abreviacion', 'cuenta', 'banco', 'sociedad'],
|
||||
[$model->rut, $model?->dv, $model?->razon, $model?->abreviacion, $model?->cuenta, $model?->banco->id, $model?->tipoSociedad->id]
|
||||
$model->rut = $this->saveNew(
|
||||
['dv', 'razon', 'abreviacion', 'cuenta', 'banco', 'sociedad'],
|
||||
[$model->dv, $model->razon, $model->abreviacion, $model->cuenta, $model->banco->id, $model->tipoSociedad->id]
|
||||
);
|
||||
return $model;
|
||||
}
|
||||
@ -43,11 +43,6 @@ class Inmobiliaria extends Ideal\Repository
|
||||
return $this->update($model, ['dv', 'razon', 'abreviacion', 'cuenta', 'banco', 'sociedad'], $new_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|array|null $sorting
|
||||
* @return array
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchAllActive(null|string|array $sorting = null): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
@ -63,18 +58,4 @@ class Inmobiliaria extends Ideal\Repository
|
||||
}
|
||||
return $this->fetchMany($query, [1, 8]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return Model\Inmobiliaria
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchByName(string $name): Model\Inmobiliaria
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select()
|
||||
->from($this->getTable())
|
||||
->where('razon LIKE :name OR abreviacion LIKE :name');
|
||||
return $this->fetchOne($query, ['name' => "%{$name}%"]);
|
||||
}
|
||||
}
|
||||
|
@ -85,11 +85,6 @@ class Proyecto extends Ideal\Repository
|
||||
return $this->fetchOne($query, [$id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return Model\Proyecto
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchByName(string $name): Model\Proyecto
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
|
@ -9,8 +9,7 @@ use Incoviba\Repository;
|
||||
|
||||
class ProyectoTipoUnidad extends Ideal\Repository
|
||||
{
|
||||
public function __construct(Define\Connection $connection, protected Repository\Proyecto $proyectoRepository,
|
||||
protected Repository\Proyecto\TipoUnidad $tipoUnidadRepository)
|
||||
public function __construct(Define\Connection $connection, protected Repository\Proyecto $proyectoRepository, protected Repository\Proyecto\TipoUnidad $tipoUnidadRepository)
|
||||
{
|
||||
parent::__construct($connection);
|
||||
$this->setTable('proyecto_tipo_unidad');
|
||||
|
@ -7,8 +7,6 @@ use Incoviba\Common\Define;
|
||||
use Incoviba\Common\Implement;
|
||||
use Incoviba\Model;
|
||||
use Incoviba\Repository;
|
||||
use PDO;
|
||||
use PDOException;
|
||||
|
||||
class EstadoPrecio extends Ideal\Repository
|
||||
{
|
||||
@ -46,24 +44,11 @@ class EstadoPrecio extends Ideal\Repository
|
||||
return $this->update($model, ['precio', 'estado', 'fecha'], $new_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $precio_id
|
||||
* @return array
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchByPrecio(int $precio_id): array
|
||||
{
|
||||
$query = "SELECT * FROM `{$this->getTable()}` WHERE `precio` = ?";
|
||||
error_log($query.PHP_EOL,3,'/logs/query.log');
|
||||
error_log($precio_id.PHP_EOL,3,'/logs/query.log');
|
||||
return $this->fetchMany($query, [$precio_id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $precio_id
|
||||
* @return Define\Model
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchCurrentByPrecio(int $precio_id): Define\Model
|
||||
{
|
||||
$query = "SELECT e1.*
|
||||
|
@ -2,8 +2,6 @@
|
||||
namespace Incoviba\Repository\Venta\MediosPago\Toku;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Incoviba\Common\Define;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Implement;
|
||||
@ -81,32 +79,4 @@ class Customer extends Ideal\Repository
|
||||
->where('toku_id = :toku_id');
|
||||
return $this->fetchOne($query, compact('toku_id'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchAllTokuIds(): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('toku_id')
|
||||
->from($this->getTable());
|
||||
try {
|
||||
$statement = $this->connection->query($query);
|
||||
} catch (PDOException $exception) {
|
||||
throw new Implement\Exception\EmptyResult($query, $exception);
|
||||
}
|
||||
if ($statement->rowCount() === 0) {
|
||||
throw new Implement\Exception\EmptyResult($query);
|
||||
}
|
||||
return $statement->fetchAll(PDO::FETCH_COLUMN);
|
||||
}
|
||||
public function removeByTokuId(string $toku_id): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->delete()
|
||||
->from($this->getTable())
|
||||
->where('toku_id = :toku_id');
|
||||
$this->connection->execute($query, compact('toku_id'));
|
||||
}
|
||||
}
|
||||
|
@ -2,8 +2,6 @@
|
||||
namespace Incoviba\Repository\Venta\MediosPago\Toku;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Incoviba\Common\Define;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Implement;
|
||||
@ -71,38 +69,4 @@ class Invoice extends Ideal\Repository
|
||||
->where('toku_id = :toku_id');
|
||||
return $this->fetchOne($query, compact('toku_id'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchAllTokuIds(): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('toku_id')
|
||||
->from($this->getTable());
|
||||
try {
|
||||
$statement = $this->connection->query($query);
|
||||
} catch (PDOException $exception) {
|
||||
throw new Implement\Exception\EmptyResult($query, $exception);
|
||||
}
|
||||
if ($statement->rowCount() === 0) {
|
||||
throw new Implement\Exception\EmptyResult($query);
|
||||
}
|
||||
return $statement->fetchAll(PDO::FETCH_COLUMN);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $toku_id
|
||||
* @return void
|
||||
* @throws PDOException
|
||||
*/
|
||||
public function removeByTokuId(string $toku_id): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->delete()
|
||||
->from($this->getTable())
|
||||
->where('toku_id = :toku_id');
|
||||
$this->connection->execute($query, compact('toku_id'));
|
||||
}
|
||||
}
|
||||
|
@ -2,8 +2,6 @@
|
||||
namespace Incoviba\Repository\Venta\MediosPago\Toku;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Incoviba\Common\Define;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Implement;
|
||||
@ -87,38 +85,4 @@ class Subscription extends Ideal\Repository
|
||||
->where("venta_id IN ({$idsQuery})");
|
||||
return $this->fetchMany($query, $ventas_ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws Implement\Exception\EmptyResult
|
||||
*/
|
||||
public function fetchAllTokuIds(): array
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('toku_id')
|
||||
->from($this->getTable());
|
||||
try {
|
||||
$statement = $this->connection->query($query);
|
||||
} catch (PDOException $exception) {
|
||||
throw new Implement\Exception\EmptyResult($query, $exception);
|
||||
}
|
||||
if ($statement->rowCount() === 0) {
|
||||
throw new Implement\Exception\EmptyResult($query);
|
||||
}
|
||||
return $statement->fetchAll(PDO::FETCH_COLUMN);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $toku_id
|
||||
* @return void
|
||||
* @throws PDOException
|
||||
*/
|
||||
public function removeByTokuId(string $toku_id): void
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->delete()
|
||||
->from($this->getTable())
|
||||
->where('toku_id = :toku_id');
|
||||
$this->connection->execute($query, compact('toku_id'));
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,6 @@
|
||||
<?php
|
||||
namespace Incoviba\Repository\Venta;
|
||||
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Incoviba\Common\Ideal;
|
||||
|
@ -4,7 +4,6 @@ namespace Incoviba\Repository\Venta;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Define;
|
||||
use Incoviba\Common\Implement;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use Incoviba\Model;
|
||||
|
||||
class TipoEstadoPrecio extends Ideal\Repository
|
||||
@ -32,18 +31,4 @@ class TipoEstadoPrecio extends Ideal\Repository
|
||||
{
|
||||
return $this->update($model, ['descripcion'], $new_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $descripcion
|
||||
* @return Model\Venta\TipoEstadoPrecio
|
||||
* @throws EmptyResult
|
||||
*/
|
||||
public function fetchByDescripcion(string $descripcion): Model\Venta\TipoEstadoPrecio
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select()
|
||||
->from($this->getTable())
|
||||
->where('descripcion = ?');
|
||||
return $this->fetchOne($query, [$descripcion]);
|
||||
}
|
||||
}
|
||||
|
@ -30,9 +30,8 @@ class Unidad extends Ideal\Repository
|
||||
public function save(Define\Model $model): Model\Venta\Unidad
|
||||
{
|
||||
$model->id = $this->saveNew(
|
||||
['proyecto', 'tipo', 'subtipo', 'piso', 'descripcion', 'abreviacion', 'orientacion', 'pt'],
|
||||
[$model->proyectoTipoUnidad->proyecto->id, $model->proyectoTipoUnidad->tipoUnidad->id, $model->subtipo,
|
||||
$model->piso, $model->descripcion, $model->proyectoTipoUnidad->abreviacion, $model->orientacion, $model->proyectoTipoUnidad->id]
|
||||
['subtipo', 'piso', 'descripcion', 'orientacion', 'pt'],
|
||||
[$model->subtipo, $model->piso, $model->descripcion, $model->orientacion, $model->proyectoTipoUnidad->id]
|
||||
);
|
||||
return $model;
|
||||
}
|
||||
|
@ -1,59 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Service;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Exception\ServiceAction;
|
||||
use Incoviba\Service\FileUpload\FileUploadInterface;
|
||||
|
||||
class FileUpload extends Ideal\Service implements FileUploadInterface
|
||||
{
|
||||
protected array $uploads = [];
|
||||
public function register(FileUploadInterface $fileUpload, string $filetype = 'default'): self
|
||||
{
|
||||
$this->uploads [$filetype]= $fileUpload;
|
||||
return $this;
|
||||
}
|
||||
/**
|
||||
* @param UploadedFileInterface $uploadedFile
|
||||
* @return array
|
||||
* @throws ServiceAction\Read
|
||||
*/
|
||||
public function getData(UploadedFileInterface $uploadedFile): array
|
||||
{
|
||||
try {
|
||||
$type = $this->getFileType($uploadedFile);
|
||||
} catch (InvalidArgumentException $exception) {
|
||||
throw new ServiceAction\Read(__CLASS__, $exception);
|
||||
}
|
||||
|
||||
$uploader = $this->getUploader($type);
|
||||
return $uploader->getData($uploadedFile);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param UploadedFileInterface $uploadedFile
|
||||
* @return string|null
|
||||
*/
|
||||
protected function getFileType(UploadedFileInterface $uploadedFile): ?string
|
||||
{
|
||||
$fileType = $uploadedFile->getClientMediaType();
|
||||
$typesMap = [
|
||||
'text/csv' => 'csv',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
|
||||
'application/vnd.ms-excel' => 'xls',
|
||||
];
|
||||
if (!array_key_exists($fileType, $typesMap)) {
|
||||
throw new InvalidArgumentException("File type {$fileType} not supported.");
|
||||
}
|
||||
return $typesMap[$fileType];
|
||||
}
|
||||
protected function getUploader(string $type): FileUploadInterface
|
||||
{
|
||||
if (!array_key_exists($type, $this->uploads)) {
|
||||
return $this->uploads['default'];
|
||||
}
|
||||
return $this->uploads[$type];
|
||||
}
|
||||
}
|
@ -1,147 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\FileUpload;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use OutOfBoundsException;
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
use PhpOffice\PhpSpreadsheet;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Exception\ServiceAction\Read;
|
||||
|
||||
class ExcelBase extends Ideal\Service implements FileUploadInterface
|
||||
{
|
||||
/**
|
||||
* @param UploadedFileInterface $uploadedFile
|
||||
* @return array
|
||||
* @throws Read
|
||||
*/
|
||||
public function getData(UploadedFileInterface $uploadedFile): array
|
||||
{
|
||||
$tempFilename = $this->createTempFile($uploadedFile);
|
||||
|
||||
$reader = PhpSpreadsheet\IOFactory::createReaderForFile($tempFilename);
|
||||
$reader->setReadDataOnly(true);
|
||||
$workbook = $reader->load($tempFilename);
|
||||
|
||||
try {
|
||||
$sheet = $this->findSheet($workbook);
|
||||
} catch (OutOfBoundsException $exception) {
|
||||
throw new Read(__CLASS__, $exception);
|
||||
}
|
||||
$titles = $this->extractTitles($sheet);
|
||||
$data = $this->extractData($sheet, $titles);
|
||||
|
||||
unlink($tempFilename);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param PhpSpreadsheet\Spreadsheet $workbook
|
||||
* @return PhpSpreadsheet\Worksheet\Worksheet
|
||||
* @throws OutOfBoundsException
|
||||
*/
|
||||
protected function findSheet(PhpSpreadsheet\Spreadsheet $workbook): PhpSpreadsheet\Worksheet\Worksheet
|
||||
{
|
||||
$sheet = $workbook->getActiveSheet();
|
||||
if ($this->findTable($sheet)) {
|
||||
return $sheet;
|
||||
}
|
||||
$sheets = $workbook->getAllSheets();
|
||||
foreach ($sheets as $sheet) {
|
||||
if ($this->findTable($sheet)) {
|
||||
return $sheet;
|
||||
}
|
||||
}
|
||||
throw new OutOfBoundsException('No table found in the workbook.');
|
||||
}
|
||||
protected function findTable(PhpSpreadsheet\Worksheet\Worksheet $sheet): bool
|
||||
{
|
||||
$rowIterator = $sheet->getRowIterator();
|
||||
foreach ($rowIterator as $row) {
|
||||
if ($row->isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$cellIterator = $row->getCellIterator();
|
||||
$cellIterator->setIterateOnlyExistingCells(true);
|
||||
if ($cellIterator->valid()) {
|
||||
return true;
|
||||
}
|
||||
foreach ($cellIterator as $cell) {
|
||||
if ($cell->getCalculatedValue() !== '') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
protected function createTempFile(UploadedFileInterface $uploadedFile): string
|
||||
{
|
||||
$filename = $uploadedFile->getClientFilename();
|
||||
$extension = pathinfo($filename, PATHINFO_EXTENSION);
|
||||
$tempFilename = tempnam(sys_get_temp_dir(), $extension);
|
||||
$uploadedFile->moveTo($tempFilename);
|
||||
|
||||
return $tempFilename;
|
||||
}
|
||||
protected function extractTitles(PhpSpreadsheet\Worksheet\Worksheet $sheet): array
|
||||
{
|
||||
$titles = [];
|
||||
$iterator = $sheet->getRowIterator();
|
||||
foreach ($iterator as $row) {
|
||||
if ($row->isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
$titles = $this->getRowData($row);
|
||||
break;
|
||||
}
|
||||
return $titles;
|
||||
}
|
||||
protected function extractData(PhpSpreadsheet\Worksheet\Worksheet $sheet, array $titles): array
|
||||
{
|
||||
$data = [];
|
||||
$rowIterator = $sheet->getRowIterator();
|
||||
foreach ($rowIterator as $row) {
|
||||
if ($row->isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
$cellIterator = $row->getCellIterator();
|
||||
$cellIterator->setIterateOnlyExistingCells(true);
|
||||
if ($cellIterator->current() === $titles[0]) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$rowData = $this->getRowData($row, $titles);
|
||||
} catch (InvalidArgumentException $exception) {
|
||||
if ($exception->getCode() === 1000) {
|
||||
continue;
|
||||
}
|
||||
throw $exception;
|
||||
}
|
||||
$data []= array_combine($titles, $rowData);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
protected function getRowData(PhpSpreadsheet\Worksheet\Row $row, ?array $titles = null): array
|
||||
{
|
||||
$data = [];
|
||||
$cellIterator = $row->getCellIterator();
|
||||
$cellIterator->setIterateOnlyExistingCells(true);
|
||||
foreach ($cellIterator as $cell) {
|
||||
if ($cell->getCalculatedValue() === null) {
|
||||
continue;
|
||||
}
|
||||
$value = $cell->getCalculatedValue();
|
||||
if ($value === null) {
|
||||
continue;
|
||||
}
|
||||
$value = mb_strtolower($value);
|
||||
if ($titles !== null and in_array($value, $titles)) {
|
||||
throw new InvalidArgumentException('Row matches title', 1000);
|
||||
}
|
||||
$data []= $value;
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\FileUpload;
|
||||
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
|
||||
interface FileUploadInterface
|
||||
{
|
||||
public function getData(UploadedFileInterface $uploadedFile): array;
|
||||
}
|
@ -1,135 +1,148 @@
|
||||
<?php
|
||||
namespace Incoviba\Service;
|
||||
|
||||
use DateInvalidTimeZoneException;
|
||||
use DateMalformedStringException;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use InvalidArgumentException;
|
||||
use OutOfRangeException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Exception\MQTT as MQTTException;
|
||||
use Incoviba\Exception\ServiceAction\{Create, Delete, Read, Update};
|
||||
use Incoviba\Model;
|
||||
use Incoviba\Common\Implement\Exception\EmptyRedis;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use Incoviba\Exception\ServiceAction\{Create, Read, Update};
|
||||
use Incoviba\Repository;
|
||||
use Incoviba\Model;
|
||||
|
||||
class Job extends Ideal\Service
|
||||
{
|
||||
public function __construct(LoggerInterface $logger, protected MQTT $mqttService,
|
||||
public function __construct(LoggerInterface $logger, protected Redis $redisService,
|
||||
protected Repository\Job $jobRepository)
|
||||
{
|
||||
parent::__construct($logger);
|
||||
}
|
||||
protected string $redisKey = 'jobs';
|
||||
|
||||
public function isPending(): bool
|
||||
public function getPending(null|string|array $orderBy = null): array
|
||||
{
|
||||
try {
|
||||
return $this->mqttService->exists();
|
||||
} catch (MQTTException $exception) {
|
||||
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
|
||||
return false;
|
||||
$jobs = $this->redisService->get($this->redisKey);
|
||||
if ($jobs === null) {
|
||||
return [];
|
||||
}
|
||||
$jobs = json_decode($jobs, true);
|
||||
if ($orderBy !== null) {
|
||||
uksort($jobs, function($a, $b) use ($orderBy) {
|
||||
return $a[$orderBy] <=> $b[$orderBy];
|
||||
});
|
||||
}
|
||||
return array_map([$this, 'load'], $jobs);
|
||||
} catch (EmptyRedis) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return Model\Job
|
||||
* @throws Read
|
||||
*/
|
||||
public function get(): Model\Job
|
||||
public function getPendingById(int $id): Model\Job
|
||||
{
|
||||
$jobs = $this->getJobs();
|
||||
try {
|
||||
return $this->load(json_decode($this->mqttService->get(), true));
|
||||
} catch (MQTTException $exception) {
|
||||
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
|
||||
$idx = $this->findJob($jobs, $id);
|
||||
} catch (EmptyResult $exception) {
|
||||
$exception = new OutOfRangeException('Job not found', count($jobs), $exception);
|
||||
throw new Read(__CLASS__, $exception);
|
||||
}
|
||||
return $this->load($jobs[$idx]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $configuration
|
||||
* @return Model\Job
|
||||
* @throws Create
|
||||
* @throws Read
|
||||
*/
|
||||
public function add(array $configuration): Model\Job
|
||||
{
|
||||
try {
|
||||
$now = (new DateTimeImmutable('now', new DateTimeZone($_ENV['TZ'] ?? 'America/Santiago')));
|
||||
} catch (DateMalformedStringException | DateInvalidTimeZoneException $exception) {
|
||||
$this->logger->warning($exception->getMessage(), ['exception' => $exception]);
|
||||
$now = new DateTimeImmutable();
|
||||
}
|
||||
$now = (new DateTimeImmutable('now', new DateTimeZone($_ENV['TZ'] ?? 'America/Santiago')));
|
||||
$data = [
|
||||
'id' => $now->format('Uu'),
|
||||
'configuration' => $configuration,
|
||||
'executed' => false,
|
||||
'created_at' => $now->format('Y-m-d H:i:s'),
|
||||
'updated_at' => null,
|
||||
'retries' => 0
|
||||
'updated_at' => null
|
||||
];
|
||||
$jobs = [];
|
||||
try {
|
||||
$this->mqttService->set(json_encode($data));
|
||||
} catch (MQTTException $exception) {
|
||||
throw new Create(__CLASS__, $exception);
|
||||
}
|
||||
$jobs = $this->redisService->get($this->redisKey);
|
||||
if ($jobs !== null) {
|
||||
$jobs = json_decode($jobs, true);
|
||||
}
|
||||
} catch (EmptyRedis) {}
|
||||
$jobs []= $data;
|
||||
$this->redisService->set($this->redisKey, json_encode($jobs), -1);
|
||||
return $this->load($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Model\Job $job
|
||||
* @return void
|
||||
* @throws Update
|
||||
*/
|
||||
public function update(Model\Job $job): void
|
||||
{
|
||||
try {
|
||||
$now = (new DateTimeImmutable('now', new DateTimeZone($_ENV['TZ'] ?? 'America/Santiago')));
|
||||
} catch (DateMalformedStringException | DateInvalidTimeZoneException) {
|
||||
$now = new DateTimeImmutable();
|
||||
}
|
||||
$data = json_decode(json_encode($job), true);
|
||||
$data['updated_at'] = $now->format('Y-m-d H:i:s');
|
||||
|
||||
try {
|
||||
$this->mqttService->update(json_encode($data));
|
||||
} catch (MQTTException $exception) {
|
||||
throw new Update(__CLASS__, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Model\Job $job
|
||||
* @throws Delete
|
||||
*/
|
||||
public function remove(Model\Job $job): void
|
||||
{
|
||||
try {
|
||||
$this->mqttService->remove();
|
||||
} catch (MQTTException $exception) {
|
||||
throw new Delete(__CLASS__, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Model\Job $job
|
||||
* @return bool
|
||||
* @throws Read
|
||||
*/
|
||||
public function execute(Model\Job $job): bool
|
||||
{
|
||||
$jobs = $this->getJobs();
|
||||
try {
|
||||
$this->mqttService->remove();
|
||||
return true;
|
||||
} catch (MQTTException $exception) {
|
||||
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
|
||||
return false;
|
||||
$idx = $this->findJob($jobs, $job->id);
|
||||
} catch (EmptyResult $exception) {
|
||||
$exception = new OutOfRangeException('Job not found', count($jobs), $exception);
|
||||
throw new Read(__CLASS__, $exception);
|
||||
}
|
||||
unset($jobs[$idx]);
|
||||
$this->redisService->set($this->redisKey, json_encode(array_values($jobs)), -1);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws Read
|
||||
*/
|
||||
protected function getJobs(): array
|
||||
{
|
||||
try {
|
||||
$jobs = $this->redisService->get($this->redisKey);
|
||||
} catch (EmptyRedis $exception) {
|
||||
throw new Read(__CLASS__, $exception);
|
||||
}
|
||||
if ($jobs === null) {
|
||||
$exception = new InvalidArgumentException("Redis Key {$this->redisKey} not found");
|
||||
throw new Read(__CLASS__, $exception);
|
||||
}
|
||||
return json_decode($jobs, true);
|
||||
}
|
||||
/**
|
||||
* @param array $jobs
|
||||
* @param int $id
|
||||
* @return int
|
||||
* @throws EmptyResult
|
||||
*/
|
||||
protected function findJob(array $jobs, int $id): int
|
||||
{
|
||||
$idx = array_find_key($jobs, function($job) use ($id) {
|
||||
return (int) $job['id'] === $id;
|
||||
});
|
||||
if ($idx === null) {
|
||||
throw new EmptyResult("SELECT * FROM jobs WHERE id = ?");
|
||||
}
|
||||
return $idx;
|
||||
}
|
||||
protected function load(array $data, ?int $id = null): Model\Job
|
||||
{
|
||||
$job = new Model\Job();
|
||||
$job->id = $id ?? $data['id'] ?? null;
|
||||
$job->configuration = $data['configuration'] ?? [];
|
||||
$job->executed = $data['executed'] ?? false;
|
||||
$job->retries = $data['retries'] ?? 0;
|
||||
return $job;
|
||||
}
|
||||
}
|
||||
|
@ -167,13 +167,8 @@ class Login
|
||||
try {
|
||||
$login = $this->repository->fetchActiveByUser($user->id);
|
||||
$this->logout($login->user);
|
||||
} catch (EmptyResult $exception) {
|
||||
$message []= "No logins for user {$user->name}";
|
||||
$message []= $exception->getMessage();
|
||||
$message []= $exception->getTraceAsString();
|
||||
error_log(implode(PHP_EOL, $message).PHP_EOL, 3, '/logs/login-exception.log');
|
||||
} catch (PDOException $exception) {
|
||||
error_log($exception.PHP_EOL, 3, '/logs/login-exception.log');
|
||||
} catch (PDOException | EmptyResult $exception) {
|
||||
error_log($exception, 3, '/logs/exception.log');
|
||||
}
|
||||
|
||||
try {
|
||||
@ -190,7 +185,7 @@ class Login
|
||||
$this->saveCookie($selector, $token, $login->dateTime->add(new DateInterval("PT{$this->max_login_time}H")));
|
||||
return true;
|
||||
} catch (PDOException | Exception $exception) {
|
||||
error_log($exception.PHP_EOL, 3, '/logs/login-exception.log');
|
||||
error_log($exception, 3, '/logs/exception.log');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
@ -1,102 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Service;
|
||||
|
||||
use Incoviba\Exception\MQTT as MQTTException;
|
||||
use Incoviba\Service\MQTT\MQTTInterface;
|
||||
|
||||
class MQTT implements MQTTInterface
|
||||
{
|
||||
protected array $clients = [];
|
||||
public function register(string $name, MQTTInterface $client): self
|
||||
{
|
||||
$this->clients[$name] = $client;
|
||||
return $this;
|
||||
}
|
||||
public function clientExists(string $name): bool
|
||||
{
|
||||
return isset($this->clients[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|null $name
|
||||
* @return MQTTInterface
|
||||
* @throws MQTTException/MissingClient
|
||||
*/
|
||||
public function getClient(?string $name = null): MQTTInterface
|
||||
{
|
||||
if ($name === null) {
|
||||
$name = array_keys($this->clients)[0];
|
||||
}
|
||||
if (!$this->clientExists($name)) {
|
||||
throw new MQTTException\MissingClient($name);
|
||||
}
|
||||
return $this->clients[$name];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|null $host
|
||||
* @return bool
|
||||
* @throws MQTTException/MissingClient
|
||||
* @throws MQTTException/MissingJob
|
||||
*/
|
||||
public function exists(?string $host = null): bool
|
||||
{
|
||||
$client = $this->getClient($host);
|
||||
return $client->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|null $host
|
||||
* @return string
|
||||
* @throws MQTTException/MissingClient
|
||||
* @throws MQTTException/MissingJob
|
||||
*/
|
||||
public function get(?string $host = null): string
|
||||
{
|
||||
$client = $this->getClient($host);
|
||||
return $client->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $value
|
||||
* @param int $delay
|
||||
* @param string|null $host
|
||||
* @return $this
|
||||
* @throws MQTTException/MissingClient
|
||||
* @throws MQTTException/SetJob
|
||||
*/
|
||||
public function set(string $value, int $delay = 0, ?string $host = null): self
|
||||
{
|
||||
$client = $this->getClient($host);
|
||||
$client->set($value, $delay);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int|null $jobId
|
||||
* @param string|null $host
|
||||
* @return $this
|
||||
* @throws MQTTException/MissingJob
|
||||
* @throws MQTTException/RemoveJob
|
||||
*/
|
||||
public function remove(?int $jobId = null, ?string $host = null): self
|
||||
{
|
||||
$this->getClient($host)->remove($jobId);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $newPayload
|
||||
* @param int|null $jobId
|
||||
* @param string|null $host
|
||||
* @return $this
|
||||
* @throws MQTTException/MissingJob
|
||||
* @throws MQTTException/RemoveJob
|
||||
* @throws MQTTException/SetJob
|
||||
*/
|
||||
public function update(string $newPayload, ?int $jobId = null, ?string $host = null): self
|
||||
{
|
||||
$this->getClient($host)->update($newPayload, $jobId);
|
||||
return $this;
|
||||
}
|
||||
}
|
@ -1,111 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\MQTT;
|
||||
|
||||
use Exception;
|
||||
use Incoviba\Exception\MQTT\MissingJob;
|
||||
use Incoviba\Exception\MQTT\RemoveJob;
|
||||
use Incoviba\Exception\MQTT\SetJob;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use xobotyi\beansclient;
|
||||
use xobotyi\beansclient\Exception\ClientException;
|
||||
use xobotyi\beansclient\Exception\CommandException;
|
||||
use xobotyi\beansclient\Exception\JobException;
|
||||
|
||||
class Beanstalkd implements MQTTInterface
|
||||
{
|
||||
/**
|
||||
* @throws JobException
|
||||
* @throws ClientException
|
||||
* @throws CommandException
|
||||
*/
|
||||
public function __construct(protected LoggerInterface $logger, protected beansclient\BeansClient $client,
|
||||
protected string $tube = 'default', protected int $ttr = beansclient\BeansClient::DEFAULT_TTR,
|
||||
protected int $priority = 1)
|
||||
{
|
||||
$this->client->watchTube($this->tube);
|
||||
}
|
||||
|
||||
public function exists(): bool
|
||||
{
|
||||
try {
|
||||
$stats = $this->client->statsTube($this->tube);
|
||||
return $stats['current-jobs-ready'] > 0;
|
||||
} catch (Exception $exception) {
|
||||
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected ?beansclient\Job $currentJob = null;
|
||||
public function get(): string
|
||||
{
|
||||
if (!$this->exists()) {
|
||||
throw new MissingJob();
|
||||
}
|
||||
try {
|
||||
$job = $this->client->watchTube($this->tube)->reserve();
|
||||
$this->currentJob = $job;
|
||||
return $job->payload;
|
||||
} catch (Exception $exception) {
|
||||
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
|
||||
throw new MissingJob($exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $value
|
||||
* @param int $delay
|
||||
* @return $this
|
||||
* @throws SetJob
|
||||
*/
|
||||
public function set(string $value, int $delay = 0): self
|
||||
{
|
||||
try {
|
||||
$this->client->useTube($this->tube)->put($value, $this->priority, $delay, $this->ttr ?? 0);
|
||||
} catch (Exception $exception) {
|
||||
$this->logger->error($exception->getMessage(), ['payload' => $value, 'delay' => $delay, 'exception' => $exception]);
|
||||
throw new SetJob($value, $exception);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $newPayload
|
||||
* @param int|null $jobId
|
||||
* @return self
|
||||
* @throws RemoveJob
|
||||
* @throws SetJob
|
||||
*/
|
||||
public function update(string $newPayload, ?int $jobId = null): self
|
||||
{
|
||||
if ($jobId === null) {
|
||||
$jobId = $this->currentJob->id;
|
||||
}
|
||||
return $this->remove($jobId)
|
||||
->set($newPayload);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int|null $jobId
|
||||
* @return $this
|
||||
* @throws RemoveJob
|
||||
*/
|
||||
public function remove(?int $jobId = null): self
|
||||
{
|
||||
if ($jobId === null) {
|
||||
$jobId = $this->currentJob->id;
|
||||
}
|
||||
try {
|
||||
if (!$this->client->useTube($this->tube)->delete($jobId)) {
|
||||
throw new JobException("Failed to delete job {$jobId}");
|
||||
}
|
||||
if ($this->currentJob !== null && $this->currentJob->id === $jobId) {
|
||||
$this->currentJob = null;
|
||||
}
|
||||
} catch (Exception $exception) {
|
||||
$this->logger->error($exception->getMessage(), ['jobId' => $jobId, 'exception' => $exception]);
|
||||
throw new RemoveJob($jobId, $exception);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\MQTT;
|
||||
|
||||
use Incoviba\Exception\MQTT\MissingJob;
|
||||
|
||||
interface MQTTInterface {
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function exists(): bool;
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws MissingJob
|
||||
*/
|
||||
public function get(): string;
|
||||
|
||||
/**
|
||||
* @param string $value
|
||||
* @param int $delay
|
||||
* @return self
|
||||
*/
|
||||
public function set(string $value, int $delay = 0): self;
|
||||
public function remove(?int $jobId = null): self;
|
||||
}
|
@ -1,59 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\MQTT;
|
||||
|
||||
use Incoviba\Common\Ideal\Service;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Pheanstalk as PBA;
|
||||
|
||||
class Pheanstalk extends Service implements MQTTInterface
|
||||
{
|
||||
const string DEFAULT_TUBE = 'default';
|
||||
const int DEFAULT_TTR = 60;
|
||||
const int DEFAULT_PRIORITY = 1_024;
|
||||
|
||||
public function __construct(LoggerInterface $logger, protected PBA\Pheanstalk $client, string $tubeName = self::DEFAULT_TUBE)
|
||||
{
|
||||
parent::__construct($logger);
|
||||
$this->tube = new PBA\Values\TubeName($tubeName);
|
||||
}
|
||||
|
||||
protected PBA\Values\TubeName $tube;
|
||||
|
||||
public function set(string $value, int $delay = 0): self
|
||||
{
|
||||
$this->client->useTube($this->tube);
|
||||
$this->client->put($value, self::DEFAULT_PRIORITY, $delay, self::DEFAULT_TTR);
|
||||
return $this;
|
||||
}
|
||||
public function exists(): bool
|
||||
{
|
||||
$stats = $this->client->statsTube($this->tube);
|
||||
return $stats->currentJobsReady > 0;
|
||||
}
|
||||
protected int $currentJobId;
|
||||
public function get(): string
|
||||
{
|
||||
$this->client->useTube($this->tube);
|
||||
$job = $this->client->reserve();
|
||||
$this->currentJobId = $job->getId();
|
||||
return $job->getData();
|
||||
}
|
||||
public function update(string $newPayload, ?int $jobId = null): self
|
||||
{
|
||||
if ($jobId === null) {
|
||||
$jobId = $this->currentJobId;
|
||||
}
|
||||
$this->remove($jobId);
|
||||
$this->set($newPayload);
|
||||
return $this;
|
||||
}
|
||||
public function remove(?int $jobId = null): self
|
||||
{
|
||||
if ($jobId === null) {
|
||||
$jobId = $this->currentJobId;
|
||||
}
|
||||
$this->client->useTube($this->tube);
|
||||
$this->client->delete(new PBA\Values\JobId($jobId));
|
||||
return $this;
|
||||
}
|
||||
}
|
@ -5,14 +5,12 @@ use Exception;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Exception\ServiceAction\{Create, Delete, Read, Update};
|
||||
use Incoviba\Exception\ServiceAction\{Create, Read};
|
||||
use Incoviba\Service;
|
||||
use Incoviba\Model;
|
||||
|
||||
class Queue extends Ideal\Service
|
||||
{
|
||||
public function __construct(LoggerInterface $logger, protected Service\Job $jobService, Worker $defaultWorker,
|
||||
protected int $maxRetries = 5)
|
||||
public function __construct(LoggerInterface $logger, protected Service\Job $jobService, Worker $defaultWorker)
|
||||
{
|
||||
parent::__construct($logger);
|
||||
$this->register('default', $defaultWorker);
|
||||
@ -36,13 +34,23 @@ class Queue extends Ideal\Service
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public function push(array $configuration): bool
|
||||
{
|
||||
return $this->enqueue($configuration);
|
||||
}
|
||||
|
||||
public function runJob(Model\Job $job, ?RequestInterface $request = null): bool
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getPendingJobs(): array
|
||||
{
|
||||
return $this->jobService->getPending();
|
||||
}
|
||||
public function runJob(int $job_id, ?RequestInterface $request = null): bool
|
||||
{
|
||||
try {
|
||||
$job = $this->jobService->getPendingById($job_id);
|
||||
} catch (Read $exception) {
|
||||
$this->logger->debug($exception);
|
||||
return false;
|
||||
}
|
||||
|
||||
$type = 'default';
|
||||
if (isset($job->configuration['type'])) {
|
||||
$type = strtolower($job->configuration['type']);
|
||||
@ -58,57 +66,38 @@ class Queue extends Ideal\Service
|
||||
|
||||
try {
|
||||
if (!$worker->execute($job)) {
|
||||
$this->logger->debug("Could not execute job {$job->id}");
|
||||
$job->retries++;
|
||||
$this->jobService->update($job);
|
||||
$this->logger->debug("Could not execute job {$job_id}");
|
||||
return false;
|
||||
}
|
||||
if (!$this->jobService->execute($job)) {
|
||||
$this->logger->debug("Could not remove job {$job->id}");
|
||||
$this->logger->debug("Could not remove job {$job_id}");
|
||||
return false;
|
||||
}
|
||||
} catch (Exception $exception) {
|
||||
$this->logger->warning("Could not run job {$job->id}", ['exception' => $exception]);
|
||||
$job->retries++;
|
||||
try {
|
||||
$this->jobService->update($job);
|
||||
} catch (Update $exception) {
|
||||
$this->logger->error($exception->getMessage(), ['job' => $job, 'exception' => $exception]);
|
||||
}
|
||||
$final = new Exception("Could not run job", 0, $exception);
|
||||
$this->logger->warning($final);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public function run(?RequestInterface $request = null): bool
|
||||
{
|
||||
if (!$this->jobService->isPending()) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
$job = $this->jobService->get();
|
||||
$jobs = $this->jobService->getPending();
|
||||
} catch (Read $exception) {
|
||||
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
|
||||
$final = new Exception("Could not get pending jobs", 0, $exception);
|
||||
$this->logger->warning($final);
|
||||
return false;
|
||||
}
|
||||
if ($job->retries >= $this->maxRetries) {
|
||||
|
||||
$errors = [];
|
||||
foreach ($jobs as $job) {
|
||||
try {
|
||||
$this->jobService->remove($job);
|
||||
} catch (Delete $exception) {
|
||||
$this->logger->error($exception->getMessage(), ['job' => $job, 'exception' => $exception]);
|
||||
$this->runJob($job->id, $request);
|
||||
} catch (Exception) {
|
||||
$errors []= $job->id;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
$this->runJob($job, $request);
|
||||
} catch (Exception) {
|
||||
$job->retries ++;
|
||||
try {
|
||||
$this->jobService->update($job);
|
||||
} catch (Update $exception) {
|
||||
$this->logger->error($exception->getMessage(), ['job' => $job, 'exception' => $exception]);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
return count($errors) === 0;
|
||||
}
|
||||
}
|
||||
|
@ -18,13 +18,9 @@ class UF
|
||||
|
||||
public function get(?DateTimeInterface $date = null): float
|
||||
{
|
||||
$today = new DateTimeImmutable();
|
||||
if ($date === null) {
|
||||
$date = new DateTimeImmutable();
|
||||
}
|
||||
if ($date->diff($today)->days < 0) {
|
||||
return 0.0;
|
||||
}
|
||||
/**
|
||||
* 1 - Redis
|
||||
* 2 - DB
|
||||
|
@ -4,7 +4,7 @@ namespace Incoviba\Service;
|
||||
use DateTimeInterface;
|
||||
use DateTimeImmutable;
|
||||
use DateMalformedStringException;
|
||||
use Incoviba\Service\Valor\Phone;
|
||||
use function PHPUnit\Framework\countOf;
|
||||
|
||||
class Valor
|
||||
{
|
||||
@ -40,14 +40,6 @@ class Valor
|
||||
}
|
||||
return $value / $this->ufService->get($date);
|
||||
}
|
||||
public function phone(): Phone
|
||||
{
|
||||
return new Phone();
|
||||
}
|
||||
public function telefono(): Phone
|
||||
{
|
||||
return $this->phone();
|
||||
}
|
||||
|
||||
protected function getDateTime(null|string|DateTimeInterface $date): DateTimeInterface
|
||||
{
|
||||
|
@ -1,28 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\Valor;
|
||||
|
||||
class Phone
|
||||
{
|
||||
public function toDatabase(?string $phone): ?int
|
||||
{
|
||||
if ($phone === null) {
|
||||
return null;
|
||||
}
|
||||
return (int) str_replace([' ', '+'], '', $phone) ?? null;
|
||||
}
|
||||
public function toDisplay(?int $phone): ?string
|
||||
{
|
||||
if ($phone === null) {
|
||||
return null;
|
||||
}
|
||||
$parts = preg_split('/(?=<country>\d{2})?(?=<area>\d)(?=<first>\d{4})(?=<last>\d{4})/', $phone);
|
||||
$output = [];
|
||||
if (array_key_exists('country', $parts)) {
|
||||
$output [] = "+{$parts[0]}";
|
||||
}
|
||||
$output [] = $parts[1] ?? '';
|
||||
$output [] = $parts[2] ?? '';
|
||||
$output [] = $parts[3] ?? '';
|
||||
return implode(' ', $output);
|
||||
}
|
||||
}
|
@ -1,10 +1,10 @@
|
||||
<?php
|
||||
namespace Incoviba\Service;
|
||||
|
||||
use Exception;
|
||||
use DateTimeImmutable;
|
||||
use DateMalformedStringException;
|
||||
use Incoviba\Exception\ServiceAction\{Create, Read, Update};
|
||||
use Incoviba\Common\Define;
|
||||
use PDOException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Common\Ideal\Service;
|
||||
@ -12,7 +12,7 @@ use Incoviba\Common\Implement;
|
||||
use Incoviba\Repository;
|
||||
use Incoviba\Model;
|
||||
|
||||
class Venta extends Service\Repository
|
||||
class Venta extends Service
|
||||
{
|
||||
public function __construct(
|
||||
LoggerInterface $logger,
|
||||
@ -189,11 +189,6 @@ class Venta extends Service\Repository
|
||||
}
|
||||
}
|
||||
|
||||
public function getRepository(): Define\Repository
|
||||
{
|
||||
return $this->ventaRepository;
|
||||
}
|
||||
|
||||
protected function process(Model\Venta $venta): Model\Venta
|
||||
{
|
||||
if ($venta->uf === 0.0) {
|
||||
|
@ -9,7 +9,6 @@ use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use Incoviba\Exception\ServiceAction\Create;
|
||||
use Incoviba\Exception\ServiceAction\Read;
|
||||
use Incoviba\Repository;
|
||||
use Incoviba\Model;
|
||||
|
||||
@ -24,20 +23,6 @@ class Cuota extends Ideal\Service
|
||||
parent::__construct($logger);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $cuota_id
|
||||
* @return Model\Venta\Cuota
|
||||
* @throws Read
|
||||
*/
|
||||
public function getById(int $cuota_id): Model\Venta\Cuota
|
||||
{
|
||||
try {
|
||||
return $this->process($this->cuotaRepository->fetchById($cuota_id));
|
||||
} catch (EmptyResult $exception) {
|
||||
throw new Read(__CLASS__, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
public function pendientes(): array
|
||||
{
|
||||
$cuotas = $this->cuotaRepository->fetchPendientes();
|
||||
@ -145,9 +130,4 @@ class Cuota extends Ideal\Service
|
||||
throw new Create(__CLASS__, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
protected function process(Model\Venta\Cuota $cuota): Model\Venta\Cuota
|
||||
{
|
||||
return $cuota;
|
||||
}
|
||||
}
|
||||
|
@ -1,13 +1,14 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\Venta\MediosPago;
|
||||
|
||||
use HttpException;
|
||||
use PDOException;
|
||||
use Psr\Http\Client\ClientExceptionInterface;
|
||||
use Psr\Http\Client\ClientInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Incoviba\Common\Define\Repository;
|
||||
use Incoviba\Common\Ideal\LoggerEnabled;
|
||||
use Incoviba\Common\Implement\Exception\{EmptyResponse, EmptyResult, HttpException};
|
||||
use Incoviba\Common\Implement\Exception\{EmptyResponse, EmptyResult};
|
||||
use Incoviba\Exception\InvalidResult;
|
||||
|
||||
abstract class AbstractEndPoint extends LoggerEnabled implements EndPoint
|
||||
@ -76,24 +77,14 @@ abstract class AbstractEndPoint extends LoggerEnabled implements EndPoint
|
||||
* @param array $data
|
||||
* @param array $validStatus
|
||||
* @param array $invalidStatus
|
||||
* @param string|null $accountKey
|
||||
* @return bool
|
||||
* @throws EmptyResponse
|
||||
*/
|
||||
protected function sendAdd(string $request_uri, array $data, array $validStatus, array $invalidStatus, ?string $accountKey = null): bool
|
||||
protected function sendAdd(string $request_uri, array $data, array $validStatus, array $invalidStatus): bool
|
||||
{
|
||||
$params = $this->mapParams($data);
|
||||
$this->logger->info('Send Add', ['uri' => $request_uri, 'params' => $params]);
|
||||
try {
|
||||
$options = [
|
||||
'json' => $params
|
||||
];
|
||||
if ($accountKey !== null) {
|
||||
$options['headers'] = [
|
||||
'X-Account-Key' => $accountKey
|
||||
];
|
||||
}
|
||||
$response = $this->client->post($request_uri, $options);
|
||||
$response = $this->client->post($request_uri, ['json' => $params]);
|
||||
} catch (ClientExceptionInterface $exception) {
|
||||
throw new EmptyResponse($request_uri, $exception);
|
||||
}
|
||||
@ -111,7 +102,6 @@ abstract class AbstractEndPoint extends LoggerEnabled implements EndPoint
|
||||
throw new EmptyResponse($request_uri);
|
||||
}
|
||||
$json = json_decode($contents, true);
|
||||
$this->logger->info('Add Response', $json);
|
||||
return $this->save($json);
|
||||
}
|
||||
|
||||
@ -120,23 +110,14 @@ abstract class AbstractEndPoint extends LoggerEnabled implements EndPoint
|
||||
* @param array $data
|
||||
* @param array $validStatus
|
||||
* @param array $invalidStatus
|
||||
* @param string|null $accountKey
|
||||
* @return bool
|
||||
* @throws EmptyResponse
|
||||
*/
|
||||
protected function sendEdit(string $request_uri, array $data, array $validStatus, array $invalidStatus, ?string $accountKey = null): bool
|
||||
protected function sendEdit(string $request_uri, array $data, array $validStatus, array $invalidStatus): bool
|
||||
{
|
||||
$params = $this->mapParams($data);
|
||||
try {
|
||||
$options = [
|
||||
'json' => $params
|
||||
];
|
||||
if ($accountKey !== null) {
|
||||
$options['headers'] = [
|
||||
'X-Account-Key' => $accountKey
|
||||
];
|
||||
}
|
||||
$response = $this->client->put($request_uri, $options);
|
||||
$response = $this->client->put($request_uri, ['json' => $params]);
|
||||
} catch (ClientExceptionInterface $exception) {
|
||||
throw new EmptyResponse($request_uri, $exception);
|
||||
}
|
||||
@ -152,25 +133,18 @@ abstract class AbstractEndPoint extends LoggerEnabled implements EndPoint
|
||||
* @param string $request_uri
|
||||
* @param array $validStatus
|
||||
* @param array $invalidStatus
|
||||
* @param array|null $data
|
||||
* @return void
|
||||
* @throws EmptyResponse
|
||||
*/
|
||||
protected function sendDelete(string $request_uri, array $validStatus, array $invalidStatus, ?array $data = null): void
|
||||
protected function sendDelete(string $request_uri, array $validStatus, array $invalidStatus): void
|
||||
{
|
||||
$this->logger->info('Send Delete', ['uri' => $request_uri]);
|
||||
try {
|
||||
$options = [];
|
||||
if ($data !== null) {
|
||||
$options = ['json' => $data];
|
||||
}
|
||||
$response = $this->client->delete($request_uri, $options);
|
||||
$response = $this->client->delete($request_uri);
|
||||
} catch (ClientExceptionInterface $exception) {
|
||||
throw new EmptyResponse($request_uri, $exception);
|
||||
}
|
||||
|
||||
$this->validateResponse($response, $request_uri, $validStatus, $invalidStatus);
|
||||
$this->logger->info('Delete Response', ['request_uri' => $request_uri]);
|
||||
}
|
||||
protected function doSave(Repository $repository, array $data): bool
|
||||
{
|
||||
|
@ -28,20 +28,18 @@ interface EndPoint
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @param string|null $accountKey
|
||||
* @return bool
|
||||
* @throws EmptyResponse
|
||||
*/
|
||||
public function add(array $data, ?string $accountKey = null): bool;
|
||||
public function add(array $data): bool;
|
||||
|
||||
/**
|
||||
* @param string $id
|
||||
* @param array $data
|
||||
* @param string|null $accountKey
|
||||
* @return bool
|
||||
* @throws EmptyResponse
|
||||
*/
|
||||
public function edit(string $id, array $data, ?string $accountKey = null): bool;
|
||||
public function edit(string $id, array $data): bool;
|
||||
|
||||
/**
|
||||
* @param string $id
|
||||
|
@ -1,10 +1,8 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\Venta\MediosPago;
|
||||
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use InvalidArgumentException;
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Incoviba\Common\Define\Connection;
|
||||
use Incoviba\Common\Ideal;
|
||||
@ -82,18 +80,13 @@ class Toku extends Ideal\Service
|
||||
try {
|
||||
return $this->subscription->getById($venta->id);
|
||||
} catch (InvalidResult $exception) {
|
||||
$inmobiliaria = $venta->proyecto()->inmobiliaria();
|
||||
$accountKey = null;
|
||||
try {
|
||||
$accountKey = $this->getAccountKey($inmobiliaria->rut);
|
||||
} catch (EmptyResult) {}
|
||||
$subscriptionData = [
|
||||
'customer' => $customer['toku_id'],
|
||||
'product_id' => $venta->id,
|
||||
'venta' => $venta
|
||||
];
|
||||
try {
|
||||
if (!$this->subscription->add($subscriptionData, $accountKey)) {
|
||||
if (!$this->subscription->add($subscriptionData)) {
|
||||
throw new InvalidResult("Could not save Subscription for Venta {$venta->id}", 409, $exception);
|
||||
}
|
||||
} catch (EmptyResponse $exception) {
|
||||
@ -102,6 +95,7 @@ class Toku extends Ideal\Service
|
||||
return $this->subscription->getById($venta->id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Model\Venta $venta
|
||||
* @param array $cuotas_ids
|
||||
@ -121,12 +115,6 @@ class Toku extends Ideal\Service
|
||||
});
|
||||
} catch (EmptyResponse) {}
|
||||
|
||||
$inmobiliaria = $venta->proyecto()->inmobiliaria();
|
||||
$accountKey = null;
|
||||
try {
|
||||
$accountKey = $this->getAccountKey($inmobiliaria->rut);
|
||||
} catch (EmptyResult) {}
|
||||
|
||||
$invoices = [];
|
||||
$errors = [];
|
||||
foreach ($venta->formaPago()->pie->cuotas() as $cuota) {
|
||||
@ -154,7 +142,7 @@ class Toku extends Ideal\Service
|
||||
'cuota' => $cuota,
|
||||
'venta' => $venta
|
||||
];
|
||||
if (!$this->invoice->add($invoiceData, $accountKey)) {
|
||||
if (!$this->invoice->add($invoiceData)) {
|
||||
throw new EmptyResponse("Could not add Invoice for Cuota {$cuota->id}", $exception);
|
||||
}
|
||||
$invoices []= $this->invoice->getById($cuota->id);
|
||||
@ -278,7 +266,6 @@ class Toku extends Ideal\Service
|
||||
try {
|
||||
$output['customer'] = $this->customer->reset($skips['customer'] ?? []);
|
||||
$output['subscription'] = $this->subscription->reset($skips['subscription'] ?? []);
|
||||
$output['payments'] = $this->invoice->resetPayments();
|
||||
$output['invoice'] = $this->invoice->reset($skips['invoice'] ?? []);
|
||||
} catch (InvalidResult $exception) {
|
||||
$this->logger->warning($exception);
|
||||
@ -302,95 +289,6 @@ class Toku extends Ideal\Service
|
||||
return $queues;
|
||||
}
|
||||
|
||||
public function update(array $ids, ?string $type = null): array
|
||||
{
|
||||
if ($type === null) {
|
||||
$types = [
|
||||
'customers',
|
||||
'subscriptions',
|
||||
'invoices'
|
||||
];
|
||||
$results = [];
|
||||
foreach ($types as $type) {
|
||||
$results[$type] = $this->update($ids[$type], $type);
|
||||
}
|
||||
return $results;
|
||||
}
|
||||
$results = [];
|
||||
switch ($type) {
|
||||
case 'subscriptions':
|
||||
try {
|
||||
$results['subscription'] = $this->subscription->update($ids);
|
||||
} catch (EmptyResult | EmptyResponse $exception) {
|
||||
$this->logger->error($exception);
|
||||
}
|
||||
break;
|
||||
case 'invoices':
|
||||
try {
|
||||
$results['invoice'] = $this->invoice->updateAll($ids);
|
||||
} catch (EmptyResult $exception) {
|
||||
$this->logger->error($exception);
|
||||
}
|
||||
break;
|
||||
}
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @param array $tokenConfig
|
||||
* @return bool
|
||||
*/
|
||||
public function validateToken(ServerRequestInterface $request, array $tokenConfig): bool
|
||||
{
|
||||
if (!$request->hasHeader('User-Agent') or !str_starts_with($request->getHeaderLine('User-Agent'), 'Toku-Webhooks')) {
|
||||
return false;
|
||||
}
|
||||
if (!$request->hasHeader('X-Datadog-Tags') or !$request->hasHeader('Tracestate')) {
|
||||
return false;
|
||||
}
|
||||
if (!$request->hasHeader('Toku-Signature')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$tokuSignature = $request->getHeaderLine('Toku-Signature');
|
||||
try {
|
||||
list($timestamp, $signature) = array_map(function($elem) {
|
||||
return explode('=', $elem)[1];
|
||||
}, explode(',', $tokuSignature));
|
||||
$body = $request->getBody()->getContents();
|
||||
$json = json_decode($body, true);
|
||||
if (!is_array($json)) {
|
||||
return false;
|
||||
}
|
||||
if (!array_key_exists('id', $json)) {
|
||||
return false;
|
||||
}
|
||||
$eventId = $json['id'];
|
||||
$eventType = $json['event_type'];
|
||||
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('secret')
|
||||
->from('toku_webhooks')
|
||||
->where('enabled = ? AND JSON_SEARCH(events, "one", ?) IS NOT NULL');
|
||||
$params = [true, $eventType];
|
||||
$statement = $this->connection->prepare($query);
|
||||
$statement->execute($params);
|
||||
$results = $statement->fetchAll(PDO::FETCH_COLUMN);
|
||||
if (count($results) === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (array_any($results, fn($secret) => $this->hmac->validate($timestamp, $signature, $eventId, $secret))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
} catch (Throwable $throwable) {
|
||||
$this->logger->error($throwable);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $request
|
||||
* @return bool
|
||||
@ -507,20 +405,54 @@ class Toku extends Ideal\Service
|
||||
$data['date'] = $data['transaction_date'];
|
||||
return $data;
|
||||
}
|
||||
protected function getAccountKey(int $sociedad_rut): string
|
||||
|
||||
public function validateToken(ServerRequestInterface $request, array $tokenConfig): bool
|
||||
{
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('account_key')
|
||||
->from('toku_accounts')
|
||||
->where('enabled = ? AND sociedad_rut = ?');
|
||||
$params = [true, $sociedad_rut];
|
||||
if (!$request->hasHeader('User-Agent') or !str_starts_with($request->getHeaderLine('User-Agent'), 'Toku-Webhooks')) {
|
||||
return false;
|
||||
}
|
||||
if (!$request->hasHeader('X-Datadog-Tags') or !$request->hasHeader('Tracestate')) {
|
||||
return false;
|
||||
}
|
||||
if (!$request->hasHeader('Toku-Signature')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$tokuSignature = $request->getHeaderLine('Toku-Signature');
|
||||
try {
|
||||
list($timestamp, $signature) = array_map(function($elem) {
|
||||
return explode('=', $elem)[1];
|
||||
}, explode(',', $tokuSignature));
|
||||
$body = $request->getBody()->getContents();
|
||||
$json = json_decode($body, true);
|
||||
if (!is_array($json)) {
|
||||
return false;
|
||||
}
|
||||
if (!array_key_exists('id', $json)) {
|
||||
return false;
|
||||
}
|
||||
$eventId = $json['id'];
|
||||
$eventType = $json['event_type'];
|
||||
|
||||
$query = $this->connection->getQueryBuilder()
|
||||
->select('secret')
|
||||
->from('toku_webhooks')
|
||||
->where('enabled = ? AND JSON_SEARCH(events, "one", ?) IS NOT NULL');
|
||||
$params = [true, $eventType];
|
||||
$statement = $this->connection->prepare($query);
|
||||
$statement->execute($params);
|
||||
return $statement->fetchColumn();
|
||||
} catch (PDOException $exception) {
|
||||
$this->logger->error($exception);
|
||||
throw new EmptyResult($query, $exception);
|
||||
$results = $statement->fetchAll(PDO::FETCH_COLUMN);
|
||||
if (count($results) === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (array_any($results, fn($secret) => $this->hmac->validate($timestamp, $signature, $eventId, $secret))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
} catch (Throwable $throwable) {
|
||||
$this->logger->error($throwable);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,10 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\Venta\MediosPago\Toku;
|
||||
|
||||
use PDOException;
|
||||
use Psr\Http\Client\ClientInterface;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResponse;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use Incoviba\Model;
|
||||
use Incoviba\Repository;
|
||||
use Incoviba\Service\Venta\MediosPago\AbstractEndPoint;
|
||||
|
||||
@ -29,15 +29,15 @@ class Customer extends AbstractEndPoint
|
||||
$request_uri = "/customers/{$id}";
|
||||
return $this->sendGet($request_uri, [200], [404, 422]);
|
||||
}
|
||||
public function add(array $data, ?string $accountKey = null): bool
|
||||
public function add(array $data): bool
|
||||
{
|
||||
$request_uri = "/customers";
|
||||
return $this->sendAdd($request_uri, $data, [200, 201], [400, 422], $accountKey);
|
||||
return $this->sendAdd($request_uri, $data, [200, 201], [400, 422]);
|
||||
}
|
||||
public function edit(string $id, array $data, ?string $accountKey = null): bool
|
||||
public function edit(string $id, array $data): bool
|
||||
{
|
||||
$request_uri = "customers/{$id}";
|
||||
return $this->sendEdit($request_uri, $data, [200], [400, 404, 422], $accountKey);
|
||||
return $this->sendEdit($request_uri, $data, [200], [400, 404, 422]);
|
||||
}
|
||||
public function delete(string $id): void
|
||||
{
|
||||
@ -47,24 +47,24 @@ class Customer extends AbstractEndPoint
|
||||
public function reset(array $skip = []): array
|
||||
{
|
||||
try {
|
||||
$tokuIds = $this->customerRepository->fetchAllTokuIds();
|
||||
$tokuIds = array_filter($tokuIds, function (string $tokuId) use ($skip) {
|
||||
return !in_array($tokuId, $skip);
|
||||
$customers = $this->customerRepository->fetchAll();
|
||||
$customers = array_filter($customers, function (Model\Venta\MediosPago\Toku\Customer $customer) use ($skip) {
|
||||
return !in_array($customer->toku_id, $skip);
|
||||
});
|
||||
} catch (EmptyResult $exception) {
|
||||
$this->logger->warning($exception);
|
||||
return [];
|
||||
}
|
||||
$this->logger->info('Resetando ' . count($tokuIds) . ' clientes');
|
||||
foreach ($tokuIds as $tokuId) {
|
||||
$this->logger->info('Resetando ' . count($customers) . ' clientes');
|
||||
foreach ($customers as $customer) {
|
||||
try {
|
||||
$this->delete($tokuId);
|
||||
$this->customerRepository->removeByTokuId($tokuId);
|
||||
} catch (EmptyResponse | PDOException $exception) {
|
||||
$this->logger->warning($exception, ['customer->toku_id' => $tokuId]);
|
||||
$this->delete($customer->toku_id);
|
||||
$this->customerRepository->remove($customer);
|
||||
} catch (EmptyResponse $exception) {
|
||||
$this->logger->warning($exception, ['customer' => $customer]);
|
||||
}
|
||||
}
|
||||
return $tokuIds;
|
||||
return $customers;
|
||||
}
|
||||
|
||||
public function save(array $data): bool
|
||||
@ -76,7 +76,7 @@ class Customer extends AbstractEndPoint
|
||||
$paramsMap = [
|
||||
'government_id' => 'rut',
|
||||
'external_id' => 'rut',
|
||||
'mail' => 'email',
|
||||
'email' => 'email',
|
||||
'name' => 'nombreCompleto',
|
||||
'phone_number' => 'telefono',
|
||||
'pac_mandate_id' => null,
|
||||
|
@ -4,10 +4,7 @@ namespace Incoviba\Service\Venta\MediosPago\Toku;
|
||||
use DateMalformedStringException;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Psr\Http\Client\ClientInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResponse;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use Incoviba\Exception\InvalidResult;
|
||||
@ -40,15 +37,15 @@ class Invoice extends AbstractEndPoint
|
||||
$request_uri = "/invoices/{$id}";
|
||||
return $this->sendGet($request_uri, [200], [404]);
|
||||
}
|
||||
public function add(array $data, ?string $accountKey = null): bool
|
||||
public function add(array $data): bool
|
||||
{
|
||||
$request_uri = "/invoices";
|
||||
return $this->sendAdd($request_uri, $data, [200, 201], [400, 409, 422], $accountKey);
|
||||
return $this->sendAdd($request_uri, $data, [200, 201], [400, 409, 422]);
|
||||
}
|
||||
public function edit(string $id, array $data, ?string $accountKey = null): bool
|
||||
public function edit(string $id, array $data): bool
|
||||
{
|
||||
$request_uri = "/invoices/{$id}";
|
||||
return $this->sendEdit($request_uri, $data, [200], [400, 404, 409, 422], $accountKey);
|
||||
return $this->sendEdit($request_uri, $data, [200], [400, 404, 409, 422]);
|
||||
}
|
||||
public function delete(string $id): void
|
||||
{
|
||||
@ -58,91 +55,23 @@ class Invoice extends AbstractEndPoint
|
||||
public function reset(array $skip = []): array
|
||||
{
|
||||
try {
|
||||
$tokuIds = $this->invoiceRepository->fetchAllTokuIds();
|
||||
$tokuIds = array_filter($tokuIds, function (string $tokuId) use ($skip) {
|
||||
return !in_array($tokuId, $skip);
|
||||
$invoices = $this->invoiceRepository->fetchAll();
|
||||
$invoices = array_filter($invoices, function (Model\Venta\MediosPago\Toku\Invoice $invoice) use ($skip) {
|
||||
return !in_array($invoice->toku_id, $skip);
|
||||
});
|
||||
} catch (EmptyResult $exception) {
|
||||
$this->logger->warning($exception);
|
||||
return [];
|
||||
}
|
||||
foreach ($tokuIds as $tokuId) {
|
||||
foreach ($invoices as $invoice) {
|
||||
try {
|
||||
$this->delete($tokuId);
|
||||
$this->invoiceRepository->removeByTokuId($tokuId);
|
||||
} catch (EmptyResponse | PDOException $exception) {
|
||||
$this->logger->warning($exception, ['invoice->toku_id' => $tokuId]);
|
||||
$this->delete($invoice->toku_id);
|
||||
$this->invoiceRepository->remove($invoice);
|
||||
} catch (EmptyResponse $exception) {
|
||||
$this->logger->warning($exception, ['invoice' => $invoice]);
|
||||
}
|
||||
}
|
||||
return $tokuIds;
|
||||
}
|
||||
public function resetPayments(): array
|
||||
{
|
||||
$page = 1;
|
||||
$pageSize = 1000;
|
||||
$totalPayments = [];
|
||||
while (true) {
|
||||
if ($page > 100) {
|
||||
break;
|
||||
}
|
||||
try {
|
||||
$request_uri = "/organization/payments?page=1&page_size=1000";
|
||||
$payments = $this->sendGet($request_uri, [200], [404, 422]);
|
||||
} catch (EmptyResponse $exception) {
|
||||
$this->logger->warning($exception, ['request_uri' => $request_uri]);
|
||||
return [];
|
||||
}
|
||||
if (array_key_exists('message', $payments)) {
|
||||
break;
|
||||
}
|
||||
$this->altLogger->info('Reset Payments', ['count' => count($payments), 'payments' => $payments]);
|
||||
$query = [];
|
||||
/*
|
||||
"id": "pay_79zh1OU1pVV5g0V0I6kShf5AF-I24cUn",
|
||||
"created_at": "2025-06-07T07:08:51+0000",
|
||||
"deleted_at": null,
|
||||
"invoice": "in_IhbKbT21x0ADlnKRCbV57sn2DDI8neq0",
|
||||
"customer": "cus_bTXPBVopZxKOqTOWzRZkhvDEM9XXtvWh",
|
||||
"government_id": "175181431",
|
||||
"name": "Augusto Felipe Schilfferli Rojas",
|
||||
"product_id": "1304-d1749582981383358",
|
||||
"due_date": "2024-11-01",
|
||||
"transaction_date": "2025-06-07T07:08:51+0000",
|
||||
"payment_amount": 14.4822,
|
||||
"buy_order": null,
|
||||
"processed_by_toku": false,
|
||||
"payment_method": null,
|
||||
"card_type": null,
|
||||
"card_number": null,
|
||||
"payment_type": null,
|
||||
"authorization_code": null,
|
||||
"mc_order_id": null,
|
||||
"amount_paid": 14.4822
|
||||
*/
|
||||
foreach ($payments as $payment) {
|
||||
$query[] = [
|
||||
'payment_amount' => $payment['payment_amount'],
|
||||
'payment_date' => $payment['transaction_date'],
|
||||
'payment_method' => $payment['payment_method'],
|
||||
'product_id' => $payment['product_id'],
|
||||
'due_date' => $payment['due_date'],
|
||||
];
|
||||
}
|
||||
try {
|
||||
$request_uri = "/payments";
|
||||
$this->sendDelete($request_uri, [204], [404, 422], ['payments' => $query]);
|
||||
} catch (EmptyResponse $exception) {
|
||||
$this->logger->warning($exception, ['request_uri' => $request_uri]);
|
||||
return [];
|
||||
}
|
||||
$this->altLogger->info('Reset Payments Payload', ['count' => count($payments), 'payments' => $query]);
|
||||
$totalPayments = array_merge($totalPayments, $payments);
|
||||
if (count($payments) < $pageSize) {
|
||||
break;
|
||||
}
|
||||
$page++;
|
||||
}
|
||||
return $totalPayments;
|
||||
return $invoices;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -200,58 +129,15 @@ class Invoice extends AbstractEndPoint
|
||||
return $this->pagoService->depositar($invoice->cuota->pago, $date);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $idsData
|
||||
* @return array
|
||||
* @throws EmptyResult
|
||||
*/
|
||||
public function updateAll(array $idsData): array
|
||||
{
|
||||
$tokuIds = array_column($idsData, 'toku_id');
|
||||
$oldIds = array_column($idsData, 'product_id');
|
||||
|
||||
$placeholders = array_map(fn($id) => "id{$id}", array_keys($oldIds));
|
||||
$placeholdersString = implode(', ', array_map(fn($id) => ":{$id}", $placeholders));
|
||||
$query = $this->pagoService->getRepository()->getConnection()->getQueryBuilder()
|
||||
->select('pago.id, CONCAT_WS("-", unidad.descripcion, CONCAT_WS("-", propietario.rut, propietario.dv)) AS old_pid')
|
||||
->from('pago')
|
||||
->joined('JOIN cuota ON cuota.pago = pago.id')
|
||||
->joined('JOIN venta ON venta.pie = cuota.pie')
|
||||
->joined('JOIN propietario ON propietario.rut = venta.propietario')
|
||||
->joined('JOIN propiedad_unidad pu ON pu.propiedad = venta.propiedad')
|
||||
->joined('JOIN unidad ON pu.unidad = unidad.id')
|
||||
->having("old_pid IN ({$placeholdersString})");
|
||||
$values = array_combine($placeholders, $oldIds);
|
||||
try {
|
||||
$statement = $this->pagoService->getRepository()->getConnection()->execute($query, $values);
|
||||
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $exception) {
|
||||
$this->logger->error($exception);
|
||||
throw new EmptyResult($query, $exception);
|
||||
}
|
||||
|
||||
$ids = array_column($results, 'pago.id');
|
||||
$newIds = array_combine($ids, $tokuIds);
|
||||
return array_map(fn($id) => ['product_id' => $id, 'toku_id' => $newIds[$id]], $ids);
|
||||
}
|
||||
|
||||
public function save(array $data): bool
|
||||
{
|
||||
return $this->doSave($this->invoiceRepository, $data);
|
||||
}
|
||||
|
||||
protected LoggerInterface $altLogger;
|
||||
public function setAltLogger(LoggerInterface $altLogger): self
|
||||
{
|
||||
$this->altLogger = $altLogger;
|
||||
return $this;
|
||||
}
|
||||
|
||||
protected function mapParams(array $data): array
|
||||
{
|
||||
$paramsMap = [
|
||||
'customer' => 'customer',
|
||||
'product_id' => 'cuota_id',
|
||||
'product_id' => 'product_id',
|
||||
'due_date' => 'fecha',
|
||||
'subscription' => 'subscription',
|
||||
'amount' => 'valor',
|
||||
@ -278,15 +164,14 @@ class Invoice extends AbstractEndPoint
|
||||
continue;
|
||||
}
|
||||
if ($ref === 'valor') {
|
||||
/*$valor = 0;
|
||||
$valor = 0;
|
||||
if ($data['cuota']->pago->fecha <= $today) {
|
||||
$valor = $data['cuota']->pago->valor();
|
||||
}
|
||||
if ($valor === 0) {
|
||||
$valor = $data['cuota']->pago->valor / $data['venta']->uf;
|
||||
}
|
||||
$params[$key] = $valor;*/
|
||||
$params[$key] = $data['cuota']->pago->valor;
|
||||
$params[$key] = $valor;
|
||||
continue;
|
||||
}
|
||||
if ($ref === 'datosCuota') {
|
||||
|
@ -1,8 +1,6 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\Venta\MediosPago\Toku;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Psr\Http\Client\ClientInterface;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResponse;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
@ -35,15 +33,15 @@ class Subscription extends AbstractEndPoint
|
||||
$request_uri = "/subscriptions/{$id}";
|
||||
return $this->sendGet($request_uri, [200], [401, 404, 422]);
|
||||
}
|
||||
public function add(array $data, ?string $accountKey = null): bool
|
||||
public function add(array $data): bool
|
||||
{
|
||||
$request_uri = '/subscriptions';
|
||||
return $this->sendAdd($request_uri, $data, [200, 201], [401, 404, 409, 422], $accountKey);
|
||||
return $this->sendAdd($request_uri, $data, [200, 201], [401, 404, 409, 422]);
|
||||
}
|
||||
public function edit(string $id, array $data, ?string $accountKey = null): bool
|
||||
public function edit(string $id, array $data): bool
|
||||
{
|
||||
$request_uri = "/subscriptions/{$id}";
|
||||
return $this->sendEdit($request_uri, $data, [200], [401, 404, 409, 422], $accountKey);
|
||||
return $this->sendEdit($request_uri, $data, [200], [401, 404, 409, 422]);
|
||||
}
|
||||
public function delete(string $id): void
|
||||
{
|
||||
@ -53,23 +51,23 @@ class Subscription extends AbstractEndPoint
|
||||
public function reset(array $skip = []): array
|
||||
{
|
||||
try {
|
||||
$tokuIds = $this->subscriptionRepsitory->fetchAllTokuIds();
|
||||
$tokuIds = array_filter($tokuIds, function (string $tokuId) use ($skip) {
|
||||
return !in_array($tokuId, $skip);
|
||||
$subscriptions = $this->subscriptionRepsitory->fetchAll();
|
||||
$subscriptions = array_filter($subscriptions, function (Venta\MediosPago\Toku\Subscription $subscription) use ($skip) {
|
||||
return !in_array($subscription->toku_id, $skip);
|
||||
});
|
||||
} catch (EmptyResult $exception) {
|
||||
$this->logger->warning($exception);
|
||||
return [];
|
||||
}
|
||||
foreach ($tokuIds as $tokuId) {
|
||||
foreach ($subscriptions as $subscription) {
|
||||
try {
|
||||
$this->delete($tokuId);
|
||||
$this->subscriptionRepsitory->removeByTokuId($tokuId);
|
||||
} catch (EmptyResponse | PDOException $exception) {
|
||||
$this->logger->warning($exception, ['subscription->toku_id' => $tokuId]);
|
||||
$this->delete($subscription->toku_id);
|
||||
$this->subscriptionRepsitory->remove($subscription);
|
||||
} catch (EmptyResponse $exception) {
|
||||
$this->logger->warning($exception, ['subscription' => $subscription]);
|
||||
}
|
||||
}
|
||||
return $tokuIds;
|
||||
return $subscriptions;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -112,101 +110,6 @@ class Subscription extends AbstractEndPoint
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $idsData
|
||||
* @return array
|
||||
* @throws EmptyResult
|
||||
* @throws EmptyResponse
|
||||
*/
|
||||
public function update(array $idsData): array
|
||||
{
|
||||
$tokuIds = array_column($idsData, 'toku_id');
|
||||
$oldPids = array_column($idsData, 'product_id');
|
||||
|
||||
$placeholders = array_map(fn($id) => "id{$id}", array_keys($oldPids));
|
||||
$placeholdersString = implode(', ', array_map(fn($id) => ":{$id}", $placeholders));
|
||||
$query = $this->ventaService->getRepository()->getConnection()->getQueryBuilder()
|
||||
->select('venta.id, CONCAT_WS("-", unidad.descripcion, CONCAT_WS("-", propietario.rut, propietario.dv)) AS old_pid')
|
||||
->from('venta')
|
||||
->joined('JOIN propietario ON propietario.rut = venta.propietario')
|
||||
->joined('JOIN propiedad_unidad pu ON pu.propiedad = venta.propiedad')
|
||||
->joined('JOIN unidad ON pu.unidad = unidad.id')
|
||||
->having("old_pid IN ({$placeholdersString})");
|
||||
$values = array_combine($placeholders, $oldPids);
|
||||
try {
|
||||
$statement = $this->ventaService->getRepository()->getConnection()->execute($query, $values);
|
||||
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $exception) {
|
||||
$this->logger->error($exception->getMessage(), [
|
||||
'query' => $query,
|
||||
'values' => $values,
|
||||
'ids' => $idsData,
|
||||
'exception' => $exception]);
|
||||
throw new EmptyResult($query, $exception);
|
||||
}
|
||||
|
||||
$accountKeys = $this->getAccountKey(array_column($results, 'id'));
|
||||
|
||||
$newPids = [];
|
||||
$keys = [];
|
||||
foreach ($results as $result) {
|
||||
$idx = array_search($result['old_pid'], $oldPids);
|
||||
$newPids[$idx] = $result['id'];
|
||||
if (array_key_exists($result['id'], $accountKeys)) {
|
||||
$keys[$idx] = $accountKeys[$result['id']];
|
||||
}
|
||||
}
|
||||
$output = [];
|
||||
foreach ($tokuIds as $idx => $tokuId) {
|
||||
if (!isset($newPids[$idx])) {
|
||||
continue;
|
||||
}
|
||||
$data = [
|
||||
'product_id' => $newPids[$idx],
|
||||
];
|
||||
try {
|
||||
if (!$this->edit($tokuId, $data, array_key_exists($idx, $keys) ? $keys[$idx] : null)) {
|
||||
$this->logger->error('Error while updating Toku', [
|
||||
'toku_id' => $tokuId,
|
||||
'old_pid' => $oldPids[$idx],
|
||||
'product_id' => $newPids[$idx],
|
||||
'account_key' => array_key_exists($idx, $keys) ? $keys[$idx] : null]);
|
||||
$output[] = [
|
||||
'toku_id' => $tokuId,
|
||||
'old_pid' => $oldPids[$idx],
|
||||
'product_id' => $newPids[$idx],
|
||||
'account_key' => array_key_exists($idx, $keys) ? $keys[$idx] : null,
|
||||
'error' => 'Error while updating Toku'
|
||||
];
|
||||
continue;
|
||||
}
|
||||
} catch (EmptyResponse $exception) {
|
||||
$this->logger->error($exception->getMessage(), [
|
||||
'toku_id' => $tokuId,
|
||||
'old_pid' => $oldPids[$idx],
|
||||
'product_id' => $newPids[$idx],
|
||||
'account_key' => array_key_exists($idx, $keys) ? $keys[$idx] : null,
|
||||
'exception' => $exception]);
|
||||
$output[] = [
|
||||
'toku_id' => $tokuId,
|
||||
'old_pid' => $oldPids[$idx],
|
||||
'product_id' => $newPids[$idx],
|
||||
'account_key' => array_key_exists($idx, $keys) ? $keys[$idx] : null,
|
||||
'error' => $exception->getMessage()
|
||||
];
|
||||
continue;
|
||||
}
|
||||
$output[] = [
|
||||
'toku_id' => $tokuId,
|
||||
'old_pid' => $oldPids[$idx],
|
||||
'product_id' => $newPids[$idx],
|
||||
'account_key' => array_key_exists($idx, $keys) ? $keys[$idx] : null
|
||||
];
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
public function save(array $data): bool
|
||||
{
|
||||
return $this->doSave($this->subscriptionRepsitory, $data);
|
||||
@ -229,11 +132,11 @@ class Subscription extends AbstractEndPoint
|
||||
if ($ref === null) {
|
||||
continue;
|
||||
}
|
||||
if ($ref === 'pieValor' and array_key_exists('venta', $data)) {
|
||||
$params[$key] = $data['venta']?->formaPago()?->pie?->valor ?? 0;
|
||||
if ($ref === 'pieValor') {
|
||||
$params[$key] = $data['venta']->formaPago()?->pie?->valor ?? 0;
|
||||
continue;
|
||||
}
|
||||
if ($ref === 'datosVenta' and array_key_exists('venta', $data)) {
|
||||
if ($ref === 'datosVenta') {
|
||||
$params[$key] = $this->datosVenta($data['venta']);
|
||||
continue;
|
||||
}
|
||||
@ -265,38 +168,4 @@ class Subscription extends AbstractEndPoint
|
||||
'Unidades' => $venta->propiedad()->summary()
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $ventaIds
|
||||
* @return array
|
||||
* @throws EmptyResult
|
||||
*/
|
||||
protected function getAccountKey(array $ventaIds): array
|
||||
{
|
||||
$placeholders = array_map(fn($id) => "id{$id}", array_keys($ventaIds));
|
||||
$placeholdersString = implode(', ', array_map(fn($id) => ":{$id}", $placeholders));
|
||||
$query = $this->ventaService->getRepository()->getConnection()->getQueryBuilder()
|
||||
->select('account_key, venta.id AS venta_id')
|
||||
->from('toku_accounts')
|
||||
->joined('JOIN proyecto ON proyecto.inmobiliaria = toku_accounts.sociedad_rut')
|
||||
->joined('JOIN proyecto_tipo_unidad ptu ON ptu.proyecto = proyecto.id')
|
||||
->joined('JOIN unidad ON unidad.pt = ptu.id')
|
||||
->joined('JOIN propiedad_unidad pu ON pu.unidad = unidad.id')
|
||||
->joined('JOIN venta ON venta.propiedad = pu.propiedad')
|
||||
->where("venta.id IN ({$placeholdersString}) AND toku_accounts.enabled = 1");
|
||||
$values = array_combine($placeholders, $ventaIds);
|
||||
try {
|
||||
$statement = $this->ventaService->getRepository()->getConnection()->execute($query, $values);
|
||||
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $exception) {
|
||||
$this->logger->error($exception->getMessage(), [
|
||||
'query' => $query,
|
||||
'values' => $values,
|
||||
'exception' => $exception]);
|
||||
throw new EmptyResult($query, $exception);
|
||||
}
|
||||
$keys = array_column($results, 'account_key');
|
||||
$ids = array_column($results, 'venta_id');
|
||||
return array_combine($ids, $keys);
|
||||
}
|
||||
}
|
||||
|
@ -4,37 +4,24 @@ namespace Incoviba\Service\Venta;
|
||||
use DateTimeInterface;
|
||||
use DateTimeImmutable;
|
||||
use DateMalformedStringException;
|
||||
use Incoviba\Common\Define;
|
||||
use Incoviba\Exception\ServiceAction\Create;
|
||||
use Incoviba\Exception\ServiceAction\Read;
|
||||
use Incoviba\Exception\ServiceAction\Update;
|
||||
use PDOException;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use Incoviba\Repository;
|
||||
use Incoviba\Model;
|
||||
use Incoviba\Service;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class Pago extends Ideal\Service\Repository
|
||||
class Pago
|
||||
{
|
||||
public function __construct(
|
||||
LoggerInterface $logger,
|
||||
protected Repository\Venta\Pago $pagoRepository,
|
||||
protected Repository\Venta\EstadoPago $estadoPagoRepository,
|
||||
protected Repository\Venta\TipoEstadoPago $tipoEstadoPagoRepository,
|
||||
protected Service\UF $ufService,
|
||||
protected Service\Valor $valorService,
|
||||
protected Service\Queue $queueService
|
||||
)
|
||||
{
|
||||
parent::__construct($logger);
|
||||
}
|
||||
|
||||
public function getRepository(): Define\Repository
|
||||
{
|
||||
return $this->pagoRepository;
|
||||
}
|
||||
protected Service\Valor $valorService
|
||||
) {}
|
||||
|
||||
public function depositar(Model\Venta\Pago $pago, DateTimeInterface $fecha): bool
|
||||
{
|
||||
@ -102,23 +89,13 @@ class Pago extends Ideal\Service\Repository
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int|null $pago_id
|
||||
* @return Model\Venta\Pago|null
|
||||
* @throws Read
|
||||
*/
|
||||
public function getById(?int $pago_id): ?Model\Venta\Pago
|
||||
{
|
||||
if ($pago_id === null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
$pago = $this->pagoRepository->fetchById($pago_id);
|
||||
return $this->process($pago);
|
||||
} catch (EmptyResult) {
|
||||
throw new Read(__CLASS__);
|
||||
}
|
||||
$pago = $this->pagoRepository->fetchById($pago_id);
|
||||
return $this->process($pago);
|
||||
}
|
||||
|
||||
public function getByVenta(int $venta_id): array
|
||||
@ -167,6 +144,9 @@ class Pago extends Ideal\Service\Repository
|
||||
$fecha = new DateTimeImmutable();
|
||||
}
|
||||
$data['fecha'] = $fecha->format('Y-m-d');
|
||||
if (!array_key_exists('uf', $data)) {
|
||||
$data['uf'] = $this->ufService->get($fecha);
|
||||
}
|
||||
}
|
||||
$data['valor'] = $this->valorService->toPesos($this->valorService->clean($data['valor']), $data['fecha']);
|
||||
|
||||
@ -178,9 +158,6 @@ class Pago extends Ideal\Service\Repository
|
||||
} catch (PDOException $exception) {
|
||||
throw new Create(__CLASS__, $exception);
|
||||
}
|
||||
if (!array_key_exists('uf', $data)) {
|
||||
$this->getUFAsync($pago);
|
||||
}
|
||||
|
||||
$tipoEstado = $this->tipoEstadoPagoRepository->fetchByDescripcion('no pagado');
|
||||
try {
|
||||
@ -249,21 +226,6 @@ class Pago extends Ideal\Service\Repository
|
||||
|
||||
return $this->process($this->pagoRepository->fetchById($pago->id));
|
||||
}
|
||||
public function updateUF(int $pago_id): bool
|
||||
{
|
||||
try {
|
||||
$pago = $this->getById($pago_id);
|
||||
} catch (Read) {
|
||||
return false;
|
||||
}
|
||||
$uf = $this->ufService->get($pago->currentEstado->fecha);
|
||||
try {
|
||||
$this->pagoRepository->edit($pago, ['uf' => $uf]);
|
||||
return true;
|
||||
} catch (EmptyResult | PDOException) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected function process($pago): Model\Venta\Pago
|
||||
{
|
||||
@ -296,14 +258,4 @@ class Pago extends Ideal\Service\Repository
|
||||
}
|
||||
return $pago->uf;
|
||||
}
|
||||
protected function getUFAsync(Model\Venta\Pago $pago): void
|
||||
{
|
||||
$queueData = [
|
||||
'type' => 'service',
|
||||
'service' => __CLASS__,
|
||||
'method' => 'updateUF',
|
||||
'params' => ['pago_id' => $pago->id]
|
||||
];
|
||||
$this->queueService->push($queueData);
|
||||
}
|
||||
}
|
||||
|
@ -1,31 +1,19 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\Venta;
|
||||
|
||||
use DateTimeInterface;
|
||||
use PDOException;
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use Incoviba\Exception\ServiceAction;
|
||||
use Incoviba\Model;
|
||||
use Incoviba\Exception\ServiceAction\Read;
|
||||
use Incoviba\Repository;
|
||||
use Incoviba\Model;
|
||||
|
||||
class Precio extends Ideal\Service
|
||||
class Precio
|
||||
{
|
||||
public function __construct(LoggerInterface $logger,
|
||||
protected Repository\Venta\Precio $precioRepository,
|
||||
protected Repository\Venta\EstadoPrecio $estadoPrecioRepository,
|
||||
protected Precio\Estado $estadoPrecioService,
|
||||
protected Precio\Import $importService)
|
||||
{
|
||||
parent::__construct($logger);
|
||||
}
|
||||
public function __construct(protected Repository\Venta\Precio $precioRepository, protected Repository\Venta\EstadoPrecio $estadoPrecioRepository) {}
|
||||
|
||||
/**
|
||||
* @param int $proyecto_id
|
||||
* @return array
|
||||
* @throws ServiceAction\Read
|
||||
* @throws Read
|
||||
*/
|
||||
public function getByProyecto(int $proyecto_id): array
|
||||
{
|
||||
@ -37,14 +25,14 @@ class Precio extends Ideal\Service
|
||||
}
|
||||
return $precios;
|
||||
} catch (EmptyResult $exception) {
|
||||
throw new ServiceAction\Read(__CLASS__, $exception);
|
||||
throw new Read(__CLASS__, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $unidad_id
|
||||
* @return Model\Venta\Precio
|
||||
* @throws ServiceAction\Read
|
||||
* @throws Read
|
||||
*/
|
||||
public function getVigenteByUnidad(int $unidad_id): Model\Venta\Precio
|
||||
{
|
||||
@ -54,14 +42,14 @@ class Precio extends Ideal\Service
|
||||
$precio->current = $this->estadoPrecioRepository->fetchCurrentByPrecio($precio->id);
|
||||
return $precio;
|
||||
} catch (EmptyResult $exception) {
|
||||
throw new ServiceAction\Read(__CLASS__, $exception);
|
||||
throw new Read(__CLASS__, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $unidad_id
|
||||
* @return array
|
||||
* @throws ServiceAction\Read
|
||||
* @throws Read
|
||||
*/
|
||||
public function getByUnidad(int $unidad_id): array
|
||||
{
|
||||
@ -73,51 +61,7 @@ class Precio extends Ideal\Service
|
||||
}
|
||||
return $precios;
|
||||
} catch (EmptyResult $exception) {
|
||||
throw new ServiceAction\Read(__CLASS__, $exception);
|
||||
throw new Read(__CLASS__, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $projectId
|
||||
* @param DateTimeInterface $date
|
||||
* @param UploadedFileInterface $uploadedFile
|
||||
* @return array
|
||||
* @throws ServiceAction\Create
|
||||
*/
|
||||
public function import(int $projectId, DateTimeInterface $date, UploadedFileInterface $uploadedFile): array
|
||||
{
|
||||
$pricesData = $this->importService->importData($projectId, $date, $uploadedFile);
|
||||
$prices = [];
|
||||
foreach ($pricesData as $data) {
|
||||
try {
|
||||
$price = $this->precioRepository->create($data);
|
||||
$price = $this->precioRepository->save($price);
|
||||
$prices[] = $price;
|
||||
} catch (EmptyResult | PDOException $exception) {
|
||||
$this->logger->error('Problemas para agregar precio', ['data' => $data, 'exception' => $exception]);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($prices as $price) {
|
||||
$idx = array_search($price->unidad->id, array_column($pricesData, 'unidad'));
|
||||
$row = $pricesData[$idx];
|
||||
try {
|
||||
$this->estadoPrecioService->replacePrices($price->unidad, $date, $price);
|
||||
} catch (ServiceAction\Update $exception) {
|
||||
$this->logger->error('Problemas para reemplazar precios', [
|
||||
'data' => $row,
|
||||
'exception' => $exception
|
||||
]);
|
||||
}
|
||||
try {
|
||||
$this->estadoPrecioService->updatePrice($price, $row['fecha']);
|
||||
} catch (ServiceAction\Update $exception) {
|
||||
$this->logger->error('Problemas para actualizar estado de precio', [
|
||||
'data' => $row,
|
||||
'exception' => $exception
|
||||
]);
|
||||
}
|
||||
}
|
||||
return $prices;
|
||||
}
|
||||
}
|
||||
|
@ -1,89 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\Venta\Precio;
|
||||
|
||||
use DateTimeInterface;
|
||||
use Incoviba\Model\Venta\Precio;
|
||||
use Incoviba\Model\Venta\Unidad;
|
||||
use PDOException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Implement;
|
||||
use Incoviba\Exception\ServiceAction;
|
||||
use Incoviba\Model;
|
||||
use Incoviba\Repository;
|
||||
|
||||
class Estado extends Ideal\Service
|
||||
{
|
||||
public function __construct(LoggerInterface $logger,
|
||||
protected Repository\Venta\Precio $precioRepository,
|
||||
protected Repository\Venta\EstadoPrecio $estadoPrecioRepository,
|
||||
protected Repository\Venta\TipoEstadoPrecio $tipoEstadoPrecioRepository)
|
||||
{
|
||||
parent::__construct($logger);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Model\Venta\Precio $price
|
||||
* @param DateTimeInterface $date
|
||||
* @return void
|
||||
* @throws ServiceAction\Update
|
||||
*/
|
||||
public function updatePrice(Model\Venta\Precio $price, DateTimeInterface $date): void
|
||||
{
|
||||
try {
|
||||
$tipoEstado = $this->tipoEstadoPrecioRepository->fetchByDescripcion('vigente');
|
||||
} catch (Implement\Exception\EmptyResult $exception) {
|
||||
throw new ServiceAction\Update(__CLASS__, $exception);
|
||||
}
|
||||
$data = [
|
||||
'precio' => $price->id,
|
||||
'fecha' => $date->format('Y-m-d'),
|
||||
'estado' => $tipoEstado->id
|
||||
];
|
||||
try {
|
||||
$estado = $this->estadoPrecioRepository->create($data);
|
||||
$this->estadoPrecioRepository->save($estado);
|
||||
} catch (Implement\Exception\EmptyResult | PDOException $exception) {
|
||||
throw new ServiceAction\Update(__CLASS__, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Unidad $unidad
|
||||
* @param DateTimeInterface $date
|
||||
* @param Precio $price
|
||||
* @return void
|
||||
* @throws ServiceAction\Update
|
||||
*/
|
||||
public function replacePrices(Model\Venta\Unidad $unidad, DateTimeInterface $date, Model\Venta\Precio $price): void
|
||||
{
|
||||
try {
|
||||
$tipoEstado = $this->tipoEstadoPrecioRepository->fetchByDescripcion('reemplazado');
|
||||
} catch (Implement\Exception\EmptyResult $exception) {
|
||||
throw new ServiceAction\Update(__CLASS__, $exception);
|
||||
}
|
||||
try {
|
||||
$precios = $this->precioRepository->fetchByUnidad($unidad->id);
|
||||
foreach ($precios as $p) {
|
||||
if ($p->id === $price->id) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$estado = $this->estadoPrecioRepository->fetchCurrentByPrecio($p->id);
|
||||
if ($estado->tipoEstadoPrecio->id === $tipoEstado->id) {
|
||||
continue;
|
||||
}
|
||||
$data = [
|
||||
'precio' => $p->id,
|
||||
'estado' => $tipoEstado->id,
|
||||
'fecha' => $date->format('Y-m-d')
|
||||
];
|
||||
$estado = $this->estadoPrecioRepository->create($data);
|
||||
$this->estadoPrecioRepository->save($estado);
|
||||
} catch (Implement\Exception\EmptyResult) {}
|
||||
}
|
||||
} catch (Implement\Exception\EmptyResult $exception) {
|
||||
throw new ServiceAction\Update(__CLASS__, $exception);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,243 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\Venta\Precio;
|
||||
|
||||
use DateTime;
|
||||
use DateTimeInterface;
|
||||
use PDOException;
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use Incoviba\Exception\ServiceAction;
|
||||
use Incoviba\Model;
|
||||
use Incoviba\Service;
|
||||
use Incoviba\Repository;
|
||||
|
||||
class Import extends Ideal\Service
|
||||
{
|
||||
public function __construct(LoggerInterface $logger,
|
||||
protected Repository\Venta\Precio $precioRepository,
|
||||
protected Repository\Inmobiliaria $inmobiliariaRepository,
|
||||
protected Repository\Proyecto $proyectoRepository,
|
||||
protected Repository\Venta\Unidad $unidadRepository,
|
||||
protected Service\FileUpload $fileUploadService)
|
||||
{
|
||||
parent::__construct($logger);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $projectId
|
||||
* @param DateTimeInterface $date
|
||||
* @param UploadedFileInterface $uploadedFile
|
||||
* @return array
|
||||
* @throws ServiceAction\Create
|
||||
*/
|
||||
public function importData(int $projectId, DateTimeInterface $date, UploadedFileInterface $uploadedFile): array
|
||||
{
|
||||
try {
|
||||
$data = $this->fileUploadService->getData($uploadedFile);
|
||||
} catch (ServiceAction\Read $exception) {
|
||||
throw new ServiceAction\Create(__CLASS__, $exception);
|
||||
}
|
||||
$mappedData = $this->mapData($data, $projectId, $date);
|
||||
$pricesData = [];
|
||||
foreach ($mappedData as $row) {
|
||||
$pricesData[] = [
|
||||
'unidad' => $row['unidad'],
|
||||
'valor' => $row['precio'],
|
||||
'fecha' => $row['fecha']
|
||||
];
|
||||
}
|
||||
try {
|
||||
$priceUnitIds = array_map(fn($price) => $price['unidad'], $pricesData);
|
||||
$prices = $this->precioRepository->fetchVigentesByUnidades($priceUnitIds);
|
||||
$priceUnitIds = array_map(fn(array $p) => $p['id'], $prices);
|
||||
$pricePrices = array_map(fn(array $p) => $p['precio']->valor, $prices);
|
||||
return array_filter($pricesData, function($price) use ($priceUnitIds, $pricePrices) {
|
||||
$idx = array_search($price['unidad'], $priceUnitIds);
|
||||
if ($idx === false) {
|
||||
return true;
|
||||
}
|
||||
return $pricePrices[$idx] !== $price['valor'];
|
||||
});
|
||||
} catch (EmptyResult $exception) {
|
||||
throw new ServiceAction\Create(__CLASS__, $exception);
|
||||
}
|
||||
}
|
||||
protected array $realTitlesMap;
|
||||
protected function extractTitlesFromData(array $data): array
|
||||
{
|
||||
if (isset($this->realTitlesMap)) {
|
||||
return $this->realTitlesMap;
|
||||
}
|
||||
$baseTitlesMap = [
|
||||
'proyecto' => [],
|
||||
'precio' => [],
|
||||
'unidad' => ['departamento'],
|
||||
'tipo' => ['tipo unidad'],
|
||||
'fecha' => []
|
||||
];
|
||||
|
||||
$realTitlesMap = [];
|
||||
$titles = array_keys($data[0]);
|
||||
foreach ($baseTitlesMap as $base => $optionals) {
|
||||
foreach ($titles as $title) {
|
||||
if (str_contains($title, $base)) {
|
||||
$realTitlesMap[$title] = $base;
|
||||
break;
|
||||
}
|
||||
foreach ($optionals as $optional) {
|
||||
if (str_contains($title, $optional)) {
|
||||
$realTitlesMap[$title] = $base;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->realTitlesMap = $realTitlesMap;
|
||||
}
|
||||
protected function mapData(array $data, int $projectId, DateTimeInterface $date): array
|
||||
{
|
||||
$mappedData = $this->mapTitles($data);
|
||||
$mappedData = $this->mapProjects($mappedData, $projectId);
|
||||
$mappedData = $this->mapUnits($mappedData);
|
||||
return $this->mapDates($mappedData, $date);
|
||||
}
|
||||
protected function mapTitles(array $data): array
|
||||
{
|
||||
$titlesMap = $this->extractTitlesFromData($data);
|
||||
$mappedData = [];
|
||||
foreach ($data as $row) {
|
||||
$mappedData []= $this->mapRow($row, $titlesMap);
|
||||
}
|
||||
return $mappedData;
|
||||
}
|
||||
protected function mapProjects(array $data, int $projectId): array
|
||||
{
|
||||
if (!array_key_exists('proyecto', $data[0])) {
|
||||
return array_map(function($row) use ($projectId) {
|
||||
$row['proyecto'] = $projectId;
|
||||
return $row;
|
||||
},$data);
|
||||
}
|
||||
$projects = $this->extractProjectsFromData($data);
|
||||
$mappedData = [];
|
||||
foreach ($data as $row) {
|
||||
$mappedRow = $row;
|
||||
$mappedRow['proyecto'] = $projects[$row['proyecto']]?->id ?? $projectId;
|
||||
$mappedData []= $mappedRow;
|
||||
}
|
||||
return $mappedData;
|
||||
}
|
||||
protected function mapUnits(array $data): array
|
||||
{
|
||||
if (!array_key_exists('unidad', $data[0]) or !array_key_exists('tipo', $data[0])) {
|
||||
return $data;
|
||||
}
|
||||
$unidades = [];
|
||||
$mappedData = [];
|
||||
foreach ($data as $row) {
|
||||
if (!isset($unidades[$row['proyecto']])) {
|
||||
$unidades[$row['proyecto']] = $this->unidadRepository->fetchByProyecto($row['proyecto']);
|
||||
}
|
||||
$tipo = $this->mapTipoUnidad($row['tipo']);
|
||||
$unidad = array_filter($unidades[$row['proyecto']], function(Model\Venta\Unidad $unidad) use ($row, $tipo) {
|
||||
return $unidad->descripcion == $row['unidad']
|
||||
and $unidad->proyectoTipoUnidad->tipoUnidad->descripcion == $tipo;
|
||||
});
|
||||
if (count($unidad) === 0) {
|
||||
$this->logger->warning('Unidad no encontrada', ['row' => $row]);
|
||||
continue;
|
||||
}
|
||||
$mappedRow = $row;
|
||||
$mappedRow['unidad'] = array_shift($unidad)->id;
|
||||
unset($mappedRow['tipo']);
|
||||
$mappedData []= $mappedRow;
|
||||
}
|
||||
return $mappedData;
|
||||
}
|
||||
protected function mapDates(array $data, DateTimeInterface $date): array
|
||||
{
|
||||
if (!array_key_exists('fecha', $data[0])) {
|
||||
return array_map(function($row) use ($date) {
|
||||
$row['fecha'] = $date;
|
||||
return $row;
|
||||
}, $data);
|
||||
}
|
||||
$mappedData = [];
|
||||
foreach ($data as $row) {
|
||||
$mappedRow = $row;
|
||||
$newDate = DateTime::createFromFormat('d/m/Y', $row['fecha']);
|
||||
$mappedRow['fecha'] = $newDate;
|
||||
if ($newDate === false) {
|
||||
$mappedRow['fecha'] = $date;
|
||||
}
|
||||
$mappedData []= $mappedRow;
|
||||
}
|
||||
return $mappedData;
|
||||
}
|
||||
protected function mapRow(array $row, array $titlesMap): array
|
||||
{
|
||||
$mappedRow = [];
|
||||
foreach ($row as $key => $value) {
|
||||
$mappedRow[$titlesMap[$key]] = $value;
|
||||
}
|
||||
return $mappedRow;
|
||||
}
|
||||
protected function mapTipoUnidad(string $tipo): string
|
||||
{
|
||||
if (str_contains(mb_strtolower($tipo), 'bod')) {
|
||||
return 'bodega';
|
||||
}
|
||||
if (str_contains(mb_strtolower($tipo), 'est')) {
|
||||
return 'estacionamiento';
|
||||
}
|
||||
if (str_contains(mb_strtolower($tipo), 'terr')) {
|
||||
return 'terraza';
|
||||
}
|
||||
return 'departamento';
|
||||
}
|
||||
protected array $projectsMap;
|
||||
protected function extractProjectsFromData(array $data): array
|
||||
{
|
||||
if (isset($this->projectsMap)) {
|
||||
return $this->projectsMap;
|
||||
}
|
||||
$projectNames = array_unique(array_map(fn($row) => $row['proyecto'], $data));
|
||||
$projects = [];
|
||||
foreach ($projectNames as $projectName) {
|
||||
try {
|
||||
$projects[$projectName] = $this->proyectoRepository->fetchByName($projectName);
|
||||
} catch (EmptyResult $exception) {
|
||||
try {
|
||||
$inm = $this->inmobiliariaRepository->fetchByName($projectName);
|
||||
$inmProjects = $this->proyectoRepository->fetchByInmobiliaria($inm->rut);
|
||||
$projects[$projectName] = $inmProjects[0];
|
||||
} catch (EmptyResult $exception2) {
|
||||
$this->logger->warning('Neither Project nor Society found', [
|
||||
'projectName' => $projectName,
|
||||
'exceptions' => [
|
||||
[
|
||||
'code' => $exception->getCode(),
|
||||
'message' => $exception->getMessage(),
|
||||
'file' => $exception->getFile(),
|
||||
'line' => $exception->getLine(),
|
||||
'data' => $exception->getData(),
|
||||
'trace' => $exception->getTraceAsString()
|
||||
],
|
||||
[
|
||||
'code' => $exception2->getCode(),
|
||||
'message' => $exception2->getMessage(),
|
||||
'file' => $exception2->getFile(),
|
||||
'line' => $exception2->getLine(),
|
||||
'data' => $exception2->getData(),
|
||||
'trace' => $exception2->getTraceAsString()
|
||||
]
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->projectsMap = $projects;
|
||||
}
|
||||
}
|
@ -1,24 +1,22 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\Venta;
|
||||
|
||||
use PDOException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Common\Ideal\Service;
|
||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||
use Incoviba\Exception\ServiceAction\Create;
|
||||
use Incoviba\Exception\ServiceAction\Read;
|
||||
use Incoviba\Exception\ServiceAction\Update;
|
||||
use Incoviba\Model;
|
||||
use Incoviba\Repository;
|
||||
use Incoviba\Service\Valor;
|
||||
use Incoviba\Model;
|
||||
use PDOException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class Propietario extends Service
|
||||
{
|
||||
public function __construct(
|
||||
LoggerInterface $logger,
|
||||
protected Repository\Venta\Propietario $propietarioRepository,
|
||||
protected Repository\Direccion $direccionRepository,
|
||||
protected Valor $valorService
|
||||
protected Repository\Direccion $direccionRepository
|
||||
) {
|
||||
parent::__construct($logger);
|
||||
}
|
||||
@ -51,9 +49,6 @@ class Propietario extends Service
|
||||
$data['direccion'] = $direccion->id;
|
||||
}
|
||||
$filteredData = $this->propietarioRepository->filterData($data);
|
||||
if (array_key_exists('telefono', $filteredData)) {
|
||||
$filteredData['telefono'] = $this->valorService->telefono()->toDatabase($filteredData['telefono']);
|
||||
}
|
||||
try {
|
||||
return $this->propietarioRepository->edit($propietario, $filteredData);
|
||||
} catch (PDOException | EmptyResult $exception) {
|
||||
@ -90,10 +85,6 @@ class Propietario extends Service
|
||||
]);
|
||||
$filtered_data = array_intersect_key($data, $fields);
|
||||
|
||||
if (array_key_exists('telefono', $filtered_data)) {
|
||||
$filtered_data['telefono'] = $this->valorService->telefono()->toDatabase($filtered_data['telefono']);
|
||||
}
|
||||
|
||||
try {
|
||||
$propietario = $this->propietarioRepository->fetchById($data['rut']);
|
||||
$edits = [];
|
||||
@ -104,7 +95,6 @@ class Propietario extends Service
|
||||
} catch (EmptyResult) {
|
||||
try {
|
||||
$propietario = $this->propietarioRepository->create($filtered_data);
|
||||
$this->logger->info('Propietario', ['propietario' => $propietario]);
|
||||
$propietario = $this->propietarioRepository->save($propietario);
|
||||
} catch (PDOException $exception) {
|
||||
throw new Create(__CLASS__, $exception);
|
||||
|
@ -1,50 +0,0 @@
|
||||
<?php
|
||||
namespace Incoviba\Service\Worker;
|
||||
|
||||
use Exception;
|
||||
use Psr\Container\ContainerExceptionInterface;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Container\NotFoundExceptionInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Model;
|
||||
use Incoviba\Service\Worker;
|
||||
|
||||
class Service extends Ideal\Service implements Worker
|
||||
{
|
||||
public function __construct(protected ContainerInterface $container ,LoggerInterface $logger)
|
||||
{
|
||||
parent::__construct($logger);
|
||||
}
|
||||
|
||||
public function execute(Model\Job $job): bool
|
||||
{
|
||||
$configuration = $job->configuration;
|
||||
$serviceClass = $configuration['service'];
|
||||
$method = $configuration['method'];
|
||||
$params = $configuration['params'] ?? [];
|
||||
try {
|
||||
$service = $this->container->get($serviceClass);
|
||||
} catch (NotFoundExceptionInterface | ContainerExceptionInterface $exception) {
|
||||
$this->logger->error($exception->getMessage());
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
$result = call_user_func_array([$service, $method], $params);
|
||||
} catch (Exception $exception) {
|
||||
$this->logger->error($exception->getMessage(), [
|
||||
'Worker' => __CLASS__,
|
||||
'job_id' => $job->id,
|
||||
'service' => $serviceClass,
|
||||
'method' => $method,
|
||||
'params' => $params,
|
||||
'exception' => $exception
|
||||
]);
|
||||
return false;
|
||||
}
|
||||
if (is_bool($result)) {
|
||||
return $result;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
@ -52,15 +52,16 @@ class TestBootstrap
|
||||
{
|
||||
public function __construct(protected array $configuration) {}
|
||||
|
||||
public function run(bool $debug = false): void
|
||||
public function run(bool $resetDatabase = false): void
|
||||
{
|
||||
if ($resetDatabase) {
|
||||
if (Benchmark::execute([$this, 'isMigrated'])) {
|
||||
Benchmark::execute([$this, 'resetDatabase']);
|
||||
}
|
||||
}
|
||||
if (!Benchmark::execute([$this, 'isMigrated'])) {
|
||||
Benchmark::execute([$this, 'migrate']);
|
||||
}
|
||||
$output = Benchmark::execute([$this, 'seedTables']);
|
||||
if ($debug) {
|
||||
var_dump($output);
|
||||
}
|
||||
}
|
||||
|
||||
protected string $baseCommand = "bin/phinx";
|
||||
@ -70,12 +71,16 @@ class TestBootstrap
|
||||
$output = shell_exec($cmd);
|
||||
$status = json_decode($output, true);
|
||||
|
||||
return $status['missing_count'] === 0 and $status['pending_count'] === 0;
|
||||
return $status['missing_count'] === 0;
|
||||
}
|
||||
public function migrate(): false|null|string
|
||||
public function migrate(): void
|
||||
{
|
||||
$cmd = "{$this->baseCommand} migrate -e testing";
|
||||
return shell_exec($cmd);
|
||||
$status = shell_exec($cmd);
|
||||
if ($status !== false and $status !== null) {
|
||||
$cmd = "{$this->baseCommand} seed:run -e testing";
|
||||
shell_exec($cmd);
|
||||
}
|
||||
}
|
||||
|
||||
public function resetDatabase(): void
|
||||
@ -120,16 +125,6 @@ class TestBootstrap
|
||||
}
|
||||
}
|
||||
}
|
||||
public function seedTables(): false|null|string
|
||||
{
|
||||
$cmd = "{$this->baseCommand} seed:run -e testing";
|
||||
$output = shell_exec($cmd);
|
||||
|
||||
$testSeeder = new Tests\Extension\TestSeeder($this->connect());
|
||||
$testSeeder->run();
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
protected PDO $connection;
|
||||
protected function connect(): PDO
|
||||
@ -164,24 +159,18 @@ spl_autoload_register(function($className) {
|
||||
];
|
||||
foreach ($namespaceMap as $namespace => $path) {
|
||||
if (str_starts_with($className, $namespace)) {
|
||||
require str_replace([$namespace, '\\'], ["{$path}/", DIRECTORY_SEPARATOR], $className) . ".php";
|
||||
require str_replace($namespace, "{$path}/", $className) . ".php";
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
$bootstrap = new TestBootstrap($_ENV);
|
||||
$resetDatabase = (array_key_exists('RESET_DATABASE', $_ENV) and $_ENV['RESET_DATABASE'] === 'true') ?? false;
|
||||
$debug = (array_key_exists('DEBUG', $_ENV) and $_ENV['DEBUG'] === 'true') ?? false;
|
||||
|
||||
Benchmark::execute([$bootstrap, 'run'], ['debug' => $debug]);
|
||||
$resetDatabase = $_ENV['RESET_DATABASE'] ?? false;
|
||||
Benchmark::execute([$bootstrap, 'run'], ['resetDatabase' => $resetDatabase]);
|
||||
Benchmark::print();
|
||||
|
||||
register_shutdown_function(function() use ($bootstrap, $resetDatabase) {
|
||||
$method = 'truncateTables';
|
||||
if ($resetDatabase) {
|
||||
$method = 'resetDatabase';
|
||||
}
|
||||
Benchmark::execute([$bootstrap, $method]);
|
||||
register_shutdown_function(function() use ($bootstrap) {
|
||||
Benchmark::execute([$bootstrap, 'truncateTables']);
|
||||
Benchmark::print();
|
||||
});
|
||||
|
@ -1,147 +0,0 @@
|
||||
<?php
|
||||
namespace Tests\Extension;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Faker;
|
||||
use Tests\Extension\Faker\Provider\Rut;
|
||||
|
||||
abstract class AbstractSeed implements SeedInterface
|
||||
{
|
||||
public function __construct(PDO $connection)
|
||||
{
|
||||
$this->setConnection($connection);
|
||||
$this->faker = Faker\Factory::create('es_AR');
|
||||
$this->faker->addProvider(new Rut($this->faker));
|
||||
}
|
||||
|
||||
protected PDO $connection;
|
||||
protected Faker\Generator $faker;
|
||||
public function setConnection(PDO $connection): SeedInterface
|
||||
{
|
||||
$this->connection = $connection;
|
||||
return $this;
|
||||
}
|
||||
public function getConnection(): PDO
|
||||
{
|
||||
return $this->connection;
|
||||
}
|
||||
public function getDependencies(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
protected string $table;
|
||||
protected function table(string $table): self
|
||||
{
|
||||
$this->table = $table;
|
||||
return $this;
|
||||
}
|
||||
|
||||
protected array $queryQueue = [];
|
||||
protected function insertValues(array $valueRows): self
|
||||
{
|
||||
$columns = array_keys($valueRows[0]);
|
||||
$columnsString = implode(', ', array_map(fn($column) => "`{$column}`", $columns));
|
||||
$placeholderArray = array_map(fn($column) => ":{$column}", $columns);
|
||||
$placeholders = implode(', ', $placeholderArray);
|
||||
$query = "INSERT INTO `{$this->table}` ({$columnsString}) VALUES ({$placeholders})";
|
||||
$this->queryQueue []= ['query' => $query, 'values' => $valueRows];
|
||||
return $this;
|
||||
}
|
||||
protected function save(): self
|
||||
{
|
||||
foreach ($this->queryQueue as $entry) {
|
||||
$query = $entry['query'];
|
||||
$valueRows = $entry['values'];
|
||||
|
||||
foreach ($valueRows as $valueRow) {
|
||||
try {
|
||||
$this->connection->beginTransaction();
|
||||
$statement = $this->connection->prepare($query);
|
||||
if ($statement === false) {
|
||||
$this->connection->rollBack();
|
||||
continue;
|
||||
}
|
||||
$statement->execute($valueRow);
|
||||
$this->connection->commit();
|
||||
} catch (PDOException | \Throwable $exception) {
|
||||
$this->connection->rollBack();
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
protected function loadValues(string $table, array $conditions = [], string|array $columns = '*'): array
|
||||
{
|
||||
$columns = $this->processColumns($columns);
|
||||
$query = "SELECT {$columns} FROM `{$table}`";
|
||||
if (count($conditions) > 0) {
|
||||
$conditionsString = $this->processConditions($conditions);
|
||||
$query = "{$query} WHERE {$conditionsString}";
|
||||
}
|
||||
try {
|
||||
$statement = $this->connection->prepare($query);
|
||||
$statement->execute();
|
||||
} catch (PDOException) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
if ($columns !== '*' and !str_contains($columns, ',')) {
|
||||
return $statement->fetchAll(PDO::FETCH_COLUMN);
|
||||
}
|
||||
return $statement->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
protected function processColumns(string|array $columns): string
|
||||
{
|
||||
if (is_array($columns)) {
|
||||
$columns = implode(',', array_map(fn($column) => "`{$column}`", $columns));
|
||||
}
|
||||
if ($columns === '*') {
|
||||
return $columns;
|
||||
}
|
||||
$columns = array_map(fn($column) => trim($column), explode(',', $columns));
|
||||
return implode(', ', array_map(function($column) {
|
||||
if (!str_contains($column, '`')) {
|
||||
return "`{$column}`";
|
||||
}
|
||||
return $column;
|
||||
}, $columns));
|
||||
}
|
||||
protected function processConditions(array $conditions): array
|
||||
{
|
||||
$processedConditions = [];
|
||||
$processedValues = [];
|
||||
foreach ($conditions as $condition) {
|
||||
if (is_string($condition) and (str_starts_with(strtolower($condition), 'and') or str_starts_with(strtolower($condition), 'or'))) {
|
||||
$processedConditions[] = $condition;
|
||||
continue;
|
||||
}
|
||||
$column = $condition['column'];
|
||||
$value = $condition['value'];
|
||||
$match = $condition['match'] ?? 'AND';
|
||||
$operator = $condition['operator'] ?? '=';
|
||||
$columnValue = ":{$column}";
|
||||
if (is_array($value)) {
|
||||
$columnString = [];
|
||||
foreach ($value as $idx => $val) {
|
||||
$columnValue = ":{$column}_{$idx}";
|
||||
$columnString[] = $columnValue;
|
||||
$processedValues["{$column}_{$idx}"] = $val;
|
||||
}
|
||||
$columnValue = '(' . implode(', ', $columnString) . ')';
|
||||
if (!str_contains($operator, 'IN')) {
|
||||
$operator = 'IN';
|
||||
}
|
||||
} else {
|
||||
$processedValues[$column] = $value;
|
||||
}
|
||||
$processedConditions[] = "{$match} `{$column}` {$operator} {$columnValue}";
|
||||
}
|
||||
return ['query' => implode(' ', $processedConditions), 'values' => $processedValues];
|
||||
}
|
||||
}
|
@ -1,38 +0,0 @@
|
||||
<?php
|
||||
namespace Tests\Extension\Faker\Provider;
|
||||
|
||||
use Faker\Provider\Base;
|
||||
|
||||
class Rut extends Base
|
||||
{
|
||||
public function rut(bool $withDigito = true, bool $withDotsAndSlash = true): string
|
||||
{
|
||||
$base = self::numberBetween(1000000, 99999999);
|
||||
$rut = $base;
|
||||
if ($withDotsAndSlash) {
|
||||
$rut = number_format($rut, 0, ',', '.');
|
||||
}
|
||||
if ($withDigito) {
|
||||
$digito = $this->getDigito($base);
|
||||
if ($withDotsAndSlash) {
|
||||
return "{$digito}-{$rut}";
|
||||
}
|
||||
return "{$digito}{$rut}";
|
||||
}
|
||||
return $rut;
|
||||
}
|
||||
public function digitoVerificador(string $rut): bool|string
|
||||
{
|
||||
if ( !preg_match("/^[0-9.]+/",$rut)) return false;
|
||||
$rut = str_replace('.','',$rut);
|
||||
return $this->getDigito($rut);
|
||||
}
|
||||
|
||||
protected function getDigito(string $rut): string
|
||||
{
|
||||
$M=0;$S=1;
|
||||
for(;$rut;$rut=floor($rut/10))
|
||||
$S=($S+$rut%10*(9-$M++%6))%11;
|
||||
return $S?$S-1:'K';
|
||||
}
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
<?php
|
||||
namespace Tests\Extension;
|
||||
|
||||
use PDO;
|
||||
|
||||
interface SeedInterface
|
||||
{
|
||||
/**
|
||||
* @param PDO $connection
|
||||
* @return self
|
||||
*/
|
||||
public function setConnection(PDO $connection): self;
|
||||
/**
|
||||
* @return PDO
|
||||
*/
|
||||
public function getConnection(): PDO;
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getDependencies(): array;
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function run(): void;
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
<?php
|
||||
namespace Tests\Extension\Seeds;
|
||||
|
||||
use Tests\Extension\AbstractSeed;
|
||||
|
||||
class Direcciones extends AbstractSeed
|
||||
{
|
||||
public function run(): void
|
||||
{
|
||||
$comunas = $this->loadValues('comuna', columns: 'id');
|
||||
|
||||
$n = 50;
|
||||
$data = [];
|
||||
for ($i = 0; $i < $n; $i++) {
|
||||
$row = [
|
||||
'calle' => $this->faker->streetName,
|
||||
'numero' => $this->faker->randomNumber(5),
|
||||
'comuna' => $this->faker->randomElement($comunas),
|
||||
'extra' => '',
|
||||
];
|
||||
$extraRand = ((int) round(rand() / getrandmax())) === 1;
|
||||
if ($extraRand) {
|
||||
$nExtra = (int) round(rand(1, 3));
|
||||
$row['extra'] = $this->faker->words($nExtra, true);
|
||||
}
|
||||
$data[] = $row;
|
||||
}
|
||||
|
||||
$this->table('direccion')
|
||||
->insertValues($data)
|
||||
->save();
|
||||
}
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
<?php
|
||||
namespace Tests\Extension\Seeds;
|
||||
|
||||
use Tests\Extension\AbstractSeed;
|
||||
|
||||
class Inmobiliarias extends AbstractSeed
|
||||
{
|
||||
public function run(): void
|
||||
{
|
||||
$tipos = $this->loadValues('tipo_sociedad', columns: 'id');
|
||||
$suffixes = [
|
||||
'Inmobiliaria ',
|
||||
'Administradora ',
|
||||
'Asesorías ',
|
||||
''
|
||||
];
|
||||
|
||||
$n = 5;
|
||||
$data = [];
|
||||
for ($i = 0; $i < $n; $i++) {
|
||||
$rut = $this->faker->rut(false, false);
|
||||
$abreviacion = $this->faker->streetName;
|
||||
$suffix = $this->faker->randomElement($suffixes);
|
||||
$razon = "{$suffix}{$abreviacion}";
|
||||
$sigla = strtoupper(substr($abreviacion, 0, 3));
|
||||
$data []= [
|
||||
'rut' => $rut,
|
||||
'dv' => $this->faker->digitoVerificador($rut),
|
||||
'razon' => $razon,
|
||||
'abreviacion' => $abreviacion,
|
||||
'sigla' => $sigla,
|
||||
'sociedad' => $this->faker->randomElement($tipos),
|
||||
];
|
||||
}
|
||||
$this->table('inmobiliaria')
|
||||
->insertValues($data)
|
||||
->save();
|
||||
}
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
<?php
|
||||
namespace Tests\Extension\Seeds;
|
||||
|
||||
use Tests\Extension\AbstractSeed;
|
||||
|
||||
class Proyectos extends AbstractSeed
|
||||
{
|
||||
public function getDependencies(): array
|
||||
{
|
||||
return [
|
||||
Inmobiliarias::class,
|
||||
Direcciones::class
|
||||
];
|
||||
}
|
||||
|
||||
public function run(): void
|
||||
{
|
||||
$inmobiliarias = $this->loadValues('inmobiliaria', columns: 'rut');
|
||||
$direcciones = $this->loadValues('direccion', columns: 'id');
|
||||
|
||||
$n = 10;
|
||||
$data = [];
|
||||
for ($i = 0; $i < $n; $i++) {
|
||||
$data[] = [
|
||||
'inmobiliaria' => $this->faker->randomElement($inmobiliarias),
|
||||
'descripcion' => $this->faker->words(2, true),
|
||||
'direccion' => $this->faker->randomElement($direcciones),
|
||||
'superficie_sobre_nivel' => $this->faker->randomFloat(2, 1000, 10000),
|
||||
'superficie_bajo_nivel' => $this->faker->randomFloat(2, 0, 5000),
|
||||
'pisos' => $this->faker->randomNumber(2),
|
||||
'subterraneos' => $this->faker->randomNumber(2),
|
||||
'corredor' => $this->faker->randomFloat(4, 0, 1)
|
||||
];
|
||||
}
|
||||
|
||||
$this->table('proyecto')
|
||||
->insertValues($data)
|
||||
->save();
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user