Compare commits

...

18 Commits

Author SHA1 Message Date
78b58d4900 Cors 2021-04-13 23:18:34 -04:00
b86e69b60e Alias UI 2021-04-13 23:07:38 -04:00
446834c100 Alias WebSocket 2021-04-13 23:07:38 -04:00
3b20fbd66f Alias API 2021-04-13 23:07:37 -04:00
f9a00578f4 Migration foreign keys 2021-04-13 23:07:37 -04:00
3651969c33 Alias models 2021-04-13 23:07:37 -04:00
76205250ad Name cron 2021-04-13 23:07:37 -04:00
b6bc007590 Migrate once when loaded 2021-04-13 21:02:23 -04:00
60cd73078c Env data 2021-04-13 21:01:56 -04:00
1dab43ca90 Seeds 2021-04-13 21:01:29 -04:00
5129cca099 Automatizado 2021-04-12 00:43:39 -04:00
35bcbd1979 Update 2021-04-12 00:43:27 -04:00
fef167c46e Uso de Websocket en mirar moneda 2021-04-12 00:41:37 -04:00
29d04ac4ad Sources 2021-04-12 00:38:51 -04:00
190dfd7c34 WebSocket app 2021-03-30 16:40:02 -03:00
5d229739fe Docker WebSocket 2021-03-30 16:39:52 -03:00
70f8671c01 Se agrega funcionalidad de WebSockets 2021-03-30 16:21:51 -03:00
4a8ae50fdc Cleanup de nginx.conf para app 2021-03-30 16:21:02 -03:00
51 changed files with 1638 additions and 228 deletions

View File

@ -0,0 +1,73 @@
<?php
namespace ProVM\Money\Common\Controller;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use ProVM\Common\Factory\Model as ModelFactory;
use ProVM\Common\Define\Controller\Json;
use ProVM\Money\Alias;
class Aliases {
use Json;
public function __invoke(Request $request, Response $response, ModelFactory $factory): Response {
$aliases = $factory->find(Alias::class)->array();
$output = compact('aliases');
return $this->withJson($response, $output);
}
public function get(Request $request, Response $response, ModelFactory $factory, $alias_id): Response {
$alias = $factory->find(Alias::class)->one($alias_id);
$output = [
'get_data' => compact('alias_id'),
'alias' => null
];
if ($alias) {
$output['alias'] = $alias->asArray();
}
return $this->withJson($response, $output);
}
public function add(Request $request, Response $response, ModelFactory $factory): Response {
$post = json_decode($request->getBody()->getContents());
$aliases = [];
if (is_array($post)) {
foreach ($post as $obj) {
if (!is_object($obj)) {
continue;
}
$aliases []= Alias::add($factory, $obj);
}
} else {
$aliases []= Alias::add($factory, $post);
}
$output = [
'post_data' => $post,
'aliases' => $aliases
];
return $this->withJson($response, $output);
}
public function edit(Request $request, Response $response, ModelFactory $factory, $alias_id) {
$post = json_decode($request->getBody()->getContents());
$output = [
'get_data' => compact('alias_id'),
'post_data' => $post
];
$alias = $factory->find(Alias::class)->one($alias_id);
$edited = false;
if ($alias) {
$edited = $alias->edit($post);
$output['alias'] = $alias->asArray();
$output['edited'] = $edited;
}
return $this->withJson($response, $output);
}
public function delete(Request $request, Response $response, ModelFactory $factory, $alias_id): Response {
$alias = $factory->find(Alias::class)->one($alias_id);
$output = ['get_data' => compact('alias_id'), 'alias' => null, 'deleted' => false];
if ($alias) {
$output['alias'] = $alias->asArray();
$status = $alias->delete();
$output['deleted'] = $status;
}
return $this->withJson($response, $output);
}
}

View File

@ -72,6 +72,49 @@ class Currencies {
}
return $this->withJson($response, $output);
}
public function getAliases(Request $request, Response $response, ModelFactory $factory, $currency_id): Response {
$currency = $factory->find(Currency::class)->one($currency_id);
$output = [
'get_data' => compact('currency_id'),
'currency' => null,
'aliases' => []
];
if ($currency) {
$output['currency'] = $currency->asArray();
if ($currency->aliases()) {
$output['aliases'] = array_map(function($item) {
return $item->asArray();
}, $currency->aliases());
}
}
return $this->withJson($response, $output);
}
public function addAliases(Request $request, Response $response, ModelFactory $factory, $currency_id): Response {
$currency = $factory->find(Currency::class)->one($currency_id);
$post = json_decode($request->getBody()->getContents());
$output = [
'get_data' => compact('currency_id'),
'post_data' => $post,
'currency' => null,
'aliases' => []
];
if ($currency) {
$output['currency'] = $currency->asArray();
$aliases = [];
if (is_array($post)) {
foreach ($post as $obj) {
if (!is_object($obj)) {
continue;
}
$aliases []= $currency->addAlias($obj);
}
} else {
$aliases []= $currency->addAlias($post);
}
$output['aliases'] = $aliases;
}
return $this->withJson($response, $output);
}
public function getValues(Request $request, Response $response, ModelFactory $factory, $currency_id): Response {
$currency = $factory->find(Currency::class)->one($currency_id);
$output = [
@ -173,4 +216,65 @@ class Currencies {
}
return $this->withJson($response, $output);
}
public function find(Request $request, Response $response, ModelFactory $factory, $query): Response {
$currency = Currency::find($factory, $query);
$output = [
'get_data' => compact('query'),
'currency' => null
];
if ($currency) {
$output['currency'] = $currency->asArray();
}
return $this->withJson($response, $output);
}
public function findValues(Request $request, Response $response, ModelFactory $factory, $query): Response {
$currency = Currency::find($factory, $query);
$output = [
'get_data' => compact('query'),
'currency' => null,
'values' => []
];
if ($currency) {
$output['currency'] = $currency->asArray();
if ($currency->values()) {
$output['values'] = array_map(function($item) {
return $item->asArray();
}, $currency->values());
}
}
return $this->withJson($response, $output);
}
public function findLatest(Request $request, Response $response, ModelFactory $factory, $query): Response {
$currency = Currency::find($factory, $query);
$output = [
'get_data' => compact('currency_id'),
'currency' => null,
'value' => null
];
if ($currency) {
$output['currency'] = $currency->asArray();
if ($currency->latest()) {
$output['value'] = $currency->latest()->asArray();
}
}
return $this->withJson($response, $output);
}
public function findSources(Request $request, Response $response, ModelFactory $factory, $query): Response {
$currency = Currency::find($factory, $query);
$output = [
'get_data' => compact('query'),
'currency' => null,
'sources' => []
];
if ($currency) {
$output['currency'] = $currency->asArray();
if ($currency->sources()) {
$output['sources'] = array_map(function($item) {
return $item->asArray();
}, $currency->sources());
}
}
return $this->withJson($response, $output);
}
}

View File

