This commit is contained in:
Juan Pablo Vial
2023-06-22 23:15:17 -04:00
parent 05e37f19ae
commit b212381bb7
25 changed files with 433 additions and 89 deletions

View File

@ -2,3 +2,4 @@ MYSQL_DATABASE=incoviba
MYSQL_PASSWORD=5GQYFvRjVw2A4KcD MYSQL_PASSWORD=5GQYFvRjVw2A4KcD
MYSQL_ROOT_PASSWORD=password MYSQL_ROOT_PASSWORD=password
MYSQL_USER=incoviba MYSQL_USER=incoviba
MYSQL_PORT=3307

View File

@ -1,8 +1,12 @@
<?php <?php
namespace App\Contract; namespace App\Contract;
use App\Alias\RemoteConnection;
use App\Definition\Contract; use App\Definition\Contract;
use App\Service\Money;
use App\Service\Remote;
use App\Service\View as ViewService; use App\Service\View as ViewService;
use GuzzleHttp\Client;
class View class View
{ {
@ -10,7 +14,12 @@ class View
protected static function newInstance() protected static function newInstance()
{ {
return new ViewService(); $remote = new Remote(new RemoteConnection());
$money = (new Money(new Client([
'base_uri' => "http://{$remote->getIP()}:8008",
'headers' => ['Accept' => 'application/json']
])));
return new ViewService(['money' => $money]);
} }
public static function show($template, $variables = null) public static function show($template, $variables = null)
{ {

View File

@ -9,12 +9,12 @@ class View
protected $cache; protected $cache;
protected $blade; protected $blade;
public function __construct() public function __construct(array $variables = [])
{ {
$this->views = config('locations.views'); $this->views = config('locations.views');
$this->cache = config('locations.cache'); $this->cache = config('locations.cache');
$this->blade = new BladeOne($this->views, $this->cache); $this->blade = new BladeOne($this->views, $this->cache, null, $variables);
} }
public function show($template, $vars = null) public function show($template, $vars = null)
{ {

50
app/Alias/Connection.php Normal file
View File

@ -0,0 +1,50 @@
<?php
namespace App\Alias;
use PDO;
use PDOException;
class Connection
{
public function __construct(
protected string $host,
protected string $database,
protected string $username,
protected string $password,
protected ?int $port = null,
protected int $retries = 5
) {}
protected PDO $connection;
public function connect(): PDO
{
if (!isset($this->connection)) {
$r = 0;
$exception = null;
while ($r < $this->retries) {
try {
$dsn = $this->getDsn();
$this->connection = new PDO($dsn, $this->username, $this->password);
return $this->connection;
} catch (PDOException $e) {
if ($exception !== null) {
$e = new PDOException($e->getMessage(), $e->getCode(), $exception);
}
$exception = $e;
usleep(500);
}
$r ++;
}
throw $exception;
}
return $this->connection;
}
protected function getDsn(): string
{
$dsn = "mysql:host={$this->host};dbname={$this->database}";
if (isset($this->port)) {
$dsn .= ";port={$this->port}";
}
return $dsn;
}
}

View File

@ -1,58 +1,17 @@
<?php <?php
namespace App\Alias; namespace App\Alias;
use PDO; class RemoteConnection extends Connection
use PDOException;
class RemoteConnection
{ {
public function __construct(protected int $retries = 5) public function __construct(protected int $retries = 5)
{ {
$this->host = $_ENV['REMOTE_HOST']; parent::__construct(
$this->database = $_ENV['REMOTE_DATABASE']; $_ENV['REMOTE_HOST'],
$this->username = $_ENV['REMOTE_USER']; $_ENV['REMOTE_DATABASE'],
$this->password = $_ENV['REMOTE_PASSWORD']; $_ENV['REMOTE_USER'],
if (isset($_ENV['REMOTE_PORT'])) { $_ENV['REMOTE_PASSWORD'],
$this->port = $_ENV['REMOTE_PORT']; $_ENV['REMOTE_PORT'] ?? null,
} $this->retries
} );
protected string $host;
protected string $database;
protected int $port;
protected string $username;
protected string $password;
protected PDO $connection;
public function connect(): PDO
{
if (!isset($this->connection)) {
$r = 0;
$exception = null;
while ($r < $this->retries) {
try {
$dsn = $this->getDsn();
$this->connection = new PDO($dsn, $this->username, $this->password);
} catch (PDOException $e) {
if ($exception !== null) {
$e = new PDOException($e->getMessage(), $e->getCode(), $exception);
}
$exception = $e;
usleep(500);
}
$r ++;
}
throw $exception;
}
return $this->connection;
}
protected function getDsn(): string
{
$dsn = "mysql:host={$this->host};dbname={$this->database}";
if (isset($this->port)) {
$dsn .= ";port={$this->port}";
}
return $dsn;
} }
} }

86
app/Command/Money/Get.php Normal file
View File

@ -0,0 +1,86 @@
<?php
namespace App\Command\Money;
use DateTimeInterface;
use DateTimeImmutable;
use PDO;
use PDOException;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use App\Alias\Connection;
use App\Service\Money;
#[AsCommand(
name: 'money:uf:get',
hidden: false
)]
class Get extends Command
{
public function __construct(protected Money $service, protected Connection $connection, string $name = null)
{
parent::__construct($name);
}
public function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$io->title('Get Money');
$dates = $this->getDates();
foreach ($dates as $date_string => $ids) {
$date = $this->parseDate($date_string);
$response = $this->service->getUF($date);
if ($response->total === 0) {
continue;
}
foreach ($ids as $id) {
$this->queueUpdate($id, $response->uf->value);
}
}
$this->updateUF();
}
protected function getDates(): array
{
$query = "SELECT id, fecha FROM pago WHERE uf IS NULL AND fecha BETWEEN 0 AND DATE_ADD(CURDATE(), INTERVAL 9 DAY) ORDER BY fecha";
$statement = $this->connection->connect()->query($query);
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
if (count($rows) === 0) {
return [];
}
$dates = [];
foreach ($rows as $row) {
if (!isset($dates[$row['fecha']])) {
$dates[$row['fecha']] = [];
}
$dates[$row['fecha']] []= (int) $row['id'];
}
return $dates;
}
protected function parseDate(string $date_string): DateTimeInterface
{
return new DateTimeImmutable($date_string);
}
protected array $rows;
protected function queueUpdate(int $id, float $value): void
{
$this->rows []= [$value, $id];
}
protected function updateUF(): void
{
$query = "UPDATE pago SET uf = ? WHERE id = ?";
$statement = $this->connection->connect()->prepare($query);
foreach ($this->rows as $row) {
$this->connection->connect()->beginTransaction();
try {
$statement->execute($row);
$this->connection->connect()->commit();
} catch (PDOException $e) {
$this->connection->connect()->rollBack();
}
}
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace App\Command\Money;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use App\Alias\Connection;
#[AsCommand(
name: 'money:lookup',
hidden: false
)]
class Lookup extends Command
{
public function __construct(protected Connection $connection, string $name = null)
{
parent::__construct($name);
}
public function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$io->title('Lookup Money');
while (true) {
$io->info('Checking pending');
if ($this->hasPendingMoney()) {
$io->success('Running money get UF');
$io->note($this->runGetUF());
}
}
}
protected function hasPendingMoney(): bool
{
$query = "SELECT 1 FROM pago WHERE uf IS NULL AND fecha BETWEEN 0 AND DATE_ADD(CURDATE(), INTERVAL 9 DAY)";
$statement = $this->connection->connect()->query($query);
return $statement->rowCount() > 0;
}
protected function runGetUF(): string
{
$command = "/code/bin/console money:uf:get";
$result = shell_exec($command);
if (!$result or $result === null) {
throw new \Exception();
}
return $result;
}
}

View File

@ -312,7 +312,7 @@ class Proyectos
} }
return view('proyectos.reservas.base', compact('proyecto', 'pisos', 'max_unidades', 'totales')); return view('proyectos.reservas.base', compact('proyecto', 'pisos', 'max_unidades', 'totales'));
} }
public function unidades() public static function unidades()
{ {
if (get('proyecto')) { if (get('proyecto')) {
$proyecto = model(Proyecto::class)->findOne(get('proyecto')); $proyecto = model(Proyecto::class)->findOne(get('proyecto'));

View File

@ -40,6 +40,7 @@ class Money
protected function checkNextMonthValueCalculationByDate(DateTimeInterface $date): bool protected function checkNextMonthValueCalculationByDate(DateTimeInterface $date): bool
{ {
$next_m_9 = Carbon::today(config('app.timezone'))->copy()->endOfMonth()->addDays(9); $next_m_9 = Carbon::today(config('app.timezone'))->copy()->endOfMonth()->addDays(9);
$date = Carbon::parse($date);
return $date->lessThan($next_m_9); return $date->lessThan($next_m_9);
} }
protected function isOk(ResponseInterface $response): bool protected function isOk(ResponseInterface $response): bool

3
bin/console Normal file
View File

@ -0,0 +1,3 @@
#!/bin/bash
php /code/bin/index.php "$@"

8
bin/index.php Normal file
View File

@ -0,0 +1,8 @@
<?php
//$__environment = 'cli';
$app = include_once implode(DIRECTORY_SEPARATOR, [
dirname(__FILE__, 2),
'setup',
'cli.app.php'
]);
$app->run();

View File

@ -1,6 +1,7 @@
<?php <?php
include_once dirname(__DIR__) . '/vendor/autoload.php'; include_once dirname(__DIR__) . '/vendor/autoload.php';
include_once 'errors.php'; include_once 'errors.php';
include_once 'logs.php';
include_once 'dotenv.php'; include_once 'dotenv.php';
include_once 'database.php'; include_once 'database.php';
include_once 'routes.php'; include_once 'routes.php';

View File

@ -27,4 +27,3 @@ function load($data, $name = '') {
} }
Model::$short_table_names = true; Model::$short_table_names = true;
?>

26
bootstrap/logs.php Normal file
View File

@ -0,0 +1,26 @@
<?php
use Monolog\{Handler,Processor,Formatter,Level};
function buildLogger() {
$logger = new Monolog\Logger('global', [
new Handler\FilterHandler(new Handler\RotatingFileHandler('/logs/php.log'),
Level::Debug,
Level::Notice
),
new Handler\FilterHandler(new Handler\RotatingFileHandler('/logs/error.log'),
Level::Warning,
Level::Critical
),
new Handler\FilterHandler(new Handler\NativeMailerHandler('jpvial@incoviba.cl', 'Incoviba Error', 'alert@incoviba.cl'),
Level::Alert
)
], [
new Processor\PsrLogMessageProcessor(),
new Processor\IntrospectionProcessor(),
new Processor\WebProcessor(),
new Processor\MemoryPeakUsageProcessor()
]);
return $logger;
}
$logger = buildLogger();
Monolog\ErrorHandler::register($logger);

View File

@ -3,28 +3,30 @@
"description" : "Intranet portal for Incoviba", "description" : "Intranet portal for Incoviba",
"type" : "project", "type" : "project",
"require" : { "require" : {
"aldarien/config" : "*", "aldarien/asset": "*",
"aldarien/asset" : "*", "aldarien/config": "*",
"aldarien/format" : "*", "aldarien/format": "*",
"aldarien/response" : "*", "aldarien/response": "*",
"aldarien/view" : "*", "aldarien/session": "*",
"aldarien/session" : "*",
"aldarien/url": "*", "aldarien/url": "*",
"j4mie/paris" : "^1.5", "aldarien/view": "*",
"voku/stringy" : "^6",
"phpoffice/phpspreadsheet": "^1",
"nesbot/carbon": "^2",
"phpoffice/phpword": "^0",
"slam/php-excel": "^4.4",
"guzzlehttp/guzzle": "*", "guzzlehttp/guzzle": "*",
"incoviba/modelos": "*", "incoviba/modelos": "*",
"slim/slim": "^4", "j4mie/paris": "^1.5",
"php-di/slim-bridge": "*", "monolog/monolog": "^3",
"rubellum/slim-blade-view": "*", "nesbot/carbon": "^2",
"nyholm/psr7": "*", "nyholm/psr7": "*",
"nyholm/psr7-server": "*", "nyholm/psr7-server": "*",
"php-di/php-di": "*",
"php-di/slim-bridge": "*",
"phpoffice/phpspreadsheet": "^1",
"phpoffice/phpword": "^0",
"rubellum/slim-blade-view": "*",
"slam/php-excel": "^4.4",
"slim/slim": "^4",
"symfony/console": "6.4.x-dev",
"vlucas/phpdotenv": "^5.3", "vlucas/phpdotenv": "^5.3",
"monolog/monolog": "^3" "voku/stringy": "^6"
}, },
"require-dev" : { "require-dev" : {
"phpunit/phpunit" : "*", "phpunit/phpunit" : "*",

View File

@ -7,4 +7,3 @@ return [
'benchmark' => false, 'benchmark' => false,
'login_hours' => 5*24 'login_hours' => 5*24
]; ];
?>

View File

@ -1,19 +1,24 @@
<?php <?php
include_once dirname(__DIR__) . '/bootstrap/dotenv.php'; include_once dirname(__DIR__) . '/bootstrap/dotenv.php';
return [ function buildDatabaseConfig(): array {
'mysql' => [ $arr = [
'host' => $_ENV['MYSQL_HOST'], 'mysql' => [
//'port' => 3306, 'host' => $_ENV['MYSQL_HOST'],
'database' => $_ENV['MYSQL_DATABASE'], 'database' => $_ENV['MYSQL_DATABASE'],
'username' => $_ENV['MYSQL_USER'], 'username' => $_ENV['MYSQL_USER'],
'password' => $_ENV['MYSQL_PASSWORD'] 'password' => $_ENV['MYSQL_PASSWORD']
], ],
'mysql_copy' => [ 'mysql_copy' => [
'host' => 'localhost', 'host' => 'localhost',
'database' => 'incoviba3', 'database' => 'incoviba3',
'username' => 'incoviba', 'username' => 'incoviba',
'password' => $_ENV['MYSQL_PASSWORD'] 'password' => $_ENV['MYSQL_PASSWORD']
] ]
] ];
?> if (isset($_ENV['MYSQL_PORT'])) {
$arr['mysql']['port'] = $_ENV['MYSQL_PORT'];
}
return $arr;
}
return buildDatabaseConfig();

View File

@ -25,6 +25,7 @@ services:
env_file: env_file:
- .env - .env
- .db.env - .db.env
- .remote.env
volumes: volumes:
- .:/code - .:/code
- ./php-errors.ini:/usr/local/etc/php/conf.d/docker-php-errors.ini - ./php-errors.ini:/usr/local/etc/php/conf.d/docker-php-errors.ini
@ -39,6 +40,9 @@ services:
env_file: .db.env env_file: .db.env
volumes: volumes:
- dbdata:/var/lib/mysql - dbdata:/var/lib/mysql
networks:
- default
- adminer_network
adminer: adminer:
profiles: profiles:
@ -68,6 +72,7 @@ services:
container_name: incoviba_logview container_name: incoviba_logview
restart: unless-stopped restart: unless-stopped
environment: environment:
WEB_URL: 'http://provm.cl:8084'
WEB_PORT: '8084' WEB_PORT: '8084'
volumes: volumes:
- "./logs:/logs" - "./logs:/logs"
@ -76,3 +81,6 @@ services:
volumes: volumes:
dbdata: dbdata:
networks:
adminer_network: {}

View File

@ -1,6 +1,6 @@
<?php <?php
$__environment = 'api'; $__environment = 'api';
include_once implode(DIRECTORY_SEPARATOR, [ $app = include_once implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__, 2), dirname(__DIR__, 2),
'setup', 'setup',
'app.php' 'app.php'

5
resources/routes/cli.php Normal file
View File

@ -0,0 +1,5 @@
<?php
use App\Command;
$app->add($app->getContainer()->get(Command\Money\Lookup::class));
$app->add($app->getContainer()->get(Command\Money\Get::class));

View File

@ -9,6 +9,9 @@ $folders = [
'setups' 'setups'
]; ];
$builder = new Builder(); $builder = new Builder();
if (isset($__environment)) {
$builder->addDefinitions(['environment' => $__environment]);
}
foreach ($folders as $f) { foreach ($folders as $f) {
$folder = implode(DIRECTORY_SEPARATOR, [ $folder = implode(DIRECTORY_SEPARATOR, [
__DIR__, __DIR__,
@ -50,3 +53,5 @@ $app->addErrorMiddleware(true, true, true);
include_once 'database.php'; include_once 'database.php';
include_once 'router.php'; include_once 'router.php';
return $app;

48
setup/cli.app.php Normal file
View File

@ -0,0 +1,48 @@
<?php
use Psr\Container\ContainerInterface;
use DI\ContainerBuilder;
use Symfony\Component\Console\Application;
require_once 'composer.php';
$builder = new ContainerBuilder();
$files = [
'config',
'setups'
];
foreach ($files as $f) {
$filename = implode(DIRECTORY_SEPARATOR, [
__DIR__,
'cli',
"{$f}.php"
]);
if (!file_exists($filename)) {
continue;
}
$builder->addDefinitions($filename);
}
$app = new class() extends Application
{
protected ContainerInterface $container;
public function getContainer(): ContainerInterface
{
return $this->container;
}
public function setContainer(ContainerInterface $container)
{
$this->container = $container;
return $this;
}
};
$app->setContainer($builder->build());
$filename = implode(DIRECTORY_SEPARATOR, [
__DIR__,
'cli',
'middlewares.php'
]);
if (file_exists($filename)) {
include_once $filename;
}
return $app;

26
setup/cli/config.php Normal file
View File

@ -0,0 +1,26 @@
<?php
return [
'databases' => function() {
$container = new DI\Container([
ORM::DEFAULT_CONNECTION => new DI\Container([
'host' => $_ENV['MYSQL_HOST'],
'database' => $_ENV['MYSQL_DATABASE'],
'username' => $_ENV['MYSQL_USER'],
'password' => $_ENV['MYSQL_PASSWORD']
]),
'remote' => new DI\Container([
'host' => $_ENV['REMOTE_HOST'],
'database' => $_ENV['REMOTE_DATABASE'],
'username' => $_ENV['REMOTE_USER'],
'password' => $_ENV['REMOTE_PASSWORD']
])
]);
if (isset($_ENV['MYSQL_PORT'])) {
$container->get(ORM::DEFAULT_CONNECTION)->set('port', $_ENV['MYSQL_PORT']);
}
if (isset($_ENV['REMOTE_PORT'])) {
$container->get('remote')->set('port', $_ENV['REMOTE_PORT']);
}
return $container;
}
];

View File

@ -0,0 +1,9 @@
<?php
include_once implode(DIRECTORY_SEPARATOR, [
dirname(__FILE__, 3),
'resources',
'routes',
'cli.php'
]);
Monolog\ErrorHandler::register($app->getContainer()->get(Psr\Log\LoggerInterface::class));

43
setup/cli/setups.php Normal file
View File

@ -0,0 +1,43 @@
<?php
use Psr\Container\ContainerInterface;
return [
Psr\Log\LoggerInterface::class => function(ContainerInterface $container) {
return new Monolog\Logger('cli', [
new Monolog\Handler\FilterHandler(new Monolog\Handler\RotatingFileHandler('/logs/cli.debug.log'), Monolog\Level::Debug, Monolog\Level::Notice),
new Monolog\Handler\FilterHandler(new Monolog\Handler\RotatingFileHandler('/logs/cli.error.log'), Monolog\Level::Warning)
], [
new Monolog\Processor\PsrLogMessageProcessor(),
new Monolog\Processor\IntrospectionProcessor(),
new Monolog\Processor\MemoryUsageProcessor(),
new Monolog\Processor\MemoryPeakUsageProcessor()
]);
},
GuzzleHttp\Client::class => function(ContainerInterface $container) {
return new GuzzleHttp\Client([
'base_uri' => "http://{$container->get(App\Service\Remote::class)->getIP()}:8008",
'headers' => [
'Accept' => 'application/json'
]
]);
},
App\Alias\RemoteConnection::class => function(ContainerInterface $container) {
return new App\Alias\RemoteConnection();
},
App\Service\Remote::class => function(ContainerInterface $container) {
return new App\Service\Remote($container->get(App\Alias\RemoteConnection::class));
},
App\Service\Money::class => function(ContainerInterface $container) {
return new App\Service\Money($container->get(GuzzleHttp\Client::class));
},
App\Alias\Connection::class => function(ContainerInterface $container) {
$data = $container->get('databases')->get(ORM::DEFAULT_CONNECTION);
return new App\Alias\Connection(
$data->get('host'),
$data->get('database'),
$data->get('username'),
$data->get('password'),
$data->has('port') ? $data->get('port') : null
);
},
];