Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SV-34/SV-36 updated Logger page #200

Merged
merged 31 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
52406cd
[SV-34] updated Logger page
MarijusCoding Sep 30, 2024
9dd4370
[SV-34] update name
MarijusCoding Sep 30, 2024
f87c447
[SV-34] added VersionUtility
MarijusCoding Oct 1, 2024
86ac36a
[SV-34] added Logger class
MarijusCoding Oct 1, 2024
64f9dd0
Merge branch 'SV-27/logger-inferface' of github.com:Invertus/saferpay…
MarijusCoding Oct 1, 2024
5234917
[SV-34] added LogFormatter and sql query for parsing logs
MarijusCoding Oct 1, 2024
f92b38e
[SV-34] added severity show
MarijusCoding Oct 1, 2024
726345a
[SV-34] fixed logs controller
MarijusCoding Oct 1, 2024
478b63f
[SV-34] added function to context adapter
MarijusCoding Oct 1, 2024
3304b4a
[SV-34] fix
MarijusCoding Oct 1, 2024
d45adb6
[SV-34] added dependencies
MarijusCoding Oct 1, 2024
ca27963
[SV-34] removed return types
MarijusCoding Oct 1, 2024
6204393
[SV-34] added licences
MarijusCoding Oct 1, 2024
8cc8767
[SV-34] minor changes
MarijusCoding Oct 1, 2024
8604a80
[SV-34] fix
MarijusCoding Oct 1, 2024
8604eae
[SV-34] minor
MarijusCoding Oct 1, 2024
8d62c30
[SV-34] added CSS
MarijusCoding Oct 1, 2024
9965357
[SV-34] removed useless code
MarijusCoding Oct 1, 2024
88c14d8
[SV-34] removed Services as interface
MarijusCoding Oct 1, 2024
95b628f
Merge branch 'SV-27/logger-inferface' of github.com:Invertus/saferpay…
MarijusCoding Oct 2, 2024
0bcee4b
[SV-34] added entity items and shown log
MarijusCoding Oct 2, 2024
bb52eb9
[SV-34] fixed GlobalShopContext
MarijusCoding Oct 2, 2024
ff085ae
[SV-34] added custom export
MarijusCoding Oct 2, 2024
0ff5d0d
[SV-34] removed types
MarijusCoding Oct 2, 2024
db181fd
[SV-34] whitespaces
MarijusCoding Oct 2, 2024
c016a04
[SV-34] types, klarna
MarijusCoding Oct 3, 2024
f7584af
[SV-34] types
MarijusCoding Oct 3, 2024
4bad4f2
[SV-34] types
MarijusCoding Oct 3, 2024
fe8c910
[SV-34] types
MarijusCoding Oct 3, 2024
ac197de
[SV-34] fix
MarijusCoding Oct 3, 2024
d526b75
csfixer
MarijusCoding Oct 3, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
344 changes: 327 additions & 17 deletions controllers/admin/AdminSaferPayOfficialLogsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,50 +21,115 @@
*@license SIX Payment Services
*/

use Invertus\SaferPay\Config\SaferPayConfig;
use Invertus\SaferPay\Controller\AbstractAdminSaferPayController;
use Invertus\SaferPay\Enum\PermissionType;
use Invertus\SaferPay\Logger\Formatter\LogFormatter;
use Invertus\SaferPay\Utility\VersionUtility;
use Invertus\SaferPay\Logger\Logger;

if (!defined('_PS_VERSION_')) {
exit;
}

