This commit is contained in:
2025-08-16 20:28:55 +03:00
parent 79c82c5109
commit 51a8255dbe
13 changed files with 265 additions and 151 deletions

View File

@@ -1,6 +1,9 @@
<?php
use Bastion\ApplicationFactory;
use Openguru\OpenCartFramework\Logger\OpenCartLogAdapter;
use Openguru\OpenCartFramework\OpenCart\Decorators\OcRegistryDecorator;
use Openguru\OpenCartFramework\OpenCart\OcConfigDecorator;
$sysLibPath = rtrim(DIR_SYSTEM, '/') . '/library/oc_telegram_shop';
$basePath = rtrim(DIR_APPLICATION, '/') . '/..';
@@ -191,7 +194,12 @@ class ControllerExtensionModuleTgshop extends Controller
],
]);
$app->bootAndHandleRequest();
$app->bind(OcRegistryDecorator::class, fn () => new OcRegistryDecorator($this->registry));
$app
->withLogger(fn () => new OpenCartLogAdapter($this->log, 'TeleCartAdmin'))
->bootAndHandleRequest();
}
protected function validate(): bool

View File

@@ -146,61 +146,71 @@
{# ChatID #}
{% elseif item['type'] == 'chatid' %}
<div class="input-group">
<span class="input-group-btn">
<button id="{{ settingKey }}-btn" class="btn btn-primary" type="button">
<i class="fa fa-refresh"></i> Получить Chat ID
</button>
</span>
<input type="text"
name="{{ settingKey }}"
value="{{ attribute(_context, settingKey) }}"
placeholder="{{ item['placeholder'] }}"
id="{{ settingKey }}"
class="form-control"
/>
<script>
$('#{{ settingKey }}-btn').click(function () {
const telegramToken = $('#module_tgshop_bot_token').val().trim(); // fetch from input
if (! telegramToken) {
alert('Сначала введите Telegram Bot Token!');
return;
}
{% if module_tgshop_bot_token %}
<div class="input-group">
<span class="input-group-btn">
<button id="{{ settingKey }}-btn" class="btn btn-primary" type="button">
<i class="fa fa-refresh"></i> Получить Chat ID
</button>
</span>
<input type="text"
name="{{ settingKey }}"
value="{{ attribute(_context, settingKey) }}"
placeholder="{{ item['placeholder'] }}"
id="{{ settingKey }}"
class="form-control"
/>
<script>
$('#{{ settingKey }}-btn').click(function () {
const $resultLabel = $('#{{ settingKey }}-result-label');
const telegramToken = $('#module_tgshop_bot_token').val().trim(); // fetch from input
if (! telegramToken) {
alert('Сначала введите Telegram Bot Token!');
return;
}
fetch('/admin/index.php?route=extension/module/tgshop/handle&api_action=getChatId&user_token={{ user_token }}')
.then(async (res) => {
const data = await res.json().catch(() => null);
fetch('/admin/index.php?route=extension/module/tgshop/handle&api_action=getChatId&user_token={{ user_token }}')
.then(async (res) => {
const data = await res.json().catch(() => null);
if (!res.ok) {
throw new Error(`Ошибка ${res.status}: ${data.message || res.statusText}`);
}
if (!res.ok) {
throw new Error(`Ошибка ${res.status}: ${data.message || res.statusText}`);
}
$('#{{ settingKey }}').val(data.data.chat_id);
alert('ChatID успешно получен и подставлен в поле.');
})
.catch(err => {
console.error(err);
alert(err);
});
});
$('#{{ settingKey }}').val(data.data.chat_id);
$resultLabel
.text('✅ ChatID успешно получен и подставлен в поле. Не забудьте сохранить настройки!')
.css('color', 'green');
})
.catch(err => {
console.error(err);
alert(err);
});
});
</script>
</div>
<button class="btn btn-link btn-xs" type="button" data-toggle="collapse" data-target="#{{ settingKey }}-collapse" aria-expanded="false" aria-controls="collapseExample">
Инструкция как получить ChatID.
</button>
<div class="collapse" id="{{ settingKey }}-collapse">
<div class="well">
<p class="text-primary">Как получить Chat ID</p>
<ol>
<li>Убедитесь, что Telegram Bot Token введён выше.</li>
<li>Откройте вашего бота в Telegram и отправьте ему кодовое слово: `opencart_get_chatid`. Важно отправить именно такое сообщение, иначе не сработает.</li>
<li>Вернитесь сюда и нажмите кнопку «Получить Chat ID» — скрипт автоматически подставит его в поле ниже.</li>
</ol>
</script>
</div>
</div>
<div id="{{ settingKey }}-result-label"></div>
<button class="btn btn-link btn-xs" type="button" data-toggle="collapse" data-target="#{{ settingKey }}-collapse" aria-expanded="false" aria-controls="collapseExample">
Инструкция как получить ChatID.
</button>
<div class="collapse" id="{{ settingKey }}-collapse">
<div class="well">
<p class="text-primary">Как получить Chat ID</p>
<ol>
<li>Убедитесь, что Telegram Bot Token введён выше.</li>
<li>Откройте вашего бота в Telegram и отправьте ему кодовое слово: `opencart_get_chatid`. Важно отправить именно такое сообщение, иначе не сработает.</li>
<li>Вернитесь сюда и нажмите кнопку «Получить Chat ID» — скрипт автоматически подставит его в поле ниже.</li>
</ol>
</div>
</div>
{% else %}
<div class="alert alert-warning">
<strong>BotToken</strong> не указан. Пожалуйста, введите корректный BotToken и сохраните настройки. После этого здесь станет доступна настройка ChatID.
</div>
{% endif %}
{% elseif item['type'] == 'tg_message_template' %}
<div style="margin-bottom: 10px;">
<textarea name="{{ settingKey }}"
@@ -328,6 +338,7 @@
const $input = $('#{{ settingKey }}');
const $resultLabel = $('#{{ settingKey }}-result-label');
const botToken = $input.val();
const url = '/admin/index.php?route=extension/module/tgshop/handle&api_action=configureBotToken&user_token={{ user_token }}';
if (botToken.trim().length === 0) {
$resultLabel
@@ -336,34 +347,46 @@
return;
}
$input.attr('disabled', true);
$input.attr('readonly', true);
$resultLabel.text('Проверяю...');
$.ajax({
url: `https://api.telegram.org/bot${botToken}/getMe`,
method: 'GET',
dataType: 'json',
success: function (resp) {
if (resp.ok) {
const user = resp.result;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ botToken }),
})
.then(async (res) => {
const response = await res.json().catch(() => null);
if (res.status === 422) {
console.error(res, response);
$resultLabel
.text(`✅ Бот: @${user.username} (id: ${user.id})`)
.css('color', 'green');
} else {
$resultLabel
.text(`❌ Ошибка: ${resp.description || 'неверный токен'}`)
.text(`❌ Ошибка: ${response.error}`)
.css('color', 'red');
return;
}
},
error: function (xhr) {
if (!res.ok) {
throw new Error(`Ошибка ${response.error || res.statusText}`);
}
if (! response.id) {
throw new Error(`bot token is not found in server response.`);
}
$resultLabel
.text(`❌ Ошибка соединения (${xhr.status})`)
.text(`✅ Бот: @${response.username} (id: ${response.id}) webhook: ${response.webhook_url}`)
.css('color', 'green');
})
.catch(err => {
console.error(err);
$resultLabel
.text(`❌ Ошибка проверки BotToken.`)
.css('color', 'red');
},
complete: function () {
$input.attr('disabled', false);
}
});
})
.finally(() => $input.attr('readonly', false))
}
</script>