Skip to content

Commit

Permalink
0.7.1
Browse files Browse the repository at this point in the history
- переходим на новую версию библиотеки Auth
- view_region теперь использует библиотеку `DataCollection()` для удобной работы с json-контентом
- для view_region добавлена ширина первой ячейки, зависящей от режима просмотра
- изменено представление информации об истории региона
- экспорт, импорт и круговая диаграмма комбинируются по-разному в зависимости от режима отображения.
- теперь ширина первой ячейки для всех строк фиксирована
  • Loading branch information
Karel Wintersky committed Jul 17, 2024
1 parent 8fbc279 commit a032b7e
Show file tree
Hide file tree
Showing 10 changed files with 561 additions and 174 deletions.
8 changes: 4 additions & 4 deletions admin.tools/auth.register.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<?php

use Arris\DelightAuth\Auth\Auth;
use Arris\DelightAuth\Auth\InvalidEmailException;
use Arris\DelightAuth\Auth\InvalidPasswordException;
use Arris\DelightAuth\Auth\TooManyRequestsException;
use Arris\DelightAuth\Auth\UserAlreadyExistsException;
use Arris\DelightAuth\Auth\Exceptions\InvalidEmailException;
use Arris\DelightAuth\Auth\Exceptions\InvalidPasswordException;
use Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException;
use Arris\DelightAuth\Auth\Exceptions\UserAlreadyExistsException;
use Dotenv\Dotenv;

define("__ROOT__", dirname(__DIR__));
Expand Down
20 changes: 10 additions & 10 deletions engine/Controllers/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@