class AdminSaferPayOfficialLogsController extends ModuleAdminController
class AdminSaferPayOfficialLogsController extends AbstractAdminSaferPayController
{
const FILE_NAME = 'AdminSaferPayOfficialLogsController';

const LOG_INFORMATION_TYPE_REQUEST = 'request';

const LOG_INFORMATION_TYPE_RESPONSE = 'response';

const LOG_INFORMATION_TYPE_CONTEXT = 'context';

public function __construct()
{
parent::__construct();
$this->className = SaferPayLog::class;
$this->table = SaferPayLog::$definition['table'];
$this->table = 'log';
$this->className = 'PrestaShopLogger';
$this->bootstrap = true;
$this->list_no_link = true;
$this->lang = false;
$this->noLink = true;
$this->allow_export = true;

parent::__construct();

$this->toolbar_btn = [];

$this->initList();

$this->_select .= '
REPLACE(a.`message`, "' . LogFormatter::SAFERPAY_LOG_PREFIX . '", "") as message,
spl.request, spl.response, spl.context
';

$shopIdCheck = '';

if (VersionUtility::isPsVersionGreaterOrEqualTo('1.7.8.0')) {
$shopIdCheck = ' AND spl.id_shop = a.id_shop';
}

$this->_join .= ' JOIN ' . _DB_PREFIX_ . SaferPayLog::$definition['table'] . ' spl ON (spl.id_log = a.id_log' . $shopIdCheck . ' AND a.object_type = "' . pSQL(Logger::LOG_OBJECT_TYPE) . '")';
$this->_use_found_rows = false;
$this->list_no_link = true;
}

public function initContent()
{
if ($this->module instanceof SaferPayOfficial) {
$this->content .= $this->module->displayNavigationTop();
}

$this->content .= $this->displaySeverityInformation();

parent::initContent();
}

public function initList()
{
$this->fields_list = [
'id_saferpay_log' => [
'title' => $this->l('ID'),
'align' => 'center',
'id_log' => [
'title' => $this->module->l('ID', self::FILE_NAME),
'align' => 'text-center',
'class' => 'fixed-width-xs',
],
'severity' => [
'title' => $this->module->l('Severity (1-4)', self::FILE_NAME),
'align' => 'text-center',
'class' => 'fixed-width-xs',
'callback' => 'printSeverityLevel',
],
'request' => [
'title' => $this->module->l('Request', self::FILE_NAME),
'align' => 'text-center',
'callback' => 'printRequestButton',
'orderby' => false,
'search' => false,
'remove_onclick' => true,
],
'payload' => [
'title' => $this->l('Payload'),
'align' => 'center',
'class' => 'saferpay-text-break',
'response' => [
'title' => $this->module->l('Response', self::FILE_NAME),
'align' => 'text-center',
'callback' => 'printResponseButton',
'orderby' => false,
'search' => false,
'remove_onclick' => true,
],
'message' => [
'align' => 'center',
'title' => $this->l('Message'),
'class' => 'saferpay-text-break',
'title' => $this->module->l('Message', self::FILE_NAME),
],
'context' => [
'title' => $this->module->l('Context', self::FILE_NAME),
'align' => 'text-center',
'callback' => 'printContextButton',
'orderby' => false,
'search' => false,
'remove_onclick' => true,
],
'date_add' => [
'title' => $this->l('Date'),
'title' => $this->module->l('Date', self::FILE_NAME),
'align' => 'right',
'type' => 'datetime',
'filter_key' => 'a!date_add',
],
];

Expand All @@ -77,12 +142,257 @@ public function initList()
public function renderList()
{
unset($this->toolbar_btn['new']);

return parent::renderList();
}

public function setMedia($isNewTheme = false)
{
$this->addCSS("{$this->module->getPathUri()}views/css/admin/logs_tab.css");
parent::setMedia($isNewTheme);

$context = $this->module->getService(\Invertus\SaferPay\Adapter\LegacyContext::class);

Media::addJsDef([
'saferpayofficial' => [
'logsUrl' => $context->getAdminLink(SaferPayOfficial::ADMIN_LOGS_CONTROLLER),
],
]);

$this->addCSS("{$this->module->getPathUri()}views/css/admin/logs_tab.css");
$this->addJS($this->module->getPathUri() . 'views/js/admin/log.js', false);
}

public function displaySeverityInformation()
{
return $this->context->smarty->fetch(
"{$this->module->getLocalPath()}views/templates/admin/logs/severity_levels.tpl"
);
}

public function printSeverityLevel($level)
{
$this->context->smarty->assign([
'log_severity_level' => $level,
'log_severity_level_informative' => defined('\PrestaShopLogger::LOG_SEVERITY_LEVEL_INFORMATIVE') ?
PrestaShopLogger::LOG_SEVERITY_LEVEL_INFORMATIVE :
SaferPayConfig::LOG_SEVERITY_LEVEL_INFORMATIVE,
'log_severity_level_warning' => defined('\PrestaShopLogger::LOG_SEVERITY_LEVEL_WARNING') ?
PrestaShopLogger::LOG_SEVERITY_LEVEL_WARNING :
SaferPayConfig::LOG_SEVERITY_LEVEL_WARNING,
'log_severity_level_error' => defined('\PrestaShopLogger::LOG_SEVERITY_LEVEL_ERROR') ?
PrestaShopLogger::LOG_SEVERITY_LEVEL_ERROR :
SaferPayConfig::LOG_SEVERITY_LEVEL_ERROR,
'log_severity_level_major' => defined('\PrestaShopLogger::LOG_SEVERITY_LEVEL_MAJOR') ?
PrestaShopLogger::LOG_SEVERITY_LEVEL_MAJOR :
SaferPayConfig::LOG_SEVERITY_LEVEL_MAJOR,
]);

return $this->context->smarty->fetch(
"{$this->module->getLocalPath()}views/templates/admin/logs/severity_level_column.tpl"
);
}

public function getDisplayButton($logId, $data, $logInformationType)
{
$unserializedData = json_decode($data);

if (empty($unserializedData)) {
return '--';
}

$this->context->smarty->assign([
'log_id' => $logId,
'log_information_type' => $logInformationType,
]);

return $this->context->smarty->fetch(
"{$this->module->getLocalPath()}views/templates/admin/logs/log_modal.tpl"
);
}

/**
* @param string $request
* @param array $data
*
* @return false|string
*
* @throws SmartyException
*/
public function printRequestButton($request, $data)
{
return $this->getDisplayButton($data['id_log'], $request, self::LOG_INFORMATION_TYPE_REQUEST);
}

public function printResponseButton($response, $data)
{
return $this->getDisplayButton($data['id_log'], $response, self::LOG_INFORMATION_TYPE_RESPONSE);
}

public function printContextButton($context, $data)
{
return $this->getDisplayButton($data['id_log'], $context, self::LOG_INFORMATION_TYPE_CONTEXT);
}

public function displayAjaxGetLog()
{
if (!$this->ensureHasPermissions([PermissionType::EDIT, PermissionType::VIEW], true)) {
return;
}

/** @var \Invertus\SaferPay\Adapter\Tools $tools */
$tools = $this->module->getService(\Invertus\SaferPay\Adapter\Tools::class);

/** @var \Invertus\SaferPay\Repository\SaferPayLogRepository $logRepository */
$logRepository = $this->module->getService(\Invertus\SaferPay\Repository\SaferPayLogRepository::class);

/** @var \Invertus\SaferPay\Context\GlobalShopContext $shopContext */
$globalShopContext = $this->module->getService(\Invertus\SaferPay\Context\GlobalShopContext::class);

$logId = $tools->getValueAsInt('log_id');

// /** @var LoggerInterface $logger */
// $logger = $this->module->getService(LoggerInterface::class);

try {
/** @var \SaferPayLog|null $log */
$log = $logRepository->findOneBy([
'id_log' => $logId,
'id_shop' => $globalShopContext->getShopId(),
]);
} catch (Exception $exception) {
// $logger->error('Failed to find log', [
// 'context' => [
// 'id_log' => $logId,
// 'id_shop' => $globalShopContext->getShopId(),
// ],
// 'exceptions' => ExceptionUtility::getExceptions($exception),
// ]);

$this->ajaxResponse(json_encode([
'error' => true,
'message' => $this->module->l('Failed to find log.', self::FILE_NAME),
]));
}

if (!isset($log)) {
// $logger->error('No log information found.', [
// 'context' => [
// 'id_log' => $logId,
// 'id_shop' => $globalShopContext->getShopId(),
// ],
// 'exceptions' => [],
// ]);

$this->ajaxRender(json_encode([
'error' => true,
'message' => $this->module->l('No log information found.', self::FILE_NAME),
]));
}

$this->ajaxResponse(json_encode([
'error' => false,
'log' => [
self::LOG_INFORMATION_TYPE_REQUEST => $log->request,
self::LOG_INFORMATION_TYPE_RESPONSE => $log->response,
self::LOG_INFORMATION_TYPE_CONTEXT => $log->context,
],
]));
}

public function processExport($textDelimiter = '"')
{
// clean buffer
if (ob_get_level() && ob_get_length() > 0) {
ob_clean();
}

header('Content-type: text/csv');
header('Content-Type: application/force-download; charset=UTF-8');
header('Cache-Control: no-store, no-cache');
header('Content-disposition: attachment; filename="' . $this->table . '_' . date('Y-m-d_His') . '.csv"');

$fd = fopen('php://output', 'wb');

/** @var Configuration $configuration */
$configuration = $this->module->getService(Configuration::class);

/** @var \Invertus\SaferPay\Adapter\LegacyContext $context */
$context = $this->module->getService(\Invertus\SaferPay\Adapter\LegacyContext::class);

$storeInfo = [
'PrestaShop Version' => _PS_VERSION_,
'PHP Version' => phpversion(),
'Module Version' => $this->module->version,
'MySQL Version' => \Db::getInstance()->getVersion(),
'Shop URL' => $context->getShopDomain(),
'Shop Name' => $context->getShopName(),
];

$moduleConfigurations = [
'Test mode' => SaferPayConfig::isTestMode() ? 'Yes' : 'No',
];

$psSettings = [
'Default country' => $configuration->get('PS_COUNTRY_DEFAULT'),
'Default currency' => $configuration->get('PS_CURRENCY_DEFAULT'),
'Default language' => $configuration->get('PS_LANG_DEFAULT'),
'Round mode' => $configuration->get('PS_PRICE_ROUND_MODE'),
'Round type' => $configuration->get('PS_ROUND_TYPE'),
'Current theme name' => $context->getShopThemeName(),
'PHP memory limit' => ini_get('memory_limit'),
];

$moduleConfigurationsInfo = "**Module configurations:**\n";
foreach ($moduleConfigurations as $key => $value) {
$moduleConfigurationsInfo .= "- $key: $value\n";
}

$psSettingsInfo = "**Prestashop settings:**\n";
foreach ($psSettings as $key => $value) {
$psSettingsInfo .= "- $key: $value\n";
}

fputcsv($fd, array_keys($storeInfo), ';', $textDelimiter);
fputcsv($fd, $storeInfo, ';', $textDelimiter);
fputcsv($fd, [], ';', $textDelimiter);

fputcsv($fd, [$moduleConfigurationsInfo], ';', $textDelimiter);
fputcsv($fd, [$psSettingsInfo], ';', $textDelimiter);

$query = new \DbQuery();

$query
->select('spl.id_log, l.severity, l.message, spl.request, spl.response, spl.context, spl.date_add')
->from('saferpay_log', 'spl')
->leftJoin('log', 'l', 'spl.id_log = l.id_log')
->orderBy('spl.id_log DESC')
->limit(1000);

$result = \Db::getInstance()->executeS($query);

$firstRow = $result[0];
$headers = [];

foreach ($firstRow as $key => $value) {
$headers[] = strtoupper($key);
}

$fd = fopen('php://output', 'wb');

fputcsv($fd, $headers, ';', $textDelimiter);

$content = !empty($result) ? $result : [];

foreach ($content as $row) {
$rowValues = [];
foreach ($row as $key => $value) {
$rowValues[] = $value;
}

fputcsv($fd, $rowValues, ';', $textDelimiter);
}

@fclose($fd);
die;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ private function displayConfigurationSettings()
'title' => $this->module->l('Description', self::FILE_NAME),
'type' => 'text',
'desc' => 'This description is visible in payment page also in payment confirmation email',
'class' => 'fixed-width-xxl'
'class' => 'fixed-width-xxl',
],
SaferPayConfig::SAFERPAY_DEBUG_MODE => [
'title' => $this->module->l('Debug mode', self::FILE_NAME),
Expand Down
Loading
Loading