@ -15,10 +15,10 @@ class Sources {
$output = compact('sources');
return $this->withJson($response, $output);
}
public function get(Request $request, Response $response, ModelFactory $factory, $currency_id, $url): Response {
$source = $factory->find(Source::class)->where([['currency_id', $currency_id], ['url', $url]])->one();
public function get(Request $request, Response $response, ModelFactory $factory, $source_id): Response {
$source = $factory->find(Source::class)->one($source_id);
$output = [
'get_data' => compact('currency_id', 'url'),
'get_data' => compact('source_id'),
'source' => null
];
if ($source) {
@ -45,13 +45,13 @@ class Sources {
];
return $this->withJson($response, $output);
}
public function edit(Request $request, Response $response, ModelFactory $factory, $currency_id, $url) {
public function edit(Request $request, Response $response, ModelFactory $factory, $source_id) {
$post = json_decode($request->getBody()->getContents());
$output = [
'get_data' => compact('currency_id', 'url'),
'get_data' => compact('source_id'),
'post_data' => $post
];
$source = $factory->find(Source::class)->where([['currency_id', $currency_id], ['url', $url]])->one();
$source = $factory->find(Source::class)->one($source_id);
$edited = false;
if ($source) {
$edited = $source->edit($post);
@ -60,9 +60,9 @@ class Sources {
}
return $this->withJson($response, $output);
}
public function delete(Request $request, Response $response, ModelFactory $factory, $currency_id, $url): Response {
$source = $factory->find(Source::class)->where([['currency_id', $currency_id], ['url', $url]])->one();
$output = ['get_data' => compact('currency_id', 'url'), 'source' => null, 'deleted' => false];
public function delete(Request $request, Response $response, ModelFactory $factory, $source_id): Response {
$source = $factory->find(Source::class)->one($source_id);
$output = ['get_data' => compact('source_id'), 'source' => null, 'deleted' => false];
if ($source) {
$output['source'] = $source->asArray();
$status = $source->delete();

View File

@ -0,0 +1,17 @@
<?php
namespace ProVM\Money\Common\Controller;
use Psr\Container\ContainerInterface as Container;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use ProVM\Common\Define\Controller\Json;
use ProVM\Money\Common\Service\Update as Updater;
class Update {
use Json;
public function __invoke(Request $request, Response $response, Updater $updater): Response {
$output = $updater->update();
return $this->withJson($response, $output);
}
}

View File

@ -15,7 +15,7 @@ class Cors {
$response = $handler->handle($request);
$response = $response->withHeader('Access-Control-Allow-Origin', 'http://localhost:8080,http://localhost:8081');
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
$response = $response->withHeader('Access-Control-Allow-Methods', implode(',', $methods));
$response = $response->withHeader('Access-Control-Allow-Headers', $requestHeaders);
//$response = $response->withHeader('Access-Control-Allow-Credentials', 'true');

View File

@ -0,0 +1,31 @@
<?php
namespace ProVM\Money\Common\Middleware;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as Handler;
use Psr\Http\Message\ResponseInterface as Response;
use Phinx\Wrapper\TextWrapper;
use GuzzleHttp\ClientInterface as Client;
use ProVM\Money\Common\Service\Update as Updater;
class Migrate {
protected $phinx;
protected $updater;
public function __construct(TextWrapper $phinx, Updater $updater) {
$this->phinx = $phinx;
$this->updater = $updater;
}
public function __invoke(Request $request, Handler $handler): Response {
$query = "SHOW TABLES";
$st = \ORM::get_db()->query($query);
$r = $st->fetchAll(\PDO::FETCH_ASSOC);
if (count($r) == 0) {
$this->phinx->getMigrate();
$this->phinx->getSeed();
$this->updater->update();
}
return $handler->handle($request);
}
}

View File

@ -0,0 +1,90 @@
<?php
namespace ProVM\Money\Common\Service;
use GuzzleHttp\ClientInterface as Client;
use Carbon\Carbon;
use ProVM\Common\Factory\Model as ModelFactory;
use ProVM\Money\Currency;
use ProVM\Money\Source;
use ProVM\Money\Value;
class Update {
protected $factory;
protected $client;
public function __construct(ModelFactory $factory, Client $client) {
$this->factory = $factory;
$this->client = $client;
}
protected function get(Client $client, string $url, bool $exception = true) {
$res = $client->get($url);
if ($res->getStatusCode() < 200 or $res->getStatusCode() >= 300) {
if ($exception) {
throw new \Exception('Url ' . $url . ' not connected.');
}
return false;
}
return json_decode($res->getBody());
}
protected function baseMap($unit) {
$map = [
'Dólar' => 'US Dollar',
'Pesos' => 'Peso Chileno'
];
return $map[$unit] ?? $unit;
}
protected function buildUrl(Source $source) {
$date = Carbon::now();
return str_replace([
'{year}',
'{month}',
'{day}',
'{hour}',
'{minute}',
'{second}'
], [
$date->year,
$date->month,
$date->day,
$date->hour,
$date->minute,
$date->second
], $source->url);
}
public function update() {
ini_set('max_execution_time', 300);
$sources = $this->factory->find(Source::class)->many();
$output = ['count' => 0, 'values' => []];
foreach ($sources as $source) {
$url = $this->buildUrl($source);
$b = $this->get($this->client, $url, false);
if ($b === false) {
continue;
}
$base = $this->factory->find(Currency::class)->where([
['name', '%' . $this->baseMap($b->unidad_medida) . '%', 'like']
])->one();
if ($base === false) {
continue;
}
foreach ($b->serie as $info) {
$f = Carbon::parse($info->fecha);
$data = [
'currency_id' => $source->currency()->id,
'date_time' => $f->format('Y-m-d H:i:s'),
'value' => $info->valor,
'base_id' => $base->id
];
$result = Value::add($this->factory, $data);
$output['values'] []= $result;
if ($result->created === true) {
$output['count'] ++;
}
}
}
return $output;
}
}

View File

@ -10,6 +10,8 @@
"provm/models": "dev-master",
"provm/controller": "dev-master",
"vlucas/phpdotenv": "^5.3",
"guzzlehttp/guzzle": "^7.3",
"robmorgan/phinx": "^0.12.5",
"nesbot/carbon": "^2.46"
},
"license": "MIT",
@ -21,7 +23,6 @@
],
"require-dev": {
"phpunit/phpunit": "^8.5",
"robmorgan/phinx": "^0.12.5",
"odan/phinx-migrations-generator": "^5.4"
},
"autoload": {

View File

@ -1,57 +1,19 @@
log_format main_json escape=json '{'
'"msec": "$msec", ' # request unixtime in seconds with a milliseconds resolution
'"connection": "$connection", ' # connection serial number
'"connection_requests": "$connection_requests", ' # number of requests made in connection
'"pid": "$pid", ' # process pid
'"request_id": "$request_id", ' # the unique request id
'"request_length": "$request_length", ' # request length (including headers and body)
'"remote_addr": "$remote_addr", ' # client IP
'"remote_user": "$remote_user", ' # client HTTP username
'"remote_port": "$remote_port", ' # client port
'"time_local": "$time_local", '
'"time_iso8601": "$time_iso8601", ' # local time in the ISO 8601 standard format
'"request": "$request", ' # full path no arguments if the request
'"request_uri": "$request_uri", ' # full path and arguments if the request
'"args": "$args", ' # args
'"status": "$status", ' # response status code
'"body_bytes_sent": "$body_bytes_sent", ' # the number of body bytes exclude headers sent to a client
'"bytes_sent": "$bytes_sent", ' # the number of bytes sent to a client
'"http_referer": "$http_referer", ' # HTTP referer
'"http_user_agent": "$http_user_agent", ' # user agent
'"http_x_forwarded_for": "$http_x_forwarded_for", ' # http_x_forwarded_for
'"http_host": "$http_host", ' # the request Host: header
'"server_name": "$server_name", ' # the name of the vhost serving the request
'"request_time": "$request_time", ' # request processing time in seconds with msec resolution
'"upstream": "$upstream_addr", ' # upstream backend server for proxied requests
'"upstream_connect_time": "$upstream_connect_time", ' # upstream handshake time incl. TLS
'"upstream_header_time": "$upstream_header_time", ' # time spent receiving upstream headers
'"upstream_response_time": "$upstream_response_time", ' # time spend receiving upstream body
'"upstream_response_length": "$upstream_response_length", ' # upstream response length
'"upstream_cache_status": "$upstream_cache_status", ' # cache HIT/MISS where applicable
'"ssl_protocol": "$ssl_protocol", ' # TLS protocol
'"ssl_cipher": "$ssl_cipher", ' # TLS cipher
'"scheme": "$scheme", ' # http or https
'"request_method": "$request_method", ' # request method
'"server_protocol": "$server_protocol", ' # request protocol, like HTTP/1.1 or HTTP/2.0
'"pipe": "$pipe", ' # “p” if request was pipelined, “.” otherwise
'"gzip_ratio": "$gzip_ratio", '
'"http_cf_ray": "$http_cf_ray"'
'}';
server {
listen 80;
server_name money_app;
index index.php;
error_log /code/app/logs/error.log;
access_log /code/app/logs/access.log main_json;
access_log /code/app/logs/access.log;
root /code/app/public;
location / {
try_files $uri /index.php$is_args$args;
}
add_header 'Access-Control-Allow-Origin' 'http://localhost:8080';
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,DELETE,OPTIONS';
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
add_header 'Content-Type' 'application/json';
location ~ \.php {
try_files $uri =404;

View File

@ -12,28 +12,28 @@ return
'default_environment' => 'development',
'production' => [
'adapter' => 'mysql',
'host' => 'localhost',
'name' => 'production_db',
'user' => 'root',
'pass' => '',
'host' => $_ENV['DB_HOST'],
'name' => $_ENV['DB_NAME'],
'user' => $_ENV['DB_USER'],
'pass' => $_ENV['DB_PASSWORD'],
'port' => '3306',
'charset' => 'utf8',
],
'development' => [
'adapter' => 'mysql',
'host' => 'localhost',
'name' => 'money_dev',
'user' => 'money',
'pass' => 'money_pass',
'host' => $_ENV['DB_HOST'] ?? 'localhost',
'name' => $_ENV['DB_NAME'] ?? 'money_dev',
'user' => $_ENV['DB_USER'] ?? 'money',
'pass' => $_ENV['DB_PASSWORD'] ?? 'money_pass',
'port' => '3307',
'charset' => 'utf8',
],
'testing' => [
'adapter' => 'mysql',
'host' => 'localhost',
'name' => 'testing_db',
'user' => 'root',
'pass' => '',
'host' => $_ENV['DB_HOST'],
'name' => $_ENV['DB_NAME'],
'user' => $_ENV['DB_USER'],
'pass' => $_ENV['DB_PASSWORD'],
'port' => '3306',
'charset' => 'utf8',
]

View File

@ -1,9 +1,16 @@
<?php
use ProVM\Money\Common\Controller\API;
include_once 'currencies.php';
include_once 'values.php';
include_once 'sources.php';
$files = new DirectoryIterator(implode(DIRECTORY_SEPARATOR, [
__DIR__,
'api'
]));
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
include_once $file->getRealPath();
}
$app->get('/', API::class);

View File

@ -0,0 +1,19 @@
<?php
use ProVM\Money\Common\Controller\Aliases;
$app->group('/aliases', function($app) {
$app->post('/add[/]', [Aliases::class, 'add']);
$app->get('[/]', Aliases::class);
$app->options('[/]', function (Request $request, Response $response): Response {
return $response;
});
});
$app->group('/alias/{alias_id}', function($app) {
$app->put('/edit[/]', [Aliases::class, 'edit']);
$app->delete('/delete[/]', [Aliases::class, 'delete']);
$app->get('[/]', [Aliases::class, 'get']);
$app->options('[/]', function (Request $request, Response $response): Response {
return $response;
});
});

View File

@ -10,9 +10,16 @@ $app->group('/currencies', function($app) {
});
});
$app->group('/currency/{currency_id}', function($app) {
$app->group('/currency/{currency_id:[0-9]+}', function($app) {
$app->put('/edit[/]', [Currencies::class, 'edit']);
$app->delete('/delete[/]', [Currencies::class, 'delete']);
$app->group('/aliases', function($app) {
$app->post('/add[/]', [Currencies::class, 'addAliases']);
$app->get('[/]', [Currencies::class, 'getAliases']);
$app->options('[/]', function (Request $request, Response $response): Response {
return $response;
});
});
$app->group('/values', function($app) {
$app->get('/latest[/]', [Currencies::class, 'latestValue']);
$app->post('/add[/]', [Currencies::class, 'addValues']);
@ -33,3 +40,18 @@ $app->group('/currency/{currency_id}', function($app) {
return $response;
});
});
$app->group('/currency/{query:[a-z]+}', function($app) {
$app->group('/values', function($app) {
$app->get('/latest[/]', [Currencies::class, 'findLatest']);
$app->get('[/]', [Currencies::class, 'findValues']);
$app->options('[/]', function (Request $request, Response $response): Response {
return $response;
});
});
$app->get('/sources', [Currencies::class, 'findSources']);
$app->get('[/]', [Currencies::class, 'find']);
$app->options('[/]', function (Request $request, Response $response): Response {
return $response;
});
});

View File

@ -6,7 +6,7 @@ $app->group('/sources', function($app) {
$app->get('[/]', Sources::class);
});
$app->group('/source/{currency_id}/{url}', function($app) {
$app->group('/source/{source_id}', function($app) {
$app->put('/edit[/]', [Sources::class, 'edit']);
$app->delete('/delete[/]', [Sources::class, 'delete']);
$app->get('[/]', [Sources::class, 'get']);

View File

@ -0,0 +1,4 @@
<?php
use ProVM\Money\Common\Controller\Update;
$app->get('/update', Update::class);

View File

@ -0,0 +1,2 @@
<?php
$app->add($app->getContainer()->get(ProVM\Money\Common\Middleware\Migrate::class));

View File

@ -22,5 +22,11 @@ return [
'routes'
]);
return (object) $arr;
})
}),
'phinx' => function(Container $c) {
return implode(DIRECTORY_SEPARATOR, [
$c->get('locations')->base,
'phinx.php'
]);
}
];

26
app/setup/api/setups.php Normal file
View File

@ -0,0 +1,26 @@
<?php
use Psr\Container\ContainerInterface as Container;
return [
GuzzleHttp\ClientInterface::class => function(Container $c) {
return new GuzzleHttp\Client();
},
ProVM\Common\Factory\Model::class => function(Container $c) {
return new ProVM\Common\Factory\Model();
},
ProVM\Money\Common\Service\Update::class => function(Container $c) {
return new ProVM\Money\Common\Service\Update($c->get(ProVM\Common\Factory\Model::class), $c->get(GuzzleHttp\ClientInterface::class));
},
ProVM\Money\Common\Middleware\Migrate::class => function(Container $c) {
return new ProVM\Money\Common\Middleware\Migrate($c->get(Phinx\Wrapper\TextWrapper::class), $c->get(ProVM\Money\Common\Service\Update::class));
},
Phinx\Console\PhinxApplication::class => function(Container $c) {
return new Phinx\Console\PhinxApplication();
},
Phinx\Wrapper\TextWrapper::class => function(Container $c) {
$options = [
'configuration' => $c->get('phinx')
];
return new Phinx\Wrapper\TextWrapper($c->get(Phinx\Console\PhinxApplication::class), $options);
}
];

1
automation/crontab Normal file
View File

@ -0,0 +1 @@
0 2 * * */1 curl http://app-server/update

View File

@ -0,0 +1,70 @@
import argparse
import keyboard
import datetime
import time
import httpx
from threading import Event, Thread
def update(url: str):
r = httpx.get(url)
def update_thread(stop: Event, url: str):
t = datetime.time(hour=2)
print('Starting update thread.')
while True:
if stop.isSet():
break
if datetime.time() == t:
print('Updating.')
update(url)
print('Sleep')
time.sleep(60 * 60 * 5)
print('Stop update thread.')
def main_thread(stop: Event):
print('Starting main thread.')
while True:
if stop.isSet():
break
try:
if keyboard.is_pressed('q'):
print('Stop')
stop.set()
break
except KeyboardInterrupt:
print('Stop2')
stop.set()
break
print('Stop main thread.')
def main(args):
print('Main')
stop_signal = Event()
threads = [
Thread(target=update_thread, args=(stop_signal, args.url, )),
Thread(target=main_thread, args=(stop_signal,))
]
[t.start() for t in threads]
while True:
try:
if True not in [t.is_alive() for t in threads]:
break
except KeyboardInterrupt:
print('Stop Main')
stop_signal.set()
break
[t.join() for t in threads]
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--url', help='API Url', default='http://localhost:8081/update')
_args = parser.parse_args()
main(_args)

View File

@ -34,13 +34,21 @@ class CreateValues extends Phinx\Migration\AbstractMigration
'signed' => false,
'after' => 'value',
])
->addIndex(['currency_id'], [
/*->addIndex(['currency_id'], [
'name' => 'currency_id',
'unique' => false,
])
->addIndex(['base_id'], [
'name' => 'base_id',
'unique' => false,
])*/
->addForeignKey(['currency_id'], 'currencies', ['id'], [
'delete' => 'CASCADE',
'update' => 'CASCADE'
])
->addForeignKey(['base_id'], 'currencies', ['id'], [
'delete' => 'CASCADE',
'update' => 'CASCADE'
])
->create();
/*$this->table('currencies', [

View File

@ -20,13 +20,19 @@ final class CreateSources extends AbstractMigration
{
$this->table('sources', [
'id' => false,
'primary_key' => ['currency_id', 'url'],
'primary_key' => ['id'],
'engine' => 'InnoDB',
'encoding' => 'utf8mb4',
'collation' => 'utf8mb4_general_ci',
'comment' => '',
'row_format' => 'DYNAMIC',
])
->addColumn('id', 'integer', [
'null' => false,
'limit' => '10',
'signed' => false,
'identity' => 'enable',
])
->addColumn('currency_id', 'integer', [
'null' => false,
'limit' => '10',
@ -47,6 +53,14 @@ final class CreateSources extends AbstractMigration
'encoding' => 'utf8mb4',
'after' => 'url',
])
/*->addIndex(['currency_id'], [
'name' => 'currency_id',
'unique' => false,
])*/
->addForeignKey(['currency_id'], 'currencies', ['id'], [
'delete' => 'CASCADE',
'update' => 'CASCADE'
])
->create();
}
}

View File

@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateAliases 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('aliases', [
'id' => false,
'primary_key' => ['id'],
'engine' => 'InnoDB',
'encoding' => 'utf8mb4',
'collation' => 'utf8mb4_general_ci',
'comment' => '',
'row_format' => 'DYNAMIC',
])
->addColumn('id', 'integer', [
'null' => false,
'limit' => '10',
'signed' => false,
'identity' => 'enable',
])
->addColumn('currency_id', 'integer', [
'null' => false,
'limit' => '10',
'signed' => false,
'after' => 'id',
])
->addColumn('alias', 'string', [
'null' => false,
'limit' => 100,
'collation' => 'utf8mb4_general_ci',
'encoding' => 'utf8mb4',
'after' => 'currency_id',
])
/*->addIndex(['currency_id'], [
'name' => 'currency_id',
'unique' => false,
])*/
->addForeignKey(['currency_id'], 'currencies', ['id'], [
'delete' => 'CASCADE',
'update' => 'CASCADE'
])
->create();
}
}

38
db/seeds/Currencies.php Normal file
View File

@ -0,0 +1,38 @@
<?php
use Phinx\Seed\AbstractSeed;
class Currencies 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()
{
$data = [
[
'code' => 'CLP',
'name' => 'Peso Chileno'
],
[
'code' => 'CLF',
'name' => 'Unidad de Fomento'
],
[
'code' => 'USD',
'name' => 'US Dollar'
],
[
'code' => 'BTC',
'name' => 'Bitcoin'
]
];
$this->table('currencies')->insert($data)->saveData();
}
}

45
db/seeds/Sources.php Normal file
View File

@ -0,0 +1,45 @@
<?php
use Phinx\Seed\AbstractSeed;
class Sources extends AbstractSeed
{
public function getDependencies() {
return [
'Currencies'
];
}
/**
* 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()
{
$id = $this->query("SELECT id FROM currencies WHERE code = 'USD'")->fetchAll(\PDO::FETCH_ASSOC);
$data = [
[
'currency_id' => $id[0]['id'],
'url' => 'https://mindicador.cl/api/dolar/{year}',
'frecuency' => '1 DAY'
]
];
$id = $this->query("SELECT id FROM currencies WHERE code = 'CLF'")->fetchAll(\PDO::FETCH_ASSOC);
$data []= [
'currency_id' => $id[0]['id'],
'url' => 'https://mindicador.cl/api/uf/{year}',
'frecuency' => '1 DAY'
];
$id = $this->query("SELECT id FROM currencies WHERE code = 'BTC'")->fetchAll(\PDO::FETCH_ASSOC);
$data []= [
'currency_id' => $id[0]['id'],
'url' => 'https://mindicador.cl/api/bitcoin/{year}',
'frecuency' => '1 DAY'
];
$this->table('sources')->insert($data)->saveData();
}
}

View File

@ -11,7 +11,6 @@ services:
- ./app/docker/nginx.conf:/etc/nginx/conf.d/default.conf
depends_on:
- app-php
app-php:
container_name: money_app_php
build:
@ -21,6 +20,12 @@ services:
- .:/code
ports:
- 9123:9000
app-cron:
container_name: money_cron
image: sleeck/crond
volumes:
- ./automation/crontab:/etc/cron.d/auto-crontab
- ./automation/logs:/var/log/cron
ui-server:
container_name: money_ui
@ -32,7 +37,6 @@ services:
- ./ui/docker/nginx.conf:/etc/nginx/conf.d/default.conf
depends_on:
- ui-php
ui-php:
container_name: money_ui_php
build:
@ -43,6 +47,25 @@ services:
ports:
- 9124:9000
ws-server:
container_name: money_ws
image: nginx:alpine
ports:
- 8020:80
volumes:
- .:/code
- ./ws/docker/nginx.conf:/etc/nginx/conf.d/default.conf
depends_on:
- ws-php
ws-php:
container_name: money_ws_php
restart: unless-stopped
build:
context: ./ws/docker
dockerfile: PHP.Dockerfile
volumes:
- .:/code
db:
container_name: money_db
image: mariadb:latest
@ -51,12 +74,11 @@ services:
- 3307:3306
environment:
MYSQL_ROOT_PASSWORD: 'money'
MYSQL_DATABASE: 'money_dev'
MYSQL_USER: 'money'
MYSQL_PASSWORD: 'money_pass'
MYSQL_DATABASE: ${DB_NAME-money_dev}
MYSQL_USER: '${DB_USER-money}'
MYSQL_PASSWORD: '${DB_PASSWORD-money_pass}'
volumes:
- dbdata:/var/lib/mysql
adminer:
container_name: money_adminer
image: adminer:latest

56
src/Alias.php Normal file
View File

@ -0,0 +1,56 @@
<?php
namespace ProVM\Money;
use ProVM\Common\Alias\Model;
use ProVM\Common\Factory\Model as ModelFactory;
/**
* @property int $id
* @property Currency $currency_id
* @property string $alias
*/
class Alias extends Model {
public static $_table = 'aliases';
protected $currency;
public function currency() {
if ($this->currency === null) {
$this->currency = $this->childOf(Currency::class, [Model::SELF_KEY => 'currency_id']);
}
return $this->currency;
}
protected static $fields = ['currency_id', 'alias'];
public static function add(ModelFactory $factory, $info) {
$input = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
$alias = $factory->find(Alias::class)->where([['currency_id', $input['currency_id']], ['alias', $input['alias']]])->one();
$created = false;
$result = (object) compact('input', 'alias', 'created');
if (!$alias) {
$alias = $factory->create(Alias::class, $input);
$created = $alias->save();
$result->created = $created;
}
$result->source = $alias->asArray();
return $result;
}
public function edit($info): bool {
$data = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
$edited = false;
foreach ($data as $field => $value) {
if ($this->{$field} != $value) {
$this->{$field} = $value;
$edited = true;
}
}
if ($edited) {
$edited = $this->save();
}
return $edited;
}
public function asArray(): array {
$output = parent::asArray();
$output['currency'] = $this->currency()->asArray();
return $output;
}
}

View File

@ -38,6 +38,13 @@ class Currency extends Model {
}
return $this->sources;
}
protected $aliases;
public function aliases() {
if ($this->aliases === null) {
$this->aliases = $this->parentOf(Alias::class, [Model::CHILD_KEY => 'currency_id']);
}
return $this->aliases;
}
protected static $fields = ['code', 'name'];
public static function add(ModelFactory $factory, $info) {
@ -73,6 +80,12 @@ class Currency extends Model {
}
return $edited;
}
public function addAlias($info) {
$arr = (array) $info;
$arr['currency_id'] = (int) $this->id;
$result = Alias::add($this->factory, $arr);
return $result;
}
public function addValue($info) {
$arr = (array) $info;
$arr['currency_id'] = (int) $this->id;
@ -85,4 +98,27 @@ class Currency extends Model {
$result = Source::add($this->factory, $arr);
return $result;
}
public static function find(ModelFactory $factory, string $query) {
$query = '%' . $query . '%';
$currency = $factory->find(Currency::class)->where([
['code', $query, 'like']
])->one();
if ($currency !== false and $currency !== null) {
return $currency;
}
$currency = $factory->find(Currency::class)->where([
['name', $query, 'like']
])->one();
if ($currency !== false and $currency !== null) {
return $currency;
}
$alias = $factory->find(Alias::class)->where([
['alias', $query, 'like']
])->one();
if ($alias !== false and $alias !== null) {
return $alias->currency();
}
return false;
}
}

View File

@ -3,15 +3,16 @@ namespace ProVM\Money;
use Carbon\CarbonInterval;
use ProVM\Common\Alias\Model;
use ProVM\Common\Factory\Model as ModelFactory;
/**
* @property int $id
* @property Currency $currency_id
* @property string $url
* @property \DateInterval $frecuency
*/
class Source extends Model {
public static $_table = 'sources';
public static $_id_column = ['currency_id', 'url'];
protected $currency;
public function currency(): ?Currency {
@ -22,7 +23,7 @@ class Source extends Model {
}
public function frecuency(\DateInterval $frecuency = null) {
if ($frecuency == null) {
return new \CarbonInterval($this->fecuency);
return CarbonInterval::createFromDateString($this->frecuency);
}
$this->frecuency = CarbonInterval::getDateIntervalSpec($frecuency);
}
@ -30,15 +31,16 @@ class Source extends Model {
protected static $fields = ['currency_id', 'url', 'frecuency'];
public static function add(ModelFactory $factory, $info) {
$input = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
$input['frecuency'] = CarbonInterval::createFromDateString($input['frecuency']);
$source = $factory->find(Source::class)->where([['currency_id', $input['currency_id']], ['url', $input['url']]])->one();
$created = false;
$result = (object) compact('input', 'source', 'created');
if (!$value) {
if (!$source) {
$source = $factory->create(Source::class, $input);
$created = $source->save();
$result->created = $created;
}
$result->value = $source->asArray();
$result->source = $source->asArray();
return $result;
}
public function edit($info): bool {
@ -46,9 +48,6 @@ class Source extends Model {
$edited = false;
foreach ($data as $field => $value) {
if ($this->{$field} != $value) {
if ($field == 'currency_id' or $field == 'url') {
continue;
}
$this->{$field} = $value;
$edited = true;
}
@ -61,7 +60,7 @@ class Source extends Model {
public function asArray(): array {
$output = parent::asArray();
$output['currency'] = $this->currency()->asArray();
$output['frecuency'] = $this->frecuency()->format('Y-m-d H:i:s');
$output['frecuency'] = $this->frecuency()->spec();
return $output;
}
}

View File

@ -12,3 +12,38 @@ function readyDate(date) {
+ ':' + date.getMinutes()
+ ':' + date.getSeconds()
}
let socket = {
url: '',
conn: null,
connect: function(ready, getMessage) {
this.conn = new WebSocket(this.url)
this.conn.onopen = (e) => {
console.debug(e)
ready()
}
this.conn.onmessage = (e) => {
console.debug(e)
getMessage(e)
}
this.conn.onerror = (e) => {
console.error(e)
}
this.conn.onclose = (e) => {
if (e.code != 1000) {
console.error(e)
return
}
console.debug(e)
}
},
sendMessage: function(action, data = null) {
var msg = {
action: action
}
if (data != null) {
msg['data'] = data
}
this.conn.send(JSON.stringify(msg))
}
}

View File

@ -1,2 +1,2 @@
"use strict";function formatValue(t,e){return new Intl.NumberFormat("es-CL",{style:"currency",currency:e,minimumSignificantDigits:2}).format(t)}function formatDate(t){return new Intl.DateTimeFormat("es-CL",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(t)}function readyDate(t){return t.getFullYear()+"-"+(t.getMonth()+1)+"-"+t.getDate()+" "+t.getHours()+":"+t.getMinutes()+":"+t.getSeconds()}
"use strict";function formatValue(n,e){return new Intl.NumberFormat("es-CL",{style:"currency",currency:e,minimumSignificantDigits:2}).format(n)}function formatDate(n){return new Intl.DateTimeFormat("es-CL",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(n)}function readyDate(n){return n.getFullYear()+"-"+(n.getMonth()+1)+"-"+n.getDate()+" "+n.getHours()+":"+n.getMinutes()+":"+n.getSeconds()}var socket={url:"",conn:null,connect:function(e,t){this.conn=new WebSocket(this.url),this.conn.onopen=function(n){console.debug(n),e()},this.conn.onmessage=function(n){console.debug(n),t(n)},this.conn.onerror=function(n){console.error(n)},this.conn.onclose=function(n){1e3==n.code?console.debug(n):console.error(n)}},sendMessage:function(n){var e=1<arguments.length&&void 0!==arguments[1]?arguments[1]:null,n={action:n};null!=e&&(n.data=e),this.conn.send(JSON.stringify(n))}};
//# sourceMappingURL=maps/main.min.js.map

View File

@ -1 +1 @@
{"version":3,"file":"../main.min.js","sources":["main.js"],"sourcesContent":["\"use strict\";\n\nfunction formatValue(value, base) {\n return new Intl.NumberFormat('es-CL', {\n style: 'currency',\n currency: base,\n minimumSignificantDigits: 2\n }).format(value);\n}\n\nfunction formatDate(date) {\n return new Intl.DateTimeFormat('es-CL', {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit'\n }).format(date);\n}\n\nfunction readyDate(date) {\n return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();\n}"],"names":["formatValue","value","base","Intl","NumberFormat","style","currency","minimumSignificantDigits","format","formatDate","date","DateTimeFormat","year","month","day","hour","minute","second","readyDate","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds"],"mappings":"aAEA,SAASA,YAAYC,EAAOC,GAC1B,OAAO,IAAIC,KAAKC,aAAa,QAAS,CACpCC,MAAO,WACPC,SAAUJ,EACVK,yBAA0B,IACzBC,OAAOP,GAGZ,SAASQ,WAAWC,GAClB,OAAO,IAAIP,KAAKQ,eAAe,QAAS,CACtCC,KAAM,UACNC,MAAO,UACPC,IAAK,UACLC,KAAM,UACNC,OAAQ,UACRC,OAAQ,YACPT,OAAOE,GAGZ,SAASQ,UAAUR,GACjB,OAAOA,EAAKS,cAAgB,KAAOT,EAAKU,WAAa,GAAK,IAAMV,EAAKW,UAAY,IAAMX,EAAKY,WAAa,IAAMZ,EAAKa,aAAe,IAAMb,EAAKc"}
{"version":3,"file":"../main.min.js","sources":["main.js"],"sourcesContent":["\"use strict\";\n\nfunction formatValue(value, base) {\n return new Intl.NumberFormat('es-CL', {\n style: 'currency',\n currency: base,\n minimumSignificantDigits: 2\n }).format(value);\n}\n\nfunction formatDate(date) {\n return new Intl.DateTimeFormat('es-CL', {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit'\n }).format(date);\n}\n\nfunction readyDate(date) {\n return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();\n}\n\nvar socket = {\n url: '',\n conn: null,\n connect: function connect(ready, getMessage) {\n this.conn = new WebSocket(this.url);\n\n this.conn.onopen = function (e) {\n console.debug(e);\n ready();\n };\n\n this.conn.onmessage = function (e) {\n console.debug(e);\n getMessage(e);\n };\n\n this.conn.onerror = function (e) {\n console.error(e);\n };\n\n this.conn.onclose = function (e) {\n if (e.code != 1000) {\n console.error(e);\n return;\n }\n\n console.debug(e);\n };\n },\n sendMessage: function sendMessage(action) {\n var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n var msg = {\n action: action\n };\n\n if (data != null) {\n msg['data'] = data;\n }\n\n this.conn.send(JSON.stringify(msg));\n }\n};"],"names":["formatValue","value","base","Intl","NumberFormat","style","currency","minimumSignificantDigits","format","formatDate","date","DateTimeFormat","year","month","day","hour","minute","second","readyDate","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","socket","url","conn","connect","ready","getMessage","this","WebSocket","onopen","e","console","debug","onmessage","onerror","error","onclose","code","sendMessage","action","data","arguments","length","undefined","msg","send","JSON","stringify"],"mappings":"aAEA,SAASA,YAAYC,EAAOC,GAC1B,OAAO,IAAIC,KAAKC,aAAa,QAAS,CACpCC,MAAO,WACPC,SAAUJ,EACVK,yBAA0B,IACzBC,OAAOP,GAGZ,SAASQ,WAAWC,GAClB,OAAO,IAAIP,KAAKQ,eAAe,QAAS,CACtCC,KAAM,UACNC,MAAO,UACPC,IAAK,UACLC,KAAM,UACNC,OAAQ,UACRC,OAAQ,YACPT,OAAOE,GAGZ,SAASQ,UAAUR,GACjB,OAAOA,EAAKS,cAAgB,KAAOT,EAAKU,WAAa,GAAK,IAAMV,EAAKW,UAAY,IAAMX,EAAKY,WAAa,IAAMZ,EAAKa,aAAe,IAAMb,EAAKc,aAGhJ,IAAIC,OAAS,CACXC,IAAK,GACLC,KAAM,KACNC,QAAS,SAAiBC,EAAOC,GAC/BC,KAAKJ,KAAO,IAAIK,UAAUD,KAAKL,KAE/BK,KAAKJ,KAAKM,OAAS,SAAUC,GAC3BC,QAAQC,MAAMF,GACdL,KAGFE,KAAKJ,KAAKU,UAAY,SAAUH,GAC9BC,QAAQC,MAAMF,GACdJ,EAAWI,IAGbH,KAAKJ,KAAKW,QAAU,SAAUJ,GAC5BC,QAAQI,MAAML,IAGhBH,KAAKJ,KAAKa,QAAU,SAAUN,GACd,KAAVA,EAAEO,KAKNN,QAAQC,MAAMF,GAJZC,QAAQI,MAAML,KAOpBQ,YAAa,SAAqBC,GAChC,IAAIC,EAA0B,EAAnBC,UAAUC,aAA+BC,IAAjBF,UAAU,GAAmBA,UAAU,GAAK,KAC3EG,EAAM,CACRL,OAAQA,GAGE,MAARC,IACFI,EAAU,KAAIJ,GAGhBb,KAAKJ,KAAKsB,KAAKC,KAAKC,UAAUH"}

View File

@ -0,0 +1,34 @@
let socket = {
url: '',
conn: null,
connect: function(ready, getMessage) {
this.conn = new WebSocket(this.url)
this.conn.onopen = (e) => {
console.debug(e)
ready()
}
this.conn.onmessage = (e) => {
console.debug(e)
getMessage(e)
}
this.conn.onerror = (e) => {
console.error(e)
}
this.conn.onclose = (e) => {
if (e.code != 1000) {
console.error(e)
return
}
console.debug(e)
}
},
sendMessage: function(action, data = null) {
var msg = {
action: action
}
if (data != null) {
msg['data'] = data
}
this.conn.send(JSON.stringify(msg))
}
}

View File

@ -6,19 +6,37 @@
@section('content')
<h3 class="ui header c_code"></h3>
<table class="ui table">
<thead>
<th>Alias</th>
<th class="right aligned" id="add_alias">
<i class="plus icon"></i>
</th>
</thead>
<tbody id="aliases"></tbody>
</table>
<table class="ui table">
<thead>
<th>Url</th>
<th class="right aligned" id="add_source">
<i class="plus icon"></i>
</th>
</thead>
<tbody id="sources"></tbody>
</table>
<table class="ui table">
<thead>
<tr>
<th>Fecha</th>
<th>Valor</th>
<th id="add_value">
<th class="right aligned" id="add_value">
<i class="plus icon"></i>
</th>
</tr>
</thead>
<tbody id="values"></tbody>
</table>
<div class="ui modal" id="add_modal">
<div class="ui modal" id="add_values">
<div class="header">
Agregar Valor para <span class="c_name"></span>
</div>
@ -52,10 +70,336 @@
</form>
</div>
</div>
<div class="ui modal" id="add_sources">
<div class="header">
Agregar Fuente para <span class="c_name"></span>
</div>
<div class="content">
<form class="ui form">
<div class="inline field">
<label>Url</label>
<input type="text" name="url" />
</div>
<div class="inline field">
<label>Frecuencia</label>
<input type="text" name="frecuency" />
<select name="frec_name" class="ui selection dropdown">
<option value="minute">Minuto(s)</option>
<option value="hour">Hora(s)</option>
<option value="day">D&iacute;a(s)</option>
<option value="week">Semana(s)</option>
<option value="month">Mes(es)</option>
<option value="year">A&ntilde;o(s)</option>
</select>
</div>
<button class="ui button">Agregar</button>
</form>
</div>
</div>
<div class="ui modal" id="add_aliases">
<div class="header">
Agregar Alias para <span class="c_name"></span>
</div>
<div class="content">
<form class="ui form">
<div class="inline field">
<label>Alias</label>
<input type="text" name="alias" />
</div>
<button class="ui button">Agregar</button>
</form>
</div>
</div>
@endsection
@push('scripts')
<script type="text/javascript">
let aliases = {
id: '#aliases',
add_button: '#add_alias',
add_modal: '#add_aliases',
loading: '',
loaded: false,
aliases: [],
setup: function() {
$(this.id).hide()
$(this.add_button).css('cursor', 'pointer').click((e) => {
this.add()
})
this.buildModal()
},
get: function(currency_id, data) {
if (!this.loaded) {
this.aliases = data.aliases
this.populate(currency_id)
socket.sendMessage('currency.sources', {currency_id: currency_id})
return
}
var url = '{{$urls->api}}/currency/' + currency_id + '/aliases'
$.getJSON(url, (data) => {
this.aliases = data.aliases
this.populate(currency_id)
})
},
buildModal: function() {
$(this.add_modal).modal()
$(this.add_modal).find('form').submit((e) => {
e.preventDefault()
this.doAdd()
return false
})
},
populate: function(currency_id) {
$(this.id).html('')
$.each(this.aliases, (i, el) => {
let row = $('<tr></tr>').append(
$('<td></td>').html(el.alias)
).append(
$('<td></td>').attr('class', 'remove_source right aligned').attr('data-id', el.id).append(
$('<i></i>').attr('class', 'minus icon')
).css('cursor', 'pointer').click((e) => {
this.remove(currency_id, $(e.currentTarget).attr('data-id'))
})
)
$(this.id).append(row)
})
$(this.id).show()
},
add: function() {
$(this.add_modal).find('form').trigger('reset')
$(this.add_modal).modal('show')
},
doAdd: function() {
let form = $(this.add_modal).find('form')
let info = {
alias: form.find("[name='alias']").val()
}
var url = '{{$urls->api}}/currency/{{$currency_id}}/aliases/add'
$(this.add_modal).modal('hide')
$(this.loading).modal('show')
$.post(url, JSON.stringify(info), (data) => {
if (data.aliases[0].created) {
this.get('{{$currency_id}}')
}
}, 'json').then(() => {
$(this.loading).modal('hide')
})
},
remove: function(id) {
var url = '{{$urls->api}}/alias/' + id + '/delete'
$(this.loading).modal('show')
$.ajax({
url: url,
method: 'DELETE',
dataType: 'json',
success: (data) => {
if (data.deleted) {
this.get()
}
}
}).then(() => {
$(this.loading).modal('hide')
})
}
}
let sources = {
id: '#sources',
add_button: '#add_source',
add_modal: '#add_sources',
loading: '',
loaded: false,
sources: [],
setup: function() {
$(this.id).hide()
$(this.add_button).css('cursor', 'pointer').click((e) => {
this.add()
})
this.buildModal()
},
get: function(currency_id, data) {
if (!this.loaded) {
this.sources = data.sources
this.populate(currency_id)
socket.sendMessage('currency.values', {currency_id: currency_id})
return
}
var url = '{{$urls->api}}/currency/' + currency_id + '/sources'
$.getJSON(url, (data) => {
this.sources = data.sources
this.populate(currency_id)
})
},
buildModal: function() {
$(this.add_modal).modal()
$(this.add_modal).find('form').submit((e) => {
e.preventDefault()
this.doAdd()
return false
})
},
populate: function(currency_id) {
$(this.id).html('')
$.each(this.sources, (i, el) => {
let row = $('<tr></tr>').append(
$('<td></td>').html(el.url)
).append(
$('<td></td>').attr('class', 'remove_source right aligned').attr('data-url', el.url).append(
$('<i></i>').attr('class', 'minus icon')
).css('cursor', 'pointer').click((e) => {
this.remove(currency_id, $(e.currentTarget).attr('data-url'))
})
)
$(this.id).append(row)
})
$(this.id).show()
},
add: function() {
$(this.add_modal).find('form').trigger('reset')
$(this.add_modal).modal('show')
},
doAdd: function() {
let form = $(this.add_modal).find('form')
let info = {
url: form.find("[name='url']").val(),
frecuency: form.find("[name='frecuency']").val() + ' ' + form.find("[name='frec_name']").val()
}
var url = '{{$urls->api}}/currency/{{$currency_id}}/sources/add'
$(this.add_modal).modal('hide')
$(this.loading).modal('show')
$.post(url, JSON.stringify(info), (data) => {
if (data.sources[0].created) {
this.get('{{$currency_id}}')
}
}, 'json').then(() => {
$(this.loading).modal('hide')
})
},
remove: function(currency_id, url) {
var url = '{{$urls->api}}/source/' + currency_id + '/' + url + '/delete'
$(this.loading).modal('show')
$.ajax({
url: url,
method: 'DELETE',
dataType: 'json',
success: (data) => {
if (data.deleted) {
this.get()
}
}
}).then(() => {
$(this.loading).modal('hide')
})
}
}
let values = {
id: '#values',
add_button: '#add_value',
add_modal: '#add_values',
loading: '',
values: [],
loaded: false,
setup: function() {
$(this.id).hide()
this.buildModal()
$(this.add_button).css('cursor', 'pointer').click((e) => {
this.add()
})
},
get: function(currency_id, data) {
if (!this.loaded) {
if (data.values.length > 0) {
this.values = data.values
this.populate(currency_id)
}
$(this.loading).modal('hide')
socket.conn.close()
return
}
var url = '{{$urls->api}}/currency/' + currency_id + '/values'
$.getJSON(url, (data) => {
this.values = data.values
this.populate(currency_id)
})
},
buildModal: function() {
this.getCurrencies()
$(this.add_modal).modal()
$(this.add_modal).find('.ui.calendar').calendar()
$(this.add_modal).find('form').submit((e) => {
e.preventDefault()
this.doAdd()
return false
})
$(this.add_modal).find('.ui.dropdown').dropdown()
},
getCurrencies: function() {
var url = '{{$urls->api}}/currencies'
$.getJSON(url, (data) => {
let dp = $(this.add_modal).find('.ui.dropdown')
vals = []
$.each(data.currencies, (i, el) => {
vals.push({name: el.name, value: el.id, text: el.name})
})
dp.dropdown('setup menu', {values: vals})
})
},
populate: function(currency_id) {
$(this.id).html('')
$.each(this.values, (i, el) => {
let row = $('<tr></tr>').append(
$('<td></td>').html(formatDate(new Date(el.date_time)))
).append(
$('<td></td>').html(formatValue(el.value, el.base.code))
).append(
$('<td></td>').attr('class', 'remove_value right aligned').attr('data-base', el.base.id).attr('data-date_time', el.date_time).append(
$('<i></i>').attr('class', 'minus icon')
).css('cursor', 'pointer').click((e) => {
this.remove(currency_id, $(e.currentTarget).attr('data-base'), $(e.currentTarget).attr('data-date_time'))
})
)
$(this.id).append(row)
})
$(this.id).show()
},
add: function() {
$(this.add_modal).find('form').trigger('reset')
$(this.add_modal).modal('show')
},
doAdd: function() {
let form = $(this.add_modal).find('form')
let info = {
date_time: readyDate(new Date(form.find('.ui.calendar').calendar('get date'))),
value: form.find("[name='valor']").val(),
base_id: form.find('.ui.dropdown').dropdown('get value')
}
var url = '{{$urls->api}}/currency/{{$currency_id}}/values/add'
$(this.add_modal).modal('hide')
$(this.loading).modal('show')
$.post(url, JSON.stringify(info), (data) => {
if (data.values[0].created) {
this.get('{{$currency_id}}')
}
}, 'json').then(() => {
$(this.loading).modal('hide')
})
},
remove: function(currency_id, base_id, date_time) {
var url = '{{$urls->api}}/value/' + currency_id + '/' + base_id + '/' + encodeURI(date_time) + '/delete'
$(this.loading).modal('show')
$.ajax({
url: url,
method: 'DELETE',
dataType: 'json',
success: (data) => {
if (data.deleted) {
this.get().then(() => {
$(this.loading).modal('hide')
})
}
}
})
}
}
let currency = {
id: {{$currency_id}},
data: {
@ -67,120 +411,43 @@
name: '.c_name',
code: '.c_code'
},
values_id: '#values',
values: [],
add_button: '#add_value',
add_modal: '#add_modal',
loading: '#loading',
setup: function() {
$(this.values_id).hide()
this.buildModal()
$(this.add_button).css('cursor', 'pointer').click((e) => {
this.addValue()
})
this.getData().then(() => {
this.getValues().then(() => {
$(this.loading).modal('hide')
})
})
aliases.loading = this.loading
aliases.setup()
sources.loading = this.loading
sources.setup()
values.loading = this.loading
values.setup()
socket.url = '{{$urls->ws}}'
socket.connect(this.ready, this.getMessage)
},
buildModal: function() {
this.getCurrencies()
$(this.add_modal).modal()
$(this.add_modal).find('.ui.calendar').calendar()
$(this.add_modal).find('form').submit((e) => {
e.preventDefault()
this.doAddValue()
return false
})
$(this.add_modal).find('.ui.dropdown').dropdown()
ready: function() {
socket.sendMessage('currency', {currency_id: '{{$currency_id}}'})
},
getData: function() {
let url = '{{$urls->api}}/currency/' + this.id
return $.getJSON(url, (data) => {
$.each(this.data, (i, el) => {
this.data[i] = data.currency[i]
})
$.each(this.map, (i, el) => {
$(el).html(data.currency[i])
})
})
},
getValues: function() {
let url = '{{$urls->api}}/currency/' + this.id + '/values'
return $.getJSON(url, (data) => {
if (data.values.length > 0) {
this.values = data.values
this.populateValues()
}
})
},
populateValues: function() {
$(this.values_id).html('')
$.each(this.values, (i, el) => {
let row = $('<tr></tr>').append(
$('<td></td>').html(formatDate(new Date(el.date_time)))
).append(
$('<td></td>').html(formatValue(el.value, el.base.code))
).append(
$('<td></td>').attr('class', 'remove_value').attr('data-base', el.base.id).attr('data-date_time', el.date_time).append(
$('<i></i>').attr('class', 'minus icon')
).css('cursor', 'pointer').click((e) => {
this.removeValue($(e.currentTarget).attr('data-base'), $(e.currentTarget).attr('data-date_time'))
})
)
$(this.values_id).append(row)
})
$(this.values_id).show()
},
getCurrencies: function() {
let url = '{{$urls->api}}/currencies'
$.getJSON(url, (data) => {
let dp = $(this.add_modal).find('.ui.dropdown')
values = []
$.each(data.currencies, (i, el) => {
values.push({name: el.name, value: el.id, text: el.name})
})
dp.dropdown('setup menu', {values: values})
})
},
addValue: function() {
$(this.add_modal).find('form').trigger('reset')
$(this.add_modal).modal('show')
},
doAddValue: function() {
let form = $(this.add_modal).find('form')
let info = {
date_time: readyDate(new Date(form.find('.ui.calendar').calendar('get date'))),
value: form.find("[name='valor']").val(),
base_id: form.find('.ui.dropdown').dropdown('get value')
getMessage: function(e) {
response = JSON.parse(e.data)
if (response.request.action == 'currency') {
currency.get(response.body)
}
if (response.request.action == 'currency.aliases') {
aliases.get(response.request.body.currency_id, response.body)
}
if (response.request.action == 'currency.sources') {
sources.get(response.request.body.currency_id, response.body)
}
if (response.request.action == 'currency.values') {
values.get(response.request.body.currency_id, response.body)
}
let url = '{{$urls->api}}/currency/' + this.data.id + '/values/add'
$(this.add_modal).modal('hide')
$(this.loading).modal('show')
$.post(url, JSON.stringify(info), (data) => {
if (data.values[0].created) {
this.getValues()
}
}, 'json').then(() => {
$(this.loading).modal('hide')
})
},
removeValue: function(base_id, date_time) {
let url = '{{$urls->api}}/value/' + this.data.id + '/' + base_id + '/' + encodeURI(date_time) + '/delete'
$(this.loading).modal('show')
$.ajax({
url: url,
method: 'DELETE',
dataType: 'json',
success: (data) => {
if (data.deleted) {
this.getValues().then(() => {
$(this.loading).modal('hide')
})
}
}
get: function(data) {
$.each(this.data, (i, el) => {
this.data[i] = data.currency[i]
})
$.each(this.map, (i, el) => {
$(el).html(data.currency[i])
})
socket.sendMessage('currency.aliases', {currency_id: '{{$currency_id}}'})
}
}
$(document).ready(() => {

View File

@ -13,47 +13,76 @@
let cards = {
id: '#cards',
setup: function() {
this.getCurrencies()
socket.url = '{{$urls->ws}}'
socket.connect(this.socketReady, this.getMessage)
},
data: [],
getCurrencies: function() {
let url = '{{$urls->api}}/currencies'
return $.getJSON(url, (data) => {
let promises = []
$.each(data.currencies, (i, el) => {
this.data[el.id] = {'currency': el, 'value': null}
promises.push(this.getValue(el.id))
})
Promise.all(promises).then(() => {
this.buildCards()
})
socketReady: function() {
socket.sendMessage('currencies')
},
getMessage: function(e) {
response = JSON.parse(e.data)
if (response.request.action == 'currencies') {
cards.getCurrencies(response.body)
}
if (response.request.action == 'currency.values.latest') {
cards.getValues(response.body)
cards.buildCards()
}
},
getCurrencies: function(data) {
let promises = []
$.each(data.currencies, (i, el) => {
this.data[el.id] = {'currency': el, 'value': null}
socket.sendMessage('currency.values.latest', {currency_id: el.id})
})
},
getValue: function(currency_id) {
let url = '{{$urls->api}}/currency/' + currency_id + '/values/latest'
return $.getJSON(url, (data) => {
if (data.value == null) {
this.data = this.data.filter(function(item) {
return item.currency.id != data.currency.id
})
return
getMaxIdx: function() {
keys = Object.keys(this.data)
max = 0
$.each(keys, (i, el) => {
if (max < parseInt(el)) {
max = parseInt(el)
}
idx = this.data.findIndex((item, i, arr) => item.currency.id == data.currency.id)
if (idx < 0) {
return
}
this.data[idx].value = data.value
}).fail(() => {
this.data = this.data.filter(function(item) {
return item.currency.id == currency_id
})
})
return max
},
getValues: function(data) {
if (data.value == null) {
this.data = this.data.filter(function(item) {
return item.currency.id != data.currency.id
})
return
}
idx = this.data.findIndex((item, i, arr) => {
if (typeof item == 'undefined') {
return false
}
return item.currency.id == data.currency.id
})
if (idx < 0) {
return
}
this.data[idx].value = data.value
},
buildCards: function() {
$(this.id).html('')
$.each(this.data, (i, el) => {
if (typeof el == 'undefined') {
return
}
if (el.value == null) {
return
}
if (el.currency == null) {
return
}
$(this.id).append(
this.buildCard(el)
)
if (i == this.getMaxIdx()) {
socket.conn.close()
}
})
},
buildCard: function(currency) {

View File

@ -26,7 +26,6 @@ $files = [
'settings',
'setups'
];
foreach ($files as $file) {
foreach ($folders as $folder) {
$filename = implode(DIRECTORY_SEPARATOR, [

View File

@ -32,7 +32,7 @@ return [
return (object) $arr;
}),
'urls' => function(Container $c) {
$arr = ['base' => ($c->has('base_url')) ? $c->get('base_url') : ''];
$arr = ['base' => ($c->has('base_url')) ? $c->get('base_url') : '/'];
$arr['assets'] = implode('/', [
$arr['base'],
'assets'
@ -50,6 +50,7 @@ return [
'images'
]);
$arr['api'] = 'http://localhost:8081';
$arr['ws'] = 'ws://localhost:8020';
return (object) $arr;
},
'format' => function(Container $c) {

View File

@ -0,0 +1,94 @@
<?php
namespace ProVM\Money\Common\Listener;
use ProVM\Common\Define\Event\Request;
use ProVM\Common\Define\Event\Response;
use ProVM\Common\Factory\Model as ModelFactory;
use ProVM\Money\Currency;
class Currencies {
public function __invoke(Request $request, Response $response, ModelFactory $factory): Response {
$currencies = $factory->find(Currency::class)->many();
array_walk($currencies, function(&$item) {
$item = $item->asArray();
});
$response->getBody()->write(compact('currencies'));
return $response;
}
public function get(Request $request, Response $response, ModelFactory $factory): Response {
$currency_id = $request->getBody()->read()['currency_id'];
$currency = $factory->find(Currency::class)->one($currency_id);
$response->getBody()->write(['currency' => $currency->asArray()]);
return $response;
}
public function latest(Request $request, Response $response, ModelFactory $factory): Response {
$currency_id = $request->getBody()->read()['currency_id'];
$currency = $factory->find(Currency::class)->one($currency_id);
$output = [
'currency' => null,
'value' => null
];
if ($currency) {
$output['currency'] = $currency->asArray();
if ($currency->latest()) {
$output['value'] = $currency->latest()->asArray();
}
}
$response->getBody()->write($output);
return $response;
}
public function getAliases(Request $request, Response $response, ModelFactory $factory): Response {
$currency_id = $request->getBody()->read()['currency_id'];
$currency = $factory->find(Currency::class)->one($currency_id);
$output = [
'currency' => null,
'aliases' => []
];
if ($currency) {
$output['currency'] = $currency->asArray();
if ($currency->aliases()) {
$output['aliases'] = array_map(function($item) {
return $item->asArray();
}, $currency->aliases());
}
}
$response->getBody()->write($output);
return $response;
}
public function getSources(Request $request, Response $response, ModelFactory $factory): Response {
$currency_id = $request->getBody()->read()['currency_id'];
$currency = $factory->find(Currency::class)->one($currency_id);
$output = [
'currency' => null,
'sources' => []
];
if ($currency) {
$output['currency'] = $currency->asArray();
if ($currency->sources()) {
$output['sources'] = array_map(function($item) {
return $item->asArray();
}, $currency->sources());
}
}
$response->getBody()->write($output);
return $response;
}
public function getValues(Request $request, Response $response, ModelFactory $factory): Response {
$currency_id = $request->getBody()->read()['currency_id'];
$currency = $factory->find(Currency::class)->one($currency_id);
$output = [
'currency' => null,
'values' => []
];
if ($currency) {
$output['currency'] = $currency->asArray();
if ($currency->values()) {
$output['values'] = array_map(function($item) {
return $item->asArray();
}, $currency->values());
}
}
$response->getBody()->write($output);
return $response;
}
}

43
ws/composer.json Normal file
View File

@ -0,0 +1,43 @@
{
"name": "provm/money-ws",
"description": "Websocket para la aplicacion web para revisar los valores de distintas monedas",
"type": "project",
"require": {
"php-di/php-di": "^6.3",
"provm/models": "dev-master",
"vlucas/phpdotenv": "^5.3",
"nesbot/carbon": "^2.46",
"provm/events": "dev-master"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"kint-php/kint": "^3.3"
},
"license": "MIT",
"authors": [
{
"name": "Aldarien",
"email": "aldarien85@gmail.com"
}
],
"autoload": {
"psr-4": {
"ProVM\\Money\\Common\\": "common",
"ProVM\\Common\\": "../provm/common",
"ProVM\\Money\\": "../src"
}
},
"repositories": [
{
"type": "git",
"url": "http://git.provm.cl/ProVM/models.git"
},
{
"type": "git",
"url": "http://git.provm.cl/ProVM/events.git"
}
],
"config": {
"secure-http": false
}
}

8
ws/docker/PHP.Dockerfile Normal file
View File

@ -0,0 +1,8 @@
FROM php:7.4-fpm
RUN docker-php-ext-install pdo pdo_mysql
RUN pecl install xdebug-3.0.3 \
&& docker-php-ext-enable xdebug
CMD ["php", "/code/ws/public/index.php"]

16
ws/docker/nginx.conf Normal file
View File

@ -0,0 +1,16 @@
upstream websocket {
server ws-php:9010;
}
server {
listen 80;
location / {
proxy_pass http://websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 86400;
}
}

7
ws/public/index.php Normal file
View File

@ -0,0 +1,7 @@
<?php
include_once implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__),
'setup',
'app.php'
]);
$app->run();

View File

@ -0,0 +1,8 @@
<?php
$files = new DirectoryIterator(implode(DIRECTORY_SEPARATOR, [__DIR__, 'ws']));
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
include_once $file->getRealPath();
}

View File

@ -0,0 +1,10 @@
<?php
use ProVM\Money\Common\Listener\Currencies;
$controller = new Currencies();
$app->add('currencies', $controller);
$app->add('currency', [$controller, 'get']);
$app->add('currency.aliases', [$controller, 'getAliases']);
$app->add('currency.values.latest', [$controller, 'latest']);
$app->add('currency.sources', [$controller, 'getSources']);
$app->add('currency.values', [$controller, 'getValues']);

45
ws/setup/app.php Normal file
View File

@ -0,0 +1,45 @@
<?php
use DI\ContainerBuilder as Builder;
include_once 'composer.php';
$builder = new Builder();
$folders = [
implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__, 2),
'setup',
'env'
]),
implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__, 2),
'setup',
'common'
]),
implode(DIRECTORY_SEPARATOR, [
__DIR__,
'ws'
])
];
$files = [
'settings',
'setups'
];
foreach ($files as $file) {
foreach ($folders as $folder) {
$filename = implode(DIRECTORY_SEPARATOR, [
$folder,
$file . '.php'
]);
if (!file_exists($filename)) {
continue;
}
$builder->addDefinitions($filename);
}
}
$container = $builder->build();
$app = $container->get(Ratchet\Server\IoServer::class);
include_once 'databases.php';
include_once 'router.php';

6
ws/setup/composer.php Normal file
View File

@ -0,0 +1,6 @@
<?php
include_once implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__),
'vendor',
'autoload.php'
]);

36
ws/setup/databases.php Normal file
View File

@ -0,0 +1,36 @@
<?php
$databases = $app->getContainer()->get('databases');
foreach ($databases as $name => $settings) {
switch($settings->system) {
case 'mysql':
$dsn = implode(':', [
'mysql',
implode(';', [
implode('=', [
'host',
$settings->host->name
]),
implode('=', [
'dbname',
$settings->name
])
])
]);
if (isset($settings->host->port)) {
$dsn .= ';' . implode('=', [
'port',
$settings->host->port
]);
}
break;
}
ORM::configure($dsn, null, $name);
switch ($settings->system) {
case 'mysql':
ORM::configure('username', $settings->user->name, $name);
ORM::configure('password', $settings->user->password, $name);
}
}
if (isset($databases->short_names)) {
Model::$short_table_names = $databases->short_names;
}

5
ws/setup/router.php Normal file
View File

@ -0,0 +1,5 @@
<?php
include_once implode(DIRECTORY_SEPARATOR, [
$app->getContainer()->get('locations')->routes,
'ws.php'
]);

19
ws/setup/ws/settings.php Normal file
View File

@ -0,0 +1,19 @@
<?php
use Psr\Container\ContainerInterface as Container;
return [
'locations' => DI\decorate(function($prev, Container $c) {
$arr = (array) $prev;
$arr['base'] = dirname(__DIR__, 2);
$arr['resources'] = implode(DIRECTORY_SEPARATOR, [
$arr['base'],
'resources'
]);
$arr['routes'] = implode(DIRECTORY_SEPARATOR, [
$arr['resources'],
'routes'
]);
return (object) $arr;
}),
'port' => '9010'
];

36
ws/setup/ws/setups.php Normal file
View File

@ -0,0 +1,36 @@
<?php
use Psr\Container\ContainerInterface as Container;
return [
'storage' => function(Container $c) {
return new \SplObjectStorage();
},
ProVM\Common\Factory\Event\Request::class => function(Container $c) {
return new ProVM\Common\Factory\Event\Request();
},
ProVM\Common\Factory\Event\Response::class => function(Container $c) {
return new ProVM\Common\Factory\Event\Response();
},
ProVM\Common\Factory\Event\Listener::class => function(Container $c) {
return new ProVM\Common\Factory\Event\Listener($c);
},
Psr\EventDispatcher\EventDispatcherInterface::class => function(Container $c) {
return new ProVM\Common\Service\Event\Dispatcher($c);
},
Ratchet\MessageComponentInterface::class => function(Container $c) {
return (new ProVM\Common\Alias\Event\Message($c->get('storage')))
->setDispatcher($c->get(Psr\EventDispatcher\EventDispatcherInterface::class))
->setRequestBuilder($c->get(ProVM\Common\Factory\Event\Request::class));
},
Ratchet\WebSocket\WsServer::class => function(Container $c) {
return new Ratchet\WebSocket\WsServer($c->get(Ratchet\MessageComponentInterface::class));
},
Ratchet\Http\HttpServer::class => function(Container $c) {
return new Ratchet\Http\HttpServer($c->get(Ratchet\WebSocket\WsServer::class));
},
Ratchet\Server\IoServer::class => function(Container $c) {
$app = ProVM\Common\Alias\Server\App::factory($c->get(Ratchet\Http\HttpServer::class), $c->get('port'));
$app->setContainer($c);
return $app;
}
];