use Arris\AppLogger;
use Arris\AppRouter;
use Arris\DelightAuth\Auth\AttemptCancelledException;
use Arris\DelightAuth\Auth\AuthError;
use Arris\DelightAuth\Auth\EmailNotVerifiedException;
use Arris\DelightAuth\Auth\InvalidEmailException;
use Arris\DelightAuth\Auth\InvalidPasswordException;
use Arris\DelightAuth\Auth\TooManyRequestsException;
use Arris\DelightAuth\Auth\Exceptions\AttemptCancelledException;
use Arris\DelightAuth\Auth\Exceptions\AuthError;
use Arris\DelightAuth\Auth\Exceptions\EmailNotVerifiedException;
use Arris\DelightAuth\Auth\Exceptions\InvalidEmailException;
use Arris\DelightAuth\Auth\Exceptions\InvalidPasswordException;
use Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException;
use Confmap\App;
use Confmap\Exceptions\AccessDeniedException;
use Psr\Log\LoggerInterface;
Expand All @@ -29,7 +29,7 @@ public function __construct($options = [], LoggerInterface $logger = null)
*
* @return void
*/
public function view_form_login()
public function view_form_login(): void
{
$this->template->setTemplate("auth/login.tpl");
}
Expand All @@ -39,7 +39,7 @@ public function view_form_login()
*
* @return void
*/
public function callback_login()
public function callback_login(): void
{
$expire = _env( 'AUTH.EXPIRE_TIME', 86400, 'int');

Expand Down Expand Up @@ -77,10 +77,10 @@ public function callback_login()
* @return void
* @throws AuthError
*/
public function callback_logout()
public function callback_logout(): void
{
if (!App::$acl->isLoggedIn()) {
die('Hacking attempt!'); //@todo: logging
die('Hacking attempt!');
}

$u_id = App::$acl->auth->getUserId();
Expand Down
17 changes: 8 additions & 9 deletions engine/Controllers/JSController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
use Confmap\App;
use Confmap\Units\Map;
use LiveMapEngine\Helpers;
use LiveMapEngine\MapMakerInterface;
use LiveMapEngine\MapMaker;
use LiveMapEngine\Map\MapMaker;
use LiveMapEngine\Map\MapMakerInterface;
use LiveMapEngine\SVGParser;
use Psr\Log\LoggerInterface;
use RuntimeException;
Expand All @@ -36,7 +36,7 @@ public function __construct($options = [], LoggerInterface $logger = null)
*
* @todo: перенести в framework, как и шаблон к нему
*/
public function view_js_map_definition()
public function view_js_map_definition(): void
{
$map_id = App::$id_map;

Expand Down Expand Up @@ -426,13 +426,17 @@ public function view_js_map_definition()
$this->template->setRenderType(Template::CONTENT_TYPE_JS);
}

/**
* Тестовый метод. Планирую функционал переноса генерации JS-файла во фреймворк
*
* @throws \SmartyException
*/
public function test()
{
// нам нужно отдать во фреймворк инстанс шаблонизатора, а получить - срендеренный текст.
// инстанс класса Template может не поддерживать chaining

$t = new Template();

$t
->setTemplateDir( '' /* путь к файлам фреймворка */)
->setCompileDir( '/dev/shm/')
Expand All @@ -441,12 +445,7 @@ public function test()
->setTemplate( '', /* путь к файлу шаблона */);
$t->assign("data", []);

// как вариант,


$t->setRenderType(Template::CONTENT_TYPE_JS);


}

}
16 changes: 12 additions & 4 deletions engine/Controllers/MapsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,26 @@
use Confmap\AbstractClass;
use Confmap\App;
use Confmap\Units\Map;
use LiveMapEngine\MapMaker;
use LiveMapEngine\Map\MapMaker;
use Psr\Log\LoggerInterface;

class MapsController extends AbstractClass
{
public MapMaker $map;

/**
* @param $options
* @param LoggerInterface|null $logger
*/
public function __construct($options = [], LoggerInterface $logger = null)
{
parent::__construct($options, $logger);
}

public function view_map_fullscreen()
/**
* @return void
*/
public function view_map_fullscreen(): void
{
$map_id = App::$id_map;

Expand All @@ -27,8 +34,9 @@ public function view_map_fullscreen()
'path_config' => Path::create( config('path.storage') )->join($map_id),
'json_parser' => [Map::class, 'parseJSONFile']
]);
// добавить метод addParser() ?
//@todo: вообще, загружаемый конфиг можно было бы кэшировать, храня дату обновления файла и данные.
// Вообще, загружаемый конфиг можно было бы кэшировать, храня дату обновления файла и данные.
// Проверять дату файла, если она не соответствует закешированной - загружать с диска.
// НО: это привязка к редису, нужно предусмотреть fallback + операция загрузки карты нетяжелая

Expand All @@ -44,7 +52,7 @@ public function view_map_fullscreen()
$custom_css_paths = [];
foreach ($this->map->getConfig("display->custom_css", []) as $file) {
$fn
= (new Path( $this->map->path_storage))
= (new Path($this->map->path_storage))
->join($this->map_alias)
->join('styles')
->join($file)
Expand Down
37 changes: 19 additions & 18 deletions engine/Controllers/RegionsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
use Confmap\App;
use Confmap\Exceptions\AccessDeniedException;
use Confmap\Units\Map;
use LiveMapEngine\MapMaker;
use LiveMapEngine\DataCollection;
use LiveMapEngine\Map\MapMaker;
use Psr\Log\LoggerInterface;

class RegionsController extends AbstractClass
Expand Down Expand Up @@ -41,9 +42,9 @@ public function __construct($options = [], LoggerInterface $logger = null)
* @throws \JsonException
* @throws \SmartyException
*/
public function view_region_info()
public function view_region_info(): void
{
$id_region = $_GET['id'] ?? null;
$id_region = $_GET['id'] ?? null;

if ($this->map->loadConfig()->is_error) {
throw new \RuntimeException($this->map->state->getMessage());
Expand All @@ -56,10 +57,7 @@ public function view_region_info()
->setTemplateDir( config('smarty.path.template'))
->setCompileDir( config('smarty.path.cache'))
->setForceCompile( config('smarty.force_compile'))
// ->registerPlugin(Template::PLUGIN_MODIFIER, 'json_decode', 'json_decode', false)
// ->registerPlugin(Template::PLUGIN_MODIFIER, 'json_encode', 'json_encode', false)
->registerPlugin(Template::PLUGIN_MODIFIER, 'dd', 'dd', false)
// ->registerPlugin(Template::PLUGIN_MODIFIER, 'implode', 'implode', false)
->registerClass("Arris\AppRouter", "Arris\AppRouter");

$t->assign('is_present', $region_data['is_present']);
Expand All @@ -70,18 +68,21 @@ public function view_region_info()
$t->assign('is_can_edit', $region_data['can_edit']);
$t->assign('edit_button_url', AppRouter::getRouter('update.region.info'));

$json = $region_data['content_json'] ?? '{}';
$t->assign("view_mode", $this->map->getConfig('display->viewmode')); // тип просмотра для шаблона

$content_json = $region_data['content_json'] ?? '{}';

/*
Для упрощения построения круговой диаграммы долей экономики часть расчетов сделаем здесь.
*/
$m = new \Confmap\Units\Map(); //@todo: по-хорошему, нужен класс Collection или как-то типа Data. Или взять с packagist?
$m->parseJSON($json);

$pcd_natural = (int)$m->getData("economy->shares->natural", 0);
$pcd_financial = (int)$m->getData("economy->shares->financial", 0);
$pcd_industrial = (int)$m->getData("economy->shares->industrial", 0);
$pcd_social = (int)$m->getData("economy->shares->social", 0);
$json = new DataCollection($content_json);
$json->setSeparator('->');
$json->parse();

$pcd_natural = (int)$json->getData("economy->shares->natural", 0);
$pcd_financial = (int)$json->getData("economy->shares->financial", 0);
$pcd_industrial = (int)$json->getData("economy->shares->industrial", 0);
$pcd_social = (int)$json->getData("economy->shares->social", 0);
$pcd_sum = $pcd_natural + $pcd_financial + $pcd_industrial + $pcd_social;

$pie_chart_data = [];
Expand Down Expand Up @@ -114,23 +115,23 @@ public function view_region_info()
}

// форматируем население (численность, не население!)
$population = $m->getData('population->count', 0);
$population = (int)$json->getData('population->count', 0);
$population
= $population >= 1
? number_format($population, 0, '.', ' ')
: number_format($population, 3, '.', ' ');
$m->setData('population->count', $population);
$json->setData('population->count', $population);

// круговая диаграмма
$t->assign("pie_chart", [
'present' => $pcd_sum > 0,
'full' => json_encode($pie_chart_data, JSON_UNESCAPED_UNICODE)
]);
// закончили с данными для круговой диаграммы
// только нужно отдать не $json, а исправленные и модифицированные данные

$t->assign('json', $json->getData());

// только нужно отдать не $json, а исправленные и модифицированные данные
$t->assign('json', $m->getData()); // а тут getData - уже JSON
// $t->assign('json', json_decode($json)); // вот тут делали json_decode потому что надо в шаблон отдать JSON из строки
//@TODO: ВАЖНО, В ШАБЛОНЕ ХОДИМ ТАК: {$json->economy->type}, А НЕ ЧЕРЕЗ ТОЧКУ!!!!

Expand Down
Loading

0 comments on commit a032b7e

Please sign in to comment.