mirror of
https://github.com/avecms/AVE.cms.git
synced 2026-12-04 00:45:07 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a26157716 | ||
|
|
3a7c4a5fbb | ||
|
|
86a41e4adc | ||
|
|
5dad4a1cf1 |
@@ -22,6 +22,7 @@
|
||||
/tmp/
|
||||
/uploads/
|
||||
/storage/backups/
|
||||
/storage/database-restore/
|
||||
/storage/importprice/
|
||||
/storage/imports/
|
||||
/storage/jobs/
|
||||
|
||||
@@ -62,6 +62,7 @@ AddDefaultCharset UTF-8
|
||||
RewriteRule ^setup/?$ setup/index.php [L,QSA]
|
||||
|
||||
# Internal implementation and runtime data must not be addressed directly.
|
||||
RewriteRule ^system/App/Frontend/Auth/assets/(?:phone-mask|auth)\.js$ - [L]
|
||||
RewriteRule ^(?:configs|storage|system|tmp)(?:/|$) - [R=404,L]
|
||||
# Module packages expose only static files from their declared asset roots.
|
||||
# Manifests, migrations, views, LESS sources and executable code stay private.
|
||||
|
||||
+216
-1
@@ -11,7 +11,222 @@
|
||||
|
||||
## Не выпущено
|
||||
|
||||
Новые изменения будут добавлены после build 0.40.
|
||||
## 3.3 build 0.44 — 19 ноября 2026
|
||||
|
||||
- Редактор документов загружает варианты поля из общего справочника через
|
||||
тип поля: активные значения и уже выбранные неактивные. Одиночный и
|
||||
множественный выбор сохраняются при повторном сохранении документа.
|
||||
- Импорт документов 1.0.3: скрытые индикатор, результат и кнопки запуска/
|
||||
остановки не появляются до соответствующего этапа импорта.
|
||||
|
||||
- Исправлено повторное экранирование названия и заголовка хлебных крошек при
|
||||
частичном сохранении, импорте и массовом редактировании документов.
|
||||
- Редактор запросов сохраняет включённые флажки при повторном открытии;
|
||||
числовые ключи вариантов поля «Выбор» больше не заменяются подписями.
|
||||
- Контактные формы 1.0.17: ошибки полей видимы и связаны с полями через ARIA;
|
||||
редактирование сохраняет служебный признак поля. Обращение записывается
|
||||
в историю до отправки уведомлений, поэтому сбой почты не удаляет его.
|
||||
- В снимке документа meta.title содержит название вместо кода редиректа.
|
||||
Canonical и og:url учитывают URL_SUFF; главная сохраняет корневой адрес.
|
||||
Для HTML-атрибутов элементов запроса добавлен тег [tag:doctitle:attr].
|
||||
|
||||
## 3.3 build 0.43 — 13 ноября 2026
|
||||
|
||||
### Ядро, панель и отдельные модули
|
||||
|
||||
- CLI-помощник выпуска самостоятельно подключает административные сервисы:
|
||||
запуск сборки не зависит от предварительного открытия панели.
|
||||
|
||||
- Исправлена потеря множественных связей «Документы из рубрики (выбор)»
|
||||
при сохранении: числовые списки с разделителем `|` больше не читаются как
|
||||
одна запись «название|ID». Сохраняются все выбранные документы и их порядок.
|
||||
В полях «HTML / код» восстановлена подсветка HTML через режим `htmlmixed`.
|
||||
|
||||
- В визуальном редакторе исправлены лишние пустые абзацы при вставке Word
|
||||
и копировании между полями: удаляются отступы HTML между блоками и пустые
|
||||
блоки по краям фрагмента. Пустые абзацы внутри текста, пробелы между
|
||||
выделениями, списки и форматирование кода сохраняются. Кнопка Word использует
|
||||
тот же механизм вставки, что и буфер обмена. Показ блоков включён по умолчанию
|
||||
и отключается кнопкой в каждом редакторе, включая компактный профиль.
|
||||
|
||||
- Исправлено создание полных бэкапов работающего сайта: отдельный согласованный
|
||||
снимок InnoDB и потоковое чтение таблиц вместо порций с OFFSET. Записи,
|
||||
добавляемые во время копирования, больше не сдвигают порции и не создают
|
||||
повторы первичных ключей в дампе; транзакция вызывающего кода не затрагивается.
|
||||
|
||||
- В «Настройки → Обслуживание» добавлена кнопка очистки просроченных публичных
|
||||
сессий: подтверждение, последовательные порции, прогресс и остановка.
|
||||
Видны отдельные счётчики просроченных и действующих записей, доступность
|
||||
фонового запуска и результат последней автоматической попытки с ошибкой.
|
||||
Исправлено переполнение страницы обслуживания на узких экранах.
|
||||
|
||||
- Витрина МедМос: отдельная статья-справочник об ИПРА с самостоятельным текстом,
|
||||
официальными источниками, оглавлением, этапами оформления, сравнением способов
|
||||
получения ТСР, FAQ, отмечаемой памяткой и печатью. Нативный документ и
|
||||
дополнительный шаблон, редактируемые поля и необязательная фотография;
|
||||
безопасный установочный файл для переноса без замены общих шаблонов сайта.
|
||||
|
||||
- Публичные сессии БД очищаются небольшими индексированными порциями:
|
||||
до 1000 просроченных записей в минуту, без параллельных проходов.
|
||||
На PHP-FPM уборка выполняется после отправки ответа; в Планировщике 1.2.1
|
||||
добавлена отдельная задача для cron. Действующие и продлённые сессии
|
||||
сохраняются, удаление всей таблицы и автоматический OPTIMIZE не выполняются.
|
||||
|
||||
- Импорт цен 1.5.4: на вкладке «Новые и выпавшие» состояние карточки на сайте
|
||||
выделено отдельным бейджем, выключенные отмечены серым с иконкой скрытого
|
||||
просмотра. Добавлены счётчики состояния текущей выборки, понятный фильтр
|
||||
«Состояние на сайте» и кнопка «Обновить список»; CSV сохраняет этот статус.
|
||||
|
||||
- Импорт цен 1.5.3: вкладка «Новые и выпавшие» показывает оба типа изменений
|
||||
ассортимента. Новые позиции отмечены зелёным, отсутствующие — оранжевым;
|
||||
добавлены отдельные счётчики и выбор «все / новые / выпавшие». CSV учитывает
|
||||
фильтр, сохранённый результат старого формата пересчитывается автоматически.
|
||||
|
||||
- Импорт цен 1.5.2: отдельная вкладка «Выпавшие товары» с фильтрами,
|
||||
переходом в карточку и CSV. При загрузке нового XLSX или получении по ссылке
|
||||
текущий прайс сохраняется как предыдущий, сравнение выполняется сразу,
|
||||
количество отсутствующих позиций видно в модуле. Повторная загрузка того
|
||||
же файла сохраняет базу сравнения; товары и цены автоматически не меняются.
|
||||
|
||||
- Витрина МедМос: текст поля «Акция (подарок)» теперь показан отдельным
|
||||
заметным блоком под ценой на странице товара. Сохраняются переносы строк;
|
||||
пустое поле не создаёт плашку. Расчёт акций и выдача подарков не менялись.
|
||||
|
||||
- Импорт цен 1.5.1: форма создания черновика подключена ко всем готовым
|
||||
разборам семейств товаров, включая кислородные концентраторы и насосы.
|
||||
Вместо 11 доступно 37 пунктов, автоматический выбор учитывает нативный
|
||||
набор раздела. В форме видны его название и ссылки на настройку;
|
||||
неоднозначные исполнения не подставляются из первого заголовка прайса.
|
||||
|
||||
- Аналитика магазина 0.9.0: отчёт «Контакты по категориям» с отдельными
|
||||
списками заказов и брошенных корзин, выбором периода и нескольких категорий,
|
||||
подкатегориями, контактами, фильтрами отмен/оплаты и обработки корзин.
|
||||
Достаточно одной подходящей позиции; снимки состава и суммы не пересчитываются.
|
||||
Добавлены сохранённые наборы фильтров и две выгрузки XLSX: одна запись на строку,
|
||||
многострочные товары/категории в ячейках, телефон текстом и лист параметров.
|
||||
|
||||
- Импорт цен 1.5.0: разбор гинекологических кресел в отдельный нативный набор,
|
||||
создание черновика прямо из строки XLSX, отдельные комплектация и опции.
|
||||
В расхождениях выделены новые и исчезнувшие артикулы, сохранён независимый
|
||||
фильтр состояния товара на сайте, добавлены подсказки о смене артикула и CSV.
|
||||
|
||||
- Товары 1.13.13: сохранение определения характеристики и фильтров раздела
|
||||
больше не подтверждает чужую транзакцию; вложенные операции используют
|
||||
точки сохранения и корректно откатываются при ошибке.
|
||||
|
||||
- Исправлен единый результат оформления заказа: первый запрос и его повтор
|
||||
получают одинаковый сохранённый снимок для оплаты и чека.
|
||||
|
||||
- В ИИ-помощнике исправлен стандартный профиль описания товара: разрешены
|
||||
абзацы `<p>`, при этом запрет `h1`, стилей и атрибутов сохранён.
|
||||
|
||||
- Упрощена вкладка расхождений прайса: компактный выбор файлов, видимые
|
||||
фильтры по разделу, виду сверки, полю и сопоставлению, сортировка,
|
||||
таблица товаров и штатная номерная пагинация. Сверка отдельного товара
|
||||
открывается в правой панели; фильтры сохраняются при повторном сравнении.
|
||||
|
||||
- Исправлена переоценка матрасов с условной ценой при покупке с кроватью:
|
||||
обычная цена больше не заменяется комплектной. Добавлен отдельный режим
|
||||
восстановления только цен таких матрасов без изменения остальных товаров
|
||||
и правил акций; предпросмотры старой версии отклоняются.
|
||||
|
||||
- В импорте прайса добавлена вкладка «Расхождения»: сравнение нативных
|
||||
характеристик, описаний, комплектации и отметок с текущими товарами,
|
||||
необязательная сверка с предыдущим XLSX, поиск, фильтры и CSV. Изменения
|
||||
цен отделены от изменений данных; сверка не изменяет товары. Исправлено
|
||||
распознавание несъёмных и неповоротных подножек.
|
||||
|
||||
- В модуле импорта прайса появился режим «Только цены» по умолчанию: гарантия,
|
||||
РУ, акции, новинки и характеристики не меняются при переоценке. Гарантия на
|
||||
обивку больше не распознаётся как гарантия на весь товар; изменённый файл
|
||||
или режим обновления требует нового предпросмотра.
|
||||
|
||||
- YooKassa формирует смешанный чек корректно: товары передаются без НДС,
|
||||
а платная доставка — как услуга с НДС 22%. Локальный SDK принимает актуальный
|
||||
код ставки `11`, действующий с 1 января 2026 года.
|
||||
|
||||
## 3.3 build 0.42 — 13 октября 2026
|
||||
|
||||
### Ядро и панель
|
||||
|
||||
- Исправлены проверки готовности и базовая конфигурация сайта: страница 404
|
||||
берётся из настройки, навигация сохраняет явно пустые шаблоны, описание
|
||||
запроса расширяется с TINYTEXT до TEXT. Главная в sitemap использует
|
||||
собственные настройки и дату документа, учитывает запреты индексации;
|
||||
искусственная текущая дата в индексе sitemap убрана.
|
||||
- Core-обновления сохраняют проектные `robots.txt` и корневой `.htaccess`,
|
||||
включая применение старых подписанных патчей и откат. В стандартном Apache
|
||||
конфиге разрешены только публичные `phone-mask.js` и `auth.js` внутри
|
||||
закрытого `/system/`, остальные служебные файлы остаются недоступными.
|
||||
|
||||
- Убрана зависимость от PHP CLI при проверке сниппетов и заданий документов,
|
||||
а также при пересборке фильтров каталога. Нативные и старые фильтры
|
||||
пересобираются штатными сервисами с откатом при ошибке, без изменения цен
|
||||
и исходных характеристик. Консоль и сборщик используют общий поиск PHP CLI
|
||||
с поддержкой Windows/OpenServer, проверкой SAPI и без запуска Apache/FPM;
|
||||
поиск команд больше не требует `sh`.
|
||||
|
||||
- Проверка PHP в блоках больше не требует CLI и временных файлов: синтаксис
|
||||
разбирается встроенным парсером без выполнения кода. Исправлен отказ
|
||||
сохранения корректных блоков при PHP, работающем модулем Apache.
|
||||
|
||||
- Доработан richtext-редактор: вставка из Word с очисткой стилей и сохранением
|
||||
структуры, полноэкранный режим, предпросмотр, таблицы, очистка форматирования
|
||||
и локальное восстановление текста. Исправлены переключение заголовков
|
||||
и создание новых документов с незаполненными полями.
|
||||
|
||||
- Добавлены массовая очистка корзины медиа, очистка inline-стилей только
|
||||
в выбранных описаниях и заметные очереди внимания менеджеров.
|
||||
|
||||
### Каталог модулей
|
||||
|
||||
- Обновлены «Готовность сайта», «Контактные формы» и «Источники трафика».
|
||||
У трафика добавлены отчёт по страницам, CSV и график за 14 дней;
|
||||
уведомления форм учитывают все формы, не только первую.
|
||||
|
||||
### Выпуск
|
||||
|
||||
- Пересборка сохраняет опубликованные ZIP неизменённых модулей.
|
||||
При отсутствии исходного core 0.20 строится прямой патч от предыдущего
|
||||
оригинального core-архива, старые переходы остаются в каталоге.
|
||||
|
||||
## 3.3 build 0.41 — 7 сентября 2026
|
||||
|
||||
### Контент и каталог
|
||||
|
||||
- Уточнены роли товарных полей и связи между разделами каталога, документами и
|
||||
нативными характеристиками; редакторы получили более понятные переходы к
|
||||
связанным настройкам.
|
||||
- Массовые и быстрые изменения документов используют единый безопасный путь
|
||||
записи и корректно обновляют производные данные и кеш.
|
||||
- Улучшены диагностика качества, выборки товаров и совместимость запросов с
|
||||
MariaDB 10.3.
|
||||
|
||||
### Публичный сайт и фиды
|
||||
|
||||
- Фиды корректно обновляются после изменения товара, устойчивее генерируются
|
||||
параллельно и учитывают видимость служебного контента.
|
||||
- Поиск и товарные выборки точнее обрабатывают доступность, роли полей и
|
||||
специальные условия показа.
|
||||
|
||||
### Панель управления
|
||||
|
||||
- Раздел 404 поддерживает безопасный редирект на произвольный локальный путь и
|
||||
выбор любого доступного публичного документа, а таблицы журнала адаптированы
|
||||
для мобильного экрана.
|
||||
- Исправлено мобильное отображение журнала событий; виджет заказов по статусам
|
||||
теперь использует тот же период 14 дней, что и общая статистика.
|
||||
- Дополнены переводы, подсказки и пользовательская справка для изменённых
|
||||
разделов.
|
||||
|
||||
### Надёжность
|
||||
|
||||
- Операции корзины, оформления заказа, оплаты и доставки получили дополнительные
|
||||
проверки целостности и регрессионные тесты.
|
||||
- Для build 0.41 подготовлены чистая core-сборка, компактный установщик,
|
||||
накопительное обновление с build 0.20 и обновлённый каталог модулей.
|
||||
- Проектные торговые расширения и ИИ-помощник не входят в публичную core-сборку
|
||||
и репозиторий модулей.
|
||||
|
||||
## 3.3 build 0.40 — 25 августа 2026
|
||||
|
||||
|
||||
+269
-183
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
# AVE.cms
|
||||
|
||||
**AVE.cms 3.3 build 0.37** — модульная система управления сайтами на PHP.
|
||||
**AVE.cms 3.3 build 0.44** — модульная система управления сайтами на PHP.
|
||||
Она подходит для проектов, в которых структуру содержимого нужно собирать из
|
||||
собственных рубрик, полей, документов, запросов, блоков и шаблонов, не
|
||||
привязываясь к заранее заданному типу сайта.
|
||||
|
||||
@@ -75,6 +75,46 @@
|
||||
return $saved;
|
||||
}
|
||||
|
||||
/** Синхронизировать переключатель из карточки модуля с общей раскладкой главной. */
|
||||
public static function setModuleDashboardVisibility($moduleCode, $visible, array $definitions)
|
||||
{
|
||||
$moduleCode = (string) $moduleCode;
|
||||
$targetCodes = array();
|
||||
foreach ($definitions as $definition) {
|
||||
if (!is_array($definition) || !isset($definition['module_code'], $definition['layout_code'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((string) $definition['module_code'] === $moduleCode) {
|
||||
$targetCodes[(string) $definition['layout_code']] = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$targetCodes) {
|
||||
return self::config('dashboard');
|
||||
}
|
||||
|
||||
$config = self::config('dashboard');
|
||||
$seen = array();
|
||||
foreach ($config as &$row) {
|
||||
$code = (string) $row['code'];
|
||||
if (isset($targetCodes[$code])) {
|
||||
$row['visible'] = (bool) $visible;
|
||||
$seen[$code] = true;
|
||||
}
|
||||
}
|
||||
|
||||
unset($row);
|
||||
foreach (array_keys($targetCodes) as $code) {
|
||||
if (!isset($seen[$code])) {
|
||||
$config[] = array('code' => $code, 'visible' => (bool) $visible);
|
||||
}
|
||||
}
|
||||
|
||||
Settings::set(self::key('dashboard'), $config, 'json');
|
||||
return $config;
|
||||
}
|
||||
|
||||
protected static function prepare(array $items, $codeKey)
|
||||
{
|
||||
$prepared = array();
|
||||
|
||||
@@ -62,6 +62,12 @@
|
||||
return self::contributions('header');
|
||||
}
|
||||
|
||||
/** Small, permission-scoped work queues; providers must not mutate their records. */
|
||||
public static function attentionQueues()
|
||||
{
|
||||
return self::contributions('attention');
|
||||
}
|
||||
|
||||
public static function dashboardWidgets(array $visibleCodes = null)
|
||||
{
|
||||
return self::contributions('dashboard', $visibleCodes);
|
||||
@@ -106,6 +112,7 @@
|
||||
public static function notifications($base, array $summary)
|
||||
{
|
||||
foreach (self::contributions('notifications') as $contribution) {
|
||||
$moduleCode = isset($contribution['module_code']) ? (string) $contribution['module_code'] : '';
|
||||
$data = isset($contribution['data']) ? $contribution['data'] : array();
|
||||
$items = isset($data['items']) && is_array($data['items']) ? $data['items'] : (self::isList($data) ? $data : array());
|
||||
foreach ($items as $item) {
|
||||
@@ -113,6 +120,11 @@
|
||||
continue;
|
||||
}
|
||||
|
||||
$key = isset($item['key']) ? trim((string) $item['key']) : '';
|
||||
if ($key !== '' && !self::notificationEnabled($moduleCode, $key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$count = isset($item['count']) ? max(0, (int) $item['count']) : 1;
|
||||
if ($count < 1) {
|
||||
continue;
|
||||
@@ -137,8 +149,7 @@
|
||||
'title' => AdminLocale::translateMarkup(isset($item['title']) ? (string) $item['title'] : ''),
|
||||
));
|
||||
$summary['total'] += $count;
|
||||
if (!empty($item['key'])) {
|
||||
$key = (string) $item['key'];
|
||||
if ($key !== '') {
|
||||
$summary[$key] = isset($summary[$key]) ? (int) $summary[$key] + $count : $count;
|
||||
}
|
||||
}
|
||||
@@ -147,6 +158,80 @@
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/** Настраиваемые элементы колокольчика без запуска их провайдеров. */
|
||||
public static function notificationPreferences()
|
||||
{
|
||||
self::boot();
|
||||
$out = array();
|
||||
foreach (self::$extensions as $code => $extension) {
|
||||
$module = self::currentModule($code, $extension['module']);
|
||||
if (empty($module['installed']) || empty($module['enabled'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$config = $extension['config'];
|
||||
if (empty($config['notifications'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (self::normalizeItems($config['notifications']) as $item) {
|
||||
if (!is_array($item) || !self::allowed($item) || empty($item['preferences']) || !is_array($item['preferences'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($item['preferences'] as $preference) {
|
||||
if (!is_array($preference)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$key = isset($preference['key']) ? trim((string) $preference['key']) : '';
|
||||
$label = isset($preference['label']) ? trim((string) $preference['label']) : '';
|
||||
if (!preg_match('/^[a-z][a-z0-9_]{0,63}$/', $key) || $label === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$default = !empty($preference['default']);
|
||||
$out[] = array(
|
||||
'module_code' => (string) $code,
|
||||
'key' => $key,
|
||||
'label' => AdminLocale::translateMarkup($label),
|
||||
'description' => AdminLocale::translateMarkup(isset($preference['description']) ? (string) $preference['description'] : ''),
|
||||
'enabled' => (bool) ModuleSettings::get(self::notificationSettingKey($key), $default, $code),
|
||||
'default' => $default,
|
||||
'sort_order' => isset($preference['sort_order']) ? (int) $preference['sort_order'] : 100,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
usort($out, function ($left, $right) {
|
||||
if ($left['sort_order'] === $right['sort_order']) {
|
||||
return strcmp($left['label'], $right['label']);
|
||||
}
|
||||
|
||||
return $left['sort_order'] <=> $right['sort_order'];
|
||||
});
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Сохранить один объявленный модулем переключатель уведомлений. */
|
||||
public static function setNotificationPreference($moduleCode, $key, $enabled)
|
||||
{
|
||||
$moduleCode = strtolower(trim((string) $moduleCode));
|
||||
$key = strtolower(trim((string) $key));
|
||||
foreach (self::notificationPreferences() as $preference) {
|
||||
if ($preference['module_code'] !== $moduleCode || $preference['key'] !== $key) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ModuleSettings::set(self::notificationSettingKey($key), (bool) $enabled, $moduleCode, 'bool');
|
||||
$preference['enabled'] = (bool) $enabled;
|
||||
return $preference;
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException('Настройка уведомления не найдена');
|
||||
}
|
||||
|
||||
public static function catalog()
|
||||
{
|
||||
self::boot();
|
||||
@@ -410,4 +495,20 @@
|
||||
{
|
||||
return (bool) ModuleSettings::get('adminx_' . $type . '_enabled', true, $code);
|
||||
}
|
||||
|
||||
protected static function notificationEnabled($moduleCode, $key)
|
||||
{
|
||||
foreach (self::notificationPreferences() as $preference) {
|
||||
if ($preference['module_code'] === (string) $moduleCode && $preference['key'] === (string) $key) {
|
||||
return !empty($preference['enabled']);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected static function notificationSettingKey($key)
|
||||
{
|
||||
return 'adminx_notification_' . preg_replace('/[^a-z0-9_]+/', '_', strtolower((string) $key)) . '_enabled';
|
||||
}
|
||||
}
|
||||
|
||||
+16
-32
@@ -16,48 +16,32 @@
|
||||
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Common\CliRuntime;
|
||||
use App\Common\PublicConfiguration;
|
||||
use App\Helpers\PhpSyntax;
|
||||
|
||||
class PhpCode
|
||||
{
|
||||
public static function source($code)
|
||||
{
|
||||
$code = trim((string) $code);
|
||||
if (preg_match('/^<\?(?:php|=)?/i', $code)) {
|
||||
return $code;
|
||||
}
|
||||
|
||||
if (preg_match('/^<\?(?:php|=)?/i', $code)) { return $code; }
|
||||
return "<?php\n" . $code . "\n";
|
||||
}
|
||||
|
||||
public static function lint($code)
|
||||
{
|
||||
$directory = BASEPATH . '/tmp/console';
|
||||
if (!is_dir($directory) && !@mkdir($directory, 0775, true)) {
|
||||
return array('ok' => false, 'message' => 'Не удалось создать временный файл.', 'output' => '', 'line' => 0);
|
||||
}
|
||||
$code = trim((string) $code);
|
||||
$offset = preg_match('/^<\?(?:php|=)?/i', $code) ? 0 : -1;
|
||||
return PhpSyntax::check(self::source($code), $offset);
|
||||
}
|
||||
|
||||
$file = $directory . '/lint-' . bin2hex(random_bytes(8)) . '.php';
|
||||
if (@file_put_contents($file, self::source($code)) === false) {
|
||||
@unlink($file);
|
||||
return array('ok' => false, 'message' => 'Не удалось записать временный файл.', 'output' => '', 'line' => 0);
|
||||
}
|
||||
|
||||
$php = defined('PHP_BINARY') && PHP_BINARY ? PHP_BINARY : 'php';
|
||||
$output = array();
|
||||
$status = 0;
|
||||
@exec(escapeshellarg($php) . ' -l ' . escapeshellarg($file) . ' 2>&1', $output, $status);
|
||||
@unlink($file);
|
||||
$text = trim(implode("\n", $output));
|
||||
$text = str_replace($file, 'код', $text);
|
||||
$line = 0;
|
||||
if (preg_match('/ on line ([0-9]+)/i', $text, $match)) {
|
||||
$line = (int) $match[1];
|
||||
}
|
||||
|
||||
return array(
|
||||
'ok' => $status === 0 && $text !== '',
|
||||
'message' => $status === 0 ? 'Синтаксис PHP без ошибок.' : 'В PHP-коде есть синтаксическая ошибка.',
|
||||
'output' => $text,
|
||||
'line' => $line,
|
||||
);
|
||||
public static function cliBinary()
|
||||
{
|
||||
$config = PublicConfiguration::value('admin_console', array());
|
||||
$preferred = array(trim((string) getenv('ADMINX_PHP_BINARY')));
|
||||
if (is_array($config) && !empty($config['php_binary'])) { $preferred[] = trim((string) $config['php_binary']); }
|
||||
try { return CliRuntime::php($preferred); }
|
||||
catch (\RuntimeException $e) { throw new \RuntimeException($e->getMessage() . ' Для панели также доступны ADMINX_PHP_BINARY и admin_console.php_binary.'); }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +76,7 @@
|
||||
protected static function definitions()
|
||||
{
|
||||
return array(
|
||||
self::item('#^/documents/bulk-editor$#', 'Массовый редактор', 'Меняет одинаковые настройки сразу у выбранной группы документов и сначала показывает точный предпросмотр.', array('Служебный документ остаётся доступен полям, запросам и связям, но его публичный адрес возвращает 404.', 'Служебные документы автоматически исключаются из публичного поиска, sitemap, SEO-задач и проверок качества.', 'Внутренний поиск, robots и участие в sitemap можно менять отдельными действиями, не скрывая саму страницу.'), 'Сначала выберите рубрику или другой узкий фильтр, проверьте примеры и только затем запускайте изменение.'),
|
||||
self::item('#^/documents/redirects$#', 'Редиректы документов', 'Управляет старыми адресами страниц и перенаправляет посетителей на актуальные документы.', array('Ищите редирект по старому URL, названию или ID документа.', 'Коды 301/308 подходят для постоянного переноса, 302/307 — для временного.', 'Перед удалением убедитесь, что старый адрес больше не используется во внешних ссылках.'), 'Каждый старый URL должен быть уникальным и вести на существующий документ.'),
|
||||
self::item('#^/documents/views$#', 'Статистика просмотров', 'Показывает посещаемость документов по дням и помогает находить наиболее востребованные страницы.', array('Период влияет только на подневную статистику.', 'Общий счётчик документа хранится отдельно и не очищается вместе с дневными данными.', 'Очистка статистики необратима и предназначена для обслуживания.'), 'Для бизнес-аналитики используйте внешнюю систему аналитики; здесь хранится внутренняя статистика CMS.'),
|
||||
self::item('#^/documents/(?:create|\d+/edit)$#', 'Редактор документа', 'Создаёт и изменяет страницу сайта: её адрес, публикацию, SEO и значения полей выбранной рубрики.', array('Набор полей и их группы задаются рубрикой.', 'Изменение alias может автоматически создать редирект со старого URL.', 'Ctrl+S сохраняет изменения и оставляет редактор открытым; ревизии позволяют вернуться к прошлой версии.'), 'Смена рубрики существующего документа запрещена без отдельной миграции полей.'),
|
||||
@@ -133,12 +134,12 @@
|
||||
self::item('#^/settings/benchmark$#', 'Производительность', 'Измеряет скорость PHP, базы данных, файловых операций и кеша на текущем сервере.', array('Результаты нужны для сравнения одного окружения во времени, а не разных проектов.', 'Повторяйте тест после обновления PHP, БД или инфраструктуры.', 'Тест создаёт кратковременную нагрузку и сохраняет историю запусков.'), 'Оценивайте не только общий балл, но и конкретный медленный этап.'),
|
||||
self::item('#^/settings#', 'Настройки системы', 'Собирает общие параметры AVE.cms, интерфейс, константы, пагинацию, обслуживание и диагностику.', array('Каждый подраздел имеет собственный URL и назначение.', 'Типизированные значения проверяются перед сохранением.', 'Настройки устанавливаемых модулей хранятся вместе с соответствующим модулем.'), 'Меняйте только параметры, назначение которых понятно и проверено на текущем сайте.', 'administration/settings'),
|
||||
self::item('#^/events#', 'Системные события', 'Объединяет аудит действий, ошибки, SQL-журнал, 404 и статистику внешних переходов.', array('Цвет и состояние помогают отличать успешные операции, предупреждения и ошибки.', 'Переходы группируются по посетителю, странице входа и источнику; открытые IP и произвольные query-параметры не сохраняются.', 'Фильтры и CSV-экспорт работают отдельно для каждого источника.'), 'Очистка журнала необратима и не исправляет причину ошибки.'),
|
||||
self::item('#^/security/ip-blocks#', 'IP-блокировки', 'Управляет ручными блокировками адресов, а автоматические ограничения выполняет RateLimiter.', array('Блокировка может быть постоянной или иметь дату окончания.', 'Причина видна администраторам и записывается в аудит.', 'Разблокировка возвращает доступ сразу.'), 'Не блокируйте адрес reverse proxy без проверки реального клиентского IP.'),
|
||||
self::item('#^/security/ip-blocks#', 'Блокировки запросов', 'Ограничивает доступ к публичному сайту по IP-адресу или характерной строке User-Agent.', array('IP и User-Agent находятся на отдельных вкладках.', 'Правило может быть постоянным или иметь дату окончания.', 'Для робота используйте его уникальное имя, а не общие слова Mozilla, Chrome или Safari.', 'Причина и действия блокировки записываются в аудит.'), 'Перед блокировкой User-Agent проверьте предложенный фрагмент: слишком общее правило может затронуть обычных посетителей.'),
|
||||
self::item('#^/database#', 'База данных', 'Показывает рабочие таблицы AVE.cms, выполняет обслуживание, применяет миграции ядра и управляет полными резервными копиями.', array('OPTIMIZE применяется только к выбранной таблице или ко всей рабочей схеме после подтверждения.', 'Применение миграций не восстанавливает данные: это отдельная операция развития структуры ядра.', 'Новые дампы используют {{prefix}}, поэтому могут восстанавливаться с другим dbpref.', 'Перед восстановлением система проверяет файл и автоматически создаёт страховочную копию.'), 'Восстановление полностью заменяет таблицы текущей установки; рабочую копию дополнительно храните вне сервера.', 'database'),
|
||||
self::item('#^/kanban$#', 'Канбан', 'Организует рабочие карточки по колонкам и показывает доску на дашборде.', array('Карточки и порядок сохраняются без перезагрузки.', 'Колонки можно настроить под собственный процесс.', 'Карточке можно назначить ответственного, срок и связанный документ.', 'Командная карточка видна коллегам, а назначенная отдельно появляется у ответственного.'), 'Колонки принадлежат владельцу доски: назначенный сотрудник видит карточку в общем списке, но не перестраивает чужую доску.'),
|
||||
self::item('#^/notes$#', 'Заметки', 'Хранит личные текстовые заметки сотрудника и закрепляет важные записи на дашборде.', array('Заметки видны только их владельцу.', 'Закрепление влияет на порядок выдачи.', 'Быстрое создание доступно из шапки, если вклад модуля включён.'), 'Не храните в заметках пароли, токены и другие секреты.'),
|
||||
self::item('#^/reminders$#', 'Напоминания', 'Хранит личные задачи с датой и выводит просроченные пункты в общем колокольчике.', array('Срок определяет состояние напоминания.', 'Выполнение сохраняется сразу.', 'Просроченный счётчик формируется отдельно для текущего сотрудника.'), 'Удаление напоминания необратимо; выполненный пункт можно вернуть в работу.'),
|
||||
self::item('#^/notfound$#', 'Ошибки 404', 'Показывает несуществующие публичные адреса и помогает создать документ или редирект.', array('Сначала проверьте источник переходов и частоту запроса.', 'Для старого адреса существующей страницы создайте постоянный редирект.', 'Случайные сканирующие URL можно удалить из журнала без создания страницы.'), 'Редирект должен вести на действительно соответствующий документ, а не всегда на главную.'),
|
||||
self::item('#^/notfound$#', 'Ошибки 404', 'Показывает несуществующие публичные адреса, источник перехода, IP и программу или робота, который сделал запрос.', array('Кнопка «Подробнее» раскрывает полный реферер, User-Agent и время первого и последнего обращения.', 'Для старого адреса существующей страницы создайте постоянный редирект.', 'Нежелательного робота можно отправить в блокировки прямо из записи.', 'CSV учитывает текущий поиск и переключатель нерешённых записей.', 'Очистка всего журнала необратима, но новые ошибки начнут собираться снова.'), 'Не блокируйте обычный браузер только из-за одного ошибочного адреса; сначала оцените источник и частоту обращений.'),
|
||||
self::item('#^/seo-audit$#', 'SEO-аудит', 'Проверяет документы на технические и редакционные проблемы, влияющие на поисковое представление.', array('Фильтры помогают сначала разобрать критичные и массовые проблемы.', 'Оценка документа складывается из нескольких независимых проверок.', 'Исправления выполняются в редакторе документа и проявляются после повторного аудита.'), 'Автоматическая оценка является подсказкой и не заменяет проверку содержания страницы.', 'modules/seo-audit'),
|
||||
self::item('#^/todo$#', 'Todo', 'Хранит рабочие задачи сотрудников со сроками и связями с документами.', array('Задачу можно создать из выпадающего списка в шапке на любой странице панели управления.', 'Ответственный видит назначенную задачу и может отметить её выполненной.', 'Режим «Команда» открывает задачу всем сотрудникам с правом просмотра Todo.', 'Связанный документ открывается прямо из строки задачи.'), 'Изменять и удалять задачу может её создатель; выполнение доступно создателю и ответственному.'),
|
||||
self::item('#^/modules/search#', 'Поиск по сайту', 'Индексирует опубликованные документы и формирует обычную страницу результатов и JSON для живого поиска.', array('Области позволяют отдельно искать по товарам, новостям, статьям и другим наборам рубрик.', 'Алгоритм определяет разбор строки и вес точного совпадения, заголовка и содержимого.', 'Штатный HTML можно заменить шаблонами модуля или существующим запросом документов.'), 'После изменения рубрик или индексируемых полей выполните полную переиндексацию.', 'modules/search'),
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
'legacy_migration.write' => 'Изменение реквизитов исходной системы',
|
||||
'legacy_migration.execute' => 'Очистка стартовых данных и миграция старой AVE.cms',
|
||||
'database.restore' => 'Полная замена рабочей схемы данными из резервной копии',
|
||||
'external_connection.write' => 'Изменение адреса или секрета внешнего подключения',
|
||||
);
|
||||
protected static $required = array(
|
||||
'POST /modules/archive/install' => array('module.code', 'install_module_code'),
|
||||
|
||||
@@ -537,6 +537,16 @@ hr {
|
||||
.notif-head b {
|
||||
font-size: 13px;
|
||||
}
|
||||
.notif-head-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.notif-head-actions .btn {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
min-height: 32px;
|
||||
}
|
||||
.notif-list {
|
||||
max-height: 60vh;
|
||||
overflow-y: auto;
|
||||
@@ -591,6 +601,66 @@ hr {
|
||||
margin-bottom: 6px;
|
||||
color: var(--color-success);
|
||||
}
|
||||
.notif-settings {
|
||||
max-height: 60vh;
|
||||
overflow-y: auto;
|
||||
padding: 6px;
|
||||
background: var(--background-subtle);
|
||||
border-top: 1px solid var(--border-default);
|
||||
}
|
||||
.notif-settings-copy {
|
||||
padding: 8px 8px 6px;
|
||||
}
|
||||
.notif-settings-copy b,
|
||||
.notif-settings-copy small {
|
||||
display: block;
|
||||
}
|
||||
.notif-settings-copy b {
|
||||
font-size: 12px;
|
||||
}
|
||||
.notif-settings-copy small {
|
||||
margin-top: 2px;
|
||||
color: var(--text-muted);
|
||||
font-size: 11px;
|
||||
line-height: 1.35;
|
||||
text-wrap: pretty;
|
||||
}
|
||||
.notif-setting-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 44px;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 56px;
|
||||
padding: 8px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--surface-card);
|
||||
cursor: pointer;
|
||||
}
|
||||
.notif-setting-row + .notif-setting-row {
|
||||
margin-top: 5px;
|
||||
}
|
||||
.notif-setting-row > span:first-child {
|
||||
min-width: 0;
|
||||
}
|
||||
.notif-setting-row b,
|
||||
.notif-setting-row small {
|
||||
display: block;
|
||||
}
|
||||
.notif-setting-row b {
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.notif-setting-row small {
|
||||
margin-top: 2px;
|
||||
color: var(--text-muted);
|
||||
font-size: 10.5px;
|
||||
line-height: 1.3;
|
||||
text-wrap: pretty;
|
||||
}
|
||||
.notif-setting-row .switch {
|
||||
min-width: 40px;
|
||||
min-height: 40px;
|
||||
justify-content: center;
|
||||
}
|
||||
/* Заголовок в меню пользователя */
|
||||
#userMenu > .dropdown-menu {
|
||||
width: 280px;
|
||||
@@ -3137,18 +3207,27 @@ table.table {
|
||||
gap: 12px;
|
||||
padding: var(--space-5) var(--space-5) 0;
|
||||
}
|
||||
.modal-header > div {
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
.modal-header h3 {
|
||||
flex: 1;
|
||||
}
|
||||
.modal-close {
|
||||
display: grid;
|
||||
flex: 0 0 32px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
place-items: center;
|
||||
border: none;
|
||||
background: none;
|
||||
cursor: pointer;
|
||||
color: var(--text-muted);
|
||||
font-size: 18px;
|
||||
padding: 4px;
|
||||
padding: 0;
|
||||
border-radius: var(--radius-xs);
|
||||
margin: -4px -4px 0 0;
|
||||
margin: -4px -4px 0 auto;
|
||||
}
|
||||
.modal-close:hover {
|
||||
color: var(--text-primary);
|
||||
@@ -4484,6 +4563,212 @@ ul.sortable {
|
||||
overflow: hidden;
|
||||
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
|
||||
}
|
||||
body.rich-editor-fullscreen-open {
|
||||
overflow: hidden;
|
||||
}
|
||||
.rich-editor-status {
|
||||
flex: 0 0 auto;
|
||||
padding: 8px 12px;
|
||||
border-top: 1px solid var(--border-default);
|
||||
background: var(--background-muted);
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.rich-table-tools {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
flex: 0 0 auto;
|
||||
gap: 4px;
|
||||
padding: 6px 12px;
|
||||
border-bottom: 1px solid var(--border-default);
|
||||
background: var(--background-surface);
|
||||
}
|
||||
.rich-table-tools[hidden],
|
||||
.rich-recovery[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.rich-search-match {
|
||||
background: #fff1ad;
|
||||
color: #242a33;
|
||||
}
|
||||
.rich-search-match.is-current {
|
||||
background: #ffcc66;
|
||||
outline: 1px solid #926600;
|
||||
}
|
||||
.rich-tools-modal {
|
||||
width: 640px;
|
||||
max-width: calc(100vw - 24px);
|
||||
}
|
||||
.rich-tools-modal .modal-header {
|
||||
gap: 12px;
|
||||
}
|
||||
.rich-tools-modal .modal-header h3 {
|
||||
flex: 1;
|
||||
}
|
||||
.rich-tools-modal .modal-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
.rich-tools-modal .modal-footer {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.rich-tools-modal .modal-footer .btn {
|
||||
white-space: normal;
|
||||
}
|
||||
.rich-tools-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.rich-symbols {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(48px, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
.rich-symbols .btn {
|
||||
height: 48px;
|
||||
font-size: 22px;
|
||||
}
|
||||
.rich-snippets {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.rich-snippets .btn {
|
||||
justify-content: flex-start;
|
||||
white-space: normal;
|
||||
text-align: left;
|
||||
}
|
||||
.rich-review-row,
|
||||
.rich-block-row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
padding: 12px 0;
|
||||
border-bottom: 1px solid var(--border-default);
|
||||
}
|
||||
.rich-review-row:last-child,
|
||||
.rich-block-row:last-child {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.rich-review-row > span,
|
||||
.rich-block-row > span {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.rich-review-row b,
|
||||
.rich-review-row small,
|
||||
.rich-block-row b,
|
||||
.rich-block-row small {
|
||||
display: block;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.rich-review-row small,
|
||||
.rich-block-row small {
|
||||
color: var(--text-secondary);
|
||||
margin-top: 4px;
|
||||
}
|
||||
.rich-block-row {
|
||||
cursor: grab;
|
||||
}
|
||||
.rich-block-row small {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.rich-tools-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
padding: 24px 0;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.rich-recovery {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
background: var(--color-primary-soft);
|
||||
}
|
||||
.rich-recovery > span {
|
||||
flex: 1;
|
||||
}
|
||||
.rich-recovery-compare {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
}
|
||||
.rich-recovery-compare textarea {
|
||||
min-height: 140px;
|
||||
}
|
||||
.rich-editor-prose .content-callout {
|
||||
padding: 14px 18px;
|
||||
border-left: 3px solid var(--color-primary);
|
||||
background: var(--background-muted);
|
||||
}
|
||||
.rich-editor-prose .content-callout--warning {
|
||||
border-left-color: #b38a20;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.rich-tools-modal {
|
||||
max-width: 100%;
|
||||
}
|
||||
.rich-snippets {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
.rich-editor-fullscreen-parent {
|
||||
transform: none !important;
|
||||
filter: none !important;
|
||||
backdrop-filter: none !important;
|
||||
perspective: none !important;
|
||||
contain: none !important;
|
||||
will-change: auto !important;
|
||||
overflow: visible !important;
|
||||
position: relative !important;
|
||||
z-index: 196 !important;
|
||||
}
|
||||
.rich-editor.rich-editor-fullscreen {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 197;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
max-width: none;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
}
|
||||
.rich-editor.rich-editor-fullscreen .rich-editor-toolbar {
|
||||
flex: 0 0 auto;
|
||||
max-height: 45%;
|
||||
overflow: auto;
|
||||
}
|
||||
.rich-editor.rich-editor-fullscreen .rich-editor-surface,
|
||||
.rich-editor.rich-editor-fullscreen .rich-editor-inline-source {
|
||||
flex: 1 1 0;
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
.rich-editor.rich-editor-fullscreen .rich-editor-content,
|
||||
.rich-editor.rich-editor-fullscreen .rich-editor-prose {
|
||||
min-height: 100% !important;
|
||||
}
|
||||
.rich-editor.rich-editor-fullscreen .rich-editor-inline-source .CodeMirror {
|
||||
height: 100% !important;
|
||||
min-height: 0;
|
||||
}
|
||||
.rich-editor-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -488,6 +488,53 @@
|
||||
}
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ //
|
||||
// Видимость отдельных элементов в колокольчике.
|
||||
// ------------------------------------------------------------------ //
|
||||
Adminx.NotificationPreferences = {
|
||||
init: function () {
|
||||
document.addEventListener('click', function (event) {
|
||||
var toggle = event.target.closest('[data-notification-settings-toggle]');
|
||||
if (!toggle) { return; }
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
var menu = toggle.closest('.notif-menu');
|
||||
var panel = menu ? menu.querySelector('[data-notification-settings]') : null;
|
||||
var list = menu ? menu.querySelector('.notif-list') : null;
|
||||
if (!panel) { return; }
|
||||
var opening = panel.hidden;
|
||||
panel.hidden = !opening;
|
||||
if (list) { list.hidden = opening; }
|
||||
toggle.setAttribute('aria-expanded', opening ? 'true' : 'false');
|
||||
});
|
||||
|
||||
document.addEventListener('change', function (event) {
|
||||
var input = event.target.closest('[data-notification-preference]');
|
||||
if (!input) { return; }
|
||||
var previous = !input.checked;
|
||||
var data = new FormData();
|
||||
data.append('module_code', input.getAttribute('data-module-code') || '');
|
||||
data.append('key', input.getAttribute('data-key') || '');
|
||||
data.append('enabled', input.checked ? '1' : '0');
|
||||
input.disabled = true;
|
||||
Adminx.Ajax.post(Adminx.base() + '/settings/notifications', data).then(function (payload) {
|
||||
var response = Adminx.Ajax.handle(payload);
|
||||
if (!payload.ok || response.success === false) {
|
||||
input.checked = previous;
|
||||
return;
|
||||
}
|
||||
|
||||
window.location.reload();
|
||||
}).catch(function () {
|
||||
input.checked = previous;
|
||||
Adminx.Toast.show(Adminx.t('server_unavailable', 'Сервер недоступен. Повторите попытку.'), 'error');
|
||||
}).then(function () {
|
||||
input.disabled = false;
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ //
|
||||
// Меню пользователя в подвале сайдбара. Сайдбар имеет overflow:hidden,
|
||||
// поэтому всплывающее меню позиционируем fixed вручную (над триггером),
|
||||
@@ -977,6 +1024,7 @@
|
||||
Adminx.Sidebar.init();
|
||||
Adminx.Theme.init();
|
||||
Adminx.Dropdown.init();
|
||||
Adminx.NotificationPreferences.init();
|
||||
Adminx.SidebarUser.init();
|
||||
Adminx.Tabs.init();
|
||||
Adminx.Drawer.init();
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
|
||||
function normalizeMode(mode) {
|
||||
if (!mode) { return 'htmlmixed'; }
|
||||
if (mode === 'html') { return 'htmlmixed'; }
|
||||
if (mode === 'php') { return 'application/x-httpd-php'; }
|
||||
if (mode === 'smarty') { return 'smartymixed'; }
|
||||
if (mode === 'js') { return 'text/javascript'; }
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,73 @@
|
||||
import { Extension } from '@tiptap/core';
|
||||
import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state';
|
||||
import { Decoration, DecorationSet } from '@tiptap/pm/view';
|
||||
import { closeHistory } from '@tiptap/pm/history';
|
||||
|
||||
export const searchKey = new PluginKey('richSearch');
|
||||
|
||||
export function findMatches(doc, query, sensitive) {
|
||||
if (!query) { return []; }
|
||||
const matches = [];
|
||||
const pattern = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), sensitive ? 'g' : 'gi');
|
||||
doc.descendants((node, pos) => {
|
||||
if (!node.isTextblock) { return; }
|
||||
// Leaf nodes occupy one ProseMirror position; never match across them.
|
||||
const text = node.textBetween(0, node.content.size, '', '\ufffc');
|
||||
let found;
|
||||
while ((found = pattern.exec(text))) {
|
||||
if (!found[0].includes('\ufffc')) { matches.push({ from: pos + 1 + found.index, to: pos + 1 + found.index + found[0].length }); }
|
||||
}
|
||||
return false;
|
||||
});
|
||||
return matches;
|
||||
}
|
||||
|
||||
export const RichSearch = Extension.create({
|
||||
name: 'richSearch',
|
||||
addProseMirrorPlugins() {
|
||||
return [new Plugin({
|
||||
key: searchKey,
|
||||
state: {
|
||||
init: () => ({ query: '', sensitive: false, active: 0, matches: [] }),
|
||||
apply(tr, previous) {
|
||||
const state = { ...previous, ...(tr.getMeta(searchKey) || {}) };
|
||||
if (tr.docChanged || tr.getMeta(searchKey)) { state.matches = findMatches(tr.doc, state.query, state.sensitive); }
|
||||
state.active = Math.max(0, Math.min(state.active, state.matches.length - 1));
|
||||
return state;
|
||||
}
|
||||
},
|
||||
props: {
|
||||
decorations(state) {
|
||||
const search = searchKey.getState(state);
|
||||
return DecorationSet.create(state.doc, search.matches.map((match, index) => Decoration.inline(match.from, match.to, { class: index === search.active ? 'rich-search-match is-current' : 'rich-search-match' })));
|
||||
}
|
||||
}
|
||||
})];
|
||||
}
|
||||
});
|
||||
|
||||
export const ContentFragments = Extension.create({
|
||||
name: 'contentFragments',
|
||||
addGlobalAttributes() {
|
||||
return [{ types: ['blockquote'], attributes: { class: {
|
||||
default: null,
|
||||
parseHTML: element => {
|
||||
const name = element.getAttribute('class') || '';
|
||||
return /\bcontent-callout(?:--(?:warning|info))?\b/.test(name) ? name : null;
|
||||
}
|
||||
} } }];
|
||||
}
|
||||
});
|
||||
|
||||
export function moveBlock(editor, fromIndex, toIndex) {
|
||||
const blocks = [];
|
||||
editor.state.doc.forEach((node, pos) => blocks.push({ node, pos }));
|
||||
if (!blocks[fromIndex] || toIndex < 0 || toIndex > blocks.length || fromIndex === toIndex || fromIndex + 1 === toIndex) { return false; }
|
||||
const source = blocks[fromIndex];
|
||||
let target = toIndex === blocks.length ? editor.state.doc.content.size : blocks[toIndex].pos;
|
||||
if (target > source.pos) { target -= source.node.nodeSize; }
|
||||
const tr = closeHistory(editor.state.tr).delete(source.pos, source.pos + source.node.nodeSize).insert(target, source.node);
|
||||
tr.setSelection(TextSelection.near(tr.doc.resolve(target))).scrollIntoView();
|
||||
editor.view.dispatch(tr);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { toolDialog } from './_rich-tools';
|
||||
|
||||
export function installRecovery(api, root, textarea, editor) {
|
||||
const form = textarea.form;
|
||||
// Documents own a full-form draft already, including rich editors and source mode.
|
||||
if (form && form.querySelector('[data-document-draft-recovery]')) { return; }
|
||||
const actor = (form && form.dataset.actorId) || document.querySelector('[data-attention-user]')?.dataset.attentionUser;
|
||||
if (!actor || actor === '0' || !textarea.name) { return; }
|
||||
const key = 'ave.rich-draft:' + actor + ':' + location.pathname + location.search + ':' + (form?.id || form?.getAttribute('action') || '') + ':' + textarea.name;
|
||||
const baseline = textarea.value;
|
||||
let candidate;
|
||||
let timer;
|
||||
let disposed = false;
|
||||
const remove = () => { try { localStorage.removeItem(key); } catch (e) {} };
|
||||
try {
|
||||
candidate = JSON.parse(localStorage.getItem(key) || 'null');
|
||||
if (candidate && (typeof candidate.html !== 'string' || Date.now() - candidate.saved > 7 * 86400000 || candidate.html === baseline)) { remove(); candidate = null; }
|
||||
} catch (e) { candidate = null; }
|
||||
const banner = document.createElement('div');
|
||||
banner.className = 'rich-recovery';
|
||||
banner.hidden = !candidate;
|
||||
banner.innerHTML = '<span>Найден несохранённый текст</span><button type="button" class="btn btn-secondary btn-sm" data-recover>Посмотреть</button><button type="button" class="btn btn-ghost btn-icon btn-sm" aria-label="Удалить локальную копию" data-discard><i class="ti ti-trash"></i></button>';
|
||||
root.querySelector('.rich-editor-toolbar').after(banner);
|
||||
banner.querySelector('[data-discard]').addEventListener('click', () => { candidate = null; banner.hidden = true; remove(); });
|
||||
banner.querySelector('[data-recover]').addEventListener('click', () => {
|
||||
if (!candidate) { return; }
|
||||
const dialog = toolDialog('Восстановить текст', '<div class="rich-recovery-compare"><label class="field"><span class="field-label">Сейчас на сервере</span><textarea class="textarea" readonly data-current></textarea></label><label class="field"><span class="field-label">Локальная копия</span><textarea class="textarea" readonly data-local></textarea></label></div>', editor);
|
||||
dialog.body.querySelector('[data-current]').value = baseline;
|
||||
dialog.body.querySelector('[data-local]').value = candidate.html;
|
||||
const restore = document.createElement('button');
|
||||
restore.type = 'button'; restore.className = 'btn btn-primary'; restore.textContent = 'Восстановить в редактор';
|
||||
restore.addEventListener('click', () => { api.replaceHtml(textarea, candidate.html); candidate = null; banner.hidden = true; dialog.close(); });
|
||||
dialog.footer.appendChild(restore);
|
||||
});
|
||||
const save = () => {
|
||||
clearTimeout(timer);
|
||||
if (disposed || candidate || editor.isDestroyed) { return; }
|
||||
const html = api.syncTextarea(textarea, editor);
|
||||
if (html === baseline) { remove(); return; }
|
||||
if (html.length > 1000000) { return; }
|
||||
try { localStorage.setItem(key, JSON.stringify({ html, saved: Date.now() })); } catch (e) {}
|
||||
};
|
||||
const schedule = () => { clearTimeout(timer); timer = setTimeout(save, 700); };
|
||||
textarea.addEventListener('input', schedule);
|
||||
window.addEventListener('pagehide', save);
|
||||
const acknowledged = () => { clearTimeout(timer); remove(); };
|
||||
if (form) { form.addEventListener('rich:saved', acknowledged); }
|
||||
editor.on('destroy', () => {
|
||||
disposed = true; clearTimeout(timer);
|
||||
textarea.removeEventListener('input', schedule);
|
||||
window.removeEventListener('pagehide', save);
|
||||
if (form) { form.removeEventListener('rich:saved', acknowledged); }
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import { searchKey, moveBlock } from './_rich-extensions';
|
||||
import { closeHistory } from '@tiptap/pm/history';
|
||||
|
||||
const escape = value => String(value == null ? '' : value).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
export const tr = value => window.Adminx.tr ? window.Adminx.tr(value) : value;
|
||||
const button = (action, title, icon, text = '') => `<button type="button" class="btn btn-ghost btn-icon btn-sm" data-tool="${action}" aria-label="${escape(tr(title))}" data-tooltip="${escape(tr(title))}"><i class="ti ti-${icon}"></i>${escape(text)}</button>`;
|
||||
|
||||
export function readOptions(textarea) {
|
||||
let options = {};
|
||||
try { options = JSON.parse(textarea.getAttribute('data-rich-options') || '{}'); } catch (e) {}
|
||||
const profile = options.profile || (textarea.getAttribute('data-rich-preset') === 'slim' ? 'compact' : 'full');
|
||||
let headings = options.headings || 'profile';
|
||||
if (headings === 'profile') { headings = ['product', 'news'].includes(profile) ? 'no_h1' : 'all'; }
|
||||
return { ...options, profile, headings, product: !!textarea.closest('[data-catalog-mode="1"]'), snippets: options.snippets || 'all' };
|
||||
}
|
||||
|
||||
// One reusable dialog for the editor tools; content is trusted markup, values are escaped.
|
||||
export function toolDialog(title, content, editor, onClose) {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'overlay rich-editor-tools-overlay show';
|
||||
overlay.innerHTML = `<div class="modal rich-tools-modal" role="dialog" aria-modal="true" aria-label="${escape(tr(title))}"><div class="modal-header"><h3>${escape(tr(title))}</h3><button class="modal-close" type="button" data-tools-close aria-label="${escape(tr('Закрыть'))}"><i class="ti ti-x"></i></button></div><div class="modal-body">${content}</div><div class="modal-footer"><button class="btn btn-secondary" type="button" data-tools-close>${escape(tr('Закрыть'))}</button></div></div>`;
|
||||
document.body.appendChild(overlay);
|
||||
let closed = false;
|
||||
const previous = document.activeElement;
|
||||
const close = () => {
|
||||
if (closed) { return; }
|
||||
closed = true;
|
||||
if (editor) { editor.off('destroy', close); }
|
||||
document.removeEventListener('keydown', key, true);
|
||||
overlay.remove();
|
||||
if (onClose) { onClose(); }
|
||||
if (previous && previous.isConnected) { previous.focus({ preventScroll: true }); }
|
||||
};
|
||||
const key = event => {
|
||||
if (event.key === 'Escape') { event.preventDefault(); event.stopImmediatePropagation(); close(); }
|
||||
if (event.key === 'Tab') {
|
||||
const nodes = Array.from(overlay.querySelectorAll('button:not(:disabled),input,select,textarea,a[href]')).filter(node => !node.hidden && node.getClientRects().length);
|
||||
if (!nodes.length) { return; }
|
||||
const index = nodes.indexOf(document.activeElement);
|
||||
event.preventDefault();
|
||||
nodes[(index + (event.shiftKey ? nodes.length - 1 : 1)) % nodes.length].focus();
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', key, true);
|
||||
if (editor) { editor.on('destroy', close); }
|
||||
overlay.addEventListener('click', event => { if (event.target === overlay || event.target.closest('[data-tools-close]')) { close(); } });
|
||||
const first = overlay.querySelector('.modal-body input, .modal-body select, .modal-body button, .modal-close');
|
||||
if (first) { first.focus(); }
|
||||
return { overlay, close, body: overlay.querySelector('.modal-body'), footer: overlay.querySelector('.modal-footer') };
|
||||
}
|
||||
|
||||
export function openSearch(editor) {
|
||||
const dialog = toolDialog('Найти и заменить', `<label class="field"><span class="field-label">${tr('Найти')}</span><input class="input" data-find autocomplete="off"></label><label class="field"><span class="field-label">${tr('Заменить на')}</span><input class="input" data-replace autocomplete="off"></label><label class="checkbox"><input type="checkbox" data-case> ${tr('Учитывать регистр')}</label><div class="rich-tools-actions">${button('prev', 'Предыдущее', 'arrow-up')}${button('next', 'Следующее', 'arrow-down')}<output data-find-count aria-live="polite"></output></div><div class="rich-tools-actions"><button type="button" class="btn btn-secondary" data-replace-one>${tr('Заменить')}</button><button type="button" class="btn btn-secondary" data-replace-all>${tr('Заменить все')}</button></div>`, editor, () => {
|
||||
editor.off('transaction', updateCount);
|
||||
if (!editor.isDestroyed) { editor.view.dispatch(editor.state.tr.setMeta(searchKey, { query: '' })); }
|
||||
});
|
||||
const query = dialog.body.querySelector('[data-find]');
|
||||
const replacement = dialog.body.querySelector('[data-replace]');
|
||||
const sensitive = dialog.body.querySelector('[data-case]');
|
||||
function updateCount() {
|
||||
const state = searchKey.getState(editor.state);
|
||||
dialog.body.querySelector('[data-find-count]').textContent = state.matches.length ? `${state.active + 1} / ${state.matches.length}` : tr('Нет совпадений');
|
||||
dialog.body.querySelectorAll('[data-replace-one],[data-replace-all],[data-tool]').forEach(node => { node.disabled = !state.matches.length; });
|
||||
}
|
||||
function search() { editor.view.dispatch(editor.state.tr.setMeta(searchKey, { query: query.value, sensitive: sensitive.checked, active: 0 })); }
|
||||
function next(step) {
|
||||
const state = searchKey.getState(editor.state);
|
||||
if (!state.matches.length) { return; }
|
||||
const active = (state.active + step + state.matches.length) % state.matches.length;
|
||||
editor.view.dispatch(editor.state.tr.setMeta(searchKey, { active }));
|
||||
const node = editor.view.dom.querySelector('.rich-search-match.is-current');
|
||||
if (node) { node.scrollIntoView({ block: 'nearest' }); }
|
||||
}
|
||||
query.addEventListener('input', search);
|
||||
sensitive.addEventListener('change', search);
|
||||
query.addEventListener('keydown', event => { if (event.key === 'Enter') { event.preventDefault(); next(event.shiftKey ? -1 : 1); } });
|
||||
dialog.body.addEventListener('click', event => {
|
||||
const control = event.target.closest('button');
|
||||
if (!control || control.disabled) { return; }
|
||||
if (control.dataset.tool) { next(control.dataset.tool === 'prev' ? -1 : 1); return; }
|
||||
const state = searchKey.getState(editor.state);
|
||||
const matches = control.hasAttribute('data-replace-all') ? state.matches : [state.matches[state.active]];
|
||||
const transaction = closeHistory(editor.state.tr);
|
||||
matches.slice().reverse().forEach(match => {
|
||||
// Insert plain text with the first character's marks, never parse replacement as HTML.
|
||||
if (replacement.value) { transaction.replaceWith(match.from, match.to, editor.schema.text(replacement.value, transaction.doc.nodeAt(match.from)?.marks || [])); }
|
||||
else { transaction.delete(match.from, match.to); }
|
||||
});
|
||||
editor.view.dispatch(transaction);
|
||||
editor.view.dispatch(closeHistory(editor.state.tr));
|
||||
});
|
||||
editor.on('transaction', updateCount);
|
||||
const selected = editor.state.doc.textBetween(editor.state.selection.from, editor.state.selection.to, ' ');
|
||||
query.value = selected;
|
||||
search();
|
||||
}
|
||||
|
||||
export function openSymbols(editor) {
|
||||
const selection = { from: editor.state.selection.from, to: editor.state.selection.to };
|
||||
const symbols = [['\u00a0', 'Неразрывный пробел'], ['°', 'Градус'], ['×', 'Умножение'], ['±', 'Плюс-минус'], ['®', 'Зарегистрированный знак'], ['©', 'Авторское право'], ['™', 'Товарный знак'], ['≤', 'Меньше или равно'], ['≥', 'Больше или равно'], ['µ', 'Микро'], ['²', 'Квадрат'], ['³', 'Куб'], ['«', 'Открывающая кавычка'], ['»', 'Закрывающая кавычка'], ['–', 'Короткое тире'], ['—', 'Длинное тире'], ['…', 'Многоточие']];
|
||||
const dialog = toolDialog('Специальные символы', `<div class="rich-symbols">${symbols.map(([symbol, name], index) => `<button type="button" class="btn btn-secondary" data-symbol="${index}" aria-label="${escape(tr(name))}" data-tooltip="${escape(tr(name))}">${index ? escape(symbol) : '␣'}</button>`).join('')}</div>`, editor);
|
||||
dialog.body.addEventListener('click', event => {
|
||||
const item = event.target.closest('[data-symbol]');
|
||||
if (!item) { return; }
|
||||
editor.chain().focus().insertContentAt(selection, { type: 'text', text: symbols[Number(item.dataset.symbol)][0] }).run();
|
||||
dialog.close();
|
||||
});
|
||||
}
|
||||
|
||||
const snippets = [
|
||||
{ id: 'warning', title: 'Внимание', group: 'info', html: '<blockquote class="content-callout content-callout--warning"><p><strong>Внимание</strong></p><p>Текст предупреждения.</p></blockquote>' },
|
||||
{ id: 'important', title: 'Важно', group: 'info', html: '<blockquote class="content-callout content-callout--info"><p><strong>Важно</strong></p><p>Дополнительная информация.</p></blockquote>' },
|
||||
{ id: 'equipment', title: 'Комплектация', group: 'product', html: '<h2>Комплектация</h2><ul><li><p>Наименование позиции</p></li></ul>' },
|
||||
{ id: 'specs', title: 'Таблица характеристик', group: 'product', html: '<h2>Характеристики</h2><table><tr><th><p>Параметр</p></th><th><p>Значение</p></th></tr><tr><td><p>Наименование</p></td><td><p>Значение</p></td></tr></table>' }
|
||||
];
|
||||
|
||||
export function openSnippets(editor, options) {
|
||||
const selection = { from: editor.state.selection.from, to: editor.state.selection.to };
|
||||
const available = options.snippets === 'none' ? [] : snippets.filter(item => options.snippets === 'all' || item.group === options.snippets).filter(item => !options.hide_table || item.id !== 'specs');
|
||||
const dialog = toolDialog('Готовые фрагменты', `<div class="rich-snippets">${available.map(item => `<button type="button" class="btn btn-secondary" data-snippet="${item.id}"><i class="ti ti-${item.id === 'specs' ? 'table' : 'template'}"></i>${escape(tr(item.title))}</button>`).join('')}</div>`, editor);
|
||||
dialog.body.addEventListener('click', event => {
|
||||
const control = event.target.closest('[data-snippet]');
|
||||
const item = control && available.find(candidate => candidate.id === control.dataset.snippet);
|
||||
if (!item) { return; }
|
||||
editor.chain().focus().insertContentAt(selection, item.html).run();
|
||||
dialog.close();
|
||||
});
|
||||
}
|
||||
|
||||
export function openBlocks(editor) {
|
||||
const dialog = toolDialog('Порядок блоков', '<div class="rich-block-list" data-block-list></div>', editor, () => editor.off('update', render));
|
||||
const list = dialog.body.firstElementChild;
|
||||
let dragged = null;
|
||||
function render() {
|
||||
const rows = [];
|
||||
editor.state.doc.forEach((node, pos, index) => {
|
||||
const names = { paragraph: 'Абзац', heading: 'Заголовок', bulletList: 'Список', orderedList: 'Нумерованный список', blockquote: 'Цитата', image: 'Изображение', table: 'Таблица', horizontalRule: 'Разделитель', codeBlock: 'Код' };
|
||||
const title = node.type.name === 'heading' ? `H${node.attrs.level}` : tr(names[node.type.name] || node.type.name);
|
||||
rows.push(`<div class="rich-block-row" draggable="true" data-block-index="${index}"><i class="ti ti-grip-vertical" aria-hidden="true"></i><span><b>${escape(title)}</b><small>${escape((node.textContent || node.attrs.alt || node.attrs.src || '').slice(0, 120))}</small></span>${button('up', 'Переместить вверх', 'arrow-up')}${button('down', 'Переместить вниз', 'arrow-down')}</div>`);
|
||||
});
|
||||
list.innerHTML = rows.join('');
|
||||
if (list.firstElementChild) { list.firstElementChild.querySelector('[data-tool=up]').disabled = true; list.lastElementChild.querySelector('[data-tool=down]').disabled = true; }
|
||||
}
|
||||
list.addEventListener('dragstart', event => {
|
||||
const row = event.target.closest('[data-block-index]');
|
||||
if (!row) { return; }
|
||||
dragged = Number(row.dataset.blockIndex);
|
||||
event.dataTransfer.effectAllowed = 'move';
|
||||
event.dataTransfer.setData('text/plain', String(dragged));
|
||||
});
|
||||
list.addEventListener('dragover', event => { if (dragged !== null) { event.preventDefault(); event.dataTransfer.dropEffect = 'move'; } });
|
||||
list.addEventListener('drop', event => {
|
||||
if (dragged === null) { return; }
|
||||
event.preventDefault();
|
||||
const row = event.target.closest('[data-block-index]');
|
||||
let target = editor.state.doc.childCount;
|
||||
if (row) { target = Number(row.dataset.blockIndex) + (event.clientY > row.getBoundingClientRect().top + row.offsetHeight / 2 ? 1 : 0); }
|
||||
moveBlock(editor, dragged, target);
|
||||
dragged = null;
|
||||
});
|
||||
list.addEventListener('dragend', () => { dragged = null; });
|
||||
list.addEventListener('click', event => {
|
||||
const control = event.target.closest('[data-tool]');
|
||||
if (!control || control.disabled) { return; }
|
||||
const index = Number(control.closest('[data-block-index]').dataset.blockIndex);
|
||||
moveBlock(editor, index, control.dataset.tool === 'up' ? index - 1 : index + 2);
|
||||
});
|
||||
editor.on('update', render);
|
||||
render();
|
||||
}
|
||||
|
||||
export function inspectHtml(html, options) {
|
||||
const doc = new DOMParser().parseFromString(html, 'text/html');
|
||||
const issues = [];
|
||||
doc.body.querySelectorAll('*').forEach(node => {
|
||||
const tag = node.tagName;
|
||||
const sample = node.textContent.trim().slice(0, 90);
|
||||
if (tag === 'H1' && (options.product || options.headings !== 'all')) { issues.push({ node, kind: 'heading', title: 'H1 в тексте', sample }); }
|
||||
else if (/^H[1-6]$/.test(tag) && !node.textContent.trim() && !node.querySelector('img')) { issues.push({ node, kind: 'empty', title: 'Пустой заголовок', sample }); }
|
||||
if (tag === 'A' && (!(node.getAttribute('href') || '').trim() || (!node.textContent.trim() && !node.querySelector('img')))) { issues.push({ node, kind: 'link', title: 'Пустая ссылка', sample }); }
|
||||
if (node.hasAttribute('style')) { issues.push({ node, kind: 'style', title: 'Встроенное оформление', sample: `${sample} (${node.getAttribute('style')})`.slice(0, 140) }); }
|
||||
if (tag === 'P' && !node.textContent.trim() && !node.querySelector('img,table') && node.previousElementSibling && node.previousElementSibling.tagName === 'P' && !node.previousElementSibling.textContent.trim()) { issues.push({ node, kind: 'empty', title: 'Лишний пустой абзац', sample }); }
|
||||
});
|
||||
return { doc, issues };
|
||||
}
|
||||
|
||||
export function openReview(editor, textarea, options) {
|
||||
const api = window.Adminx.RichEditor;
|
||||
const dialog = toolDialog('Проверка оформления', '<div data-review-list></div>', editor);
|
||||
function render() {
|
||||
const result = inspectHtml(api.syncTextarea(textarea, editor), options);
|
||||
dialog.body.firstElementChild.innerHTML = result.issues.length ? result.issues.map((issue, index) => `<div class="rich-review-row"><span><b>${escape(tr(issue.title))}</b><small>${escape(issue.sample)}</small></span><button type="button" class="btn btn-secondary btn-sm" data-fix="${index}">${tr('Исправить')}</button></div>`).join('') : `<div class="rich-tools-empty"><i class="ti ti-circle-check"></i>${tr('Замечаний нет')}</div>`;
|
||||
dialog.body.querySelectorAll('[data-fix]').forEach(control => control.addEventListener('click', () => {
|
||||
const issue = result.issues[Number(control.dataset.fix)];
|
||||
if (issue.kind === 'style') { issue.node.removeAttribute('style'); }
|
||||
if (issue.kind === 'empty') { issue.node.remove(); }
|
||||
if (issue.kind === 'link') { issue.node.replaceWith(...Array.from(issue.node.childNodes)); }
|
||||
if (issue.kind === 'heading') {
|
||||
const heading = result.doc.createElement('h2');
|
||||
Array.from(issue.node.attributes).forEach(attr => heading.setAttribute(attr.name, attr.value));
|
||||
while (issue.node.firstChild) { heading.appendChild(issue.node.firstChild); }
|
||||
issue.node.replaceWith(heading);
|
||||
}
|
||||
api.replaceHtml(textarea, result.doc.body.innerHTML);
|
||||
render();
|
||||
}));
|
||||
}
|
||||
render();
|
||||
}
|
||||
|
||||
export function reviewBeforeSave(form, done) {
|
||||
const fields = Array.from(form.querySelectorAll('textarea[data-rich-editor]')).filter(node => node._adminxTiptap && !node._adminxTiptap.isDestroyed);
|
||||
const issues = fields.map(field => ({ field, result: inspectHtml(window.Adminx.RichEditor.syncTextarea(field, field._adminxTiptap), readOptions(field)) })).filter(item => item.result.issues.length);
|
||||
if (!issues.length) { return false; }
|
||||
const dialog = toolDialog('Проверьте оформление', `<div class="rich-review-summary">${issues.map((item, index) => `<div class="rich-review-row"><span><b>${escape(item.field.closest('.ax-document-field')?.querySelector('.field-label')?.textContent || item.field.name || tr('Текст'))}</b><small>${escape(item.result.issues.map(issue => tr(issue.title)).filter((v, i, a) => a.indexOf(v) === i).join(', '))}</small></span><button type="button" class="btn btn-secondary btn-sm" data-check-field="${index}">${tr('Проверить')}</button></div>`).join('')}</div>`, null);
|
||||
const save = document.createElement('button');
|
||||
save.type = 'button'; save.className = 'btn btn-primary'; save.textContent = tr('Сохранить без исправлений');
|
||||
save.addEventListener('click', () => { dialog.close(); done(); });
|
||||
dialog.footer.appendChild(save);
|
||||
dialog.body.addEventListener('click', event => {
|
||||
const control = event.target.closest('[data-check-field]');
|
||||
if (!control) { return; }
|
||||
const field = issues[Number(control.dataset.checkField)].field;
|
||||
dialog.close();
|
||||
openReview(field._adminxTiptap, field, readOptions(field));
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
export function installTools(api, root, textarea, editor, options) {
|
||||
const footer = document.createElement('div');
|
||||
footer.className = 'rich-editor-status';
|
||||
root.appendChild(footer);
|
||||
const tablebar = document.createElement('div');
|
||||
tablebar.className = 'rich-table-tools';
|
||||
tablebar.hidden = true;
|
||||
const commands = [
|
||||
['addRowBefore', 'Строка выше', 'row-insert-top'], ['addRowAfter', 'Строка ниже', 'row-insert-bottom'], ['deleteRow', 'Удалить строку', 'row-remove'],
|
||||
['addColumnBefore', 'Столбец слева', 'column-insert-left'], ['addColumnAfter', 'Столбец справа', 'column-insert-right'], ['deleteColumn', 'Удалить столбец', 'column-remove'],
|
||||
['mergeCells', 'Объединить ячейки', 'table-alias'], ['splitCell', 'Разделить ячейку', 'table-options'], ['toggleHeaderRow', 'Строка заголовков', 'table-row'], ['toggleHeaderColumn', 'Столбец заголовков', 'table-column'], ['deleteTable', 'Удалить таблицу', 'table-minus']
|
||||
];
|
||||
tablebar.innerHTML = commands.map(([name, title, icon]) => button(name, title, icon)).join('');
|
||||
root.querySelector('.rich-editor-toolbar').after(tablebar);
|
||||
tablebar.addEventListener('mousedown', event => event.preventDefault());
|
||||
tablebar.addEventListener('click', event => { const control = event.target.closest('[data-tool]'); if (control && !control.disabled) { editor.chain().focus()[control.dataset.tool]().run(); } });
|
||||
let lastDoc;
|
||||
let total = '';
|
||||
const stats = value => `${tr('Слов')}: ${(value.trim().match(/\S+/gu) || []).length} · ${tr('Символов')}: ${Array.from(value).length}`;
|
||||
function update() {
|
||||
const source = root.classList.contains('rich-editor-source-open');
|
||||
tablebar.hidden = source || !editor.isActive('table') || options.hide_table;
|
||||
if (!tablebar.hidden) { commands.forEach(([name]) => { tablebar.querySelector(`[data-tool="${name}"]`).disabled = !editor.can()[name](); }); }
|
||||
const selected = editor.state.doc.textBetween(editor.state.selection.from, editor.state.selection.to, ' ');
|
||||
if (source && root._richSourceEditor) {
|
||||
total = stats(new DOMParser().parseFromString(root._richSourceEditor.getValue(), 'text/html').body.textContent);
|
||||
lastDoc = null;
|
||||
} else if (lastDoc !== editor.state.doc) {
|
||||
lastDoc = editor.state.doc;
|
||||
total = stats(lastDoc.textBetween(0, lastDoc.content.size, ' '));
|
||||
}
|
||||
footer.textContent = total + (!source && selected ? ' | ' + tr('Выделено') + ': ' + stats(selected) : '');
|
||||
}
|
||||
editor.on('transaction', update);
|
||||
root.addEventListener('rich:source-change', update);
|
||||
root.addEventListener('rich:mode-change', update);
|
||||
update();
|
||||
editor.on('destroy', () => { editor.off('transaction', update); root.removeEventListener('rich:source-change', update); root.removeEventListener('rich:mode-change', update); });
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// Clipboard HTML is parsed in an inert document, never inserted into the live DOM.
|
||||
export function isWordHtml(html) {
|
||||
return /\bmso-|class=["']?Mso|urn:schemas-microsoft-com:office|Microsoft Word/i.test(html);
|
||||
}
|
||||
|
||||
function normalizeClipboardDocument(doc) {
|
||||
doc.querySelectorAll('br.Apple-interchange-newline, br.ProseMirror-trailingBreak').forEach(node => node.remove());
|
||||
const block = /^(?:BODY|DIV|SECTION|ARTICLE|MAIN|P|H[1-6]|BLOCKQUOTE|PRE|UL|OL|LI|TABLE|THEAD|TBODY|TFOOT|TR|TD|TH|HR)$/;
|
||||
const whitespace = doc.createTreeWalker(doc.body, NodeFilter.SHOW_TEXT);
|
||||
const remove = [];
|
||||
while (whitespace.nextNode()) {
|
||||
const node = whitespace.currentNode;
|
||||
if (node.textContent.trim() || node.parentElement.closest('pre, code')) { continue; }
|
||||
// HTML indentation between blocks is not an empty paragraph or a hard break.
|
||||
if (block.test((node.previousSibling || {}).nodeName) || block.test((node.nextSibling || {}).nodeName)) {
|
||||
remove.push(node);
|
||||
}
|
||||
}
|
||||
remove.forEach(node => node.remove());
|
||||
|
||||
function padding(node) {
|
||||
if (node.nodeType === 3) { return !node.textContent.replace(/[\s\u200b\ufeff]/g, ''); }
|
||||
if (node.nodeType !== 1 || !/^(?:P|DIV|SPAN|BR)$/.test(node.nodeName)) { return false; }
|
||||
return !node.textContent.replace(/[\s\u200b\ufeff]/g, '') &&
|
||||
Array.from(node.querySelectorAll('*')).every(child => /^(?:P|DIV|SPAN|BR|STRONG|B|EM|I|U|S|STRIKE|DEL)$/.test(child.nodeName));
|
||||
}
|
||||
function trimEdge(parent, edge) {
|
||||
while (parent[edge] && padding(parent[edge])) { parent[edge].remove(); }
|
||||
const node = parent[edge];
|
||||
if (node && /^(?:DIV|SECTION|ARTICLE|MAIN)$/.test(node.nodeName)) { trimEdge(node, edge); }
|
||||
}
|
||||
// Trim only the fragment edges; intentional blank paragraphs inside it stay intact.
|
||||
if (Array.from(doc.body.children).some(node => block.test(node.nodeName)) &&
|
||||
Array.from(doc.body.childNodes).some(node => !padding(node))) {
|
||||
trimEdge(doc.body, 'firstChild');
|
||||
trimEdge(doc.body, 'lastChild');
|
||||
}
|
||||
return doc.body.innerHTML;
|
||||
}
|
||||
|
||||
export function cleanClipboardHtml(html) {
|
||||
return normalizeClipboardDocument(new DOMParser().parseFromString(html, 'text/html'));
|
||||
}
|
||||
|
||||
export function cleanWordHtml(html) {
|
||||
const doc = new DOMParser().parseFromString(html, 'text/html');
|
||||
doc.querySelectorAll('script,style,meta,link,iframe,object,embed,svg,math,form,input,button').forEach(node => node.remove());
|
||||
const comments = doc.createTreeWalker(doc.body, NodeFilter.SHOW_COMMENT);
|
||||
const remove = [];
|
||||
while (comments.nextNode()) { remove.push(comments.currentNode); }
|
||||
remove.forEach(node => node.remove());
|
||||
|
||||
doc.querySelectorAll('p').forEach(node => {
|
||||
const level = (node.className || '').match(/\bMsoHeading([1-6])\b/i) || (node.getAttribute('style') || '').match(/mso-outline-level:\s*([1-6])\b/i);
|
||||
if (!level) { return; }
|
||||
const heading = doc.createElement('h' + level[1]);
|
||||
while (node.firstChild) { heading.appendChild(node.firstChild); }
|
||||
node.replaceWith(heading);
|
||||
});
|
||||
|
||||
// Desktop Word exports list items as paragraphs with mso-list and marker spans.
|
||||
const lists = new Map();
|
||||
doc.querySelectorAll('p').forEach(node => {
|
||||
const style = node.getAttribute('style') || '';
|
||||
const match = style.match(/mso-list:\s*(l\d+)\s+level(\d+)\s+(lfo\d+)/i);
|
||||
if (!match) { return; }
|
||||
const marker = Array.from(node.querySelectorAll('span')).find(span => /mso-list:\s*ignore/i.test(span.getAttribute('style') || ''));
|
||||
const label = marker ? marker.textContent.trim() : '';
|
||||
const ordered = /^(?:\d+|[a-z]+)[.)]/i.test(label);
|
||||
lists.set(node, { key: match[1] + match[3], level: Number(match[2]), type: ordered ? 'ol' : 'ul', start: /^\d+/.test(label) ? parseInt(label, 10) : 1 });
|
||||
if (marker) { marker.remove(); }
|
||||
});
|
||||
const parents = new Set(Array.from(lists.keys()).map(node => node.parentNode));
|
||||
parents.forEach(parent => {
|
||||
let stack = [];
|
||||
let key = '';
|
||||
Array.from(parent.childNodes).forEach(node => {
|
||||
if (node.nodeType === 3 && !node.textContent.trim()) { return; }
|
||||
const item = lists.get(node);
|
||||
if (!item) { stack = []; key = ''; return; }
|
||||
if (key !== item.key) { stack = []; key = item.key; }
|
||||
while (stack.length && stack[stack.length - 1].level > item.level) { stack.pop(); }
|
||||
if (stack.length && stack[stack.length - 1].level === item.level && stack[stack.length - 1].type !== item.type) { stack.pop(); }
|
||||
if (!stack.length || stack[stack.length - 1].level < item.level) {
|
||||
const list = doc.createElement(item.type);
|
||||
if (item.type === 'ol' && item.start > 1) { list.setAttribute('start', item.start); }
|
||||
if (stack.length) { stack[stack.length - 1].last.appendChild(list); }
|
||||
else { parent.insertBefore(list, node); }
|
||||
stack.push({ level: item.level, type: item.type, list: list, last: null });
|
||||
}
|
||||
const li = doc.createElement('li');
|
||||
const entry = stack[stack.length - 1];
|
||||
entry.list.appendChild(li);
|
||||
li.appendChild(node);
|
||||
entry.last = li;
|
||||
});
|
||||
});
|
||||
|
||||
const allowed = new Set('p div br h1 h2 h3 h4 h5 h6 strong b em i u s strike del blockquote pre code ul ol li a table thead tbody tfoot tr td th hr'.split(' '));
|
||||
Array.from(doc.body.querySelectorAll('*')).reverse().forEach(node => {
|
||||
if (!node.parentNode) { return; }
|
||||
const tag = node.tagName.toLowerCase();
|
||||
// Convert meaningful inline formatting before stripping presentation attributes.
|
||||
const marks = [];
|
||||
const weight = node.style.fontWeight;
|
||||
if (weight === 'bold' || Number(weight) >= 600) { marks.push('strong'); }
|
||||
if (node.style.fontStyle === 'italic') { marks.push('em'); }
|
||||
const decoration = node.style.textDecoration;
|
||||
if (/underline/.test(decoration)) { marks.push('u'); }
|
||||
if (/line-through/.test(decoration)) { marks.push('s'); }
|
||||
marks.forEach(mark => {
|
||||
const wrapper = doc.createElement(mark);
|
||||
while (node.firstChild) { wrapper.appendChild(node.firstChild); }
|
||||
node.appendChild(wrapper);
|
||||
});
|
||||
Array.from(node.attributes).forEach(attr => {
|
||||
const name = attr.name.toLowerCase();
|
||||
const value = attr.value.trim();
|
||||
const safeLink = tag === 'a' && name === 'href' && /^(https?:\/\/|mailto:|tel:|\/|#)/i.test(value) && !/[\u0000-\u0020]/.test(value);
|
||||
const span = /^(td|th)$/.test(tag) && /^(colspan|rowspan)$/.test(name) && /^[1-9]\d{0,2}$/.test(value);
|
||||
const start = tag === 'ol' && name === 'start' && /^[1-9]\d{0,5}$/.test(value);
|
||||
if (!safeLink && !span && !start) { node.removeAttribute(attr.name); }
|
||||
});
|
||||
if (!allowed.has(tag)) {
|
||||
node.replaceWith(...Array.from(node.childNodes));
|
||||
}
|
||||
});
|
||||
return normalizeClipboardDocument(doc);
|
||||
}
|
||||
@@ -7,6 +7,10 @@ import TableRow from '@tiptap/extension-table-row';
|
||||
import TableCell from '@tiptap/extension-table-cell';
|
||||
import TableHeader from '@tiptap/extension-table-header';
|
||||
import TextAlign from '@tiptap/extension-text-align';
|
||||
import { isWordHtml, cleanWordHtml, cleanClipboardHtml } from './_word-paste';
|
||||
import { RichSearch, ContentFragments } from './_rich-extensions';
|
||||
import { tr, readOptions, openSearch, openSymbols, openSnippets, openBlocks, openReview, reviewBeforeSave, installTools } from './_rich-tools';
|
||||
import { installRecovery } from './_rich-recovery';
|
||||
|
||||
var EnhancedImage = Image.extend({
|
||||
addAttributes: function () {
|
||||
@@ -90,6 +94,8 @@ var EnhancedImage = Image.extend({
|
||||
|
||||
extensions: function () {
|
||||
return [
|
||||
RichSearch,
|
||||
ContentFragments,
|
||||
StarterKit.configure({ link: false }),
|
||||
Link.configure({
|
||||
openOnClick: false,
|
||||
@@ -107,8 +113,9 @@ var EnhancedImage = Image.extend({
|
||||
},
|
||||
|
||||
create: function (textarea) {
|
||||
var options = readOptions(textarea);
|
||||
var preset = textarea.getAttribute('data-rich-preset') || 'full';
|
||||
var root = el('div', { class: 'rich-editor rich-editor-' + preset });
|
||||
var root = el('div', { class: 'rich-editor rich-editor-' + preset + ' rich-editor-show-blocks' });
|
||||
var toolbar = el('div', { class: 'rich-editor-toolbar', role: 'toolbar' });
|
||||
var surface = el('div', { class: 'rich-editor-surface' });
|
||||
var editorEl = el('div', { class: 'rich-editor-content' });
|
||||
@@ -131,6 +138,9 @@ var EnhancedImage = Image.extend({
|
||||
extensions: this.extensions(),
|
||||
content: textarea.value || '',
|
||||
editorProps: {
|
||||
transformPastedHTML: function (html) {
|
||||
return isWordHtml(html) ? cleanWordHtml(html) : cleanClipboardHtml(html);
|
||||
},
|
||||
attributes: {
|
||||
class: 'rich-editor-prose',
|
||||
spellcheck: textarea.getAttribute('spellcheck') || 'true'
|
||||
@@ -155,15 +165,18 @@ var EnhancedImage = Image.extend({
|
||||
}
|
||||
});
|
||||
|
||||
this.buildToolbar(toolbar, editor);
|
||||
this.buildToolbar(toolbar, editor, options, textarea);
|
||||
textarea.setAttribute('data-rich-editor-ready', '1');
|
||||
textarea._adminxTiptap = editor;
|
||||
this.instances.push(editor);
|
||||
this.bindForm(textarea, editor);
|
||||
this.syncToolbar(root, editor);
|
||||
installTools(this, root, textarea, editor, options);
|
||||
installRecovery(this, root, textarea, editor);
|
||||
},
|
||||
|
||||
button: function (name, tooltip, iconName, run) {
|
||||
tooltip = tr(tooltip);
|
||||
var btn = el('button', {
|
||||
class: 'btn btn-ghost btn-icon btn-sm rich-editor-btn',
|
||||
type: 'button',
|
||||
@@ -175,7 +188,7 @@ var EnhancedImage = Image.extend({
|
||||
return btn;
|
||||
},
|
||||
|
||||
buildToolbar: function (toolbar, editor) {
|
||||
buildToolbar: function (toolbar, editor, options, textarea) {
|
||||
var group;
|
||||
var self = this;
|
||||
function addGroup() {
|
||||
@@ -183,6 +196,11 @@ var EnhancedImage = Image.extend({
|
||||
toolbar.appendChild(group);
|
||||
}
|
||||
function add(name, tooltip, iconName, run) {
|
||||
if (options.hide_image && name === 'image') { return; }
|
||||
if (options.hide_table && name === 'table') { return; }
|
||||
if (options.hide_source && name === 'source') { return; }
|
||||
if (options.hide_align && name.indexOf('align') === 0) { return; }
|
||||
if (options.profile === 'compact' && ['image', 'table', 'code', 'alignCenter', 'alignRight'].indexOf(name) !== -1) { return; }
|
||||
group.appendChild(self.button(name, tooltip, iconName, run));
|
||||
}
|
||||
function addBlockSelect() {
|
||||
@@ -201,16 +219,20 @@ var EnhancedImage = Image.extend({
|
||||
['heading-5', 'Заголовок H5'],
|
||||
['heading-6', 'Заголовок H6']
|
||||
].forEach(function (item) {
|
||||
if (item[0].indexOf('heading-') === 0 && (options.headings === 'none' || (options.headings === 'no_h1' && item[0] === 'heading-1'))) { return; }
|
||||
var option = el('option', { value: item[0] });
|
||||
option.textContent = item[1];
|
||||
select.appendChild(option);
|
||||
});
|
||||
select.addEventListener('change', function () {
|
||||
if (select.value === 'paragraph') {
|
||||
// Focusing in Safari/iOS synchronously refreshes the toolbar value.
|
||||
var block = select.value;
|
||||
var level = parseInt(block.replace('heading-', ''), 10);
|
||||
if (block === 'paragraph') {
|
||||
editor.chain().focus().setParagraph().run();
|
||||
return;
|
||||
}
|
||||
editor.chain().focus().setHeading({ level: parseInt(select.value.replace('heading-', ''), 10) }).run();
|
||||
editor.chain().focus().setHeading({ level: level }).run();
|
||||
});
|
||||
group.appendChild(select);
|
||||
}
|
||||
@@ -218,6 +240,7 @@ var EnhancedImage = Image.extend({
|
||||
addGroup();
|
||||
add('undo', 'Отменить', 'arrow-back-up', function () { editor.chain().focus().undo().run(); });
|
||||
add('redo', 'Повторить', 'arrow-forward-up', function () { editor.chain().focus().redo().run(); });
|
||||
add('pasteWord', 'Вставить из Word', 'clipboard-text', function () { self.openWordPaste(editor); });
|
||||
|
||||
addGroup();
|
||||
add('bold', 'Жирный', 'bold', function () { editor.chain().focus().toggleBold().run(); });
|
||||
@@ -238,6 +261,14 @@ var EnhancedImage = Image.extend({
|
||||
|
||||
addGroup();
|
||||
add('link', 'Ссылка', 'link', function () { self.openLink(editor); });
|
||||
add('documentLink', 'Ссылка на документ или товар', 'file-search', function () {
|
||||
var selection = { from: editor.state.selection.from, to: editor.state.selection.to };
|
||||
self.openDocumentLinkPicker(function (item) {
|
||||
var href = item.url || '/' + String(item.alias || '').replace(/^\/+/, '');
|
||||
if (selection.from !== selection.to) { editor.chain().focus().setTextSelection(selection).setLink({ href: href }).run(); }
|
||||
else { editor.chain().focus().insertContentAt(selection, { type: 'text', text: item.title || href, marks: [{ type: 'link', attrs: { href: href } }] }).run(); }
|
||||
});
|
||||
});
|
||||
add('image', 'Изображение', 'photo-plus', function () {
|
||||
self.openMediaPicker(editor);
|
||||
});
|
||||
@@ -252,10 +283,141 @@ var EnhancedImage = Image.extend({
|
||||
});
|
||||
|
||||
addGroup();
|
||||
add('fullscreen', 'Развернуть редактор', 'arrows-maximize', function () { self.toggleFullscreen(editor); });
|
||||
if (window.CodeMirror) {
|
||||
add('source', 'Исходник', 'code-dots', function () { self.openSource(editor); });
|
||||
}
|
||||
add('clear', 'Очистить формат', 'eraser', function () { editor.chain().focus().unsetAllMarks().clearNodes().run(); });
|
||||
addGroup();
|
||||
add('find', 'Найти и заменить', 'replace', function () { openSearch(editor); });
|
||||
add('symbols', 'Специальные символы', 'omega', function () { openSymbols(editor); });
|
||||
if (options.snippets !== 'none') { add('snippets', 'Готовые фрагменты', 'template', function () { openSnippets(editor, options); }); }
|
||||
if (!options.hide_blocks) { add('blocks', 'Порядок блоков', 'list-details', function () { openBlocks(editor); }); }
|
||||
add('review', 'Проверка оформления', 'text-spellcheck', function () { openReview(editor, textarea, options); });
|
||||
toolbar.querySelectorAll('.rich-editor-group').forEach(function (node) { if (!node.children.length) { node.remove(); } });
|
||||
},
|
||||
|
||||
reviewBeforeSave: reviewBeforeSave,
|
||||
|
||||
replaceHtml: function (textarea, html) {
|
||||
var editor = textarea._adminxTiptap;
|
||||
if (!editor || editor.isDestroyed) { return; }
|
||||
var root = textarea.closest('.rich-editor');
|
||||
editor.commands.setContent(html || '<p></p>');
|
||||
if (root && root._richSourceEditor) {
|
||||
root._richSourceSyncing = true;
|
||||
root._richSourceEditor.setValue(html);
|
||||
root._richSourceSyncing = false;
|
||||
}
|
||||
// Preserve source attributes Tiptap does not model until the next visual edit.
|
||||
textarea.value = html;
|
||||
textarea.removeAttribute('data-rich-editor-dirty');
|
||||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
},
|
||||
|
||||
toggleFullscreen: function (editor) {
|
||||
if (this.fullscreen && this.fullscreen.editor === editor) { this.fullscreen.close(); return; }
|
||||
if (this.fullscreen) { this.fullscreen.close(); }
|
||||
var self = this;
|
||||
var root = editor.view.dom.closest('.rich-editor');
|
||||
var ancestors = [];
|
||||
var scrollX = window.scrollX;
|
||||
var scrollY = window.scrollY;
|
||||
var parent = root.parentElement;
|
||||
// Keep the editor inside its form; transformed drawers must not clip fixed positioning.
|
||||
while (parent && parent !== document.body) {
|
||||
parent.classList.add('rich-editor-fullscreen-parent');
|
||||
ancestors.push(parent);
|
||||
parent = parent.parentElement;
|
||||
}
|
||||
root.classList.add('rich-editor-fullscreen');
|
||||
document.body.classList.add('rich-editor-fullscreen-open');
|
||||
function refresh() {
|
||||
if (root._richSourceEditor) { root._richSourceEditor.refresh(); }
|
||||
}
|
||||
function close() {
|
||||
if (!self.fullscreen || self.fullscreen.editor !== editor) { return; }
|
||||
root.classList.remove('rich-editor-fullscreen');
|
||||
ancestors.forEach(function (node) { node.classList.remove('rich-editor-fullscreen-parent'); });
|
||||
document.body.classList.remove('rich-editor-fullscreen-open');
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
window.removeEventListener('resize', refresh);
|
||||
observer.disconnect();
|
||||
editor.off('destroy', close);
|
||||
self.fullscreen = null;
|
||||
if (!editor.isDestroyed) { self.syncToolbar(root, editor); refresh(); }
|
||||
window.scrollTo(scrollX, scrollY);
|
||||
}
|
||||
function onKey(event) {
|
||||
if (event.key !== 'Escape') { return; }
|
||||
var childDialog = Array.from(document.querySelectorAll('.overlay.show, .rich-editor-tools-overlay, .rich-editor-word-overlay, .rich-editor-link-overlay, .rich-editor-image-overlay, .rich-editor-document-picker-overlay, .media-picker-overlay.show')).some(function (node) { return !node.contains(root); });
|
||||
if (childDialog) { return; }
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
close();
|
||||
}
|
||||
var observer = new MutationObserver(function () { if (!root.isConnected || editor.isDestroyed) { close(); } });
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
this.fullscreen = { editor: editor, close: close };
|
||||
editor.on('destroy', close);
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
window.addEventListener('resize', refresh);
|
||||
this.syncToolbar(root, editor);
|
||||
requestAnimationFrame(refresh);
|
||||
},
|
||||
|
||||
openWordPaste: function (editor) {
|
||||
var self = this;
|
||||
var selection = { from: editor.state.selection.from, to: editor.state.selection.to };
|
||||
var overlay = el('div', { class: 'overlay rich-editor-word-overlay' });
|
||||
var modal = el('div', { class: 'modal rich-editor-prompt', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'richEditorWordTitle' });
|
||||
modal.innerHTML = '<div class="modal-header"><span class="dialog-icon info"><i class="ti ti-clipboard-text"></i></span>' +
|
||||
'<div style="flex:1"><h3 id="richEditorWordTitle">Вставить из Word</h3></div>' +
|
||||
'<button class="modal-close" type="button" data-word-cancel aria-label="Закрыть"><i class="ti ti-x"></i></button></div>' +
|
||||
'<div class="modal-body"><textarea class="input" rows="8" style="width:100%;resize:vertical;min-height:180px" aria-label="Текст из Word" placeholder="Вставьте скопированный текст" data-word-input></textarea></div>' +
|
||||
'<div class="modal-footer"><button class="btn btn-ghost" type="button" data-word-cancel>Отмена</button><button class="btn btn-primary" type="button" data-word-apply disabled><i class="ti ti-check"></i>Вставить</button></div>';
|
||||
overlay.appendChild(modal);
|
||||
document.body.appendChild(overlay);
|
||||
var input = overlay.querySelector('[data-word-input]');
|
||||
var apply = overlay.querySelector('[data-word-apply]');
|
||||
var html = null;
|
||||
var closed = false;
|
||||
function close() {
|
||||
if (closed) { return; }
|
||||
closed = true;
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
overlay.remove();
|
||||
if (!editor.isDestroyed) { editor.commands.focus(); }
|
||||
}
|
||||
function onKey(event) {
|
||||
if (event.key === 'Escape') { event.preventDefault(); event.stopImmediatePropagation(); close(); }
|
||||
if (event.key === 'Tab') {
|
||||
var controls = Array.from(modal.querySelectorAll('button:not(:disabled),textarea'));
|
||||
var index = controls.indexOf(document.activeElement);
|
||||
event.preventDefault();
|
||||
controls[(index + (event.shiftKey ? controls.length - 1 : 1)) % controls.length].focus();
|
||||
}
|
||||
}
|
||||
input.addEventListener('paste', function (event) {
|
||||
var data = event.clipboardData;
|
||||
if (!data) { return; }
|
||||
event.preventDefault();
|
||||
var source = data.getData('text/html');
|
||||
html = source ? cleanWordHtml(source) : null;
|
||||
input.value = data.getData('text/plain') || (html ? new DOMParser().parseFromString(html, 'text/html').body.textContent : '');
|
||||
apply.disabled = !input.value.trim();
|
||||
});
|
||||
input.addEventListener('input', function () { html = null; apply.disabled = !input.value.trim(); });
|
||||
overlay.addEventListener('click', function (event) {
|
||||
if (event.target === overlay || event.target.closest('[data-word-cancel]')) { close(); return; }
|
||||
if (!event.target.closest('[data-word-apply]') || apply.disabled || editor.isDestroyed) { return; }
|
||||
editor.chain().focus().setTextSelection(selection).run();
|
||||
if (html !== null) { editor.view.pasteHTML(html); }
|
||||
else { editor.view.pasteText(input.value); }
|
||||
close();
|
||||
});
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
requestAnimationFrame(function () { if (!closed) { overlay.classList.add('show'); input.focus(); } });
|
||||
},
|
||||
|
||||
syncToolbar: function (root, editor) {
|
||||
@@ -278,12 +440,29 @@ var EnhancedImage = Image.extend({
|
||||
var btn = root.querySelector('[data-rich-command="' + name + '"]');
|
||||
if (btn) { btn.setAttribute('aria-pressed', states[name] ? 'true' : 'false'); }
|
||||
});
|
||||
var fullscreen = root.querySelector('[data-rich-command="fullscreen"]');
|
||||
if (fullscreen) {
|
||||
var expanded = root.classList.contains('rich-editor-fullscreen');
|
||||
var label = tr(expanded ? 'Свернуть редактор' : 'Развернуть редактор');
|
||||
fullscreen.setAttribute('aria-pressed', expanded ? 'true' : 'false');
|
||||
fullscreen.setAttribute('aria-label', label);
|
||||
fullscreen.setAttribute('data-tooltip', label);
|
||||
fullscreen.innerHTML = icon(expanded ? 'arrows-minimize' : 'arrows-maximize');
|
||||
}
|
||||
var blockSelect = root.querySelector('[data-rich-block-select]');
|
||||
if (blockSelect) {
|
||||
var blockValue = 'paragraph';
|
||||
for (var level = 1; level <= 6; level++) {
|
||||
if (editor.isActive('heading', { level: level })) { blockValue = 'heading-' + level; break; }
|
||||
}
|
||||
var currentOnly = blockSelect.querySelector('[data-rich-current-block]');
|
||||
if (currentOnly) { currentOnly.remove(); }
|
||||
if (!Array.from(blockSelect.options).some(function (option) { return option.value === blockValue; })) {
|
||||
var currentOption = el('option', { value: blockValue, 'data-rich-current-block': '' });
|
||||
currentOption.textContent = 'H' + blockValue.replace('heading-', '') + ' (' + tr('в тексте') + ')';
|
||||
currentOption.disabled = true;
|
||||
blockSelect.appendChild(currentOption);
|
||||
}
|
||||
blockSelect.value = blockValue;
|
||||
}
|
||||
},
|
||||
@@ -328,6 +507,7 @@ var EnhancedImage = Image.extend({
|
||||
root.classList.remove('rich-editor-source-open');
|
||||
this.setSourceControls(root, false);
|
||||
this.syncToolbar(root, editor);
|
||||
root.dispatchEvent(new Event('rich:mode-change'));
|
||||
editor.commands.focus();
|
||||
return;
|
||||
}
|
||||
@@ -352,23 +532,25 @@ var EnhancedImage = Image.extend({
|
||||
storage.value = cm.getValue();
|
||||
storage.setAttribute('data-rich-editor-dirty', '1');
|
||||
storage.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
root.dispatchEvent(new Event('rich:source-change'));
|
||||
});
|
||||
}
|
||||
|
||||
var height = Math.max(260, Math.round(surface.getBoundingClientRect().height || 0));
|
||||
root._richSourceSyncing = true;
|
||||
root._richSourceEditor.setValue(editor.getHTML());
|
||||
root._richSourceEditor.setValue(storage ? this.syncTextarea(storage, editor) : editor.getHTML());
|
||||
root._richSourceSyncing = false;
|
||||
root._richSourceEditor.setSize('100%', height);
|
||||
root.classList.add('rich-editor-source-open');
|
||||
this.setSourceControls(root, true);
|
||||
this.syncToolbar(root, editor);
|
||||
root.dispatchEvent(new Event('rich:mode-change'));
|
||||
setTimeout(function () { root._richSourceEditor.refresh(); root._richSourceEditor.focus(); }, 0);
|
||||
},
|
||||
|
||||
setSourceControls: function (root, sourceOpen) {
|
||||
root.querySelectorAll('.rich-editor-toolbar [data-rich-command], .rich-editor-toolbar [data-rich-block-select]').forEach(function (control) {
|
||||
if (control.getAttribute('data-rich-command') === 'source') { return; }
|
||||
if (['source', 'fullscreen'].indexOf(control.getAttribute('data-rich-command')) !== -1) { return; }
|
||||
control.disabled = !!sourceOpen;
|
||||
});
|
||||
},
|
||||
|
||||
+38
-4
@@ -62,6 +62,7 @@
|
||||
//-- Ядро: автозагрузчик, БД, сессии, настройки, Twig, хуки.
|
||||
include BASEPATH . DS . 'system' . DS . 'bootstrap.php';
|
||||
App::init();
|
||||
\App\Common\ResponseSecurityHeaders::apply(array('http://127.0.0.1:*', 'http://localhost:*'));
|
||||
|
||||
use App\Common\AdminAssets;
|
||||
use App\Common\Auth;
|
||||
@@ -172,6 +173,7 @@
|
||||
|
||||
$authUser && Auth::ensureBrowserToken();
|
||||
$canAdmin = $authUser !== null && Permission::checkAcp('admin_panel');
|
||||
$isAttentionPoll = $requestPath === '/dashboard/attention';
|
||||
$forcePasswordPath = in_array($requestPath, array('/account/password', '/logout', '/locale'), true);
|
||||
if ($canAdmin && !empty($authUser['must_change_password']) && !$forcePasswordPath) {
|
||||
if (Request::isAjax()) {
|
||||
@@ -207,6 +209,20 @@
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($navFlat['modules']['children'])) {
|
||||
usort($navFlat['modules']['children'], function ($left, $right) {
|
||||
$leftRegistry = isset($left['code']) && (string) $left['code'] === 'modules_registry';
|
||||
$rightRegistry = isset($right['code']) && (string) $right['code'] === 'modules_registry';
|
||||
if ($leftRegistry !== $rightRegistry) { return $leftRegistry ? -1 : 1; }
|
||||
$leftLabel = isset($left['label']) ? (string) $left['label'] : '';
|
||||
$rightLabel = isset($right['label']) ? (string) $right['label'] : '';
|
||||
$leftCyrillic = preg_match('/^\p{Cyrillic}/u', $leftLabel) === 1;
|
||||
$rightCyrillic = preg_match('/^\p{Cyrillic}/u', $rightLabel) === 1;
|
||||
if ($leftCyrillic !== $rightCyrillic) { return $leftCyrillic ? -1 : 1; }
|
||||
return strnatcasecmp($leftLabel, $rightLabel);
|
||||
});
|
||||
}
|
||||
|
||||
$commandPaletteItems = array();
|
||||
foreach ($navigationItems as $navItem) {
|
||||
if (!isset($navItem['url']) || (string) $navItem['url'] === '#') { continue; }
|
||||
@@ -220,7 +236,7 @@
|
||||
|
||||
$canClearCache = Permission::check('manage_settings');
|
||||
$cacheSizes = array();
|
||||
if ($canClearCache) {
|
||||
if ($canClearCache && !$isAttentionPoll) {
|
||||
$cacheSizes = Cache::remember('adminx.cache.sizes.' . md5((string) ADMINX_BASE), 30, function () {
|
||||
$out = array();
|
||||
foreach (\App\Adminx\Settings\Model::cacheRows() as $row) {
|
||||
@@ -237,7 +253,7 @@
|
||||
'user_name' => $authUser['name'] ?? '',
|
||||
'user_email' => $authUser['email'] ?? '',
|
||||
'user_role' => $authUser['role'] ?? '',
|
||||
'module_header_actions' => $canAdmin
|
||||
'module_header_actions' => $canAdmin && !$isAttentionPoll
|
||||
? \App\Adminx\Support\ModuleExtensions::headerActions()
|
||||
: array(),
|
||||
'can_clear_cache' => $canClearCache,
|
||||
@@ -249,7 +265,9 @@
|
||||
|
||||
//-- Сводка уведомлений в шапке (новые заказы/письма) — только для админа.
|
||||
$notifications = array('total' => 0, 'orders' => 0, 'messages' => 0, 'items' => array());
|
||||
if ($canAdmin) {
|
||||
$notificationPreferences = array();
|
||||
if ($canAdmin && !$isAttentionPoll) {
|
||||
$notificationPreferences = \App\Adminx\Support\ModuleExtensions::notificationPreferences();
|
||||
$notificationKey = 'adminx.notifications.' . (int) Auth::id() . '.' . md5((string) ADMINX_BASE);
|
||||
$notifications = Cache::remember($notificationKey, 15, function () {
|
||||
$summary = \App\Adminx\Support\Notifications::summary(ADMINX_BASE);
|
||||
@@ -257,7 +275,23 @@
|
||||
});
|
||||
}
|
||||
|
||||
Twig::addGlobal('notifications', $notifications);
|
||||
Twig::addGlobals(array(
|
||||
'notifications' => $notifications,
|
||||
'notification_preferences' => $notificationPreferences,
|
||||
'can_manage_notification_preferences' => Permission::check('manage_settings'),
|
||||
));
|
||||
|
||||
$attention = array('items' => array());
|
||||
$dashboardModule = \App\Common\ModuleManager::get('dashboard');
|
||||
if ($canAdmin && !empty($dashboardModule['enabled'])) {
|
||||
$attention = \App\Adminx\Dashboard\Attention::summary(ADMINX_BASE);
|
||||
if ($attention['items'] && !$isAttentionPoll) {
|
||||
AdminAssets::addStyle(ADMINX_BASE . '/modules/Dashboard/assets/attention.css', 55);
|
||||
AdminAssets::addScript(ADMINX_BASE . '/modules/Dashboard/assets/attention.js', 55);
|
||||
}
|
||||
}
|
||||
|
||||
Twig::addGlobals(array('attention' => $attention, 'attention_user_id' => (int) Auth::id()));
|
||||
|
||||
if (!$isPublic && !$canAdmin) {
|
||||
if (Request::isAjax()) {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="attention_heading">Needs attention</phrase>
|
||||
<phrase data="attention_empty">Nothing new</phrase>
|
||||
<phrase data="attention_wait">Oldest waiting %s</phrase>
|
||||
<phrase data="attention_waiting">Awaiting processing</phrase>
|
||||
<phrase data="attention_minutes">min</phrase>
|
||||
<phrase data="attention_hours">h</phrase>
|
||||
<phrase data="attention_days">d</phrase>
|
||||
<phrase data="attention_unavailable">Unable to refresh</phrase>
|
||||
<phrase data="attention_stale">Updates temporarily unavailable</phrase>
|
||||
<phrase data="attention_orders">New orders</phrase>
|
||||
<phrase data="attention_messages">New messages</phrase>
|
||||
<phrase data="attention_order_filter">New: awaiting processing</phrase>
|
||||
</language>
|
||||
@@ -1,5 +1,84 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="rich_tool_001">Find and replace</phrase>
|
||||
<phrase data="rich_tool_002">Find</phrase>
|
||||
<phrase data="rich_tool_003">Replace with</phrase>
|
||||
<phrase data="rich_tool_004">Replace</phrase>
|
||||
<phrase data="rich_tool_005">Replace all</phrase>
|
||||
<phrase data="rich_tool_006">Match case</phrase>
|
||||
<phrase data="rich_tool_007">No matches</phrase>
|
||||
<phrase data="rich_tool_008">Previous</phrase>
|
||||
<phrase data="rich_tool_009">Next</phrase>
|
||||
<phrase data="rich_tool_010">Special characters</phrase>
|
||||
<phrase data="rich_tool_011">Non-breaking space</phrase>
|
||||
<phrase data="rich_tool_012">Degree</phrase>
|
||||
<phrase data="rich_tool_013">Multiplication</phrase>
|
||||
<phrase data="rich_tool_014">Plus/minus</phrase>
|
||||
<phrase data="rich_tool_015">Registered trademark</phrase>
|
||||
<phrase data="rich_tool_016">Copyright</phrase>
|
||||
<phrase data="rich_tool_017">Trademark</phrase>
|
||||
<phrase data="rich_tool_018">Less than or equal</phrase>
|
||||
<phrase data="rich_tool_019">Greater than or equal</phrase>
|
||||
<phrase data="rich_tool_020">Micro</phrase>
|
||||
<phrase data="rich_tool_021">Squared</phrase>
|
||||
<phrase data="rich_tool_022">Cubed</phrase>
|
||||
<phrase data="rich_tool_023">Opening quote</phrase>
|
||||
<phrase data="rich_tool_024">Closing quote</phrase>
|
||||
<phrase data="rich_tool_025">En dash</phrase>
|
||||
<phrase data="rich_tool_026">Em dash</phrase>
|
||||
<phrase data="rich_tool_027">Ellipsis</phrase>
|
||||
<phrase data="rich_tool_028">Content fragments</phrase>
|
||||
<phrase data="rich_tool_029">Warning</phrase>
|
||||
<phrase data="rich_tool_030">Important</phrase>
|
||||
<phrase data="rich_tool_031">Included items</phrase>
|
||||
<phrase data="rich_tool_032">Specifications table</phrase>
|
||||
<phrase data="rich_tool_033">Block order</phrase>
|
||||
<phrase data="rich_tool_034">Move up</phrase>
|
||||
<phrase data="rich_tool_035">Move down</phrase>
|
||||
<phrase data="rich_tool_036">Formatting check</phrase>
|
||||
<phrase data="rich_tool_037">Review formatting</phrase>
|
||||
<phrase data="rich_tool_038">H1 in content</phrase>
|
||||
<phrase data="rich_tool_039">Empty heading</phrase>
|
||||
<phrase data="rich_tool_040">Empty link</phrase>
|
||||
<phrase data="rich_tool_041">Inline formatting</phrase>
|
||||
<phrase data="rich_tool_042">Extra empty paragraph</phrase>
|
||||
<phrase data="rich_tool_043">Fix</phrase>
|
||||
<phrase data="rich_tool_044">No issues found</phrase>
|
||||
<phrase data="rich_tool_045">Save without changes</phrase>
|
||||
<phrase data="rich_tool_046">Words</phrase>
|
||||
<phrase data="rich_tool_047">Characters</phrase>
|
||||
<phrase data="rich_tool_048">Selection</phrase>
|
||||
<phrase data="rich_tool_049">in content</phrase>
|
||||
<phrase data="rich_tool_050">Insert row above</phrase>
|
||||
<phrase data="rich_tool_051">Insert row below</phrase>
|
||||
<phrase data="rich_tool_052">Delete row</phrase>
|
||||
<phrase data="rich_tool_053">Insert column left</phrase>
|
||||
<phrase data="rich_tool_054">Insert column right</phrase>
|
||||
<phrase data="rich_tool_055">Delete column</phrase>
|
||||
<phrase data="rich_tool_056">Merge cells</phrase>
|
||||
<phrase data="rich_tool_057">Split cell</phrase>
|
||||
<phrase data="rich_tool_058">Header row</phrase>
|
||||
<phrase data="rich_tool_059">Header column</phrase>
|
||||
<phrase data="rich_tool_060">Delete table</phrase>
|
||||
<phrase data="rich_tool_061">Link to document or product</phrase>
|
||||
<phrase data="rich_tool_062">Expand editor</phrase>
|
||||
<phrase data="rich_tool_063">Collapse editor</phrase>
|
||||
<phrase data="rich_tool_064">Visual editor toolbar</phrase>
|
||||
<phrase data="rich_tool_065">Full</phrase>
|
||||
<phrase data="rich_tool_066">Compact</phrase>
|
||||
<phrase data="rich_tool_067">Product description</phrase>
|
||||
<phrase data="rich_tool_068">News / article</phrase>
|
||||
<phrase data="rich_tool_069">Headings in toolbar</phrase>
|
||||
<phrase data="rich_tool_070">Use profile</phrase>
|
||||
<phrase data="rich_tool_071">No headings</phrase>
|
||||
<phrase data="rich_tool_072">Informational</phrase>
|
||||
<phrase data="rich_tool_073">Product</phrase>
|
||||
<phrase data="rich_tool_074">Hide</phrase>
|
||||
<phrase data="rich_tool_075">Hide images in toolbar</phrase>
|
||||
<phrase data="rich_tool_076">Hide tables in toolbar</phrase>
|
||||
<phrase data="rich_tool_077">Hide source code in toolbar</phrase>
|
||||
<phrase data="rich_tool_078">Hide alignment in toolbar</phrase>
|
||||
<phrase data="rich_tool_079">Hide block ordering in toolbar</phrase>
|
||||
<phrase data="action_done">Done</phrase>
|
||||
<phrase data="auto_1cc70f8e0fc03e82">Delete view</phrase>
|
||||
<phrase data="auto_86433d57abc272e9">Saved Views</phrase>
|
||||
@@ -7,6 +86,7 @@
|
||||
<phrase data="btn_cancel">Cancel</phrase>
|
||||
<phrase data="btn_close">Close</phrase>
|
||||
<phrase data="btn_confirm">Confirm</phrase>
|
||||
<phrase data="btn_create">Create</phrase>
|
||||
<phrase data="btn_delete">Delete</phrase>
|
||||
<phrase data="btn_save">Save</phrase>
|
||||
<phrase data="btn_show">Show</phrase>
|
||||
@@ -34,6 +114,7 @@
|
||||
<phrase data="topbar_theme">Theme</phrase>
|
||||
<phrase data="ui_loading">Loading...</phrase>
|
||||
<phrase data="ui_main">General</phrase>
|
||||
<phrase data="ui_name">Name</phrase>
|
||||
<phrase data="ui_nothing_found">Nothing found</phrase>
|
||||
<phrase data="ui_remove">Remove</phrase>
|
||||
<phrase data="ui_search">Search</phrase>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="attention_heading">Требуют внимания</phrase>
|
||||
<phrase data="attention_empty">Новых нет</phrase>
|
||||
<phrase data="attention_wait">Самое старое ждёт %s</phrase>
|
||||
<phrase data="attention_waiting">Ожидают обработки</phrase>
|
||||
<phrase data="attention_minutes">мин</phrase>
|
||||
<phrase data="attention_hours">ч</phrase>
|
||||
<phrase data="attention_days">дн</phrase>
|
||||
<phrase data="attention_unavailable">Не удалось обновить</phrase>
|
||||
<phrase data="attention_stale">Данные временно не обновляются</phrase>
|
||||
<phrase data="attention_orders">Новые заказы</phrase>
|
||||
<phrase data="attention_messages">Новые обращения</phrase>
|
||||
<phrase data="attention_order_filter">Новые: ожидают обработки</phrase>
|
||||
</language>
|
||||
@@ -1,5 +1,84 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="rich_tool_001">Найти и заменить</phrase>
|
||||
<phrase data="rich_tool_002">Найти</phrase>
|
||||
<phrase data="rich_tool_003">Заменить на</phrase>
|
||||
<phrase data="rich_tool_004">Заменить</phrase>
|
||||
<phrase data="rich_tool_005">Заменить все</phrase>
|
||||
<phrase data="rich_tool_006">Учитывать регистр</phrase>
|
||||
<phrase data="rich_tool_007">Нет совпадений</phrase>
|
||||
<phrase data="rich_tool_008">Предыдущее</phrase>
|
||||
<phrase data="rich_tool_009">Следующее</phrase>
|
||||
<phrase data="rich_tool_010">Специальные символы</phrase>
|
||||
<phrase data="rich_tool_011">Неразрывный пробел</phrase>
|
||||
<phrase data="rich_tool_012">Градус</phrase>
|
||||
<phrase data="rich_tool_013">Умножение</phrase>
|
||||
<phrase data="rich_tool_014">Плюс-минус</phrase>
|
||||
<phrase data="rich_tool_015">Зарегистрированный знак</phrase>
|
||||
<phrase data="rich_tool_016">Авторское право</phrase>
|
||||
<phrase data="rich_tool_017">Товарный знак</phrase>
|
||||
<phrase data="rich_tool_018">Меньше или равно</phrase>
|
||||
<phrase data="rich_tool_019">Больше или равно</phrase>
|
||||
<phrase data="rich_tool_020">Микро</phrase>
|
||||
<phrase data="rich_tool_021">Квадрат</phrase>
|
||||
<phrase data="rich_tool_022">Куб</phrase>
|
||||
<phrase data="rich_tool_023">Открывающая кавычка</phrase>
|
||||
<phrase data="rich_tool_024">Закрывающая кавычка</phrase>
|
||||
<phrase data="rich_tool_025">Короткое тире</phrase>
|
||||
<phrase data="rich_tool_026">Длинное тире</phrase>
|
||||
<phrase data="rich_tool_027">Многоточие</phrase>
|
||||
<phrase data="rich_tool_028">Готовые фрагменты</phrase>
|
||||
<phrase data="rich_tool_029">Внимание</phrase>
|
||||
<phrase data="rich_tool_030">Важно</phrase>
|
||||
<phrase data="rich_tool_031">Комплектация</phrase>
|
||||
<phrase data="rich_tool_032">Таблица характеристик</phrase>
|
||||
<phrase data="rich_tool_033">Порядок блоков</phrase>
|
||||
<phrase data="rich_tool_034">Переместить вверх</phrase>
|
||||
<phrase data="rich_tool_035">Переместить вниз</phrase>
|
||||
<phrase data="rich_tool_036">Проверка оформления</phrase>
|
||||
<phrase data="rich_tool_037">Проверьте оформление</phrase>
|
||||
<phrase data="rich_tool_038">H1 в тексте</phrase>
|
||||
<phrase data="rich_tool_039">Пустой заголовок</phrase>
|
||||
<phrase data="rich_tool_040">Пустая ссылка</phrase>
|
||||
<phrase data="rich_tool_041">Встроенное оформление</phrase>
|
||||
<phrase data="rich_tool_042">Лишний пустой абзац</phrase>
|
||||
<phrase data="rich_tool_043">Исправить</phrase>
|
||||
<phrase data="rich_tool_044">Замечаний нет</phrase>
|
||||
<phrase data="rich_tool_045">Сохранить без исправлений</phrase>
|
||||
<phrase data="rich_tool_046">Слов</phrase>
|
||||
<phrase data="rich_tool_047">Символов</phrase>
|
||||
<phrase data="rich_tool_048">Выделено</phrase>
|
||||
<phrase data="rich_tool_049">в тексте</phrase>
|
||||
<phrase data="rich_tool_050">Строка выше</phrase>
|
||||
<phrase data="rich_tool_051">Строка ниже</phrase>
|
||||
<phrase data="rich_tool_052">Удалить строку</phrase>
|
||||
<phrase data="rich_tool_053">Столбец слева</phrase>
|
||||
<phrase data="rich_tool_054">Столбец справа</phrase>
|
||||
<phrase data="rich_tool_055">Удалить столбец</phrase>
|
||||
<phrase data="rich_tool_056">Объединить ячейки</phrase>
|
||||
<phrase data="rich_tool_057">Разделить ячейку</phrase>
|
||||
<phrase data="rich_tool_058">Строка заголовков</phrase>
|
||||
<phrase data="rich_tool_059">Столбец заголовков</phrase>
|
||||
<phrase data="rich_tool_060">Удалить таблицу</phrase>
|
||||
<phrase data="rich_tool_061">Ссылка на документ или товар</phrase>
|
||||
<phrase data="rich_tool_062">Развернуть редактор</phrase>
|
||||
<phrase data="rich_tool_063">Свернуть редактор</phrase>
|
||||
<phrase data="rich_tool_064">Панель визуального редактора</phrase>
|
||||
<phrase data="rich_tool_065">Полная</phrase>
|
||||
<phrase data="rich_tool_066">Компактная</phrase>
|
||||
<phrase data="rich_tool_067">Описание товара</phrase>
|
||||
<phrase data="rich_tool_068">Новость / статья</phrase>
|
||||
<phrase data="rich_tool_069">Заголовки в панели</phrase>
|
||||
<phrase data="rich_tool_070">По профилю</phrase>
|
||||
<phrase data="rich_tool_071">Без заголовков</phrase>
|
||||
<phrase data="rich_tool_072">Информационные</phrase>
|
||||
<phrase data="rich_tool_073">Товарные</phrase>
|
||||
<phrase data="rich_tool_074">Не показывать</phrase>
|
||||
<phrase data="rich_tool_075">Скрыть в панели: изображения</phrase>
|
||||
<phrase data="rich_tool_076">Скрыть в панели: таблицы</phrase>
|
||||
<phrase data="rich_tool_077">Скрыть в панели: исходный код</phrase>
|
||||
<phrase data="rich_tool_078">Скрыть в панели: выравнивание</phrase>
|
||||
<phrase data="rich_tool_079">Скрыть в панели: перемещение блоков</phrase>
|
||||
<phrase data="action_done">Готово</phrase>
|
||||
<phrase data="auto_1cc70f8e0fc03e82">Удалить представление</phrase>
|
||||
<phrase data="auto_86433d57abc272e9">Сохранённые представления</phrase>
|
||||
@@ -7,6 +86,7 @@
|
||||
<phrase data="btn_cancel">Отмена</phrase>
|
||||
<phrase data="btn_close">Закрыть</phrase>
|
||||
<phrase data="btn_confirm">Подтвердить</phrase>
|
||||
<phrase data="btn_create">Создать</phrase>
|
||||
<phrase data="btn_delete">Удалить</phrase>
|
||||
<phrase data="btn_save">Сохранить</phrase>
|
||||
<phrase data="btn_show">Показать</phrase>
|
||||
@@ -34,6 +114,7 @@
|
||||
<phrase data="topbar_theme">Тема</phrase>
|
||||
<phrase data="ui_loading">Загрузка...</phrase>
|
||||
<phrase data="ui_main">Основное</phrase>
|
||||
<phrase data="ui_name">Название</phrase>
|
||||
<phrase data="ui_nothing_found">Ничего не найдено</phrase>
|
||||
<phrase data="ui_remove">Убрать</phrase>
|
||||
<phrase data="ui_search">Поиск</phrase>
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Helpers\PhpSyntax;
|
||||
|
||||
class Syntax
|
||||
{
|
||||
public static function check($code, $eval)
|
||||
@@ -30,44 +32,8 @@
|
||||
);
|
||||
}
|
||||
|
||||
$tmp = tempnam(sys_get_temp_dir(), 'ave-sysblock-');
|
||||
if ($tmp === false) {
|
||||
return self::unavailable('Не удалось создать временный файл для проверки.');
|
||||
}
|
||||
|
||||
$file = $tmp . '.php';
|
||||
@rename($tmp, $file);
|
||||
$written = @file_put_contents($file, '?>' . (string) $code . '<?php ');
|
||||
if ($written === false) {
|
||||
@unlink($file);
|
||||
return self::unavailable('Не удалось записать временный файл для проверки.');
|
||||
}
|
||||
|
||||
$php = defined('PHP_BINARY') && PHP_BINARY ? PHP_BINARY : 'php';
|
||||
$cmd = escapeshellarg($php) . ' -l ' . escapeshellarg($file) . ' 2>&1';
|
||||
$output = array();
|
||||
$status = 0;
|
||||
@exec($cmd, $output, $status);
|
||||
@unlink($file);
|
||||
|
||||
$text = trim(implode("\n", $output));
|
||||
if ($text === '') {
|
||||
return self::unavailable('PHP CLI недоступен для проверки синтаксиса.');
|
||||
}
|
||||
|
||||
$clean = str_replace($file, 'код блока', $text);
|
||||
$line = 0;
|
||||
if (preg_match('/ on line ([0-9]+)/i', $clean, $m)) {
|
||||
$line = (int) $m[1];
|
||||
}
|
||||
|
||||
return array(
|
||||
'ok' => (int) $status === 0,
|
||||
'checked' => true,
|
||||
'message' => (int) $status === 0 ? 'Синтаксис PHP без ошибок.' : 'В PHP-коде есть синтаксическая ошибка.',
|
||||
'line' => $line,
|
||||
'output' => $clean,
|
||||
);
|
||||
$result = PhpSyntax::check('<?php ?>' . (string) $code);
|
||||
return $result['checked'] ? $result : self::unavailable($result['message']);
|
||||
}
|
||||
|
||||
protected static function unavailable($message)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="runtime_c55667032216bcac">Built-in PHP syntax checking is not available on this server.</phrase>
|
||||
<phrase data="runtime_287ef8ef854ce1aa">(copy)</phrase>
|
||||
<phrase data="runtime_eb35949a5a0f8ff5">PHP CLI is not available for syntax checking.</phrase>
|
||||
<phrase data="runtime_46c24d5ef1a06bf8">PHP syntax: error in block code</phrase>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="runtime_c55667032216bcac">Встроенная проверка PHP недоступна на сервере.</phrase>
|
||||
<phrase data="runtime_287ef8ef854ce1aa">(копия)</phrase>
|
||||
<phrase data="runtime_eb35949a5a0f8ff5">PHP CLI недоступен для проверки синтаксиса.</phrase>
|
||||
<phrase data="runtime_46c24d5ef1a06bf8">PHP-синтаксис: ошибка в коде блока</phrase>
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
return array(
|
||||
'code' => 'blocks',
|
||||
'name' => 'Блоки',
|
||||
'version' => '0.1.4',
|
||||
'version' => '0.1.6',
|
||||
|
||||
'permissions' => array(
|
||||
'key' => 'blocks',
|
||||
|
||||
@@ -121,6 +121,8 @@
|
||||
if (!Permission::check('view_products')) { return $this->renderStatus('@adminx/404.twig', array('title' => 'Недостаточно прав'), 403); }
|
||||
if (!Model::hasCommerceCatalogs()) { return $this->renderStatus('@adminx/404.twig', array('title' => 'Товарные каталоги не настроены'), 404); }
|
||||
$this->assets();
|
||||
$state = Request::getStr('state', 'active');
|
||||
if (!in_array($state, array('active', 'inactive', 'all'), true)) { $state = 'active'; }
|
||||
$stats = Model::productQualityStats();
|
||||
$issues = Model::productQualityIssues($stats);
|
||||
$allowed = array();
|
||||
@@ -130,11 +132,15 @@
|
||||
$filters = array(
|
||||
'q' => Request::getStr('q', ''),
|
||||
'issue' => $issue,
|
||||
'state' => $state,
|
||||
'page' => Request::getInt('page', 1),
|
||||
'per_page' => Request::getInt('per_page', 25),
|
||||
'include_quality' => true,
|
||||
'quality_scope' => true,
|
||||
'quality_scope' => $state === 'active',
|
||||
);
|
||||
$aiModule = ModuleManager::get('ai_assistant');
|
||||
$aiAvailable = $aiModule && !empty($aiModule['installed']) && !empty($aiModule['enabled'])
|
||||
&& class_exists('\App\Modules\AiAssistant\Repository') && Permission::check('manage_ai_assistant');
|
||||
return $this->render('@products/product-quality.twig', array(
|
||||
'result' => Model::products($filters),
|
||||
'stats' => $stats,
|
||||
@@ -142,6 +148,8 @@
|
||||
'filters' => $filters,
|
||||
'saved_views' => SavedViews::all('catalog_quality', Auth::id(), $this->savedViewFields('quality')),
|
||||
'can_manage' => Permission::check('manage_products'),
|
||||
'can_toggle' => Permission::check('manage_products') && Permission::check('manage_documents'),
|
||||
'ai_available' => (bool) $aiAvailable,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -1367,6 +1375,7 @@
|
||||
'shipping_profile' => $shippingProfile,
|
||||
'package_templates' => ShippingPackageTemplates::all(),
|
||||
'native_attributes' => $nativeAttributes,
|
||||
'product_context_links' => EditorContextLinks::product($document, $nativeAttributes),
|
||||
'product_readiness' => ProductReadiness::build($product, $nativeAttributes, $shippingProfile, $variantGroup),
|
||||
'product_promotions_available' => Promotions::available(),
|
||||
'product_promotions' => Promotions::forProduct($id),
|
||||
@@ -1692,9 +1701,12 @@
|
||||
$settings['filters_default_ids'] = $this->ids(isset($settings['filters_default']) ? $settings['filters_default'] : '');
|
||||
$styles = @unserialize(isset($settings['filters_default_settings']) ? (string) $settings['filters_default_settings'] : '', array('allowed_classes' => false));
|
||||
$settings['filter_styles'] = is_array($styles) ? $styles : array();
|
||||
$flat = Model::items($rubricId, $fieldId);
|
||||
return $this->render('@catalog/edit.twig', array(
|
||||
'catalog' => $catalog, 'settings' => $settings,
|
||||
'tree' => Model::tree($rubricId, $fieldId), 'flat' => Model::items($rubricId, $fieldId),
|
||||
'tree' => Model::tree($rubricId, $fieldId), 'flat' => $flat,
|
||||
'source_options' => Model::sourceOptions($rubricId, $fieldId),
|
||||
'source_schema_available' => Model::sourceItemsAvailable(),
|
||||
'fields' => $fields,
|
||||
'field_groups' => array_values($fieldGroups),
|
||||
'request_options' => Model::requestOptions(),
|
||||
@@ -1704,15 +1716,44 @@
|
||||
'filter_template_options' => $filterTemplatesAvailable ? FilterTemplates::options() : array(),
|
||||
'filter_templates_available' => $filterTemplatesAvailable,
|
||||
'products_available' => $productsAvailable,
|
||||
'product_roles' => $productsAvailable ? \App\Adminx\Packages\Products\ProductRoleSettings::view($rubricId, $settings, Request::getInt('product_preview', 0)) : array(),
|
||||
'can_manage' => Permission::check('manage_catalog'),
|
||||
));
|
||||
}
|
||||
|
||||
public function productPreview(array $params = array())
|
||||
{
|
||||
$rubricId = isset($params['rubric']) ? (int) $params['rubric'] : 0;
|
||||
$fieldId = isset($params['field']) ? (int) $params['field'] : 0;
|
||||
if (!Permission::check('view_catalog') || !$this->productsAvailable()
|
||||
|| !\App\Adminx\Packages\Products\ProductRoleSettings::canReadRubric($rubricId)) {
|
||||
return $this->renderStatus('@adminx/404.twig', array('title' => 'Недостаточно прав'), 403);
|
||||
}
|
||||
|
||||
$catalog = Model::catalog($rubricId, $fieldId);
|
||||
if (!$catalog) { return $this->renderStatus('@adminx/404.twig', array('title' => 'Каталог не найден'), 404); }
|
||||
$settings = Model::settings($rubricId, $fieldId);
|
||||
$selection = array();
|
||||
foreach (array('context', 'category', 'feed', 'scope', 'query', 'source', 'limit') as $key) {
|
||||
$selection[$key] = Request::getStr('selection_' . $key, $key === 'context' ? 'catalog' : ($key === 'limit' ? '8' : ''));
|
||||
}
|
||||
|
||||
return $this->partial('@catalog/_product-role-preview.twig', array(
|
||||
'catalog' => $catalog, 'settings' => $settings,
|
||||
'product_roles' => \App\Adminx\Packages\Products\ProductRoleSettings::view($rubricId, $settings,
|
||||
Request::getInt('product_preview', 0), $selection, Request::getInt('selection_check', 0) === 1),
|
||||
));
|
||||
}
|
||||
|
||||
public function item(array $params = array())
|
||||
{
|
||||
if (!Permission::check('view_catalog')) { return $this->error('Недостаточно прав', array(), 403); }
|
||||
$item = Model::item(isset($params['id']) ? (int) $params['id'] : 0);
|
||||
if ($item) { $item['condition_context'] = Model::conditionContext($item['id']); }
|
||||
if ($item) {
|
||||
$item['condition_context'] = Model::conditionContext($item['id']);
|
||||
$item['context_links'] = EditorContextLinks::section($item, $this->productsAvailable());
|
||||
}
|
||||
|
||||
return $item ? $this->success('', array('data' => $item)) : $this->error('Раздел не найден', array(), 404);
|
||||
}
|
||||
|
||||
@@ -1818,6 +1859,7 @@
|
||||
return $this->success($id > 0 ? 'Раздел сохранён' : 'Раздел создан', array('data' => array(
|
||||
'id' => $saved,
|
||||
'condition_context' => Model::conditionContext($saved),
|
||||
'context_links' => EditorContextLinks::section(Model::item($saved), $this->productsAvailable()),
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -1893,7 +1935,7 @@
|
||||
protected function savedViewFields($scope)
|
||||
{
|
||||
return $scope === 'quality'
|
||||
? array('q', 'issue', 'per_page')
|
||||
? array('q', 'issue', 'state', 'per_page')
|
||||
: array('q', 'state', 'issue', 'payment', 'per_page', 'view');
|
||||
}
|
||||
|
||||
@@ -1934,6 +1976,7 @@
|
||||
{
|
||||
AdminAssets::addStyle($this->base() . '/modules/Catalog/assets/catalog.css', 50);
|
||||
AdminAssets::addStyle($this->base() . '/modules/Catalog/assets/catalog-drawer.css', 51);
|
||||
AdminAssets::addStyle($this->base() . '/modules/Catalog/assets/context-links.css', 52);
|
||||
AdminAssets::addScript($this->base() . '/modules/Catalog/assets/catalog.js', 50);
|
||||
if ($this->productsAvailable()) {
|
||||
if (is_file(BASEPATH . '/modules/products/admin/assets/products.css')) {
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------------
|
||||
| AVE.cms
|
||||
|--------------------------------------------------------------------------------------
|
||||
| @package AVE.cms
|
||||
| @file adminx/modules/Catalog/EditorContextLinks.php
|
||||
| @author AVE.cms <support@ave-cms.ru>
|
||||
| @copyright 2007-2026 (c) AVE.cms
|
||||
| @link https://ave-cms.ru
|
||||
| @version 3.3
|
||||
*/
|
||||
|
||||
namespace App\Adminx\Catalog;
|
||||
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Adminx\Support\AdminLocale;
|
||||
use App\Common\AdminLocation;
|
||||
use App\Common\Permission;
|
||||
use App\Content\CatalogTables;
|
||||
use App\Content\ContentTables;
|
||||
use App\Content\Presentation\PresentationRenderer;
|
||||
use App\Helpers\Html;
|
||||
use App\Modules\Products\CardSettings;
|
||||
use App\Modules\Products\CardTemplateRepository;
|
||||
use DB;
|
||||
|
||||
/** Saved editor context, linking to HTML parent pages rather than JSON drawer endpoints. */
|
||||
class EditorContextLinks
|
||||
{
|
||||
public static function product(array $document, array $attributes)
|
||||
{
|
||||
$links = static::page($document);
|
||||
$sections = DB::query(
|
||||
'SELECT DISTINCT i.id,i.rubric_id,i.field_id,i.name,i.filter_runtime FROM %b cp JOIN %b i ON i.id=cp.catalog_item_id WHERE cp.product_id=%i ORDER BY i.name,i.id',
|
||||
CatalogTables::table('catalog_category_products'), CatalogTables::table('module_catalog_items'), (int) $document['Id']
|
||||
)->getAll() ?: array();
|
||||
$sets = array();
|
||||
foreach ($attributes['groups'] as $group) {
|
||||
$id = (int) $group['set_id'];
|
||||
if (isset($sets[$id])) { continue; }
|
||||
$sets[$id] = true;
|
||||
static::add($links, 'attribute_set', '/catalog/attribute-sets/' . $id, array(), 'view_products', $group['set_name']);
|
||||
}
|
||||
|
||||
if (!$sections) { static::card($links, (int) $document['rubric_id'], array(), array()); }
|
||||
$catalogSettings = array();
|
||||
foreach ($sections as $section) {
|
||||
$key = (int) $section['rubric_id'] . ':' . (int) $section['field_id'];
|
||||
if (!isset($catalogSettings[$key])) {
|
||||
$catalogSettings[$key] = Model::settings((int) $section['rubric_id'], (int) $section['field_id']);
|
||||
}
|
||||
|
||||
static::filters($links, $section);
|
||||
static::card($links, (int) $document['rubric_id'], $section, $catalogSettings[$key]);
|
||||
}
|
||||
|
||||
return $links;
|
||||
}
|
||||
|
||||
public static function section(array $section, $productsAvailable = true)
|
||||
{
|
||||
$document = !empty($section['document_id']) ? DB::query(
|
||||
'SELECT Id,rubric_id,rubric_tmpl_id FROM %b WHERE Id=%i LIMIT 1',
|
||||
ContentTables::table('documents'), (int) $section['document_id']
|
||||
)->getAssoc() : array();
|
||||
$links = $document ? static::page($document) : array();
|
||||
static::filters($links, $section, $productsAvailable);
|
||||
if (!$productsAvailable) { return $links; }
|
||||
$settings = Model::settings((int) $section['rubric_id'], (int) $section['field_id']);
|
||||
if (!empty($section['attribute_set_id'])) {
|
||||
static::add($links, 'attribute_set', '/catalog/attribute-sets/' . (int) $section['attribute_set_id'], array(), 'view_products', '#' . (int) $section['attribute_set_id']);
|
||||
}
|
||||
|
||||
if (isset($settings['purpose']) && $settings['purpose'] === 'commerce') {
|
||||
static::card($links, (int) $section['rubric_id'], $section, $settings);
|
||||
}
|
||||
|
||||
return $links;
|
||||
}
|
||||
|
||||
protected static function filters(array &$links, array $section, $productsAvailable = true)
|
||||
{
|
||||
$native = isset($section['filter_runtime']) && $section['filter_runtime'] === 'native';
|
||||
if ($native && !$productsAvailable) { return; }
|
||||
if ($native) {
|
||||
static::add($links, 'filters', '/catalog/attributes', array('view' => 'filters', 'section_id' => (int) $section['id']), 'view_products', $section['name']);
|
||||
} elseif (static::allowed('manage_catalog')) {
|
||||
static::add($links, 'filters', '/catalog/' . (int) $section['rubric_id'] . '/' . (int) $section['field_id'], array('item' => (int) $section['id'], 'tab' => 'filters'), 'view_catalog', $section['name']);
|
||||
}
|
||||
}
|
||||
|
||||
protected static function card(array &$links, $rubricId, array $section, array $settings)
|
||||
{
|
||||
$targets = array('rubric' => (string) $rubricId, 'module' => 'products');
|
||||
if (!empty($section['rubric_id'])) { $targets['rubric'] = (string) $section['rubric_id']; }
|
||||
if (!empty($section['id'])) { $targets['catalog'] = (string) $section['id']; }
|
||||
if (!empty($settings['request_id'])) { $targets['request'] = (string) $settings['request_id']; }
|
||||
$scope = isset($section['name']) ? $section['name'] : '';
|
||||
$presentation = static::presentation($targets);
|
||||
if ($presentation && trim((string) $presentation['published_item_markup']) !== '') {
|
||||
if (static::allowed('manage_public_presentations')) {
|
||||
static::add($links, 'card', '/public-site/presentations', array('edit' => (int) $presentation['presentation_id']), 'view_public_site', $scope);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$template = static::cardTemplate($rubricId);
|
||||
if ($template && trim((string) $template['published_markup']) !== '') {
|
||||
if (static::allowed('manage_products')) {
|
||||
static::add($links, 'card', '/catalog/card-templates', array('edit' => (int) $template['id']), 'view_products', $scope);
|
||||
}
|
||||
} else {
|
||||
static::add($links, 'card', '/catalog/public-templates', array('template' => 'product-card'), 'view_products', $scope);
|
||||
}
|
||||
}
|
||||
|
||||
protected static function page(array $document)
|
||||
{
|
||||
$links = array();
|
||||
if (!static::allowed('view_rubrics') || !static::allowed('manage_rubrics')) { return $links; }
|
||||
$query = array('templates' => (int) $document['rubric_id']);
|
||||
$alternate = !empty($document['rubric_tmpl_id']) ? static::alternate($document) : null;
|
||||
// DocumentRepository falls back to the rubric template when the alternate is empty.
|
||||
if ($alternate && trim((string) $alternate['template']) !== '') { $query['template'] = (int) $alternate['id']; }
|
||||
static::add($links, 'page', '/rubrics', $query, 'view_rubrics');
|
||||
return $links;
|
||||
}
|
||||
|
||||
protected static function alternate(array $document)
|
||||
{
|
||||
return DB::query('SELECT id,template FROM %b WHERE id=%i AND rubric_id=%i LIMIT 1', ContentTables::table('rubric_templates'), (int) $document['rubric_tmpl_id'], (int) $document['rubric_id'])->getAssoc();
|
||||
}
|
||||
|
||||
protected static function presentation(array $targets) { return PresentationRenderer::resolve('content_list', $targets); }
|
||||
|
||||
protected static function cardTemplate($rubricId)
|
||||
{
|
||||
$settings = CardSettings::forRubric($rubricId);
|
||||
return CardTemplateRepository::published((int) $settings['template_id']);
|
||||
}
|
||||
|
||||
protected static function allowed($permission) { return Permission::check($permission); }
|
||||
|
||||
protected static function add(array &$links, $kind, $path, array $query, $permission, $scope = '')
|
||||
{
|
||||
if (!static::allowed($permission)) { return; }
|
||||
$url = AdminLocation::url($path);
|
||||
$links[] = array(
|
||||
'kind' => $kind,
|
||||
'url' => $query ? Html::appendQuery($url, $query) : $url,
|
||||
'label' => AdminLocale::text('catalog_context_' . $kind),
|
||||
'scope' => (string) $scope,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -23,14 +23,19 @@
|
||||
use App\Common\DatabaseSchema;
|
||||
use App\Common\FileCacheInvalidator;
|
||||
use App\Common\ModuleManager;
|
||||
use App\Common\ModuleSettings;
|
||||
use App\Common\Registry;
|
||||
use App\Modules\Products\ProductRoles;
|
||||
use App\Content\CatalogTables;
|
||||
use App\Content\ContentTables;
|
||||
use App\Content\Fields\FieldValueCodec;
|
||||
use App\Content\Requests\RequestConditionValue;
|
||||
use App\Frontend\Feeds\Service as FeedService;
|
||||
use App\Helpers\Json;
|
||||
use App\Adminx\Rubrics\Model as RubricsModel;
|
||||
use App\Adminx\Documents\Model as DocumentsModel;
|
||||
use App\Adminx\Packages\Products\ProductIndexer;
|
||||
use App\Adminx\Packages\Products\Attributes;
|
||||
|
||||
class Model
|
||||
{
|
||||
@@ -146,8 +151,21 @@
|
||||
}
|
||||
|
||||
public static function saveSettings($rubricId, $fieldId, array $input)
|
||||
{
|
||||
if (DB::$transaction_in_progress) {
|
||||
throw new \LogicException('Catalog settings must be saved outside an existing transaction');
|
||||
}
|
||||
|
||||
$throwOnError = DB::$throw_exception_on_error;
|
||||
DB::$throw_exception_on_error = true;
|
||||
try { return self::saveSettingsOwned($rubricId, $fieldId, $input); }
|
||||
finally { DB::$throw_exception_on_error = $throwOnError; }
|
||||
}
|
||||
|
||||
protected static function saveSettingsOwned($rubricId, $fieldId, array $input)
|
||||
{
|
||||
self::requireCatalog($rubricId, $fieldId);
|
||||
$existing = self::settings($rubricId, $fieldId);
|
||||
$data = array();
|
||||
$data['purpose'] = isset($input['purpose']) && $input['purpose'] === 'commerce' ? 'commerce' : 'content';
|
||||
if ($data['purpose'] === 'commerce' && !self::productsAvailable()) {
|
||||
@@ -162,7 +180,24 @@
|
||||
throw new \InvalidArgumentException('У рубрики уже есть товарный каталог');
|
||||
}
|
||||
|
||||
foreach(array('product_title_field_id','product_article_field_id','product_price_field_id','product_old_price_field_id','product_stock_field_id','product_images_field_id') as $key){$data[$key]=isset($input[$key])?max(0,(int)$input[$key]):0;if($data[$key]&&!DB::query('SELECT Id FROM '.self::fieldsTable().' WHERE Id=%i AND rubric_id=%i LIMIT 1',$data[$key],(int)$rubricId)->getValue()){throw new \InvalidArgumentException('Коммерческое поле не принадлежит рубрике');}}
|
||||
foreach (array('product_title_field_id','product_article_field_id','product_price_field_id','product_old_price_field_id','product_stock_field_id','product_images_field_id') as $key) {
|
||||
$data[$key] = isset($input[$key]) ? max(0, (int) $input[$key]) : (int) $existing[$key];
|
||||
if (isset($input[$key]) && $data[$key] && !DB::query('SELECT Id FROM ' . self::fieldsTable() . ' WHERE Id=%i AND rubric_id=%i LIMIT 1', $data[$key], (int) $rubricId)->getValue()) {
|
||||
throw new \InvalidArgumentException('Коммерческое поле не принадлежит рубрике');
|
||||
}
|
||||
}
|
||||
|
||||
$roleInput = null;
|
||||
if ($data['purpose'] === 'commerce' && isset($input['product_roles']) && is_array($input['product_roles'])) {
|
||||
$roleFields = ProductRoles::fields($rubricId);
|
||||
$roleInput = array_replace(ProductRoles::configured($rubricId), ProductRoles::validate($input['product_roles'], $roleFields));
|
||||
$roleSettings = self::settings($rubricId, $fieldId);
|
||||
$resolved = ProductRoles::resolve($roleFields, $roleSettings, $roleInput);
|
||||
foreach (ProductRoles::definitions() as $role => $definition) {
|
||||
if (isset($definition['column'])) { $data[$definition['column']] = $resolved[$role]; }
|
||||
}
|
||||
}
|
||||
|
||||
$data['product_card_template_id'] = isset($input['product_card_template_id']) ? max(0, (int) $input['product_card_template_id']) : 0;
|
||||
if ($data['product_card_template_id'] > 0 && !DB::query(
|
||||
'SELECT id FROM ' . CatalogTables::table('catalog_card_templates') . ' WHERE id=%i LIMIT 1',
|
||||
@@ -215,30 +250,41 @@
|
||||
);
|
||||
}
|
||||
|
||||
$existing = self::settings($rubricId, $fieldId);
|
||||
if ((int) $existing['id'] > 0) {
|
||||
DB::Update(self::settingsTable(), $data, 'id = %i', (int) $existing['id']);
|
||||
if ($data['purpose'] !== $existing['purpose'] && self::productsAvailable()) {
|
||||
try { ProductIndexer::rebuild(); }
|
||||
catch (\Throwable $e) { DB::Update(self::settingsTable(), array('purpose'=>$existing['purpose']), 'id=%i', (int) $existing['id']); throw $e; }
|
||||
$reindex = $data['purpose'] !== $existing['purpose'];
|
||||
foreach ($data as $key => $value) {
|
||||
if (preg_match('/^product_.*_field_id$/', $key) && (int) $value !== (int) $existing[$key]) { $reindex = true; }
|
||||
}
|
||||
|
||||
if ($roleInput !== null && $resolved !== ProductRoles::resolve($roleFields, $existing, ProductRoles::configured($rubricId))) { $reindex = true; }
|
||||
$registrySettings = Registry::get('settings');
|
||||
DB::startTransaction();
|
||||
try {
|
||||
$settingsId = (int) $existing['id'];
|
||||
if ($settingsId > 0) {
|
||||
DB::Update(self::settingsTable(), $data, 'id=%i', $settingsId);
|
||||
} else {
|
||||
$data['rubric_id'] = (int) $rubricId;
|
||||
$data['field_id'] = (int) $fieldId;
|
||||
DB::Insert(self::settingsTable(), $data);
|
||||
$settingsId = (int) DB::insertId();
|
||||
}
|
||||
|
||||
Cache::forgetTag(CacheKey::tag('catalog'));
|
||||
FileCacheInvalidator::publicPresentation();
|
||||
return (int) $existing['id'];
|
||||
if ($roleInput !== null) { ModuleSettings::set('field_roles_' . (int) $rubricId, $roleInput, 'products', 'json'); }
|
||||
if (self::productsAvailable()) { ProductRoles::reset(); }
|
||||
if ($reindex && self::productsAvailable()) { ProductIndexer::reindexRubric($rubricId, $existing['purpose'] === 'commerce' && $data['purpose'] === 'commerce'); }
|
||||
DB::afterCommit(function () {
|
||||
DB::clearTags(array('settings'));
|
||||
Cache::forgetTag(CacheKey::tag('catalog'));
|
||||
FileCacheInvalidator::publicPresentation();
|
||||
});
|
||||
DB::commit();
|
||||
} catch (\Throwable $e) {
|
||||
DB::rollback();
|
||||
Registry::set('settings', $registrySettings);
|
||||
if (self::productsAvailable()) { ProductRoles::reset(); }
|
||||
throw $e;
|
||||
}
|
||||
|
||||
$data['rubric_id'] = (int) $rubricId;
|
||||
$data['field_id'] = (int) $fieldId;
|
||||
DB::Insert(self::settingsTable(), $data);
|
||||
$settingsId = (int) DB::insertId();
|
||||
if ($data['purpose'] === 'commerce') {
|
||||
try { ProductIndexer::rebuild(); }
|
||||
catch (\Throwable $e) { DB::Delete(self::settingsTable(), 'id=%i', $settingsId); throw $e; }
|
||||
}
|
||||
|
||||
Cache::forgetTag(CacheKey::tag('catalog'));
|
||||
FileCacheInvalidator::publicPresentation();
|
||||
return $settingsId;
|
||||
}
|
||||
|
||||
@@ -358,6 +404,33 @@
|
||||
return $tree;
|
||||
}
|
||||
|
||||
public static function sourceOptions($rubricId, $fieldId)
|
||||
{
|
||||
$items = self::items($rubricId, $fieldId);
|
||||
$map = array();
|
||||
foreach ($items as $item) { $map[(int) $item['id']] = $item; }
|
||||
$out = array();
|
||||
foreach ($items as $item) {
|
||||
$parts = array((string) $item['name']);
|
||||
$parentId = (int) $item['parent_id'];
|
||||
$visited = array((int) $item['id'] => true);
|
||||
while ($parentId > 0 && isset($map[$parentId]) && empty($visited[$parentId])) {
|
||||
$visited[$parentId] = true;
|
||||
array_unshift($parts, (string) $map[$parentId]['name']);
|
||||
$parentId = (int) $map[$parentId]['parent_id'];
|
||||
}
|
||||
|
||||
$out[] = array(
|
||||
'id' => (int) $item['id'],
|
||||
'name' => (string) $item['name'],
|
||||
'path' => implode(' / ', $parts),
|
||||
'status' => (int) $item['status'],
|
||||
);
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
public static function item($id)
|
||||
{
|
||||
$row = DB::query(
|
||||
@@ -385,6 +458,12 @@
|
||||
if ($documentId > 0 && !self::documentExists($documentId)) { throw new \RuntimeException('Выбранный документ не найден'); }
|
||||
$filterIds = self::ids(isset($input['filters_use']) ? $input['filters_use'] : array());
|
||||
$filterIds = self::orderedIds(isset($input['filters_order']) ? $input['filters_order'] : array(), $filterIds);
|
||||
$sourceIds = self::validSourceItemIds(
|
||||
isset($input['source_item_ids']) ? $input['source_item_ids'] : array(),
|
||||
$id,
|
||||
$rubricId,
|
||||
$fieldId
|
||||
);
|
||||
$data = array(
|
||||
'rubric_id' => (int) $rubricId, 'field_id' => (int) $fieldId,
|
||||
'name' => $name, 'parent_id' => $parentId,
|
||||
@@ -396,6 +475,12 @@
|
||||
'filters_use' => implode(',', $filterIds),
|
||||
'filters_settings' => serialize(self::filterStyles(isset($input['filter_style']) ? $input['filter_style'] : array(), $filterIds)),
|
||||
);
|
||||
if (self::sourceItemsAvailable()) {
|
||||
$data['source_item_ids'] = implode(',', $sourceIds);
|
||||
} elseif ($sourceIds) {
|
||||
throw new \RuntimeException('Сначала примените миграцию каталога для источников товаров');
|
||||
}
|
||||
|
||||
if ($id > 0) {
|
||||
DB::Update(self::itemsTable(), $data, 'id = %i', $id);
|
||||
} else {
|
||||
@@ -608,7 +693,7 @@
|
||||
return array(
|
||||
'total'=>0,'quality_total'=>0,'active'=>0,'inactive'=>0,'without_category'=>0,
|
||||
'without_image'=>0,'without_article'=>0,'without_price'=>0,'without_stock'=>0,
|
||||
'without_excerpt'=>0,'without_seo'=>0,'stale'=>0,'shipping_incomplete'=>0,
|
||||
'without_description'=>0,'without_seo'=>0,'stale'=>0,'shipping_incomplete'=>0,
|
||||
'shipping_disabled'=>0,'duplicate_articles'=>0,'legacy_attributes'=>0,
|
||||
'filter_index_errors'=>0,'registration_incomplete'=>0,'without_video'=>0,
|
||||
'variant_errors'=>0,'description_markup'=>0,'sfr'=>0,'issues'=>0,'recommendations'=>0,'indexed_at'=>0,
|
||||
@@ -1053,27 +1138,50 @@
|
||||
|
||||
protected static function runFilterRecompile($rubricId, $itemId)
|
||||
{
|
||||
$runner = AdminLocation::path('modules/Catalog/bin/recompile.php');
|
||||
if (!is_file($runner)) { throw new \RuntimeException('Сценарий пересборки фильтров не найден'); }
|
||||
if (!function_exists('exec')) { throw new \RuntimeException('Функция exec недоступна'); }
|
||||
$output = array(); $code = 0;
|
||||
$command = escapeshellarg(self::phpCliBinary()) . ' ' . escapeshellarg($runner) . ' ' . (int) $rubricId . ' ' . (int) $itemId . ' 2>&1';
|
||||
exec($command, $output, $code);
|
||||
if ($code !== 0) { throw new \RuntimeException(trim(implode("\n", $output)) ?: 'Пересборка завершилась с ошибкой'); }
|
||||
return array('item_id' => (int) $itemId, 'output' => trim(implode("\n", $output)));
|
||||
}
|
||||
$item = static::item((int) $itemId);
|
||||
if (!$item || (int) $item['rubric_id'] !== (int) $rubricId) { throw new \RuntimeException('Раздел каталога не найден'); }
|
||||
$settings = static::settings((int) $rubricId, (int) $item['field_id']);
|
||||
$native = isset($item['filter_runtime']) && in_array($item['filter_runtime'], array('native', 'shadow'), true);
|
||||
$products = static::productsAvailable() && isset($settings['purpose']) && $settings['purpose'] === 'commerce';
|
||||
if ($native && !$products) { throw new \RuntimeException('Для нативных фильтров включите модуль «Товары»'); }
|
||||
if (!$native && $products && !method_exists(ProductIndexer::class, 'rebuildFilterIndex')) { throw new \RuntimeException('Обновите модуль «Товары» для пересборки индекса фильтров'); }
|
||||
$requestId = isset($settings['request_id']) ? (int) $settings['request_id'] : 0;
|
||||
if (!$native && !$products && $requestId < 1) { throw new \RuntimeException('Сначала выберите запрос фильтра в настройках каталога'); }
|
||||
$owns = !DB::$transaction_in_progress;
|
||||
$previousMode = DB::$throw_exception_on_error;
|
||||
$savepoint = 'catalog_filters_' . bin2hex(random_bytes(6));
|
||||
$started = false;
|
||||
DB::$throw_exception_on_error = true;
|
||||
try {
|
||||
if ($owns) { DB::startTransaction(); } else { DB::query('SAVEPOINT ' . $savepoint); }
|
||||
$started = true;
|
||||
$result = array('item_id' => (int) $itemId, 'runtime' => $native ? 'native' : 'legacy', 'request_id' => 0, 'products' => 0, 'filters' => 0);
|
||||
if ($native) {
|
||||
$report = Attributes::rebuildShadowIndex((int) $itemId);
|
||||
$result['filters'] = (int) $report['indexed_values'];
|
||||
$result['products'] = (int) DB::query('SELECT COUNT(DISTINCT product_id) FROM ' . Attributes::table('attribute_filter_index') . ' WHERE catalog_item_id=%i', (int) $itemId)->getValue();
|
||||
} else {
|
||||
if ($requestId > 0) {
|
||||
$compiled = \App\Content\Requests\RequestConditionCompiler::compile($requestId, true);
|
||||
if (!$compiled) { throw new \RuntimeException('Запрос фильтра не найден'); }
|
||||
$result['request_id'] = $requestId;
|
||||
}
|
||||
|
||||
protected static function phpCliBinary()
|
||||
{
|
||||
$candidates = array(getenv('PHP_CLI_BINARY'));
|
||||
if (defined('PHP_BINDIR')) { $candidates[] = PHP_BINDIR . '/php'; }
|
||||
if (defined('PHP_BINARY') && preg_match('/^php(?:[0-9.]*)?$/i', basename((string) PHP_BINARY))) { $candidates[] = PHP_BINARY; }
|
||||
$candidates[] = '/usr/local/bin/php'; $candidates[] = '/usr/bin/php';
|
||||
foreach (array_unique(array_filter($candidates)) as $candidate) {
|
||||
if (is_file($candidate) && is_executable($candidate)) { return $candidate; }
|
||||
}
|
||||
if ($products) {
|
||||
$ids = array_merge(array((int) $itemId), isset($item['source_item_ids']) ? (array) $item['source_item_ids'] : array());
|
||||
$result = array_merge($result, ProductIndexer::rebuildFilterIndex($ids));
|
||||
}
|
||||
}
|
||||
|
||||
throw new \RuntimeException('CLI-интерпретатор PHP не найден');
|
||||
if ($owns) { DB::commit(); } else { DB::query('RELEASE SAVEPOINT ' . $savepoint); }
|
||||
} catch (\Throwable $e) {
|
||||
if ($started && $owns) { DB::rollback(); }
|
||||
elseif ($started) { DB::query('ROLLBACK TO SAVEPOINT ' . $savepoint); DB::query('RELEASE SAVEPOINT ' . $savepoint); }
|
||||
throw $e;
|
||||
} finally { DB::$throw_exception_on_error = $previousMode; }
|
||||
DB::afterCommit(function () { static::clearCache(); });
|
||||
$result['output'] = $native ? 'Нативный индекс фильтров пересобран.' : 'Условия запроса и индекс фильтров пересобраны.';
|
||||
return $result;
|
||||
}
|
||||
|
||||
protected static function rebuildRequest($requestId)
|
||||
@@ -1084,6 +1192,7 @@
|
||||
protected static function clearCache()
|
||||
{
|
||||
DB::clearTags(array('documents', 'requests', 'modules', 'catalog'));
|
||||
(new FeedService())->clearAll();
|
||||
Cache::forgetTag(CacheKey::tag('catalog'));
|
||||
}
|
||||
|
||||
@@ -1124,6 +1233,28 @@
|
||||
|
||||
protected static function idsString($value) { return implode(',', self::ids($value)); }
|
||||
|
||||
public static function sourceItemsAvailable()
|
||||
{
|
||||
return DatabaseSchema::columnExists(self::itemsTable(), 'source_item_ids');
|
||||
}
|
||||
|
||||
protected static function validSourceItemIds($value, $itemId, $rubricId, $fieldId)
|
||||
{
|
||||
$ids = array_values(array_diff(self::ids($value), array((int) $itemId)));
|
||||
if (!$ids) { return array(); }
|
||||
$rows = DB::query(
|
||||
'SELECT id FROM ' . self::itemsTable()
|
||||
. ' WHERE rubric_id=%i AND field_id=%i AND id IN (' . implode(',', $ids) . ')',
|
||||
(int) $rubricId,
|
||||
(int) $fieldId
|
||||
)->getAll() ?: array();
|
||||
$allowed = array();
|
||||
foreach ($rows as $row) { $allowed[(int) $row['id']] = true; }
|
||||
return array_values(array_filter($ids, function ($id) use ($allowed) {
|
||||
return isset($allowed[(int) $id]);
|
||||
}));
|
||||
}
|
||||
|
||||
protected static function orderedIds($order, array $selected)
|
||||
{
|
||||
$selectedMap = array_fill_keys($selected, true); $out = array();
|
||||
@@ -1164,6 +1295,7 @@
|
||||
'level' => (int) $row['level'], 'position' => (int) $row['position'],
|
||||
'fields_use' => self::ids(isset($row['fields_use']) ? $row['fields_use'] : ''),
|
||||
'filters_use' => self::ids(isset($row['filters_use']) ? $row['filters_use'] : ''),
|
||||
'source_item_ids' => self::ids(isset($row['source_item_ids']) ? $row['source_item_ids'] : ''),
|
||||
'filter_styles' => is_array($styles) ? $styles : array(),
|
||||
'attribute_set_id' => isset($row['attribute_set_id']) ? (int) $row['attribute_set_id'] : 0,
|
||||
'attributes_runtime' => isset($row['attributes_runtime']) ? (string) $row['attributes_runtime'] : 'legacy',
|
||||
|
||||
@@ -739,6 +739,45 @@
|
||||
grid-template-columns: minmax(0, 1fr) 40px;
|
||||
gap: 6px;
|
||||
}
|
||||
.catalog-source-picker {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 40px;
|
||||
gap: 6px;
|
||||
}
|
||||
.catalog-source-picker [data-catalog-source-inputs] {
|
||||
display: none;
|
||||
}
|
||||
.catalog-source-value {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
min-width: 0;
|
||||
min-height: 40px;
|
||||
padding: 8px 11px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--background-card);
|
||||
color: var(--text-primary);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.catalog-source-value:hover:not(:disabled) {
|
||||
border-color: var(--blue-300);
|
||||
background: var(--blue-50);
|
||||
}
|
||||
.catalog-source-value:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.catalog-source-value i {
|
||||
flex: 0 0 auto;
|
||||
color: var(--blue-600);
|
||||
}
|
||||
.catalog-source-value span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.catalog-document-value {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -832,6 +871,74 @@
|
||||
font-size: 11px;
|
||||
font-style: normal;
|
||||
}
|
||||
.catalog-source-modal {
|
||||
width: min(66.666vw, 1000px);
|
||||
height: min(72vh, 760px);
|
||||
max-height: calc(100vh - 40px);
|
||||
}
|
||||
.catalog-source-modal .modal-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.catalog-source-modal .modal-header > div {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.catalog-source-modal .modal-header p {
|
||||
margin: 3px 0 0;
|
||||
}
|
||||
.catalog-source-options {
|
||||
display: grid;
|
||||
flex: 1 1 auto;
|
||||
align-content: start;
|
||||
gap: 6px;
|
||||
min-height: 0;
|
||||
margin-top: 12px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.catalog-source-option {
|
||||
display: grid;
|
||||
grid-template-columns: 20px minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 54px;
|
||||
padding: 8px 11px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--background-card);
|
||||
cursor: pointer;
|
||||
}
|
||||
.catalog-source-option:hover {
|
||||
border-color: var(--blue-300);
|
||||
background: var(--blue-50);
|
||||
}
|
||||
.catalog-source-option[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.catalog-source-option > span {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
}
|
||||
.catalog-source-option b,
|
||||
.catalog-source-option small {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.catalog-source-option small {
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
}
|
||||
.catalog-source-option em {
|
||||
font-style: normal;
|
||||
}
|
||||
.catalog-source-empty {
|
||||
padding: 28px 0;
|
||||
color: var(--text-secondary);
|
||||
text-align: center;
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.catalog-condition-toolbar {
|
||||
align-items: stretch;
|
||||
@@ -885,6 +992,16 @@
|
||||
.catalog-document-result em {
|
||||
display: none;
|
||||
}
|
||||
.catalog-source-modal {
|
||||
width: calc(100vw - 20px);
|
||||
height: calc(100vh - 20px);
|
||||
}
|
||||
.catalog-source-option {
|
||||
grid-template-columns: 20px minmax(0, 1fr);
|
||||
}
|
||||
.catalog-source-option em {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@media (max-width: 1100px) {
|
||||
.catalog-behavior-grid {
|
||||
@@ -956,3 +1073,123 @@
|
||||
height: 40px;
|
||||
}
|
||||
}
|
||||
.catalog-role-preview {
|
||||
margin-top: 24px;
|
||||
min-width: 0;
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-preview {
|
||||
margin: 20px 0;
|
||||
padding: 16px 0;
|
||||
border-top: 1px solid var(--border-color, #e3e5e8);
|
||||
border-bottom: 1px solid var(--border-color, #e3e5e8);
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-preview h4 {
|
||||
margin: 0 0 12px;
|
||||
font-size: 15px;
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-preview [hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-controls {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 210px), 1fr));
|
||||
align-items: end;
|
||||
gap: 12px;
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-controls .field {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-controls .select,
|
||||
.catalog-role-preview .catalog-selection-controls .input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 40px;
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-controls .btn {
|
||||
min-height: 40px;
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-result {
|
||||
margin-top: 16px;
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-result ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-result li {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
margin: 6px 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-result li .ti {
|
||||
flex: 0 0 16px;
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-result li span {
|
||||
min-width: 0;
|
||||
}
|
||||
.catalog-role-preview .catalog-selection-result b {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.catalog-role-preview h3,
|
||||
.catalog-role-preview p {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.catalog-role-preview .table {
|
||||
table-layout: fixed;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
.catalog-role-preview th:first-child {
|
||||
width: 24%;
|
||||
}
|
||||
.catalog-role-preview th:nth-child(2) {
|
||||
width: 32%;
|
||||
}
|
||||
.catalog-role-preview td {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.catalog-role-preview .btn-group {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.catalog-role-preview .btn {
|
||||
white-space: normal;
|
||||
min-height: 40px;
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.catalog-role-preview .table-wrap {
|
||||
overflow: visible;
|
||||
}
|
||||
.catalog-role-preview .table,
|
||||
.catalog-role-preview tbody,
|
||||
.catalog-role-preview tr,
|
||||
.catalog-role-preview td {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
.catalog-role-preview thead {
|
||||
display: none;
|
||||
}
|
||||
.catalog-role-preview tr {
|
||||
padding: 12px 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.catalog-role-preview td {
|
||||
padding: 4px 8px;
|
||||
border: 0;
|
||||
}
|
||||
.catalog-role-preview td:first-child {
|
||||
font-weight: 600;
|
||||
}
|
||||
.catalog-role-preview td[data-label]::before {
|
||||
content: attr(data-label) ': ';
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
'use strict';
|
||||
var Adminx = window.Adminx || (window.Adminx = {});
|
||||
Adminx.Catalog = {
|
||||
itemForm: null, settingsForm: null, dragItem: null, dragGroup: [], dragPlaceholder: null, dragGhost: null, dragPointerId: null, dragStartX: 0, dragStartY: 0, dragStarted: false, dragOrderSnapshot: '', orderSaving: false, filterOrder: [], itemSaveTimer: null, settingsSaveTimer: null, conditionContext: null,
|
||||
itemForm: null, settingsForm: null, dragItem: null, dragGroup: [], dragPlaceholder: null, dragGhost: null, dragPointerId: null, dragStartX: 0, dragStartY: 0, dragStarted: false, dragOrderSnapshot: '', orderSaving: false, filterOrder: [], sourceItemIds: [], sourceOptionsData: null, itemSaveTimer: null, settingsSaveTimer: null, conditionContext: null,
|
||||
init: function () {
|
||||
this.itemForm = document.getElementById('catalogItemForm');
|
||||
this.settingsForm = document.getElementById('catalogSettingsForm');
|
||||
var self = this;
|
||||
document.addEventListener('click', function (e) {
|
||||
if (e.target.closest('[data-product-role-refresh]')) { self.refreshRolePreview(false); return; }
|
||||
if (e.target.closest('[data-product-selection-check]')) { self.refreshRolePreview(true); return; }
|
||||
var pageTab = e.target.closest('[data-catalog-page-tab]');
|
||||
if (pageTab) { self.tab('[data-catalog-page-tab]', '[data-catalog-page-panel]', pageTab.getAttribute('data-catalog-page-tab')); }
|
||||
var drawerTab = e.target.closest('[data-catalog-drawer-tab]');
|
||||
@@ -27,6 +29,8 @@
|
||||
if (treeRow && !e.target.closest('button, input, label, a, select')) { self.editItem(treeRow.getAttribute('data-catalog-builder-item')); return; }
|
||||
if (e.target.closest('[data-catalog-document-pick]')) { self.openDocumentPicker(); }
|
||||
if (e.target.closest('[data-catalog-document-clear]')) { self.setDocument(null); self.scheduleItemSave(); }
|
||||
if (e.target.closest('[data-catalog-source-open]')) { self.openSourcePicker(); }
|
||||
if (e.target.closest('[data-catalog-source-clear]')) { self.setSources([]); self.scheduleItemSave(); }
|
||||
var conditionView = e.target.closest('[data-catalog-condition-view]');
|
||||
if (conditionView) { self.showCondition(conditionView.getAttribute('data-catalog-condition-view')); }
|
||||
var conditionSync = e.target.closest('[data-catalog-condition-sync]');
|
||||
@@ -37,9 +41,11 @@
|
||||
if (e.target.closest('[data-catalog-recompile-all]')) { self.recompileAll(); }
|
||||
});
|
||||
document.addEventListener('input', function (e) {
|
||||
if (e.target.closest('[data-product-role-preview]')) { self.selectionChanged(); return; }
|
||||
if (e.target.matches('[data-catalog-tree-search]')) { self.search(e.target.value); }
|
||||
});
|
||||
document.addEventListener('change', function (e) {
|
||||
if (e.target.closest('[data-product-role-preview]')) { self.selectionChanged(); return; }
|
||||
if (e.target.matches('[data-catalog-item-status]')) { self.setTreeStatus(e.target); return; }
|
||||
if (self.itemForm && e.target.closest('#catalogItemForm')) {
|
||||
if (e.target.matches('[name="filters_use[]"]')) { self.syncFilterOrderSelection(); }
|
||||
@@ -59,6 +65,44 @@
|
||||
document.addEventListener('pointercancel', function () { self.treeDragEnd(); });
|
||||
this.normalizeTreeHierarchy();
|
||||
this.openRequestedItem();
|
||||
if (window.location.hash === '#settings') { this.tab('[data-catalog-page-tab]', '[data-catalog-page-panel]', 'settings'); }
|
||||
},
|
||||
selectionChanged: function () {
|
||||
this.rolePreviewSequence = (this.rolePreviewSequence || 0) + 1;
|
||||
var root = document.querySelector('[data-product-role-preview]');
|
||||
if (!root) { return; }
|
||||
var context = root.querySelector('[data-selection="context"]');
|
||||
root.querySelectorAll('[data-selection-context]').forEach(function (el) { el.hidden = !context || el.getAttribute('data-selection-context') !== context.value; });
|
||||
var result = root.querySelector('[data-selection-result]'), stale = root.querySelector('[data-selection-stale]');
|
||||
if (result) { result.hidden = true; if (stale) { stale.hidden = false; } }
|
||||
},
|
||||
refreshRolePreview: function (check) {
|
||||
var input = document.querySelector('[data-product-role-document]');
|
||||
if (!input || !input.checkValidity()) { if (input) { input.reportValidity(); } return; }
|
||||
var root = input.closest('[data-product-role-preview]');
|
||||
var invalid = Array.prototype.find.call(root.querySelectorAll('[data-selection-context]:not([hidden]) input'), function (el) { return !el.checkValidity(); });
|
||||
if (invalid) { invalid.reportValidity(); return; }
|
||||
var self = this, sequence = (this.rolePreviewSequence || 0) + 1;
|
||||
var errorMessage = root.getAttribute('data-error');
|
||||
this.rolePreviewSequence = sequence;
|
||||
var url = new URL(this.url() + '/product-preview', window.location.origin);
|
||||
url.searchParams.set('product_preview', input.value || '0');
|
||||
url.searchParams.set('selection_check', check === true ? '1' : '0');
|
||||
root.querySelectorAll('[data-selection]').forEach(function (el) { url.searchParams.set('selection_' + el.getAttribute('data-selection'), el.value); });
|
||||
root.setAttribute('aria-busy', 'true');
|
||||
root.querySelectorAll('button').forEach(function (el) { el.disabled = true; });
|
||||
fetch(url.toString(), { credentials: 'same-origin' }).then(function (response) {
|
||||
if (!response.ok) { throw new Error(errorMessage); }
|
||||
return response.text();
|
||||
}).then(function (html) {
|
||||
if (sequence !== self.rolePreviewSequence) { return; }
|
||||
var preview = new DOMParser().parseFromString(html, 'text/html').querySelector('[data-product-role-preview]');
|
||||
var current = document.querySelector('[data-product-role-preview]');
|
||||
if (!preview || !current) { throw new Error(errorMessage); }
|
||||
current.replaceWith(preview);
|
||||
}).catch(function (error) { if (sequence === self.rolePreviewSequence) { Adminx.Toast.show(error.message, 'error'); } }).finally(function () {
|
||||
root.removeAttribute('aria-busy'); root.querySelectorAll('button').forEach(function (el) { el.disabled = false; });
|
||||
});
|
||||
},
|
||||
base: function () { return (this.itemForm || this.settingsForm).getAttribute('data-base'); },
|
||||
rubric: function () { return (this.itemForm || this.settingsForm).getAttribute('data-rubric'); },
|
||||
@@ -76,6 +120,7 @@
|
||||
document.querySelectorAll(panels).forEach(function (el) { el.hidden = el.getAttribute(panels.indexOf('drawer') >= 0 ? 'data-catalog-drawer-panel' : 'data-catalog-page-panel') !== value; });
|
||||
},
|
||||
newItem: function (parentId) {
|
||||
this.renderContextLinks([]);
|
||||
this.itemForm.reset(); this.itemForm.querySelector('[name="id"]').value = ''; this.itemForm.querySelector('[name="status"]').checked = true;
|
||||
this.itemForm.querySelectorAll('[name="parent_id"] option').forEach(function (option) { option.disabled = false; });
|
||||
var parent = this.itemForm.querySelector('[name="parent_id"]');
|
||||
@@ -84,7 +129,7 @@
|
||||
this.checkValues('fields_use[]', defaultFields); this.checkValues('filters_use[]', defaultFilters);
|
||||
defaultFilters.forEach(function (id) { var source = this.settingsForm.querySelector('[name="filter_style[' + id + ']"]'), target = this.itemForm.querySelector('[name="filter_style[' + id + ']"]'); if (source && target) { target.value = source.value; } }, this);
|
||||
this.filterOrder = defaultFilters.slice(); this.syncFilterOrderInput();
|
||||
this.setDocument(null); this.setState('item', ''); this.renderConditionContext(null);
|
||||
this.setDocument(null); this.setSources([]); this.setState('item', ''); this.renderConditionContext(null);
|
||||
document.querySelector('[data-catalog-drawer-title]').textContent = 'Новый раздел'; this.tab('[data-catalog-drawer-tab]', '[data-catalog-drawer-panel]', 'main'); this.updateCounts();
|
||||
Adminx.Drawer.open('catalogItemDrawer');
|
||||
},
|
||||
@@ -105,10 +150,12 @@
|
||||
this.editItem(itemId, params.get('tab') || 'main');
|
||||
},
|
||||
fill: function (item) {
|
||||
this.renderContextLinks(item.context_links || []);
|
||||
this.itemForm.reset(); this.itemForm.querySelector('[name="id"]').value = item.id || ''; this.itemForm.querySelector('[name="name"]').value = item.name || '';
|
||||
this.itemForm.querySelectorAll('[name="parent_id"] option').forEach(function (option) { option.disabled = false; });
|
||||
this.itemForm.querySelector('[name="parent_id"]').value = item.parent_id || 0; this.itemForm.querySelector('[name="status"]').checked = Number(item.status) === 1;
|
||||
this.setDocument(item.document_id ? { id: item.document_id, title: item.document_title || '', alias: item.document_alias || '' } : null);
|
||||
this.setSources(item.source_item_ids || []);
|
||||
this.filterOrder = (item.filters_use || []).map(function (id) { return String(id); }); this.syncFilterOrderInput(); this.checkValues('fields_use[]', item.fields_use || []); this.checkValues('filters_use[]', item.filters_use || []);
|
||||
Object.keys(item.filter_styles || {}).forEach(function (id) { var select = this.itemForm.querySelector('[name="filter_style[' + id + ']"]'); if (select) { select.value = item.filter_styles[id]; } }, this);
|
||||
var own = this.itemForm.querySelector('[name="parent_id"] option[value="' + item.id + '"]'); if (own) { own.disabled = true; }
|
||||
@@ -125,6 +172,20 @@
|
||||
syncFilterOrderSelection: function () { var selected = {}, next = []; this.itemForm.querySelectorAll('[name="filters_use[]"]:checked').forEach(function (input) { selected[input.value] = true; }); this.filterOrder.forEach(function (id) { if (selected[id]) { next.push(id); delete selected[id]; } }); this.itemForm.querySelectorAll('[name="filters_use[]"]:checked').forEach(function (input) { if (selected[input.value]) { next.push(input.value); delete selected[input.value]; } }); this.filterOrder = next; this.syncFilterOrderInput(); },
|
||||
syncFilterOrderInput: function () { var input = this.itemForm && this.itemForm.querySelector('[name="filters_order"]'); if (input) { input.value = this.filterOrder.join(','); } },
|
||||
openFilterOrder: function () { var self = this; this.syncFilterOrderSelection(); if (this.filterOrder.length < 2) { return; } var overlay = document.createElement('div'), rows = ''; this.filterOrder.forEach(function (id) { var input = self.itemForm.querySelector('[name="filters_use[]"][value="' + id + '"]'), row = input.closest('.catalog-filter-row'), title = row.querySelector('.catalog-choice-copy b').textContent.trim(), type = row.querySelector('.catalog-field-type b').textContent.trim(); rows += '<div class="catalog-filter-order-row" data-filter-order-id="' + self.esc(id) + '"><button class="catalog-filter-order-handle" type="button" draggable="true" aria-label="Перетащить"><i class="ti ti-grip-vertical"></i></button><span><b>' + self.esc(title) + '</b><small>' + self.esc(type) + ' · #' + self.esc(id) + '</small></span></div>'; }); overlay.className = 'overlay catalog-filter-order-overlay'; overlay.innerHTML = '<div class="modal catalog-filter-order-modal" role="dialog" aria-modal="true"><div class="modal-header"><span class="dialog-icon info"><i class="ti ti-arrows-sort"></i></span><div><h3>Порядок фильтров</h3><p class="text-secondary">' + this.filterOrder.length + ' включённых фильтров.</p></div><button class="modal-close" type="button" data-filter-order-close aria-label="Закрыть"><i class="ti ti-x"></i></button></div><div class="modal-body"><div class="catalog-filter-order-list">' + rows + '</div></div><div class="modal-footer"><button class="btn btn-ghost" type="button" data-filter-order-close>Закрыть</button><button class="btn btn-primary" type="button" data-filter-order-save><i class="ti ti-device-floppy"></i>Сохранить порядок</button></div></div>'; document.body.appendChild(overlay); requestAnimationFrame(function () { overlay.classList.add('show'); }); var dragged = null, close = function () { overlay.classList.remove('show'); setTimeout(function () { overlay.remove(); }, 160); }; overlay.addEventListener('dragstart', function (e) { var handle = e.target.closest('.catalog-filter-order-handle'), row = handle ? handle.closest('[data-filter-order-id]') : null; if (!row) { e.preventDefault(); return; } dragged = row; row.classList.add('is-dragging'); e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', row.getAttribute('data-filter-order-id')); }); overlay.addEventListener('dragover', function (e) { var target = e.target.closest('[data-filter-order-id]'); if (!dragged || !target || target === dragged) { return; } e.preventDefault(); var rect = target.getBoundingClientRect(), reference = e.clientY < rect.top + rect.height / 2 ? target : target.nextSibling; if (reference !== dragged && dragged.nextSibling !== reference) { target.parentNode.insertBefore(dragged, reference); } }); overlay.addEventListener('dragend', function () { if (dragged) { dragged.classList.remove('is-dragging'); dragged = null; } }); overlay.addEventListener('click', function (e) { if (e.target === overlay || e.target.closest('[data-filter-order-close]')) { close(); return; } if (e.target.closest('[data-filter-order-save]')) { self.filterOrder = Array.prototype.map.call(overlay.querySelectorAll('[data-filter-order-id]'), function (row) { return row.getAttribute('data-filter-order-id'); }); self.syncFilterOrderInput(); self.scheduleItemSave(); close(); } }); },
|
||||
renderContextLinks: function (links) {
|
||||
var panel = this.itemForm && this.itemForm.querySelector('[data-catalog-context-links]');
|
||||
if (!panel) { return; }
|
||||
var list = panel.querySelector('nav');
|
||||
list.textContent = '';
|
||||
(links || []).forEach(function (link) {
|
||||
var anchor = document.createElement('a'), icon = document.createElement('i'), label = document.createElement('span');
|
||||
anchor.href = link.url; anchor.target = '_blank'; anchor.rel = 'noopener'; anchor.setAttribute('data-context-kind', link.kind);
|
||||
icon.className = 'ti ti-external-link'; icon.setAttribute('aria-hidden', 'true'); label.textContent = link.label;
|
||||
if (link.scope) { var scope = document.createElement('small'); scope.textContent = link.scope; label.appendChild(scope); }
|
||||
anchor.appendChild(icon); anchor.appendChild(label); list.appendChild(anchor);
|
||||
});
|
||||
panel.hidden = !list.children.length;
|
||||
},
|
||||
renderConditionContext: function (context) {
|
||||
this.conditionContext = context || { request: { id: 0, title: '' }, states: {}, summary: { synced: 0, staged: 0, missing: 0, different: 0, unsupported: 0 } };
|
||||
var request = this.conditionContext.request || {}, summary = this.conditionContext.summary || {}, requestEl = document.querySelector('[data-catalog-condition-request]'), summaryEl = document.querySelector('[data-catalog-condition-summary]'), bulk = document.querySelector('[data-catalog-conditions-sync]');
|
||||
@@ -172,16 +233,61 @@
|
||||
saveItem: function (auto) {
|
||||
var id = this.itemForm.querySelector('[name="id"]').value; var self = this;
|
||||
this.ajax(this.url() + '/items' + (id ? '/' + id : ''), new FormData(this.itemForm), function (payload) {
|
||||
if (payload.data && payload.data.context_links) { self.renderContextLinks(payload.data.context_links); }
|
||||
if (auto) { self.setState('item', 'Сохранено', 'ok'); self.syncTreeRow(id); if (payload.data && payload.data.condition_context) { self.renderConditionContext(payload.data.condition_context); } return; }
|
||||
Adminx.Toast.show(payload.message, 'success'); if (Adminx.Drawer) { Adminx.Drawer.close('catalogItemDrawer'); } window.location.reload();
|
||||
}, { quiet: !!auto, fail: function () { self.setState('item', 'Не сохранено', 'error'); } });
|
||||
},
|
||||
saveSettings: function (auto) { var self = this; this.ajax(this.url() + '/settings', new FormData(this.settingsForm), function (payload) { if (auto) { self.setState('settings', 'Сохранено', 'ok'); } else { self.setState('settings', 'Сохранено', 'ok'); Adminx.Toast.show(payload.message, 'success'); } }, { quiet: !!auto, fail: function () { self.setState('settings', 'Не сохранено', 'error'); } }); },
|
||||
saveSettings: function (auto) { var self = this; this.ajax(this.url() + '/settings', new FormData(this.settingsForm), function (payload) { self.refreshRolePreview(); if (auto) { self.setState('settings', 'Сохранено', 'ok'); } else { self.setState('settings', 'Сохранено', 'ok'); Adminx.Toast.show(payload.message, 'success'); } }, { quiet: !!auto, fail: function () { self.setState('settings', 'Не сохранено', 'error'); } }); },
|
||||
setState: function (type, message, state) { var el = document.querySelector('[data-catalog-' + type + '-state]'); if (!el) { return; } el.textContent = message || ''; el.classList.toggle('is-ok', state === 'ok'); el.classList.toggle('is-error', state === 'error'); },
|
||||
syncTreeRow: function (id) { var row = document.querySelector('[data-catalog-item][data-id="' + id + '"]'); if (!row) { return; } var toggle = row.querySelector('[data-catalog-item-status]'), active = this.itemForm.querySelector('[name="status"]').checked, filterCount = this.itemForm.querySelectorAll('[name="filters_use[]"]:checked').length, name = row.querySelector('.catalog-tree-name b'); if (toggle) { toggle.checked = active; this.updateTreeStatus(toggle); } if (name) { name.textContent = this.itemForm.querySelector('[name="name"]').value || 'Без названия'; } row.setAttribute('data-filter-count', String(filterCount)); var count = row.querySelector('.catalog-tree-count'); if (count) { count.textContent = this.itemForm.querySelectorAll('[name="fields_use[]"]:checked').length + ' / ' + filterCount; } },
|
||||
updateTreeStatus: function (input) { var item = input.closest('[data-catalog-item]'), active = input.checked, label = item.querySelector('[data-catalog-item-status-label]'), control = input.closest('.switch'); item.classList.toggle('is-inactive', !active); if (label) { label.textContent = active ? 'активен' : 'скрыт'; } input.setAttribute('aria-label', active ? 'Скрыть раздел' : 'Включить раздел'); if (control) { control.setAttribute('data-tooltip', active ? 'Скрыть раздел' : 'Включить раздел'); } },
|
||||
setTreeStatus: function (input) { var self = this, id = input.getAttribute('data-catalog-item-status'), previous = !input.checked, data = new FormData(); this.updateTreeStatus(input); input.disabled = true; data.append('_csrf', this.csrf()); data.append('status', input.checked ? '1' : '0'); this.ajax(this.url() + '/items/' + encodeURIComponent(id) + '/status', data, function (payload) { input.checked = Number(payload.data.status) === 1; input.disabled = false; self.updateTreeStatus(input); }, { quiet: true, fail: function () { input.checked = previous; input.disabled = false; self.updateTreeStatus(input); } }); },
|
||||
setDocument: function (item) { if (!this.itemForm) { return; } var input = this.itemForm.querySelector('[name="document_id"]'); var label = this.itemForm.querySelector('[data-catalog-document-label]'); var clear = this.itemForm.querySelector('[data-catalog-document-clear]'); var id = item && item.id ? Number(item.id) : 0; input.value = id || ''; if (label) { label.textContent = id ? ('#' + id + ' · ' + (item.title || item.alias || 'Без названия')) : 'Документ не выбран'; } if (clear) { clear.disabled = !id; } },
|
||||
sourceOptions: function () {
|
||||
if (this.sourceOptionsData !== null) { return this.sourceOptionsData; }
|
||||
var node = document.querySelector('[data-catalog-source-options]');
|
||||
try { this.sourceOptionsData = node ? JSON.parse(node.textContent || '[]') : []; }
|
||||
catch (e) { this.sourceOptionsData = []; }
|
||||
return this.sourceOptionsData;
|
||||
},
|
||||
setSources: function (values) {
|
||||
if (!this.itemForm) { return; }
|
||||
var ownId = Number(this.itemForm.querySelector('[name="id"]').value) || 0, allowed = {}, selected = [];
|
||||
this.sourceOptions().forEach(function (item) { if (Number(item.id) !== ownId) { allowed[String(item.id)] = item; } });
|
||||
(values || []).forEach(function (id) { id = String(Number(id) || 0); if (allowed[id] && selected.indexOf(id) === -1) { selected.push(id); } });
|
||||
this.sourceItemIds = selected;
|
||||
var inputs = this.itemForm.querySelector('[data-catalog-source-inputs]'), label = this.itemForm.querySelector('[data-catalog-source-label]'), clear = this.itemForm.querySelector('[data-catalog-source-clear]');
|
||||
if (inputs) {
|
||||
inputs.innerHTML = '';
|
||||
selected.forEach(function (id) { var input = document.createElement('input'); input.type = 'hidden'; input.name = 'source_item_ids[]'; input.value = id; inputs.appendChild(input); });
|
||||
}
|
||||
if (label) {
|
||||
var names = selected.map(function (id) { return allowed[id].name; });
|
||||
label.textContent = names.length === 0 ? 'Товары только из этого раздела' : (names.slice(0, 2).join(', ') + (names.length > 2 ? ' · ещё ' + (names.length - 2) : ''));
|
||||
}
|
||||
if (clear) { clear.disabled = selected.length === 0; }
|
||||
},
|
||||
openSourcePicker: function () {
|
||||
var self = this, ownId = Number(this.itemForm.querySelector('[name="id"]').value) || 0;
|
||||
var options = this.sourceOptions().filter(function (item) { return Number(item.id) !== ownId; });
|
||||
var selected = {}; this.sourceItemIds.forEach(function (id) { selected[String(id)] = true; });
|
||||
var overlay = document.createElement('div'), rows = '';
|
||||
options.forEach(function (item) {
|
||||
var id = String(item.id), search = (id + ' ' + (item.path || item.name || '')).toLowerCase();
|
||||
rows += '<label class="catalog-source-option" data-catalog-source-option data-search="' + self.esc(search) + '"><input type="checkbox" value="' + self.esc(id) + '"' + (selected[id] ? ' checked' : '') + '><span><b>' + self.esc(item.name || 'Без названия') + '</b><small>' + self.esc(item.path || ('Раздел #' + id)) + '</small></span><em class="badge ' + (Number(item.status) === 1 ? 'badge-green' : 'badge-gray') + '">' + (Number(item.status) === 1 ? 'активен' : 'скрыт') + '</em></label>';
|
||||
});
|
||||
overlay.className = 'overlay catalog-source-overlay';
|
||||
overlay.innerHTML = '<div class="modal catalog-source-modal" role="dialog" aria-modal="true"><div class="modal-header"><span class="dialog-icon info"><i class="ti ti-folders"></i></span><div><h3>Источники товаров</h3><p class="text-secondary">Товары выбранных разделов появятся на текущей странице.</p></div><button class="modal-close" type="button" data-catalog-source-close aria-label="Закрыть"><i class="ti ti-x"></i></button></div><div class="modal-body"><label class="input-wrap"><i class="ti ti-search"></i><input class="input" type="search" placeholder="Найти раздел по названию или ID" data-catalog-source-search></label><div class="catalog-source-options">' + rows + '</div><div class="catalog-source-empty" data-catalog-source-empty' + (options.length ? ' hidden' : '') + '>Подходящих разделов нет</div></div><div class="modal-footer"><span class="mf-left text-secondary text-sm" data-catalog-source-count></span><button class="btn btn-ghost" type="button" data-catalog-source-close>Закрыть</button><button class="btn btn-primary" type="button" data-catalog-source-save><i class="ti ti-check"></i>Применить</button></div></div>';
|
||||
document.body.appendChild(overlay); requestAnimationFrame(function () { overlay.classList.add('show'); });
|
||||
var search = overlay.querySelector('[data-catalog-source-search]'), count = overlay.querySelector('[data-catalog-source-count]'), empty = overlay.querySelector('[data-catalog-source-empty]');
|
||||
var update = function () { var checked = overlay.querySelectorAll('[data-catalog-source-option] input:checked').length; count.textContent = checked ? ('Выбрано: ' + checked) : 'Источники не выбраны'; };
|
||||
var filter = function () { var query = (search.value || '').trim().toLowerCase(), visible = 0; overlay.querySelectorAll('[data-catalog-source-option]').forEach(function (row) { var show = !query || row.getAttribute('data-search').indexOf(query) !== -1; row.hidden = !show; if (show) { visible++; } }); empty.hidden = visible > 0; };
|
||||
var close = function () { overlay.classList.remove('show'); setTimeout(function () { overlay.remove(); }, 160); };
|
||||
overlay.addEventListener('change', update);
|
||||
overlay.addEventListener('click', function (e) { if (e.target === overlay || e.target.closest('[data-catalog-source-close]')) { close(); return; } if (e.target.closest('[data-catalog-source-save]')) { self.setSources(Array.prototype.map.call(overlay.querySelectorAll('[data-catalog-source-option] input:checked'), function (input) { return input.value; })); self.scheduleItemSave(); close(); } });
|
||||
search.addEventListener('input', filter); update(); search.focus();
|
||||
},
|
||||
openDocumentPicker: function () {
|
||||
var self = this, overlay = document.createElement('div');
|
||||
overlay.className = 'overlay catalog-document-overlay';
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
.catalog-context-links {
|
||||
padding: 16px 0;
|
||||
border-bottom: 1px solid var(--border-default);
|
||||
min-width: 0;
|
||||
}
|
||||
.catalog-context-links h3 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.catalog-context-links nav {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px 24px;
|
||||
}
|
||||
.catalog-context-links a {
|
||||
display: inline-flex;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
.catalog-context-links a > i {
|
||||
flex: none;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.catalog-context-links a > span {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.catalog-context-links small {
|
||||
display: block;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.catalog-item-form > .catalog-context-links {
|
||||
padding: 16px 20px;
|
||||
}
|
||||
@@ -20,6 +20,7 @@
|
||||
<phrase data="auto_944019ea5d01e63a">hidden</phrase>
|
||||
<phrase data="auto_9729bca62f6c558e">Request Error</phrase>
|
||||
<phrase data="auto_99d406eeba4f9acb">Section</phrase>
|
||||
<phrase data="auto_9b62723a4333bb4a">Find section</phrase>
|
||||
<phrase data="auto_9f8bfc6bf2339426"><div class="alert alert-error"><i class="ti ti-alert-triangle"></i><div>Errors:</phrase>
|
||||
<phrase data="auto_a456fd20d54a422c"></p></div><button class="modal-close" type="button" data-catalog-recompile-close aria-label="Close" disabled><i class="ti ti-x"></i></button></div><div class="modal-body"><div class="catalog-recompile-status" data-catalog-recompile-status>Preparing...</div><div class="progress"><div class="progress-bar" data-catalog-recompile-progress style="width:0%;--progress-color:var(--blue-500)"></div></div><div class="catalog-recompile-errors" data-catalog-recompile-errors></div></div><div class="modal-footer"><button class="btn btn-ghost" type="button" data-catalog-recompile-stop>Stop</button><button class="btn btn-primary" type="button" data-catalog-recompile-close disabled>Close</button></div></div></phrase>
|
||||
<phrase data="auto_a4c0ae2fa076f2fd">Hide section</phrase>
|
||||
@@ -36,6 +37,11 @@
|
||||
<phrase data="auto_f61de80bf0ca15a4">No document selected</phrase>
|
||||
<phrase data="auto_f6bde2876efe2658">Not included</phrase>
|
||||
<phrase data="auto_fda18205701b609b">Replace condition?</phrase>
|
||||
<phrase data="catalog_roles_more">more</phrase>
|
||||
<phrase data="catalog_roles_no">No</phrase>
|
||||
<phrase data="catalog_selection_catalog">Catalog</phrase>
|
||||
<phrase data="catalog_selection_category">Category</phrase>
|
||||
<phrase data="catalog_selection_search">Search</phrase>
|
||||
<phrase data="runtime_6291ecb1784ea2de">Catalog created</phrase>
|
||||
<phrase data="runtime_6b3607219bc8c7f0">different</phrase>
|
||||
<phrase data="runtime_d0ef3540b088bbf6">Catalog</phrase>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="catalog_context_title">Related Settings</phrase>
|
||||
<phrase data="catalog_context_filters">Section Filters</phrase>
|
||||
<phrase data="catalog_context_attribute_set">Attribute Set</phrase>
|
||||
<phrase data="catalog_context_card">Catalog Card Template</phrase>
|
||||
<phrase data="catalog_context_page">Page Template</phrase>
|
||||
</language>
|
||||
@@ -0,0 +1,63 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="catalog_roles_description">Product Description</phrase>
|
||||
<phrase data="catalog_roles_warranty">Warranty</phrase>
|
||||
<phrase data="catalog_roles_registration_text">Registration Document Text</phrase>
|
||||
<phrase data="catalog_roles_registration_number">Registration Document Number</phrase>
|
||||
<phrase data="catalog_roles_title">Product Field Roles</phrase>
|
||||
<phrase data="catalog_roles_saved">Saved Mapping</phrase>
|
||||
<phrase data="catalog_roles_document">Document #</phrase>
|
||||
<phrase data="catalog_roles_sample">Sample Product</phrase>
|
||||
<phrase data="catalog_roles_check">Check</phrase>
|
||||
<phrase data="catalog_roles_optional">Optional Project Fields</phrase>
|
||||
<phrase data="catalog_roles_auto">Automatic:</phrase>
|
||||
<phrase data="catalog_roles_unassigned">Not Assigned</phrase>
|
||||
<phrase data="catalog_roles_name">Name</phrase>
|
||||
<phrase data="catalog_roles_article">SKU</phrase>
|
||||
<phrase data="catalog_roles_price">Price</phrase>
|
||||
<phrase data="catalog_roles_old_price">Old Price</phrase>
|
||||
<phrase data="catalog_roles_stock">Stock Quantity</phrase>
|
||||
<phrase data="catalog_roles_images">Images</phrase>
|
||||
<phrase data="catalog_roles_manufacturer">Manufacturer</phrase>
|
||||
<phrase data="catalog_roles_caption">Card Caption</phrase>
|
||||
<phrase data="catalog_roles_hide_price">Hide Price</phrase>
|
||||
<phrase data="catalog_roles_exclude">Exclude From Price List</phrase>
|
||||
<phrase data="catalog_roles_new">New Product</phrase>
|
||||
<phrase data="catalog_roles_discount">Discount</phrase>
|
||||
<phrase data="catalog_roles_gift">Gift</phrase>
|
||||
<phrase data="catalog_roles_video">Video</phrase>
|
||||
<phrase data="catalog_roles_instruction">Video Instructions</phrase>
|
||||
<phrase data="catalog_roles_square">Square Image</phrase>
|
||||
<phrase data="catalog_roles_banner">Cover Image</phrase>
|
||||
<phrase data="catalog_roles_registration">Registration Document</phrase>
|
||||
<phrase data="catalog_roles_program">Payment Program Eligibility</phrase>
|
||||
<phrase data="catalog_roles_program_code">Payment Program Code</phrase>
|
||||
<phrase data="catalog_roles_published">Published</phrase>
|
||||
<phrase data="catalog_roles_not_public">Not Publicly Available</phrase>
|
||||
<phrase data="catalog_roles_orderable">Available to Order</phrase>
|
||||
<phrase data="catalog_roles_not_orderable">Not Available to Order</phrase>
|
||||
<phrase data="catalog_roles_unpublished">Not Published</phrase>
|
||||
<phrase data="catalog_roles_deleted">Deleted</phrase>
|
||||
<phrase data="catalog_roles_technical">Technical Document or Rubric</phrase>
|
||||
<phrase data="catalog_roles_scheduled">Publication Has Not Started</phrase>
|
||||
<phrase data="catalog_roles_expired">Publication Has Ended</phrase>
|
||||
<phrase data="catalog_roles_missing_price">No Positive Price</phrase>
|
||||
<phrase data="catalog_roles_hidden_price">Price Is Hidden</phrase>
|
||||
<phrase data="catalog_roles_excluded">Price List Exclusion Is Enabled.</phrase>
|
||||
<phrase data="catalog_roles_role">Role</phrase>
|
||||
<phrase data="catalog_roles_field">Field</phrase>
|
||||
<phrase data="catalog_roles_value">Value</phrase>
|
||||
<phrase data="catalog_roles_yes">Yes</phrase>
|
||||
<phrase data="catalog_roles_no">No</phrase>
|
||||
<phrase data="catalog_roles_empty">Not Filled</phrase>
|
||||
<phrase data="catalog_roles_more">more</phrase>
|
||||
<phrase data="catalog_roles_missing_document">No Document Found in This Rubric.</phrase>
|
||||
<phrase data="catalog_roles_request">Request Conditions</phrase>
|
||||
<phrase data="catalog_roles_template">Page Template</phrase>
|
||||
<phrase data="catalog_roles_card">Product Card</phrase>
|
||||
<phrase data="catalog_roles_filters">filters</phrase>
|
||||
<phrase data="catalog_roles_set">Attribute Set</phrase>
|
||||
<phrase data="catalog_roles_error">Could Not Check the Mapping</phrase>
|
||||
<phrase data="catalog_roles_invalid">Invalid Field Role</phrase>
|
||||
<phrase data="catalog_roles_wrong_rubric">Role Field Does Not Belong to the Product Rubric</phrase>
|
||||
</language>
|
||||
@@ -0,0 +1,52 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="catalog_selection_check_title">Selection Check</phrase>
|
||||
<phrase data="catalog_selection_selection">Selection</phrase>
|
||||
<phrase data="catalog_selection_catalog">Catalog</phrase>
|
||||
<phrase data="catalog_selection_recommendation">Recommendations</phrase>
|
||||
<phrase data="catalog_selection_search">Search</phrase>
|
||||
<phrase data="catalog_selection_feed">Feed</phrase>
|
||||
<phrase data="catalog_selection_category">Category</phrase>
|
||||
<phrase data="catalog_selection_none">Not Selected</phrase>
|
||||
<phrase data="catalog_selection_scope">Search Scope</phrase>
|
||||
<phrase data="catalog_selection_everywhere">Everywhere</phrase>
|
||||
<phrase data="catalog_selection_query">Search Query</phrase>
|
||||
<phrase data="catalog_selection_source">Source Product #</phrase>
|
||||
<phrase data="catalog_selection_limit">Limit</phrase>
|
||||
<phrase data="catalog_selection_check">Check Selection</phrase>
|
||||
<phrase data="catalog_selection_stale">Parameters Changed; Result Is Outdated</phrase>
|
||||
<phrase data="catalog_selection_yes">Included in Selection</phrase>
|
||||
<phrase data="catalog_selection_no">Not Included in Selection</phrase>
|
||||
<phrase data="catalog_selection_unknown">Check Incomplete</phrase>
|
||||
<phrase data="catalog_selection_denied">Insufficient Permissions</phrase>
|
||||
<phrase data="catalog_selection_unknown_context">Unknown Selection</phrase>
|
||||
<phrase data="catalog_selection_error">Check Unavailable: Review Settings and Index Health</phrase>
|
||||
<phrase data="catalog_selection_catalog_note">Eligibility Before Grouping and Pagination, Without Visitor Filters</phrase>
|
||||
<phrase data="catalog_selection_category_missing">Category Not Found</phrase>
|
||||
<phrase data="catalog_selection_category_page">Published Category Page</phrase>
|
||||
<phrase data="catalog_selection_request_denied">Insufficient Permissions for Request Conditions</phrase>
|
||||
<phrase data="catalog_selection_catalog_base">Index, Publication, Category Sources and Variant Status</phrase>
|
||||
<phrase data="catalog_selection_conditions">Saved Request Conditions</phrase>
|
||||
<phrase data="catalog_selection_group">Product or Its Group Is Eligible</phrase>
|
||||
<phrase data="catalog_selection_search_note">Search Before Pagination Using the Effective Query, Including Synonyms and Typo Correction</phrase>
|
||||
<phrase data="catalog_selection_effective_query">Effective Search Query</phrase>
|
||||
<phrase data="catalog_selection_ambiguous_query">Ambiguous Correction: No Replacement Selected</phrase>
|
||||
<phrase data="catalog_selection_missing_plan">Search Handler Did Not Return a Verification Plan</phrase>
|
||||
<phrase data="catalog_selection_pipeline_results">Search Pipeline Returned Results</phrase>
|
||||
<phrase data="catalog_selection_search_unavailable">Search Unavailable</phrase>
|
||||
<phrase data="catalog_selection_scope_missing">Search Scope Not Found</phrase>
|
||||
<phrase data="catalog_selection_short_query">Search Query Is Too Short</phrase>
|
||||
<phrase data="catalog_selection_search_base">Search Index, Text and Public Visibility</phrase>
|
||||
<phrase data="catalog_selection_search_rubrics">Search Scope Rubrics</phrase>
|
||||
<phrase data="catalog_selection_search_conditions">Search Scope Conditions</phrase>
|
||||
<phrase data="catalog_selection_feed_note">Export Eligibility Under Saved Settings, Without File Generation</phrase>
|
||||
<phrase data="catalog_selection_feed_missing">Feed Not Found</phrase>
|
||||
<phrase data="catalog_selection_feed_active">Feed Is Enabled</phrase>
|
||||
<phrase data="catalog_selection_feed_categories">Allowed Feed Categories</phrase>
|
||||
<phrase data="catalog_selection_feed_base">Index, Publication, Price Visibility and Feed Categories</phrase>
|
||||
<phrase data="catalog_selection_feed_conditions">Price and Price List Inclusion Under Feed Settings</phrase>
|
||||
<phrase data="catalog_selection_rec_note">Actual Recommendations Including Limit, Ranking and Cache</phrase>
|
||||
<phrase data="catalog_selection_source_missing">Source Product Unavailable</phrase>
|
||||
<phrase data="catalog_selection_rec_result">Native Recommendation Result</phrase>
|
||||
<phrase data="catalog_selection_rec_policy">Source Categories, Active Status, Primary Variant, Price, Stock and Limit Apply</phrase>
|
||||
</language>
|
||||
@@ -20,6 +20,7 @@
|
||||
<phrase data="auto_944019ea5d01e63a">скрыт</phrase>
|
||||
<phrase data="auto_9729bca62f6c558e">Ошибка запроса</phrase>
|
||||
<phrase data="auto_99d406eeba4f9acb">Раздел</phrase>
|
||||
<phrase data="auto_9b62723a4333bb4a">Найти раздел</phrase>
|
||||
<phrase data="auto_9f8bfc6bf2339426"><div class="alert alert-error"><i class="ti ti-alert-triangle"></i><div>Ошибки:</phrase>
|
||||
<phrase data="auto_a456fd20d54a422c"></p></div><button class="modal-close" type="button" data-catalog-recompile-close aria-label="Закрыть" disabled><i class="ti ti-x"></i></button></div><div class="modal-body"><div class="catalog-recompile-status" data-catalog-recompile-status>Подготовка...</div><div class="progress"><div class="progress-bar" data-catalog-recompile-progress style="width:0%;--progress-color:var(--blue-500)"></div></div><div class="catalog-recompile-errors" data-catalog-recompile-errors></div></div><div class="modal-footer"><button class="btn btn-ghost" type="button" data-catalog-recompile-stop>Остановить</button><button class="btn btn-primary" type="button" data-catalog-recompile-close disabled>Закрыть</button></div></div></phrase>
|
||||
<phrase data="auto_a4c0ae2fa076f2fd">Скрыть раздел</phrase>
|
||||
@@ -36,6 +37,11 @@
|
||||
<phrase data="auto_f61de80bf0ca15a4">Документ не выбран</phrase>
|
||||
<phrase data="auto_f6bde2876efe2658">Не включён</phrase>
|
||||
<phrase data="auto_fda18205701b609b">Заменить условие?</phrase>
|
||||
<phrase data="catalog_roles_more">ещё</phrase>
|
||||
<phrase data="catalog_roles_no">Нет</phrase>
|
||||
<phrase data="catalog_selection_catalog">Каталог</phrase>
|
||||
<phrase data="catalog_selection_category">Раздел</phrase>
|
||||
<phrase data="catalog_selection_search">Поиск</phrase>
|
||||
<phrase data="runtime_6291ecb1784ea2de">Каталог создан</phrase>
|
||||
<phrase data="runtime_6b3607219bc8c7f0">отличается</phrase>
|
||||
<phrase data="runtime_d0ef3540b088bbf6">Каталог</phrase>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="catalog_context_title">Связанные настройки</phrase>
|
||||
<phrase data="catalog_context_filters">Фильтры раздела</phrase>
|
||||
<phrase data="catalog_context_attribute_set">Набор характеристик</phrase>
|
||||
<phrase data="catalog_context_card">Шаблон карточки в каталоге</phrase>
|
||||
<phrase data="catalog_context_page">Шаблон страницы</phrase>
|
||||
</language>
|
||||
@@ -0,0 +1,63 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="catalog_roles_description">Описание товара</phrase>
|
||||
<phrase data="catalog_roles_warranty">Гарантия</phrase>
|
||||
<phrase data="catalog_roles_registration_text">Текст регистрационного документа</phrase>
|
||||
<phrase data="catalog_roles_registration_number">Номер регистрационного документа</phrase>
|
||||
<phrase data="catalog_roles_title">Назначение полей товара</phrase>
|
||||
<phrase data="catalog_roles_saved">Сохранённое сопоставление</phrase>
|
||||
<phrase data="catalog_roles_document">Документ #</phrase>
|
||||
<phrase data="catalog_roles_sample">Образец товара</phrase>
|
||||
<phrase data="catalog_roles_check">Проверить</phrase>
|
||||
<phrase data="catalog_roles_optional">Дополнительные поля проекта</phrase>
|
||||
<phrase data="catalog_roles_auto">Автоматически:</phrase>
|
||||
<phrase data="catalog_roles_unassigned">Не назначено</phrase>
|
||||
<phrase data="catalog_roles_name">Название</phrase>
|
||||
<phrase data="catalog_roles_article">Артикул</phrase>
|
||||
<phrase data="catalog_roles_price">Цена</phrase>
|
||||
<phrase data="catalog_roles_old_price">Старая цена</phrase>
|
||||
<phrase data="catalog_roles_stock">Остаток</phrase>
|
||||
<phrase data="catalog_roles_images">Изображения</phrase>
|
||||
<phrase data="catalog_roles_manufacturer">Производитель</phrase>
|
||||
<phrase data="catalog_roles_caption">Подпись карточки</phrase>
|
||||
<phrase data="catalog_roles_hide_price">Скрывать цену</phrase>
|
||||
<phrase data="catalog_roles_exclude">Исключить из прайса</phrase>
|
||||
<phrase data="catalog_roles_new">Новинка</phrase>
|
||||
<phrase data="catalog_roles_discount">Скидка</phrase>
|
||||
<phrase data="catalog_roles_gift">Подарок</phrase>
|
||||
<phrase data="catalog_roles_video">Видео</phrase>
|
||||
<phrase data="catalog_roles_instruction">Видеоинструкция</phrase>
|
||||
<phrase data="catalog_roles_square">Квадратное изображение</phrase>
|
||||
<phrase data="catalog_roles_banner">Обложка</phrase>
|
||||
<phrase data="catalog_roles_registration">Регистрационный документ</phrase>
|
||||
<phrase data="catalog_roles_program">Участие в программе оплаты</phrase>
|
||||
<phrase data="catalog_roles_program_code">Код программы оплаты</phrase>
|
||||
<phrase data="catalog_roles_published">Опубликован</phrase>
|
||||
<phrase data="catalog_roles_not_public">Не доступен публично</phrase>
|
||||
<phrase data="catalog_roles_orderable">Доступен к покупке</phrase>
|
||||
<phrase data="catalog_roles_not_orderable">Покупка недоступна</phrase>
|
||||
<phrase data="catalog_roles_unpublished">Не опубликован</phrase>
|
||||
<phrase data="catalog_roles_deleted">Удалён</phrase>
|
||||
<phrase data="catalog_roles_technical">Служебный документ или рубрика</phrase>
|
||||
<phrase data="catalog_roles_scheduled">Публикация ещё не началась</phrase>
|
||||
<phrase data="catalog_roles_expired">Публикация завершена</phrase>
|
||||
<phrase data="catalog_roles_missing_price">Нет положительной цены</phrase>
|
||||
<phrase data="catalog_roles_hidden_price">Цена скрыта</phrase>
|
||||
<phrase data="catalog_roles_excluded">Исключение из прайса включено.</phrase>
|
||||
<phrase data="catalog_roles_role">Назначение</phrase>
|
||||
<phrase data="catalog_roles_field">Поле</phrase>
|
||||
<phrase data="catalog_roles_value">Значение</phrase>
|
||||
<phrase data="catalog_roles_yes">Да</phrase>
|
||||
<phrase data="catalog_roles_no">Нет</phrase>
|
||||
<phrase data="catalog_roles_empty">Не заполнено</phrase>
|
||||
<phrase data="catalog_roles_more">ещё</phrase>
|
||||
<phrase data="catalog_roles_missing_document">Документ этой рубрики не найден.</phrase>
|
||||
<phrase data="catalog_roles_request">Условия запроса</phrase>
|
||||
<phrase data="catalog_roles_template">Шаблон страницы</phrase>
|
||||
<phrase data="catalog_roles_card">Карточка товара</phrase>
|
||||
<phrase data="catalog_roles_filters">фильтры</phrase>
|
||||
<phrase data="catalog_roles_set">Набор характеристик</phrase>
|
||||
<phrase data="catalog_roles_error">Не удалось проверить сопоставление</phrase>
|
||||
<phrase data="catalog_roles_invalid">Некорректное назначение поля</phrase>
|
||||
<phrase data="catalog_roles_wrong_rubric">Поле роли не принадлежит рубрике товара</phrase>
|
||||
</language>
|
||||
@@ -0,0 +1,52 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="catalog_selection_check_title">Проверка выборки</phrase>
|
||||
<phrase data="catalog_selection_selection">Выборка</phrase>
|
||||
<phrase data="catalog_selection_catalog">Каталог</phrase>
|
||||
<phrase data="catalog_selection_recommendation">Рекомендации</phrase>
|
||||
<phrase data="catalog_selection_search">Поиск</phrase>
|
||||
<phrase data="catalog_selection_feed">Фид</phrase>
|
||||
<phrase data="catalog_selection_category">Раздел</phrase>
|
||||
<phrase data="catalog_selection_none">Не выбран</phrase>
|
||||
<phrase data="catalog_selection_scope">Область поиска</phrase>
|
||||
<phrase data="catalog_selection_everywhere">Везде</phrase>
|
||||
<phrase data="catalog_selection_query">Поисковая строка</phrase>
|
||||
<phrase data="catalog_selection_source">Исходный товар #</phrase>
|
||||
<phrase data="catalog_selection_limit">Лимит</phrase>
|
||||
<phrase data="catalog_selection_check">Проверить выборку</phrase>
|
||||
<phrase data="catalog_selection_stale">Параметры изменены, результат не актуален</phrase>
|
||||
<phrase data="catalog_selection_yes">Входит в выборку</phrase>
|
||||
<phrase data="catalog_selection_no">Не входит в выборку</phrase>
|
||||
<phrase data="catalog_selection_unknown">Проверка не завершена</phrase>
|
||||
<phrase data="catalog_selection_denied">Недостаточно прав</phrase>
|
||||
<phrase data="catalog_selection_unknown_context">Неизвестная выборка</phrase>
|
||||
<phrase data="catalog_selection_error">Проверка недоступна: проверьте настройки и состояние индексов</phrase>
|
||||
<phrase data="catalog_selection_catalog_note">Допуск до группировки и страниц, без выбранных посетителем фильтров</phrase>
|
||||
<phrase data="catalog_selection_category_missing">Раздел не найден</phrase>
|
||||
<phrase data="catalog_selection_category_page">Опубликованная страница раздела</phrase>
|
||||
<phrase data="catalog_selection_request_denied">Недостаточно прав для условий запроса</phrase>
|
||||
<phrase data="catalog_selection_catalog_base">Индекс, публикация, источники раздела и активность варианта</phrase>
|
||||
<phrase data="catalog_selection_conditions">Сохранённые условия запроса</phrase>
|
||||
<phrase data="catalog_selection_group">Допуск товара или его группы в выдачу</phrase>
|
||||
<phrase data="catalog_selection_search_note">Поиск до пагинации по фактической строке, с синонимами и исправлением опечаток</phrase>
|
||||
<phrase data="catalog_selection_effective_query">Фактическая поисковая строка</phrase>
|
||||
<phrase data="catalog_selection_ambiguous_query">Неоднозначное исправление: поиск не выбрал замену</phrase>
|
||||
<phrase data="catalog_selection_missing_plan">Поисковый обработчик не вернул план проверки</phrase>
|
||||
<phrase data="catalog_selection_pipeline_results">Поисковый pipeline вернул результаты</phrase>
|
||||
<phrase data="catalog_selection_search_unavailable">Поиск недоступен</phrase>
|
||||
<phrase data="catalog_selection_scope_missing">Область поиска не найдена</phrase>
|
||||
<phrase data="catalog_selection_short_query">Поисковый запрос слишком короткий</phrase>
|
||||
<phrase data="catalog_selection_search_base">Поисковый индекс, текст и публичная доступность</phrase>
|
||||
<phrase data="catalog_selection_search_rubrics">Рубрики области поиска</phrase>
|
||||
<phrase data="catalog_selection_search_conditions">Условия области поиска</phrase>
|
||||
<phrase data="catalog_selection_feed_note">Допуск в экспорт по сохранённым настройкам, без генерации файла</phrase>
|
||||
<phrase data="catalog_selection_feed_missing">Фид не найден</phrase>
|
||||
<phrase data="catalog_selection_feed_active">Фид включён</phrase>
|
||||
<phrase data="catalog_selection_feed_categories">Разрешённые разделы фида</phrase>
|
||||
<phrase data="catalog_selection_feed_base">Индекс, публикация, видимость цены и разделы фида</phrase>
|
||||
<phrase data="catalog_selection_feed_conditions">Цена и включение в прайс по настройкам фида</phrase>
|
||||
<phrase data="catalog_selection_rec_note">Фактическая выдача рекомендаций с учётом лимита, ранжирования и кеша</phrase>
|
||||
<phrase data="catalog_selection_source_missing">Исходный товар недоступен</phrase>
|
||||
<phrase data="catalog_selection_rec_result">Результат штатных рекомендаций</phrase>
|
||||
<phrase data="catalog_selection_rec_policy">Учитываются категории исходного товара, активность, основной вариант, цена, остаток и лимит</phrase>
|
||||
</language>
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------------
|
||||
| AVE.cms
|
||||
|--------------------------------------------------------------------------------------
|
||||
| @package AVE.cms
|
||||
| @file adminx/modules/Catalog/migrations/006_add_item_sources.php
|
||||
| @author AVE.cms <support@ave-cms.ru>
|
||||
| @copyright 2007-2026 (c) AVE.cms
|
||||
| @link https://ave-cms.ru
|
||||
| @version 3.3
|
||||
*/
|
||||
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Common\DatabaseSchema;
|
||||
use App\Content\CatalogTables;
|
||||
|
||||
return function () {
|
||||
$table = CatalogTables::table('module_catalog_items');
|
||||
if (!DatabaseSchema::tableExists($table) || DatabaseSchema::columnExists($table, 'source_item_ids')) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
DB::query('ALTER TABLE %b ADD COLUMN `source_item_ids` TEXT NULL AFTER `filters_settings`', $table);
|
||||
return 1;
|
||||
};
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
return array(
|
||||
'code' => 'catalog', 'name' => 'Каталог', 'version' => '0.3.5',
|
||||
'code' => 'catalog', 'name' => 'Каталог', 'version' => '0.3.10',
|
||||
'permissions' => array('key' => 'catalog', 'items' => array(
|
||||
array(
|
||||
'code' => 'view_catalog',
|
||||
@@ -51,6 +51,7 @@
|
||||
array('GET', '/catalog/documents', array(\App\Adminx\Catalog\Controller::class, 'documents')),
|
||||
array('GET', '/catalog/items/{id}', array(\App\Adminx\Catalog\Controller::class, 'item')),
|
||||
array('GET', '/catalog/{rubric}/{field}', array(\App\Adminx\Catalog\Controller::class, 'edit')),
|
||||
array('GET', '/catalog/{rubric}/{field}/product-preview', array(\App\Adminx\Catalog\Controller::class, 'productPreview'), array('permission' => 'view_products')),
|
||||
array('POST', '/catalog/{rubric}/{field}/items', array(\App\Adminx\Catalog\Controller::class, 'storeItem')),
|
||||
array('POST', '/catalog/{rubric}/{field}/items/{id}', array(\App\Adminx\Catalog\Controller::class, 'updateItem')),
|
||||
array('POST', '/catalog/{rubric}/{field}/items/{id}/conditions/sync', array(\App\Adminx\Catalog\Controller::class, 'syncMissingConditions')),
|
||||
@@ -63,6 +64,7 @@
|
||||
),
|
||||
'migrations' => array(
|
||||
array('id' => '005_add_catalog_purpose', 'file' => 'migrations/005_add_catalog_purpose.sql'),
|
||||
array('id' => '006_add_item_sources', 'file' => 'migrations/006_add_item_sources.php'),
|
||||
),
|
||||
'view_globals' => array('module_code' => 'catalog'),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<section class="catalog-context-links" data-catalog-context-links{{ context_links ? '' : ' hidden' }} aria-label="{{ lang.catalog_context_title|default('Связанные настройки') }}">
|
||||
<h3>{{ lang.catalog_context_title|default('Связанные настройки') }}</h3>
|
||||
<nav>{% for link in context_links %}<a href="{{ link.url }}" target="_blank" rel="noopener" data-context-kind="{{ link.kind }}"><i class="ti ti-external-link" aria-hidden="true"></i><span>{{ link.label }}{% if link.scope %}<small>{{ link.scope }}</small>{% endif %}</span></a>{% endfor %}</nav>
|
||||
</section>
|
||||
@@ -0,0 +1,28 @@
|
||||
<div class="catalog-role-preview" data-product-role-preview data-error="{{ 'Не удалось проверить сопоставление'|admin_trans }}" aria-live="polite">
|
||||
<h3>{{ 'Сохранённое сопоставление'|admin_trans }}</h3>
|
||||
{% if product_roles.denied %}<p class="text-secondary">{{ 'Недостаточно прав'|admin_trans }}</p>{% else %}
|
||||
<div class="form-grid">
|
||||
<label class="field col-4"><span class="field-label">{{ 'Документ #'|admin_trans }}</span><input class="input" type="number" min="1" value="{{ product_roles.document_id ?: '' }}" data-product-role-document></label>
|
||||
<div class="field col-4"><span class="field-label">{{ 'Образец товара'|admin_trans }}</span><button type="button" class="btn btn-secondary" data-product-role-refresh><i class="ti ti-refresh"></i>{{ 'Проверить'|admin_trans }}</button></div>
|
||||
</div>
|
||||
{% include '@catalog/_product-selection-preview.twig' %}
|
||||
{% if product_roles.snapshot %}
|
||||
{% set sample = product_roles.snapshot %}
|
||||
<p>{% if product_roles.can_edit_product %}<a href="{{ ADMINX_BASE }}/catalog/products/{{ sample.id }}/edit">{{ sample.title }} · #{{ sample.id }}</a>{% else %}{{ sample.title }} · #{{ sample.id }}{% endif %}</p>
|
||||
<p><span class="badge {{ sample.published ? 'badge-green' : 'badge-gray' }}">{{ (sample.published ? 'Опубликован' : 'Не доступен публично')|admin_trans }}</span> <span class="badge {{ sample.orderable ? 'badge-green' : 'badge-gray' }}">{{ (sample.orderable ? 'Доступен к покупке' : 'Покупка недоступна')|admin_trans }}</span></p>
|
||||
{% for reason in product_roles.reasons %}<p class="text-secondary">{{ reason|admin_trans }}</p>{% endfor %}
|
||||
{% if sample.exclude_from_price %}<p class="text-secondary">{{ 'Исключение из прайса включено.'|admin_trans }}</p>{% endif %}
|
||||
<div class="table-wrap"><table class="table"><thead><tr><th>{{ 'Назначение'|admin_trans }}</th><th>{{ 'Поле'|admin_trans }}</th><th>{{ 'Значение'|admin_trans }}</th></tr></thead><tbody>
|
||||
{% for role,definition in product_roles.definitions %}{% if not definition.optional or definition.field_id %}
|
||||
<tr><td>{{ definition.label|admin_trans }}</td><td data-label="{{ 'Поле'|admin_trans }}">{% if definition.field %}<a href="{{ ADMINX_BASE }}/rubrics?fields={{ catalog.rubric_id }}&field={{ definition.field_id }}">{{ definition.field.title ?: definition.field.alias }} · #{{ definition.field_id }}</a>{% else %}{{ 'Не назначено'|admin_trans }}{% endif %}</td><td data-label="{{ 'Значение'|admin_trans }}">{% set value = attribute(sample,role) %}{% if value is same as(true) %}{{ 'Да'|admin_trans }}{% elseif value is same as(false) %}{{ 'Нет'|admin_trans }}{% elseif value is iterable %}{% if value is empty %}{{ 'Не заполнено'|admin_trans }}{% else %}{{ value|slice(0, 3)|join(', ') }}{% if value|length > 3 %} · {{ 'ещё'|admin_trans }} {{ value|length - 3 }}{% endif %}{% endif %}{% elseif value is same as('') %}{{ 'Не заполнено'|admin_trans }}{% else %}{{ value }}{% endif %}</td></tr>
|
||||
{% endif %}{% endfor %}
|
||||
</tbody></table></div>
|
||||
{% else %}<p class="text-secondary">{{ 'Документ этой рубрики не найден.'|admin_trans }}</p>{% endif %}
|
||||
<div class="btn-group">
|
||||
{% if settings.request_id and product_roles.can_requests %}<a class="btn btn-ghost" href="{{ ADMINX_BASE }}/requests/{{ settings.request_id }}"><i class="ti ti-filter"></i>{{ 'Условия запроса'|admin_trans }}</a>{% endif %}
|
||||
{% if product_roles.can_rubrics %}<a class="btn btn-ghost" href="{{ ADMINX_BASE }}/rubrics?templates={{ catalog.rubric_id }}{% if product_roles.snapshot.document.rubric_tmpl_id %}&template={{ product_roles.snapshot.document.rubric_tmpl_id }}{% endif %}"><i class="ti ti-template"></i>{{ 'Шаблон страницы'|admin_trans }}</a>{% endif %}
|
||||
<a class="btn btn-ghost" href="{{ ADMINX_BASE }}/catalog/{% if product_roles.card_template_id %}card-templates?edit={{ product_roles.card_template_id }}{% else %}public-templates?template=product-card{% endif %}"><i class="ti ti-layout-cards"></i>{{ 'Карточка товара'|admin_trans }}</a>
|
||||
</div>
|
||||
{% for section in product_roles.sections %}<p><a href="{{ ADMINX_BASE }}/catalog/{{ section.rubric_id }}/{{ section.field_id }}?item={{ section.id }}&tab=filters">{{ section.name }}: {{ 'фильтры'|admin_trans }}</a>{% if section.attribute_set_id %} · <a href="{{ ADMINX_BASE }}/catalog/attribute-sets/{{ section.attribute_set_id }}">{{ 'Набор характеристик'|admin_trans }} #{{ section.attribute_set_id }}</a>{% endif %}</p>{% endfor %}
|
||||
{% endif %}
|
||||
</div>
|
||||
@@ -0,0 +1,20 @@
|
||||
<section class="catalog-commerce-fields" data-catalog-commerce-fields>
|
||||
<div class="catalog-behavior-head"><span class="icon-tile catalog-behavior-icon is-green"><i class="ti ti-shopping-bag"></i></span><h3>{{ 'Назначение полей товара'|admin_trans }}</h3></div>
|
||||
<div class="form-grid">
|
||||
{% for role,definition in product_roles.definitions %}{% if not definition.optional %}
|
||||
<label class="field col-4"><span class="field-label">{{ definition.label|admin_trans }}</span><select class="select" name="product_roles[{{ role }}]">
|
||||
<option value="-1"{{ definition.selected == -1 ? ' selected' : '' }}>{{ 'Автоматически:'|admin_trans }} {{ definition.alias }}</option><option value="0"{{ definition.selected == 0 ? ' selected' : '' }}>{{ 'Не назначено'|admin_trans }}</option>
|
||||
{% for group in field_groups %}{% for field in group.items %}<option value="{{ field.id }}"{{ definition.selected == field.id ? ' selected' : '' }}>{{ field.title ?: field.alias }} · #{{ field.id }}</option>{% endfor %}{% endfor %}
|
||||
</select></label>
|
||||
{% endif %}{% endfor %}
|
||||
</div>
|
||||
<details><summary>{{ 'Дополнительные поля проекта'|admin_trans }}</summary><div class="form-grid">
|
||||
{% for role,definition in product_roles.definitions %}{% if definition.optional %}
|
||||
<label class="field col-4"><span class="field-label">{{ definition.label|admin_trans }}</span><select class="select" name="product_roles[{{ role }}]">
|
||||
<option value="-1"{{ definition.selected == -1 ? ' selected' : '' }}>{{ 'Автоматически:'|admin_trans }} {{ definition.alias }}</option><option value="0"{{ definition.selected == 0 ? ' selected' : '' }}>{{ 'Не назначено'|admin_trans }}</option>
|
||||
{% for group in field_groups %}{% for field in group.items %}<option value="{{ field.id }}"{{ definition.selected == field.id ? ' selected' : '' }}>{{ field.title ?: field.alias }} · #{{ field.id }}</option>{% endfor %}{% endfor %}
|
||||
</select></label>
|
||||
{% endif %}{% endfor %}
|
||||
</div></details>
|
||||
{% include '@catalog/_product-role-preview.twig' %}
|
||||
</section>
|
||||
@@ -0,0 +1,24 @@
|
||||
{% set selection = product_roles.selection %}
|
||||
{% set options = product_roles.selection_options %}
|
||||
<section class="catalog-selection-preview" data-product-selection>
|
||||
<h4>{{ 'Проверка выборки'|admin_trans }}</h4>
|
||||
<div class="catalog-selection-controls">
|
||||
<label class="field"><span class="field-label">{{ 'Выборка'|admin_trans }}</span><select class="select" data-selection="context">{% for code,label in options.contexts %}<option value="{{ code }}"{{ selection.context == code ? ' selected' : '' }}>{{ label|admin_trans }}</option>{% endfor %}</select></label>
|
||||
<label class="field" data-selection-context="catalog"{{ selection.context != 'catalog' ? ' hidden' : '' }}><span class="field-label">{{ 'Раздел'|admin_trans }}</span><select class="select" data-selection="category"><option value="0">{{ 'Не выбран'|admin_trans }}</option>{% for item in options.categories %}<option value="{{ item.id }}"{{ selection.category == item.id ? ' selected' : '' }}>{{ item.name }} #{{ item.id }}</option>{% endfor %}</select></label>
|
||||
<label class="field" data-selection-context="feed"{{ selection.context != 'feed' ? ' hidden' : '' }}><span class="field-label">{{ 'Фид'|admin_trans }}</span><select class="select" data-selection="feed"><option value="0">{{ 'Не выбран'|admin_trans }}</option>{% for item in options.feeds %}<option value="{{ item.id }}"{{ selection.feed == item.id ? ' selected' : '' }}>{{ item.name }} #{{ item.id }}</option>{% endfor %}</select></label>
|
||||
<label class="field" data-selection-context="search"{{ selection.context != 'search' ? ' hidden' : '' }}><span class="field-label">{{ 'Область поиска'|admin_trans }}</span><select class="select" data-selection="scope">{% for item in options.scopes %}<option value="{{ item.code }}"{{ selection.scope == item.code ? ' selected' : '' }}>{{ item.label|admin_trans }}</option>{% endfor %}</select></label>
|
||||
<label class="field" data-selection-context="search"{{ selection.context != 'search' ? ' hidden' : '' }}><span class="field-label">{{ 'Поисковая строка'|admin_trans }}</span><input class="input" type="search" maxlength="200" value="{{ selection.query }}" data-selection="query"></label>
|
||||
<label class="field" data-selection-context="recommendation"{{ selection.context != 'recommendation' ? ' hidden' : '' }}><span class="field-label">{{ 'Исходный товар #'|admin_trans }}</span><input class="input" type="number" min="1" value="{{ selection.source ?: '' }}" data-selection="source"></label>
|
||||
<label class="field" data-selection-context="recommendation"{{ selection.context != 'recommendation' ? ' hidden' : '' }}><span class="field-label">{{ 'Лимит'|admin_trans }}</span><input class="input" type="number" min="1" max="24" value="{{ selection.limit ?: 8 }}" data-selection="limit"></label>
|
||||
<button class="btn btn-secondary" type="button" data-product-selection-check><i class="ti ti-list-search" aria-hidden="true"></i>{{ 'Проверить выборку'|admin_trans }}</button>
|
||||
</div>
|
||||
<p class="text-secondary" data-selection-stale hidden>{{ 'Параметры изменены, результат не актуален'|admin_trans }}</p>
|
||||
{% if product_roles.selection_result %}
|
||||
{% set result = product_roles.selection_result %}
|
||||
<div class="catalog-selection-result" data-selection-result>
|
||||
<p><span class="badge {{ result.matched is same as(true) ? 'badge-green' : 'badge-gray' }}">{{ (result.matched is same as(true) ? 'Входит в выборку' : (result.matched is same as(false) ? 'Не входит в выборку' : 'Проверка не завершена'))|admin_trans }}</span></p>
|
||||
<ul>{% for step in result.steps %}<li data-selection-step="{{ step.code }}"><i class="ti {{ step.pass is same as(true) ? 'ti-check text-success' : (step.pass is same as(false) ? 'ti-x text-danger' : 'ti-info-circle') }}" aria-hidden="true"></i><span>{{ step.label|admin_trans }}{% if step.detail != '' %}: <b>{{ step.detail }}</b>{% endif %}<span class="sr-only"> {{ (step.pass is same as(true) ? 'Да' : (step.pass is same as(false) ? 'Нет' : ''))|admin_trans }}</span></span></li>{% endfor %}</ul>
|
||||
{% if result.note %}<p class="text-secondary text-sm">{{ result.note|admin_trans }}</p>{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</section>
|
||||
@@ -42,7 +42,7 @@
|
||||
<label class="field col-3"><span class="field-label">Навигация в шапке</span><select class="select" name="navi_id"><option value="0">Не связана</option>{% for item in navigation_options %}<option value="{{ item.id }}"{{ settings.navi_id == item.id ? ' selected' : '' }}>{{ item.title ?: item.alias }}{% if item.alias and item.alias != item.title %} · {{ item.alias }}{% endif %} (#{{ item.id }})</option>{% endfor %}</select><span class="field-hint">Дополнительные ссылки и подборки перед разделами каталога.</span></label>
|
||||
<label class="field col-3"><span class="field-label">Рубрика разделов</span><select class="select" name="rub_cat_id"><option value="0">Не выбрана</option>{% for item in rubric_options %}<option value="{{ item.id }}"{{ settings.rub_cat_id == item.id ? ' selected' : '' }}>{{ item.title ?: item.alias }}{% if item.alias and item.alias != item.title %} · {{ item.alias }}{% endif %} (#{{ item.id }})</option>{% endfor %}</select><span class="field-hint">Рубрика документов, связанных с разделами каталога.</span></label>
|
||||
</div>
|
||||
{% if products_available %}<section class="catalog-commerce-fields" data-catalog-commerce-fields><div class="catalog-behavior-head"><span class="icon-tile catalog-behavior-icon is-green"><i class="ti ti-shopping-bag"></i></span><h3>Поля товарного представления</h3></div><div class="form-grid">{% set commerce_fields={'product_title_field_id':'Название товара','product_article_field_id':'Артикул','product_price_field_id':'Цена','product_old_price_field_id':'Старая цена','product_stock_field_id':'Остаток','product_images_field_id':'Изображения'} %}{% for key,label in commerce_fields %}<label class="field col-4"><span class="field-label">{{ label }}</span><select class="select" name="{{ key }}"><option value="0">Не назначено</option>{% for group in field_groups %}{% for field in group.items %}<option value="{{ field.id }}"{{ attribute(settings,key) == field.id ? ' selected' : '' }}>{{ field.title ?: field.alias }} · #{{ field.id }}</option>{% endfor %}{% endfor %}</select></label>{% endfor %}</div></section>
|
||||
{% if products_available %}{% include '@catalog/_product-roles.twig' %}
|
||||
<section class="catalog-product-card-settings" data-catalog-commerce-fields>
|
||||
<div class="catalog-behavior-head"><span class="icon-tile catalog-behavior-icon is-blue"><i class="ti ti-layout-cards"></i></span><div><h3>Карточка товара</h3><p class="text-secondary text-sm">Единый вид для главной страницы и разделов товарного каталога.</p></div></div>
|
||||
<div class="catalog-product-card-layout">
|
||||
@@ -95,11 +95,12 @@
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{% if can_manage %}<aside class="drawer drawer-right drawer-xl catalog-drawer" id="catalogItemDrawer" role="dialog" aria-modal="true" hidden>
|
||||
{% if can_manage %}<script type="application/json" data-catalog-source-options>{{ source_options|json_encode|raw }}</script><aside class="drawer drawer-right drawer-xl catalog-drawer" id="catalogItemDrawer" role="dialog" aria-modal="true" hidden>
|
||||
<div class="drawer-header"><div><h3 data-catalog-drawer-title>Раздел каталога</h3><p class="text-secondary text-sm">Свойства, поля документа и фильтры.</p></div><button class="btn btn-ghost btn-icon" type="button" data-close-drawer aria-label="Закрыть"><i class="ti ti-x"></i></button></div>
|
||||
<form id="catalogItemForm" class="drawer-body catalog-item-form" data-base="{{ ADMINX_BASE }}" data-rubric="{{ catalog.rubric_id }}" data-field="{{ catalog.field_id }}"><input type="hidden" name="_csrf" value="{{ csrf_token }}"><input type="hidden" name="id" value=""><input type="hidden" name="filters_order" value="">
|
||||
<div class="tabs catalog-drawer-tabs"><button class="tab is-active" type="button" data-catalog-drawer-tab="main">Основное</button><button class="tab" type="button" data-catalog-drawer-tab="fields">Поля <span class="tab-count" data-catalog-fields-count>0</span></button><button class="tab" type="button" data-catalog-drawer-tab="filters">Фильтры <span class="tab-count" data-catalog-filters-count>0</span></button></div>
|
||||
<section data-catalog-drawer-panel="main"><div class="form-grid"><label class="field col-12"><span class="field-label">Название</span><input class="input" type="text" name="name" maxlength="255" required><span class="field-error" data-error="name"></span></label><label class="field col-6"><span class="field-label">Родитель</span><select class="select" name="parent_id"><option value="0">Верхний уровень</option>{% for item in flat %}<option value="{{ item.id }}" data-level="{{ item.level }}">{{ item.name }}</option>{% endfor %}</select></label><div class="field col-6"><span class="field-label">Связанный документ</span><input type="hidden" name="document_id" value=""><div class="catalog-document-picker"><button class="catalog-document-value" type="button" data-catalog-document-pick><i class="ti ti-file-search"></i><span data-catalog-document-label>Документ не выбран</span></button><button class="btn btn-ghost btn-icon" type="button" data-catalog-document-clear data-tooltip="Убрать связь" aria-label="Убрать связанный документ"><i class="ti ti-x"></i></button></div></div><div class="field col-12 catalog-toggle-row"><span><b>Раздел активен</b><small>Доступен в поле документа и на сайте.</small></span><label class="switch"><input type="checkbox" name="status" value="1" aria-label="Раздел активен"></label></div></div></section>
|
||||
<section data-catalog-drawer-panel="main"><div class="form-grid"><label class="field col-12"><span class="field-label">Название</span><input class="input" type="text" name="name" maxlength="255" required><span class="field-error" data-error="name"></span></label><label class="field col-6"><span class="field-label">Родитель</span><select class="select" name="parent_id"><option value="0">Верхний уровень</option>{% for item in flat %}<option value="{{ item.id }}" data-level="{{ item.level }}">{{ item.name }}</option>{% endfor %}</select></label><div class="field col-6"><span class="field-label">Связанный документ</span><input type="hidden" name="document_id" value=""><div class="catalog-document-picker"><button class="catalog-document-value" type="button" data-catalog-document-pick><i class="ti ti-file-search"></i><span data-catalog-document-label>Документ не выбран</span></button><button class="btn btn-ghost btn-icon" type="button" data-catalog-document-clear data-tooltip="Убрать связь" aria-label="Убрать связанный документ"><i class="ti ti-x"></i></button></div></div><div class="field col-12"><span class="field-label">Источники товаров</span><div class="catalog-source-picker" data-catalog-source-picker><div data-catalog-source-inputs></div><button class="catalog-source-value" type="button" data-catalog-source-open{{ not source_schema_available ? ' disabled' : '' }}><i class="ti ti-folders"></i><span data-catalog-source-label>Товары только из этого раздела</span></button><button class="btn btn-ghost btn-icon" type="button" data-catalog-source-clear data-tooltip="Очистить источники" aria-label="Очистить источники" disabled><i class="ti ti-x"></i></button></div><span class="field-hint">Выберите другие разделы, если эта страница должна объединять их товары. Сами разделы и их место в каталоге не изменятся.</span>{% if not source_schema_available %}<span class="field-hint text-danger">Примените миграцию модуля «Каталог», чтобы включить эту настройку.</span>{% endif %}</div><div class="field col-12 catalog-toggle-row"><span><b>Раздел активен</b><small>Включённый раздел доступен в списках и меню; связанный документ можно открыть по прямому адресу независимо от этой настройки.</small></span><label class="switch"><input type="checkbox" name="status" value="1" aria-label="Раздел активен"></label></div></div></section>
|
||||
{% include '@catalog/_context-links.twig' with {context_links: []} %}
|
||||
<section data-catalog-drawer-panel="fields" hidden>
|
||||
<div class="catalog-choice-head catalog-fields-grid"><span>Поле</span><span>Тип</span><span>Включено</span></div>
|
||||
<div class="catalog-field-groups">{% for group in field_groups %}<section class="catalog-field-group" data-catalog-field-group="fields"><div class="catalog-field-group-head"><div class="catalog-field-group-title"><span class="icon-tile catalog-field-group-icon"><i class="ti ti-category-2"></i></span><span class="catalog-field-group-copy"><small>Группа полей</small><b>{{ group.title }}</b></span></div><div class="catalog-field-group-meta"><span>Всего: {{ group.items|length }}</span><span class="badge badge-blue" data-catalog-group-selected>Включено: 0</span></div></div><div class="catalog-check-list">{% for field in group.items %}<div class="catalog-choice-row catalog-fields-grid"><span class="catalog-choice-copy"><b>{{ field.title ?: field.alias }}</b><small>{{ field.alias ?: 'field_' ~ field.id }} · #{{ field.id }}</small></span><span class="catalog-field-type"><b>{{ field.type_title }}</b><small>{{ field.type }}</small></span><label class="switch"><input type="checkbox" name="fields_use[]" value="{{ field.id }}" aria-label="Использовать поле {{ field.title ?: field.alias }}"></label></div>{% endfor %}</div></section>{% endfor %}</div>
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Adminx\Support\PhpCode;
|
||||
use App\Common\PublicConfiguration;
|
||||
use App\Common\TemporaryDirectory;
|
||||
|
||||
class Runner
|
||||
@@ -31,7 +32,8 @@
|
||||
return filter_var($value, FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
return false;
|
||||
$config = PublicConfiguration::value('admin_console', array());
|
||||
return is_array($config) && !empty($config['enabled']);
|
||||
}
|
||||
|
||||
public static function execute($code)
|
||||
@@ -49,6 +51,7 @@
|
||||
throw new \RuntimeException($lint['message'] . ($lint['line'] ? ' Строка ' . $lint['line'] . '.' : ''));
|
||||
}
|
||||
|
||||
$php = PhpCode::cliBinary();
|
||||
$dir = TemporaryDirectory::create('console');
|
||||
|
||||
$codeFile = $dir . '/snippet.php';
|
||||
@@ -68,7 +71,6 @@
|
||||
@file_put_contents($codeFile, PhpCode::source($code));
|
||||
@file_put_contents($runnerFile, $runner);
|
||||
|
||||
$php = self::resolvePhpBinary();
|
||||
$command = escapeshellarg($php)
|
||||
. ' -d display_errors=1 -d memory_limit=128M'
|
||||
. ' -d disable_functions=exec,shell_exec,system,passthru,popen'
|
||||
@@ -80,7 +82,7 @@
|
||||
0 => array('pipe', 'r'),
|
||||
1 => array('pipe', 'w'),
|
||||
2 => array('pipe', 'w'),
|
||||
), $pipes, $dir);
|
||||
), $pipes, $dir, null, array('bypass_shell' => DIRECTORY_SEPARATOR === '\\'));
|
||||
if (!is_resource($process)) {
|
||||
self::cleanup($dir);
|
||||
throw new \RuntimeException('Не удалось запустить PHP-процесс.');
|
||||
@@ -135,94 +137,6 @@
|
||||
);
|
||||
}
|
||||
|
||||
/** Find a CLI binary compatible with the application runtime. */
|
||||
protected static function resolvePhpBinary()
|
||||
{
|
||||
$candidates = array();
|
||||
$configured = trim((string) getenv('ADMINX_PHP_BINARY'));
|
||||
if ($configured !== '') {
|
||||
$candidates[] = $configured;
|
||||
}
|
||||
|
||||
if (defined('PHP_BINDIR') && PHP_BINDIR !== '') {
|
||||
$candidates[] = rtrim(PHP_BINDIR, '/\\') . DIRECTORY_SEPARATOR . 'php';
|
||||
}
|
||||
|
||||
if (defined('PHP_BINARY') && PHP_BINARY !== '') {
|
||||
$candidates[] = dirname(PHP_BINARY) . DIRECTORY_SEPARATOR . 'php';
|
||||
$candidates[] = PHP_BINARY;
|
||||
}
|
||||
|
||||
$candidates[] = 'php';
|
||||
$candidates = array_values(array_unique($candidates));
|
||||
$detected = array();
|
||||
foreach ($candidates as $candidate) {
|
||||
$version = self::probePhpBinary($candidate);
|
||||
if ($version >= 70300) {
|
||||
return $candidate;
|
||||
}
|
||||
|
||||
if ($version > 0) {
|
||||
$detected[] = $candidate . ' (PHP ' . self::formatVersionId($version) . ')';
|
||||
}
|
||||
}
|
||||
|
||||
$message = 'Для PHP-консоли нужен CLI-интерпретатор PHP 7.3 или новее.';
|
||||
if ($detected) {
|
||||
$message .= ' Найдены несовместимые: ' . implode(', ', $detected) . '.';
|
||||
}
|
||||
|
||||
throw new \RuntimeException($message . ' Укажите путь в ADMINX_PHP_BINARY.');
|
||||
}
|
||||
|
||||
protected static function probePhpBinary($binary)
|
||||
{
|
||||
$command = escapeshellarg((string) $binary) . ' -r ' . escapeshellarg('echo PHP_VERSION_ID;');
|
||||
$pipes = array();
|
||||
$process = @proc_open($command, array(
|
||||
0 => array('pipe', 'r'),
|
||||
1 => array('pipe', 'w'),
|
||||
2 => array('pipe', 'w'),
|
||||
), $pipes);
|
||||
if (!is_resource($process)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
fclose($pipes[0]);
|
||||
stream_set_blocking($pipes[1], false);
|
||||
stream_set_blocking($pipes[2], false);
|
||||
$started = microtime(true);
|
||||
$output = '';
|
||||
do {
|
||||
$output .= (string) stream_get_contents($pipes[1]);
|
||||
$status = proc_get_status($process);
|
||||
if (!$status['running']) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (microtime(true) - $started >= 2) {
|
||||
proc_terminate($process, 9);
|
||||
break;
|
||||
}
|
||||
|
||||
usleep(10000);
|
||||
} while (true);
|
||||
$output .= (string) stream_get_contents($pipes[1]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
proc_close($process);
|
||||
|
||||
$output = trim($output);
|
||||
return preg_match('/^\d{5,6}$/', $output) === 1 ? (int) $output : 0;
|
||||
}
|
||||
|
||||
protected static function formatVersionId($version)
|
||||
{
|
||||
$version = (int) $version;
|
||||
return (int) floor($version / 10000)
|
||||
. '.' . (int) floor(($version % 10000) / 100)
|
||||
. '.' . (int) ($version % 100);
|
||||
}
|
||||
|
||||
protected static function cleanup($dir)
|
||||
{
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
return array(
|
||||
'code' => 'console',
|
||||
'name' => 'PHP-консоль',
|
||||
'version' => '0.1.1',
|
||||
'version' => '0.1.3',
|
||||
'registry' => array('dynamic' => true),
|
||||
);
|
||||
}
|
||||
@@ -28,7 +28,7 @@
|
||||
return array(
|
||||
'code' => 'console',
|
||||
'name' => 'PHP-консоль',
|
||||
'version' => '0.1.1',
|
||||
'version' => '0.1.3',
|
||||
'registry' => array('dynamic' => true),
|
||||
'permissions' => array(
|
||||
'key' => 'console',
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
<h1>PHP-консоль</h1>
|
||||
<p class="text-secondary">Системный инструмент · изолированный PHP-процесс</p>
|
||||
</div>
|
||||
<span class="badge badge-{{ runner_enabled ? 'orange' : 'red' }} badge-dot">{{ runner_enabled ? 'Локальное выполнение' : 'Выполнение отключено' }}</span>
|
||||
<span class="badge badge-{{ runner_enabled ? 'orange' : 'red' }} badge-dot">{{ runner_enabled ? 'Выполнение включено' : 'Выполнение отключено' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -102,7 +102,9 @@
|
||||
public function toggle(array $params=array())
|
||||
{
|
||||
if(($e=$this->guard())!==null){return $e;}
|
||||
try{$active=Model::toggle(isset($params['id'])?$params['id']:0,Auth::id());}catch(\InvalidArgumentException $e){return $this->error($e->getMessage(),array(),422);}
|
||||
$id=isset($params['id'])?(int)$params['id']:0;
|
||||
try{$active=Model::toggle($id,Auth::id());}catch(\InvalidArgumentException $e){return $this->error($e->getMessage(),array(),422);}
|
||||
AuditLog::record('customers.status_changed',array('actor_id'=>Auth::id(),'target_type'=>'public_user','target_id'=>$id,'meta'=>array('active'=>$active)));
|
||||
return $this->success($active?'Пользователь включён':'Пользователь отключён');
|
||||
}
|
||||
|
||||
@@ -119,6 +121,7 @@
|
||||
$id=isset($params['id'])?(int)$params['id']:0;$input=Request::postAll();
|
||||
if(!Permission::check('manage_users')){$current=Model::customer($id,Auth::id());$input['admin_access']=!empty($current['system']['is_active'])?'1':'';$input['admin_role']=!empty($current['system']['role'])?(string)$current['system']['role']:'manager';}
|
||||
try{$customer=Model::updateCustomer($id,$input,Auth::id());}catch(\InvalidArgumentException $e){return $this->error($e->getMessage(),array(),422);}catch(\Throwable $e){return $this->error('Не удалось сохранить пользователя',array(),500);}
|
||||
AuditLog::record('customers.updated',array('actor_id'=>Auth::id(),'target_type'=>'public_user','target_id'=>$id));
|
||||
return $this->success('Профиль пользователя сохранён',array('data'=>$customer));
|
||||
}
|
||||
|
||||
@@ -128,14 +131,17 @@
|
||||
return $e;
|
||||
}
|
||||
|
||||
$id = isset($params['id']) ? (int) $params['id'] : 0;
|
||||
try {
|
||||
Model::deleteCustomer(isset($params['id']) ? $params['id'] : 0, Auth::id());
|
||||
Model::deleteCustomer($id, Auth::id());
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return $this->error($e->getMessage(), array(), 422);
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error('Не удалось удалить пользователя', array(), 500);
|
||||
}
|
||||
|
||||
AuditLog::record('customers.deleted', array('actor_id' => Auth::id(), 'target_type' => 'public_user', 'target_id' => $id));
|
||||
|
||||
return $this->success('Пользователь удалён', array('reload' => true));
|
||||
}
|
||||
|
||||
@@ -143,10 +149,10 @@
|
||||
public function deleteField(array $params=array()){if(($e=$this->guard())!==null){return $e;}Model::deleteField(isset($params['id'])?$params['id']:0);return $this->success('Поле удалено',array('reload'=>true));}
|
||||
public function toggleField(array $params=array()){if(($e=$this->guard())!==null){return $e;}$active=Model::toggleField(isset($params['id'])?$params['id']:0);return $this->success($active?'Поле включено':'Поле скрыто',array('data'=>array('is_active'=>$active?1:0)));}
|
||||
public function reorderFields(array $params=array()){if(($e=$this->guard())!==null){return $e;}$ids=json_decode(Request::postStr('order','[]'),true);if(!is_array($ids)){return $this->error('Некорректный порядок полей',array(),422);}$count=Model::reorderFields($ids);return $this->success('Порядок полей сохранён',array('data'=>array('count'=>$count)));}
|
||||
public function saveAuthSettings(array $params=array()){if(($e=$this->guard())!==null){return $e;}try{$settings=Model::saveAuthSettings(Request::postAll());}catch(\Throwable $e){return $this->error($e->getMessage(),array(),422);}return $this->success('Настройки регистрации сохранены',array('data'=>array('settings'=>$settings)));}
|
||||
public function saveAuthPages(array $params=array()){if(($e=$this->guard())!==null){return $e;}try{$settings=Model::saveAuthPages(Request::postAll());}catch(\Throwable $e){return $this->error($e->getMessage(),array(),422);}return $this->success('Страницы входа сохранены',array('data'=>array('settings'=>$settings)));}
|
||||
public function saveAuthSettings(array $params=array()){if(($e=$this->guard())!==null){return $e;}try{$settings=Model::saveAuthSettings(Request::postAll());}catch(\Throwable $e){return $this->error($e->getMessage(),array(),422);}AuditLog::record('customers.auth_settings_updated',array('actor_id'=>Auth::id(),'target_type'=>'public_auth'));return $this->success('Настройки регистрации сохранены',array('data'=>array('settings'=>$settings)));}
|
||||
public function saveAuthPages(array $params=array()){if(($e=$this->guard())!==null){return $e;}try{$settings=Model::saveAuthPages(Request::postAll());}catch(\Throwable $e){return $this->error($e->getMessage(),array(),422);}AuditLog::record('customers.auth_pages_updated',array('actor_id'=>Auth::id(),'target_type'=>'public_auth'));return $this->success('Страницы входа сохранены',array('data'=>array('settings'=>$settings)));}
|
||||
public function authForm(array $params=array()){if(!Permission::check('view_customers')){return $this->error('Недостаточно прав',array(),403);}try{$form=Model::authForm(isset($params['key'])?(string)$params['key']:'');}catch(\Throwable $e){return $this->error($e->getMessage(),array(),404);}return $this->success('',array('data'=>$form));}
|
||||
public function saveAuthForm(array $params=array()){if(($e=$this->guard())!==null){return $e;}try{$template=Model::saveAuthForm(isset($params['key'])?(string)$params['key']:'',Request::postStr('template',''),Auth::id());}catch(\Throwable $e){return $this->error($e->getMessage(),array('template'=>$e->getMessage()),422);}return $this->success('Шаблон формы сохранён',array('data'=>array('template'=>$template,'customized'=>1)));}
|
||||
public function resetAuthForm(array $params=array()){if(($e=$this->guard())!==null){return $e;}try{$template=Model::resetAuthForm(isset($params['key'])?(string)$params['key']:'');}catch(\Throwable $e){return $this->error($e->getMessage(),array(),422);}return $this->success('Восстановлен штатный шаблон формы',array('data'=>array('template'=>$template,'customized'=>0)));}
|
||||
public function saveAuthForm(array $params=array()){if(($e=$this->guard())!==null){return $e;}$key=isset($params['key'])?(string)$params['key']:'';try{$template=Model::saveAuthForm($key,Request::postStr('template',''),Auth::id());}catch(\Throwable $e){return $this->error($e->getMessage(),array('template'=>$e->getMessage()),422);}AuditLog::record('customers.auth_form_updated',array('actor_id'=>Auth::id(),'target_type'=>'public_auth_form','meta'=>array('form'=>$key)));return $this->success('Шаблон формы сохранён',array('data'=>array('template'=>$template,'customized'=>1)));}
|
||||
public function resetAuthForm(array $params=array()){if(($e=$this->guard())!==null){return $e;}$key=isset($params['key'])?(string)$params['key']:'';try{$template=Model::resetAuthForm($key);}catch(\Throwable $e){return $this->error($e->getMessage(),array(),422);}AuditLog::record('customers.auth_form_reset',array('actor_id'=>Auth::id(),'target_type'=>'public_auth_form','meta'=>array('form'=>$key)));return $this->success('Восстановлен штатный шаблон формы',array('data'=>array('template'=>$template,'customized'=>0)));}
|
||||
protected function guard(){return $this->guardPermission('manage_customers');}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
. ($orderJoin !== '' ? 'COALESCE(orders.orders_count,0)' : '0') . ' orders_count,'
|
||||
. ($orderJoin !== '' ? 'COALESCE(orders.orders_total,0)' : '0') . ' orders_total,'
|
||||
. ($orderJoin !== '' ? 'COALESCE(orders.last_order_at,0)' : '0') . ' last_order_at'
|
||||
. ' FROM ' . $users . ' u' . $orderJoin . ' WHERE u.deleted!=%s';
|
||||
. ' FROM ' . $users . ' u' . $orderJoin . ' WHERE COALESCE(u.deleted,0)!=%s';
|
||||
$args = array('1');
|
||||
if ($query !== '') {
|
||||
$sql .= ' AND (u.email LIKE %ss OR u.firstname LIKE %ss OR u.lastname LIKE %ss OR u.user_name LIKE %ss OR u.phone LIKE %ss OR u.company LIKE %ss';
|
||||
@@ -78,7 +78,7 @@
|
||||
$users = PublicUserTables::table('users');
|
||||
$orders = BasketTables::table('module_basket_history');
|
||||
$result = array(
|
||||
'total' => (int) DB::query('SELECT COUNT(*) FROM ' . $users . ' WHERE deleted!=%s', '1')->getValue(),
|
||||
'total' => (int) DB::query('SELECT COUNT(*) FROM ' . $users . ' WHERE COALESCE(deleted,0)!=%s', '1')->getValue(),
|
||||
'buyers' => 0, 'repeat' => 0, 'duplicates' => count(self::duplicateGroups()),
|
||||
);
|
||||
if (DatabaseSchema::tableExists($orders)) {
|
||||
@@ -169,10 +169,10 @@
|
||||
{
|
||||
$table = PublicUserTables::table('users'); $groups = array();
|
||||
$queries = array(
|
||||
'email' => "SELECT LOWER(TRIM(email)) duplicate_value,GROUP_CONCAT(Id ORDER BY Id) ids,COUNT(*) amount FROM $table WHERE deleted!='1' AND email!='' GROUP BY LOWER(TRIM(email)) HAVING COUNT(*)>1 LIMIT 30",
|
||||
'email' => "SELECT LOWER(TRIM(email)) duplicate_value,GROUP_CONCAT(Id ORDER BY Id) ids,COUNT(*) amount FROM $table WHERE COALESCE(deleted,0)!='1' AND email!='' GROUP BY LOWER(TRIM(email)) HAVING COUNT(*)>1 LIMIT 30",
|
||||
);
|
||||
if (DatabaseSchema::columnExists($table, 'phone_normalized')) {
|
||||
$queries['phone'] = "SELECT phone_normalized duplicate_value,GROUP_CONCAT(Id ORDER BY Id) ids,COUNT(*) amount FROM $table WHERE deleted!='1' AND phone_normalized IS NOT NULL GROUP BY phone_normalized HAVING COUNT(*)>1 LIMIT 30";
|
||||
$queries['phone'] = "SELECT phone_normalized duplicate_value,GROUP_CONCAT(Id ORDER BY Id) ids,COUNT(*) amount FROM $table WHERE COALESCE(deleted,0)!='1' AND phone_normalized IS NOT NULL GROUP BY phone_normalized HAVING COUNT(*)>1 LIMIT 30";
|
||||
}
|
||||
|
||||
foreach ($queries as $kind => $sql) {
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
{
|
||||
$query = trim((string) $query); if ($query === '') { return array(); }
|
||||
$sql = 'SELECT Id,email,firstname,lastname,user_name,phone,company,status FROM ' . PublicUserTables::table('users')
|
||||
. ' WHERE deleted!=%s AND (email LIKE %ss OR firstname LIKE %ss OR lastname LIKE %ss OR user_name LIKE %ss OR phone LIKE %ss OR company LIKE %ss';
|
||||
. ' WHERE COALESCE(deleted,0)!=%s AND (email LIKE %ss OR firstname LIKE %ss OR lastname LIKE %ss OR user_name LIKE %ss OR phone LIKE %ss OR company LIKE %ss';
|
||||
$args = array('1', $query, $query, $query, $query, $query, $query);
|
||||
if (ctype_digit($query)) { $sql .= ' OR Id=%i'; $args[] = (int) $query; }
|
||||
$sql .= ') ORDER BY status DESC,Id DESC LIMIT ' . max(1, min(12, (int) $limit));
|
||||
|
||||
@@ -35,15 +35,15 @@
|
||||
{
|
||||
public static function customers($q='')
|
||||
{
|
||||
$sql='SELECT Id AS id,email,firstname,lastname,user_name,phone,company,status,reg_time,last_visit FROM '.self::table('users').' WHERE deleted!=%s';$args=array('1');$q=trim((string)$q);
|
||||
if($q!==''){$sql.=' AND (email LIKE %ss OR firstname LIKE %ss OR lastname LIKE %ss OR phone LIKE %ss OR company LIKE %ss)';for($i=0;$i<5;$i++){$args[]=$q;}}$sql.=' ORDER BY Id DESC LIMIT 500';return call_user_func_array(array('DB','query'),array_merge(array($sql),$args))->getAll()?:array();
|
||||
$sql='SELECT Id AS id,email,firstname,lastname,user_name,phone,company,status,reg_time,last_visit FROM '.self::table('users').' WHERE COALESCE(deleted,0)!=%s';$args=array('1');$q=trim((string)$q);
|
||||
if($q!==''){$sql.=' AND (email LIKE %ss OR firstname LIKE %ss OR lastname LIKE %ss OR user_name LIKE %ss OR phone LIKE %ss OR company LIKE %ss';for($i=0;$i<6;$i++){$args[]=$q;}if(ctype_digit($q)){$sql.=' OR Id=%i';$args[]=(int)$q;}$sql.=')';}$sql.=' ORDER BY Id DESC LIMIT 500';return call_user_func_array(array('DB','query'),array_merge(array($sql),$args))->getAll()?:array();
|
||||
}
|
||||
|
||||
public static function exportChunk($q, $beforeId, $limit = 500)
|
||||
{
|
||||
$sql = 'SELECT Id AS id,email,firstname,lastname,user_name,phone,company,status,reg_time,last_visit FROM ' . self::table('users') . ' WHERE deleted!=%s';
|
||||
$sql = 'SELECT Id AS id,email,firstname,lastname,user_name,phone,company,status,reg_time,last_visit FROM ' . self::table('users') . ' WHERE COALESCE(deleted,0)!=%s';
|
||||
$args = array('1'); $q = trim((string) $q);
|
||||
if ($q !== '') { $sql .= ' AND (email LIKE %ss OR firstname LIKE %ss OR lastname LIKE %ss OR phone LIKE %ss OR company LIKE %ss)'; for ($i = 0; $i < 5; $i++) { $args[] = $q; } }
|
||||
if ($q !== '') { $sql .= ' AND (email LIKE %ss OR firstname LIKE %ss OR lastname LIKE %ss OR user_name LIKE %ss OR phone LIKE %ss OR company LIKE %ss)'; for ($i = 0; $i < 6; $i++) { $args[] = $q; } }
|
||||
if ((int) $beforeId > 0) { $sql .= ' AND Id<%i'; $args[] = (int) $beforeId; }
|
||||
$sql .= ' ORDER BY Id DESC LIMIT ' . max(1, min(1000, (int) $limit));
|
||||
return call_user_func_array(array('DB', 'query'), array_merge(array($sql), $args))->getAll() ?: array();
|
||||
@@ -51,7 +51,7 @@
|
||||
|
||||
public static function stats()
|
||||
{
|
||||
$table=self::table('users');return array('total'=>(int)DB::query('SELECT COUNT(*) FROM '.$table.' WHERE deleted!=%s','1')->getValue(),'active'=>(int)DB::query('SELECT COUNT(*) FROM '.$table.' WHERE deleted!=%s AND status=%s','1','1')->getValue(),'verified'=>(int)DB::query('SELECT COUNT(*) FROM '.$table.' WHERE deleted!=%s AND (email_verified_at>0 OR phone_verified_at>0)','1')->getValue(),'fields'=>count(self::fields()));
|
||||
$table=self::table('users');return array('total'=>(int)DB::query('SELECT COUNT(*) FROM '.$table.' WHERE COALESCE(deleted,0)!=%s','1')->getValue(),'active'=>(int)DB::query('SELECT COUNT(*) FROM '.$table.' WHERE COALESCE(deleted,0)!=%s AND status=%s','1','1')->getValue(),'verified'=>(int)DB::query('SELECT COUNT(*) FROM '.$table.' WHERE COALESCE(deleted,0)!=%s AND (email_verified_at>0 OR phone_verified_at>0)','1')->getValue(),'fields'=>count(self::fields()));
|
||||
}
|
||||
|
||||
public static function toggle($id, $currentSystemId = 0)
|
||||
@@ -65,7 +65,7 @@
|
||||
throw new \InvalidArgumentException('Нельзя отключить собственную учётную запись');
|
||||
}
|
||||
|
||||
DB::query('UPDATE '.self::table('users')." SET status=IF(status='1','0','1') WHERE Id=%i AND deleted!=%s",(int)$id,'1');
|
||||
DB::query('UPDATE '.self::table('users')." SET status=IF(status='1','0','1') WHERE Id=%i AND COALESCE(deleted,0)!=%s",(int)$id,'1');
|
||||
$active=(string)DB::query('SELECT status FROM '.self::table('users').' WHERE Id=%i',(int)$id)->getValue()==='1';
|
||||
if(!$active){self::invalidateCustomerSessions((int)$id);}
|
||||
return $active;
|
||||
@@ -73,9 +73,25 @@
|
||||
|
||||
public static function customer($id, $currentSystemId = 0)
|
||||
{
|
||||
$row=DB::query('SELECT Id AS id,email,email_verified_at,firstname,lastname,user_name,phone,phone_normalized,phone_verified_at,company,city,street,street_nr,zipcode,birthday,description,user_group,status,reg_time,last_visit FROM '.self::table('users').' WHERE Id=%i AND deleted!=%s LIMIT 1',(int)$id,'1')->getAssoc();
|
||||
if(!$row){return null;}
|
||||
$row=(array)$row;
|
||||
$source = (new UserRepository())->find((int) $id);
|
||||
if (!$source) { return null; }
|
||||
|
||||
$defaults = array(
|
||||
'email' => null, 'email_verified_at' => 0, 'firstname' => '', 'lastname' => '',
|
||||
'user_name' => '', 'phone' => '', 'phone_normalized' => null, 'phone_verified_at' => 0,
|
||||
'company' => '', 'city' => '', 'street' => '', 'street_nr' => '', 'zipcode' => '',
|
||||
'birthday' => '', 'description' => '', 'user_group' => 0, 'status' => '0',
|
||||
'reg_time' => 0, 'last_visit' => 0,
|
||||
);
|
||||
$row = array('id' => (int) $source['Id']);
|
||||
foreach ($defaults as $key => $default) {
|
||||
$row[$key] = array_key_exists($key, $source) ? $source[$key] : $default;
|
||||
}
|
||||
|
||||
if (empty($row['phone_normalized']) && !empty($row['phone'])) {
|
||||
$row['phone_normalized'] = Phone::normalize($row['phone']);
|
||||
}
|
||||
|
||||
$row['birthday']=(int)$row['birthday']>0?date('Y-m-d',(int)$row['birthday']):'';
|
||||
$values=DB::query('SELECT field_id,value FROM '.self::table('user_profile_values').' WHERE user_id=%i',(int)$id)->getAll()?:array();
|
||||
$extra=array();
|
||||
@@ -137,9 +153,9 @@
|
||||
if($email===''&&$phone===''){throw new \InvalidArgumentException('Укажите email или телефон');}
|
||||
if($adminAccess&&$email===''){throw new \InvalidArgumentException('Для доступа в панель управления укажите email');}
|
||||
if(mb_strlen($email)>100||mb_strlen($userName)>50||mb_strlen($firstName)>50||mb_strlen($lastName)>50){throw new \InvalidArgumentException('Имя, email или логин превышают допустимую длину');}
|
||||
if($email!==''&&DB::query('SELECT Id FROM '.self::table('users').' WHERE LOWER(email)=LOWER(%s) AND Id!=%i AND deleted!=%s LIMIT 1',$email,$id,'1')->getValue()){throw new \InvalidArgumentException('Этот email уже используется');}
|
||||
if($phone!==''&&DB::query('SELECT Id FROM '.self::table('users').' WHERE phone_normalized=%s AND Id!=%i AND deleted!=%s LIMIT 1',$phone,$id,'1')->getValue()){throw new \InvalidArgumentException('Этот телефон уже используется');}
|
||||
if(DB::query('SELECT Id FROM '.self::table('users').' WHERE LOWER(user_name)=LOWER(%s) AND Id!=%i AND deleted!=%s LIMIT 1',$userName,$id,'1')->getValue()){throw new \InvalidArgumentException('Этот логин уже используется');}
|
||||
if($email!==''&&DB::query('SELECT Id FROM '.self::table('users').' WHERE LOWER(email)=LOWER(%s) AND Id!=%i AND COALESCE(deleted,0)!=%s LIMIT 1',$email,$id,'1')->getValue()){throw new \InvalidArgumentException('Этот email уже используется');}
|
||||
if($phone!==''&&DB::query('SELECT Id FROM '.self::table('users').' WHERE phone_normalized=%s AND Id!=%i AND COALESCE(deleted,0)!=%s LIMIT 1',$phone,$id,'1')->getValue()){throw new \InvalidArgumentException('Этот телефон уже используется');}
|
||||
if(DB::query('SELECT Id FROM '.self::table('users').' WHERE LOWER(user_name)=LOWER(%s) AND Id!=%i AND COALESCE(deleted,0)!=%s LIMIT 1',$userName,$id,'1')->getValue()){throw new \InvalidArgumentException('Этот логин уже используется');}
|
||||
$groupIds=array_map(function($item){return (int)$item['id'];},self::groups());
|
||||
if(!in_array($group,$groupIds,true)){throw new \InvalidArgumentException('Выберите активную группу публичных пользователей');}
|
||||
$authSettings=PublicAuthSettings::all();
|
||||
@@ -175,7 +191,10 @@
|
||||
self::saveExtraValues($id,$extra);
|
||||
if($password!==''){(new UserRepository())->setPassword($id,$password);}
|
||||
IdentityLinker::setAdminAccess($id,$adminAccess,$adminRole,(int)$currentSystemId);
|
||||
if($password!==''||$active!=='1'){self::invalidateCustomerSessions($id);}
|
||||
$securityChanged=$password!==''||$active!==(string)$current['user']['status']
|
||||
||$group!==(int)$current['user']['user_group']||$email!==mb_strtolower(trim((string)$current['user']['email']))
|
||||
||$phone!==(string)$current['user']['phone_normalized']||$userName!==(string)$current['user']['user_name'];
|
||||
if($securityChanged){self::invalidateCustomerSessions($id);}
|
||||
DB::commit();
|
||||
}catch(\Throwable $e){DB::rollback();throw $e;}
|
||||
return self::customer($id);
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
use App\Adminx\Customers\GlobalSearchProvider;
|
||||
|
||||
return array(
|
||||
'code' => 'customers', 'name' => 'Пользователи сайта', 'version' => '0.10.3',
|
||||
'code' => 'customers', 'name' => 'Пользователи сайта', 'version' => '0.10.4',
|
||||
'permissions' => array('key' => 'customers', 'items' => array(
|
||||
array(
|
||||
'code' => 'view_customers',
|
||||
|
||||
@@ -177,7 +177,7 @@
|
||||
<div class="drawer-body">
|
||||
<div class="customers-editor-meta"><span><i class="ti ti-id"></i><b data-customer-meta-id>#—</b></span><span><i class="ti ti-user-plus"></i><b data-customer-meta-created>—</b><small>Регистрация</small></span><span><i class="ti ti-clock"></i><b data-customer-meta-visit>—</b><small>Последний вход</small></span></div>
|
||||
<div class="customers-editor-sections">
|
||||
<section class="customers-form-section"><div class="customers-form-section-head"><span class="icon-tile" style="--tile-bg:var(--blue-100);--tile-fg:var(--blue-600)"><i class="ti ti-user"></i></span><div><b>Основные данные</b><span>Имя, контакты и данные организации.</span></div></div><div class="form-grid"><label class="field col-6"><span class="field-label">Имя</span><span class="input-wrap customers-editor-input"><i class="ti ti-user"></i><input class="input" name="firstname" maxlength="50"></span></label><label class="field col-6"><span class="field-label">Фамилия</span><span class="input-wrap customers-editor-input"><i class="ti ti-user"></i><input class="input" name="lastname" maxlength="50"></span></label><label class="field col-6"><span class="field-label">Email</span><span class="input-wrap customers-editor-input"><i class="ti ti-mail"></i><input class="input" type="email" name="email" maxlength="100" required></span></label><label class="field col-6"><span class="field-label">Логин</span><span class="input-wrap customers-editor-input"><i class="ti ti-at"></i><input class="input mono" name="user_name" maxlength="50" required></span><span class="field-hint">Можно использовать для входа наравне с email.</span></label><label class="field col-6"><span class="field-label">Телефон</span><span class="input-wrap customers-editor-input"><i class="ti ti-phone"></i><input class="input" type="tel" name="phone" maxlength="50"></span></label><label class="field col-6"><span class="field-label">Компания</span><span class="input-wrap customers-editor-input"><i class="ti ti-building"></i><input class="input" name="company" maxlength="255"></span></label><label class="field col-4"><span class="field-label">Дата рождения</span><span class="input-wrap customers-editor-input"><i class="ti ti-calendar"></i><input class="input" type="date" name="birthday"></span></label><label class="field col-8"><span class="field-label">О пользователе</span><textarea class="textarea" name="description" rows="2"></textarea></label></div></section>
|
||||
<section class="customers-form-section"><div class="customers-form-section-head"><span class="icon-tile" style="--tile-bg:var(--blue-100);--tile-fg:var(--blue-600)"><i class="ti ti-user"></i></span><div><b>Основные данные</b><span>Имя, контакты и данные организации.</span></div></div><div class="form-grid"><label class="field col-6"><span class="field-label">Имя</span><span class="input-wrap customers-editor-input"><i class="ti ti-user"></i><input class="input" name="firstname" maxlength="50"></span></label><label class="field col-6"><span class="field-label">Фамилия</span><span class="input-wrap customers-editor-input"><i class="ti ti-user"></i><input class="input" name="lastname" maxlength="50"></span></label><label class="field col-6"><span class="field-label">Email</span><span class="input-wrap customers-editor-input"><i class="ti ti-mail"></i><input class="input" type="email" name="email" maxlength="100"></span><span class="field-hint">Для аккаунта с подтверждённым телефоном необязателен.</span></label><label class="field col-6"><span class="field-label">Логин</span><span class="input-wrap customers-editor-input"><i class="ti ti-at"></i><input class="input mono" name="user_name" maxlength="50" required></span><span class="field-hint">Системный идентификатор аккаунта; при регистрации по телефону заполняется номером.</span></label><label class="field col-6"><span class="field-label">Телефон</span><span class="input-wrap customers-editor-input"><i class="ti ti-phone"></i><input class="input" type="tel" name="phone" maxlength="50"></span></label><label class="field col-6"><span class="field-label">Компания</span><span class="input-wrap customers-editor-input"><i class="ti ti-building"></i><input class="input" name="company" maxlength="255"></span></label><label class="field col-4"><span class="field-label">Дата рождения</span><span class="input-wrap customers-editor-input"><i class="ti ti-calendar"></i><input class="input" type="date" name="birthday"></span></label><label class="field col-8"><span class="field-label">О пользователе</span><textarea class="textarea" name="description" rows="2"></textarea></label></div></section>
|
||||
<section class="customers-form-section"><div class="customers-form-section-head"><span class="icon-tile" style="--tile-bg:var(--cyan-100);--tile-fg:var(--cyan-600)"><i class="ti ti-map-pin"></i></span><div><b>Адрес</b><span>Данные для профиля и предзаполнения заказов.</span></div></div><div class="form-grid"><label class="field col-4"><span class="field-label">Город</span><span class="input-wrap customers-editor-input"><i class="ti ti-building-community"></i><input class="input" name="city"></span></label><label class="field col-4"><span class="field-label">Улица</span><span class="input-wrap customers-editor-input"><i class="ti ti-road"></i><input class="input" name="street"></span></label><label class="field col-2"><span class="field-label">Дом</span><span class="input-wrap customers-editor-input"><i class="ti ti-home"></i><input class="input" name="street_nr"></span></label><label class="field col-2"><span class="field-label">Индекс</span><span class="input-wrap customers-editor-input"><i class="ti ti-mailbox"></i><input class="input" name="zipcode"></span></label></div></section>
|
||||
<section class="customers-form-section">
|
||||
<div class="customers-form-section-head"><span class="icon-tile" style="--tile-bg:var(--green-100);--tile-fg:var(--green-600)"><i class="ti ti-shield-check"></i></span><div><b>Доступ</b><span>Публичная группа, состояние аккаунта и роль в панели управления.</span></div></div>
|
||||
@@ -189,11 +189,11 @@
|
||||
<label class="customers-switch-card" data-customer-account-card><span><b>Аккаунт включён</b><small data-customer-account-hint>Может входить на сайт и в личный кабинет.</small></span><span class="switch"><input type="checkbox" name="status" value="1"><span></span></span></label>
|
||||
<label class="customers-switch-card" data-customer-admin-card><span><b>Доступ в панель управления</b><small data-customer-admin-hint>{{ can_manage_admin_access ? 'Та же учётная запись сможет работать в административном интерфейсе.' : 'Изменение требует права управления системными пользователями.' }}</small></span><span class="switch"><input type="checkbox" name="admin_access" value="1" data-customer-admin-access{{ can_manage_admin_access ? '' : ' disabled' }}><span></span></span></label>
|
||||
<label class="customers-switch-card"><span><b>Email подтверждён</b><small>Администратор может изменить статус вручную.</small></span><span class="switch"><input type="checkbox" name="email_verified" value="1"><span></span></span></label>
|
||||
<label class="customers-switch-card"><span><b>Телефон подтверждён</b><small>Подготовлено для будущего SMS-гейта.</small></span><span class="switch"><input type="checkbox" name="phone_verified" value="1"><span></span></span></label>
|
||||
<label class="customers-switch-card"><span><b>Телефон подтверждён</b><small>Подтверждается кодом из SMS; администратор может изменить статус вручную.</small></span><span class="switch"><input type="checkbox" name="phone_verified" value="1"><span></span></span></label>
|
||||
</div>
|
||||
</section>
|
||||
{% if fields %}<section class="customers-form-section"><div class="customers-form-section-head"><span class="icon-tile" style="--tile-bg:var(--violet-100);--tile-fg:var(--violet-600)"><i class="ti ti-forms"></i></span><div><b>Дополнительные поля</b><span>Активные поля из конструктора публичного профиля.</span></div></div><div class="form-grid">{% for field in fields %}{% if field.is_active %}<label class="field col-6"><span class="field-label">{{ field.name }}{% if field.is_required %} <span class="text-danger">*</span>{% endif %}</span>{% if field.type=='textarea' %}<textarea class="textarea" name="extra[{{ field.id }}]" rows="3"{{ field.is_required?' required':'' }}></textarea>{% elseif field.type=='select' %}<select class="select" name="extra[{{ field.id }}]"{{ field.is_required?' required':'' }}><option value="">Выберите значение</option>{% for choice in field.choices %}<option value="{{ choice|e('html_attr') }}">{{ choice }}</option>{% endfor %}</select>{% elseif field.type=='checkbox' %}<span class="customers-editor-checkbox"><span class="switch"><input type="checkbox" name="extra[{{ field.id }}]" value="1"><span></span></span><span>Да / нет</span></span>{% else %}<input class="input" type="{{ field.type in ['date','number','email','tel'] ? field.type : 'text' }}" name="extra[{{ field.id }}]"{{ field.is_required?' required':'' }}>{% endif %}<span class="field-hint mono">{{ field.code }}</span></label>{% endif %}{% endfor %}</div></section>{% endif %}
|
||||
<section class="customers-form-section"><div class="customers-form-section-head"><span class="icon-tile" style="--tile-bg:var(--red-100);--tile-fg:var(--red-600)"><i class="ti ti-key"></i></span><div><b>Безопасность</b><span>Пароль изменится, только если заполнить поле.</span></div></div><label class="field customers-editor-password"><span class="field-label">Новый пароль</span><span class="input-wrap customers-editor-input"><i class="ti ti-lock"></i><input class="input" type="password" name="password" autocomplete="new-password" placeholder="Оставьте пустым, чтобы не менять"></span><span class="field-hint">При смене пароля будут отозваны remember-сессии и ссылки восстановления.</span></label></section>
|
||||
<section class="customers-form-section"><div class="customers-form-section-head"><span class="icon-tile" style="--tile-bg:var(--red-100);--tile-fg:var(--red-600)"><i class="ti ti-key"></i></span><div><b>Безопасность</b><span>Пароль изменится, только если заполнить поле.</span></div></div><label class="field customers-editor-password"><span class="field-label">Новый пароль</span><span class="input-wrap customers-editor-input"><i class="ti ti-lock"></i><input class="input" type="password" name="password" autocomplete="new-password" placeholder="Оставьте пустым, чтобы не менять"></span><span class="field-hint">Используется только при разрешённом входе по паролю; активные ссылки и сессии будут отозваны.</span></label></section>
|
||||
</div>
|
||||
</div>
|
||||
<footer class="drawer-footer"><button class="btn btn-secondary" type="button" data-close-drawer>Закрыть</button><button class="btn btn-primary" type="submit"><i class="ti ti-device-floppy"></i>Сохранить</button></footer>
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------------
|
||||
| AVE.cms
|
||||
|--------------------------------------------------------------------------------------
|
||||
| @package AVE.cms
|
||||
| @file adminx/modules/Dashboard/Attention.php
|
||||
| @author AVE.cms <support@ave-cms.ru>
|
||||
| @copyright 2007-2026 (c) AVE.cms
|
||||
| @link https://ave-cms.ru
|
||||
| @version 3.3
|
||||
*/
|
||||
|
||||
namespace App\Adminx\Dashboard;
|
||||
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Adminx\Support\AdminLocale;
|
||||
use App\Adminx\Support\ModuleExtensions;
|
||||
|
||||
class Attention
|
||||
{
|
||||
protected static $summary;
|
||||
|
||||
public static function summary($base)
|
||||
{
|
||||
if (self::$summary !== null) { return self::$summary; }
|
||||
$items = array();
|
||||
foreach (ModuleExtensions::attentionQueues() as $queue) {
|
||||
$data = isset($queue['data']) ? $queue['data'] : array();
|
||||
$item = self::normalize($data, $queue['layout_code'], $base, time());
|
||||
if ($item !== null) { $items[] = $item; }
|
||||
}
|
||||
|
||||
return self::$summary = array('items' => $items, 'updated_at' => time());
|
||||
}
|
||||
|
||||
public static function normalize(array $data, $key, $base, $now)
|
||||
{
|
||||
$url = isset($data['url']) ? (string) $data['url'] : '';
|
||||
if (empty($data['title']) || !preg_match('~^/(?!/)[a-zA-Z0-9/_?=&.%-]+$~D', $url)) { return null; }
|
||||
$available = !isset($data['available']) || $data['available'];
|
||||
$count = max(0, (int) (isset($data['count']) ? $data['count'] : 0));
|
||||
$oldest = max(0, (int) (isset($data['oldest_at']) ? $data['oldest_at'] : 0));
|
||||
$wait = '';
|
||||
if (!$available) {
|
||||
$wait = AdminLocale::text('attention_unavailable', 'Не удалось обновить');
|
||||
} elseif ($count === 0) {
|
||||
$wait = AdminLocale::text('attention_empty', 'Новых нет');
|
||||
} elseif ($oldest > 0) {
|
||||
$minutes = max(1, (int) floor(($now - $oldest) / 60));
|
||||
$wait = sprintf(AdminLocale::text('attention_wait', 'Самое старое ждёт %s'),
|
||||
$minutes < 60 ? $minutes . ' ' . AdminLocale::text('attention_minutes', 'мин')
|
||||
: ($minutes < 1440 ? (int) floor($minutes / 60) . ' ' . AdminLocale::text('attention_hours', 'ч')
|
||||
: (int) floor($minutes / 1440) . ' ' . AdminLocale::text('attention_days', 'дн')));
|
||||
} else {
|
||||
$wait = AdminLocale::text('attention_waiting', 'Ожидают обработки');
|
||||
}
|
||||
|
||||
return array('key' => (string) $key, 'title' => AdminLocale::translateMarkup($data['title']),
|
||||
'icon' => isset($data['icon']) && preg_match('/^ti ti-[a-z0-9-]+$/D', $data['icon']) ? $data['icon'] : 'ti ti-bell',
|
||||
'tone' => isset($data['tone']) && in_array($data['tone'], array('blue', 'green'), true) ? $data['tone'] : 'amber',
|
||||
'count' => $count, 'available' => (bool) $available, 'oldest_at' => $oldest,
|
||||
'latest_id' => max(0, (int) (isset($data['latest_id']) ? $data['latest_id'] : 0)),
|
||||
'url' => rtrim((string) $base, '/') . $url, 'wait' => $wait);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,16 @@
|
||||
*/
|
||||
class Controller extends BaseController
|
||||
{
|
||||
public function attention(array $params = array())
|
||||
{
|
||||
if (!\App\Common\Auth::user() || !\App\Common\Permission::checkAcp('admin_panel')) {
|
||||
return $this->error('Недостаточно прав', array(), 403);
|
||||
}
|
||||
|
||||
\App\Helpers\Request::setHeader('Cache-Control: private, no-store', true);
|
||||
return $this->success('', array('data' => Attention::summary($this->base())));
|
||||
}
|
||||
|
||||
/** GET / и /dashboard */
|
||||
public function index(array $params = [])
|
||||
{
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
.attention-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.attention-topbar[hidden],
|
||||
.attention-overview[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.attention-shortcut,
|
||||
.attention-card {
|
||||
--attention-color: var(--amber-700);
|
||||
--attention-soft: var(--amber-100);
|
||||
--attention-border: var(--amber-300);
|
||||
color: var(--text-secondary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
text-decoration: none;
|
||||
}
|
||||
.attention-shortcut.is-blue,
|
||||
.attention-card.is-blue {
|
||||
--attention-color: var(--blue-700);
|
||||
--attention-soft: var(--blue-100);
|
||||
--attention-border: var(--blue-300);
|
||||
}
|
||||
.attention-shortcut.is-green,
|
||||
.attention-card.is-green {
|
||||
--attention-color: var(--green-700);
|
||||
--attention-soft: var(--green-100);
|
||||
--attention-border: var(--green-300);
|
||||
}
|
||||
.attention-shortcut.has-pending,
|
||||
.attention-card.has-pending {
|
||||
color: var(--attention-color);
|
||||
background: var(--attention-soft);
|
||||
border-color: var(--attention-border);
|
||||
}
|
||||
.attention-shortcut:hover,
|
||||
.attention-card:hover {
|
||||
color: var(--attention-color);
|
||||
text-decoration: none;
|
||||
}
|
||||
.attention-shortcut:focus-visible,
|
||||
.attention-card:focus-visible {
|
||||
outline: 2px solid var(--attention-color);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.attention-shortcut.is-arriving,
|
||||
.attention-card.is-arriving {
|
||||
animation: attention-arrival 0.7s ease-out 2;
|
||||
}
|
||||
.attention-shortcut[hidden],
|
||||
.attention-card[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.attention-shortcut {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 0 0 36px;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
padding: 0;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 6px;
|
||||
background: var(--surface-card);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.attention-shortcut > .ti {
|
||||
font-size: 18px;
|
||||
}
|
||||
.attention-shortcut b {
|
||||
position: absolute;
|
||||
top: -6px;
|
||||
right: -5px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 18px;
|
||||
min-width: 18px;
|
||||
padding: 0 4px;
|
||||
border-radius: 9px;
|
||||
border: 2px solid var(--surface-card);
|
||||
background: var(--attention-color);
|
||||
color: #fff;
|
||||
font-size: 10px;
|
||||
line-height: 1;
|
||||
text-align: center;
|
||||
}
|
||||
.attention-overview {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.attention-heading {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.attention-heading h2 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.attention-heading > span {
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.attention-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
.attention-card {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
min-width: 0;
|
||||
min-height: 140px;
|
||||
padding: 20px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 8px;
|
||||
background: var(--surface-card);
|
||||
}
|
||||
.attention-card-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 0 0 42px;
|
||||
height: 42px;
|
||||
border-radius: 8px;
|
||||
background: var(--surface-card);
|
||||
font-size: 24px;
|
||||
}
|
||||
.attention-card-body {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
gap: 5px;
|
||||
}
|
||||
.attention-card-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.attention-card-body strong {
|
||||
font-size: 30px;
|
||||
line-height: 1.15;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.attention-wait {
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.attention-card-arrow {
|
||||
flex: 0 0 auto;
|
||||
margin-left: auto;
|
||||
font-size: 19px;
|
||||
}
|
||||
.attention-dot {
|
||||
display: none;
|
||||
flex: 0 0 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
}
|
||||
.has-pending .attention-dot {
|
||||
display: inline-block;
|
||||
animation: attention-pulse 2.2s ease-in-out infinite;
|
||||
}
|
||||
.attention-shortcut.is-stale {
|
||||
opacity: 0.65;
|
||||
}
|
||||
@keyframes attention-pulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.35;
|
||||
}
|
||||
}
|
||||
@keyframes attention-arrival {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
40% {
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
}
|
||||
@media (max-width: 680px) {
|
||||
.attention-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 10px;
|
||||
}
|
||||
.attention-card {
|
||||
padding: 16px;
|
||||
min-height: 125px;
|
||||
gap: 12px;
|
||||
}
|
||||
.attention-topbar {
|
||||
gap: 7px;
|
||||
}
|
||||
.topbar.has-attention {
|
||||
padding-inline: 8px;
|
||||
gap: 6px;
|
||||
}
|
||||
.topbar.has-attention .topbar-right {
|
||||
gap: 4px;
|
||||
}
|
||||
.topbar.has-attention .topbar-site-link,
|
||||
.topbar.has-attention .env-badge {
|
||||
display: none;
|
||||
}
|
||||
.topbar.has-attention .logo-suffix {
|
||||
display: none;
|
||||
}
|
||||
.topbar.has-attention .topbar-logo .logo-img {
|
||||
width: 52px;
|
||||
height: auto;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.has-pending .attention-dot,
|
||||
.attention-shortcut.is-arriving,
|
||||
.attention-card.is-arriving {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
@media (max-width: 380px) {
|
||||
.topbar.has-attention .logo-suffix {
|
||||
display: none;
|
||||
}
|
||||
.topbar.has-attention .topbar-logo .logo-img {
|
||||
width: 52px;
|
||||
height: auto;
|
||||
}
|
||||
.attention-shortcut {
|
||||
flex-basis: 32px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
}
|
||||
}
|
||||
@media (max-width: 480px) {
|
||||
.topbar.has-attention .topbar-logo {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
(function (window, document) {
|
||||
'use strict';
|
||||
var A = window.Adminx || (window.Adminx = {});
|
||||
var root = document.querySelector('[data-attention-root]');
|
||||
if (!root) return;
|
||||
var endpoint = root.dataset.attentionUrl;
|
||||
var storageKey = 'ave.attention.' + endpoint + '.' + root.dataset.attentionUser;
|
||||
var timer = null, busy = false, stopped = false, lastRequest = 0, seen = {};
|
||||
try { seen = JSON.parse(sessionStorage.getItem(storageKey) || '{}') || {}; } catch (e) {}
|
||||
|
||||
function saveSeen() { try { sessionStorage.setItem(storageKey, JSON.stringify(seen)); } catch (e) {} }
|
||||
function update(payload) {
|
||||
var present = {};
|
||||
payload.items.forEach(function (item) {
|
||||
present[item.key] = true;
|
||||
var baseline = seen[item.key];
|
||||
var arriving = item.available && baseline && (item.latest_id > baseline.latest_id || item.count > baseline.count);
|
||||
if (item.available) {
|
||||
seen[item.key] = { latest_id: Math.max(item.latest_id, baseline ? baseline.latest_id : 0), count: item.count };
|
||||
}
|
||||
document.querySelectorAll('[data-attention-key]').forEach(function (el) {
|
||||
if (el.dataset.attentionKey !== item.key) return;
|
||||
el.hidden = false;
|
||||
el.href = item.url;
|
||||
el.classList.toggle('has-pending', item.available && item.count > 0);
|
||||
el.classList.toggle('is-stale', !item.available);
|
||||
var count = el.querySelector('[data-attention-count]');
|
||||
if (count) count.textContent = item.available ? (el.classList.contains('attention-shortcut') && item.count > 99 ? '99+' : item.count) : '\u2014';
|
||||
var wait = el.querySelector('[data-attention-wait]');
|
||||
if (wait) wait.textContent = item.wait;
|
||||
if (el.classList.contains('attention-shortcut')) {
|
||||
var label = item.title + ': ' + (item.available ? item.count : '\u2014') + ' \u00b7 ' + item.wait;
|
||||
el.setAttribute('aria-label', label);
|
||||
el.setAttribute('data-tooltip', label);
|
||||
}
|
||||
if (arriving) {
|
||||
el.classList.remove('is-arriving');
|
||||
void el.offsetWidth;
|
||||
el.classList.add('is-arriving');
|
||||
window.setTimeout(function () { el.classList.remove('is-arriving'); }, 1500);
|
||||
}
|
||||
});
|
||||
});
|
||||
document.querySelectorAll('[data-attention-key]').forEach(function (el) {
|
||||
if (!present[el.dataset.attentionKey]) el.hidden = true;
|
||||
});
|
||||
var any = Object.keys(present).length > 0;
|
||||
root.hidden = !any;
|
||||
var overview = document.querySelector('[data-attention-overview]');
|
||||
if (overview) overview.hidden = !any;
|
||||
stale(false);
|
||||
saveSeen();
|
||||
}
|
||||
function stale(value) {
|
||||
root.classList.toggle('is-stale', value);
|
||||
document.querySelectorAll('[data-attention-health]').forEach(function (el) { el.hidden = !value; });
|
||||
if (value) root.querySelectorAll('.attention-shortcut').forEach(function (el) { el.classList.add('is-stale'); });
|
||||
}
|
||||
function schedule(delay) {
|
||||
window.clearTimeout(timer);
|
||||
if (!stopped && !document.hidden) timer = window.setTimeout(refresh, delay || 30000);
|
||||
}
|
||||
function refresh() {
|
||||
if (stopped || busy || document.hidden) return;
|
||||
if (Date.now() - lastRequest < 3000) { schedule(3000); return; }
|
||||
busy = true; lastRequest = Date.now();
|
||||
var controller = new AbortController();
|
||||
var timeout = window.setTimeout(function () { controller.abort(); }, 10000);
|
||||
fetch(endpoint, { credentials: 'same-origin', cache: 'no-store', signal: controller.signal,
|
||||
headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' } })
|
||||
.then(function (response) {
|
||||
if (response.status === 401 || response.status === 403 || response.status === 428 || response.redirected) {
|
||||
stopped = true;
|
||||
throw Error('Session unavailable');
|
||||
}
|
||||
if (!response.ok) throw Error('Refresh failed');
|
||||
return response.json();
|
||||
}).then(function (result) {
|
||||
if (!result.success || !result.data || !Array.isArray(result.data.items)) throw Error('Invalid summary');
|
||||
update(result.data);
|
||||
}).catch(function () { stale(true); })
|
||||
.finally(function () { window.clearTimeout(timeout); busy = false; schedule(); });
|
||||
}
|
||||
try { update(JSON.parse(root.dataset.attentionInitial)); } catch (e) { stale(true); }
|
||||
document.addEventListener('visibilitychange', function () { window.clearTimeout(timer); if (!document.hidden) refresh(); });
|
||||
document.addEventListener('adminx:drawer:closed', function () { schedule(1000); });
|
||||
document.addEventListener('adminx:form-saved', function () { schedule(1000); });
|
||||
window.addEventListener('pageshow', function (event) { if (event.persisted) refresh(); });
|
||||
A.Attention = { refresh: refresh };
|
||||
schedule();
|
||||
})(window, document);
|
||||
@@ -21,7 +21,7 @@
|
||||
return [
|
||||
'code' => 'dashboard',
|
||||
'name' => 'Дашборд',
|
||||
'version' => '0.1.0',
|
||||
'version' => '0.2.3',
|
||||
|
||||
'navigation' => array(
|
||||
array(
|
||||
@@ -39,6 +39,7 @@
|
||||
),
|
||||
|
||||
'routes' => array(
|
||||
array('GET', '/dashboard/attention', array(\App\Adminx\Dashboard\Controller::class, 'attention')),
|
||||
array('GET', '/', array(\App\Adminx\Dashboard\Controller::class, 'index')),
|
||||
array('GET', '/dashboard', array(\App\Adminx\Dashboard\Controller::class, 'index')),
|
||||
),
|
||||
|
||||
@@ -5,6 +5,21 @@
|
||||
|
||||
<div class="page-header dashboard-page-header"><div><h1>{{ greeting }}</h1><p class="text-secondary">{{ lang.dashboard_summary|default('Сводка системы и последние изменения') }}</p></div><div class="dashboard-date"><i class="ti ti-calendar"></i>{{ 'now'|date('d.m.Y') }}</div></div>
|
||||
|
||||
{% if attention.items %}
|
||||
<section class="attention-overview" data-attention-overview aria-labelledby="attention-heading">
|
||||
<div class="attention-heading"><h2 id="attention-heading">{{ lang.attention_heading|default('Требуют внимания') }}</h2><span data-attention-health hidden>{{ lang.attention_stale|default('Данные временно не обновляются') }}</span></div>
|
||||
<div class="attention-grid">
|
||||
{% for item in attention.items %}
|
||||
<a class="attention-card is-{{ item.tone }}{{ item.available and item.count > 0 ? ' has-pending' : '' }}" href="{{ item.url }}" data-attention-key="{{ item.key }}">
|
||||
<span class="attention-card-icon"><i class="{{ item.icon }}" aria-hidden="true"></i></span>
|
||||
<span class="attention-card-body"><span class="attention-card-title">{{ item.title }}<i class="attention-dot" aria-hidden="true"></i></span><strong data-attention-count>{{ item.available ? item.count : '—' }}</strong><span class="attention-wait" data-attention-wait>{{ item.wait }}</span></span>
|
||||
<i class="ti ti-arrow-up-right attention-card-arrow" aria-hidden="true"></i>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% if dashboard_widgets %}
|
||||
<div class="dashboard-module-widgets">
|
||||
{% for dashboard_widget in dashboard_widgets %}
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Common\Settings;
|
||||
use App\Common\DatabaseConfiguration;
|
||||
use App\Common\Db\Core\MysqliDriver;
|
||||
use DB;
|
||||
|
||||
/**
|
||||
@@ -229,8 +231,10 @@
|
||||
gzwrite($fp, "-- AVE.cms full dump\n-- database: " . Model::databaseName() . "\n-- prefixes: {{prefix}}\n-- source-prefix: " . Model::basePrefix() .
|
||||
"\n-- date: " . date('Y-m-d H:i:s') . "\n\nSET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS=0;\n\n");
|
||||
|
||||
$mysqli = DB::mysqli();
|
||||
$driver = null;
|
||||
try {
|
||||
$driver = self::openSnapshot();
|
||||
$mysqli = $driver->getMysqli();
|
||||
$total = count($tables);
|
||||
foreach ($tables as $index => $table) {
|
||||
self::notify($progress, array(
|
||||
@@ -254,6 +258,11 @@
|
||||
flock($lock, LOCK_UN);
|
||||
fclose($lock);
|
||||
throw $e;
|
||||
} finally {
|
||||
if ($driver !== null) {
|
||||
$driver->getMysqli()->rollback();
|
||||
$driver->close();
|
||||
}
|
||||
}
|
||||
|
||||
flock($lock, LOCK_UN);
|
||||
@@ -284,24 +293,22 @@
|
||||
$portableTable = Model::portableTableName($table);
|
||||
gzwrite($fp, "\n-- ----- Table `{$portableTable}` -----\nDROP TABLE IF EXISTS `{$portableTable}`;\n");
|
||||
|
||||
$create = (array) DB::query('SHOW CREATE TABLE `' . $table . '`')->getObject();
|
||||
$result = $mysqli->query('SHOW CREATE TABLE `' . $table . '`');
|
||||
if (!$result) { throw new \RuntimeException('Не удалось прочитать структуру таблицы ' . $table . ': ' . $mysqli->error); }
|
||||
$create = $result->fetch_assoc();
|
||||
$result->free();
|
||||
$ddl = isset($create['Create Table']) ? $create['Create Table'] : '';
|
||||
$enumFallbacks = SqlDumpReader::enumFallbacks($ddl);
|
||||
if ($ddl !== '') {
|
||||
gzwrite($fp, self::portableDdl($ddl) . ";\n\n");
|
||||
}
|
||||
|
||||
//-- Данные пакетами, чтобы не держать всё в памяти.
|
||||
$offset = 0;
|
||||
$batch = 500;
|
||||
do {
|
||||
$rows = DB::query('SELECT * FROM `' . $table . '` LIMIT ' . $batch . ' OFFSET ' . $offset)->getAll();
|
||||
if (!$rows) {
|
||||
break;
|
||||
}
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$row = (array) $row;
|
||||
// A single streaming SELECT cannot repeat or skip rows when writers change offsets.
|
||||
$result = $mysqli->query('SELECT * FROM `' . $table . '`', MYSQLI_USE_RESULT);
|
||||
if (!$result) { throw new \RuntimeException('Не удалось прочитать таблицу ' . $table . ': ' . $mysqli->error); }
|
||||
$count = 0;
|
||||
try {
|
||||
while ($row = $result->fetch_assoc()) {
|
||||
$cols = array();
|
||||
$vals = array();
|
||||
foreach ($row as $col => $val) {
|
||||
@@ -318,22 +325,40 @@
|
||||
}
|
||||
|
||||
gzwrite($fp, 'INSERT INTO `' . $portableTable . '` (' . implode(',', $cols) . ') VALUES (' . implode(',', $vals) . ");\n");
|
||||
$count++;
|
||||
if ($count % 5000 === 0) {
|
||||
self::notify($progress, array('table' => $table, 'current' => (int) $current, 'total' => (int) $total, 'rows' => $count));
|
||||
}
|
||||
}
|
||||
|
||||
$offset += $batch;
|
||||
if ($offset === $batch || $offset % 5000 === 0 || count($rows) < $batch) {
|
||||
self::notify($progress, array(
|
||||
'table' => $table,
|
||||
'current' => (int) $current,
|
||||
'total' => (int) $total,
|
||||
'rows' => $offset,
|
||||
));
|
||||
}
|
||||
} while (count($rows) === $batch);
|
||||
if ($mysqli->errno) { throw new \RuntimeException('Ошибка чтения таблицы ' . $table . ': ' . $mysqli->error); }
|
||||
} finally {
|
||||
$result->free();
|
||||
}
|
||||
|
||||
self::notify($progress, array('table' => $table, 'current' => (int) $current, 'total' => (int) $total, 'rows' => $count));
|
||||
|
||||
gzwrite($fp, "\n");
|
||||
}
|
||||
|
||||
/** Keep the read snapshot independent of the caller and progress callbacks. */
|
||||
protected static function openSnapshot()
|
||||
{
|
||||
$config = DatabaseConfiguration::all();
|
||||
$config['dbname'] = Model::databaseName();
|
||||
$driver = new MysqliDriver($config);
|
||||
try {
|
||||
foreach (array('SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ', 'START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY') as $sql) {
|
||||
if (!$driver->query($sql)) { throw new \RuntimeException('Не удалось открыть согласованный снимок БД: ' . $driver->error()); }
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$driver->close();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return $driver;
|
||||
}
|
||||
|
||||
/** Заменяет префикс только внутри SQL-идентификаторов, не затрагивая данные строк. */
|
||||
protected static function portableDdl($ddl)
|
||||
{
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
return [
|
||||
'code' => 'database',
|
||||
'name' => 'База данных',
|
||||
'version' => '0.2.2',
|
||||
'version' => '0.2.3',
|
||||
|
||||
'permissions' => [
|
||||
'key' => 'database',
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
*/
|
||||
class BulkEditor
|
||||
{
|
||||
const VERSION = 1;
|
||||
const VERSION = 2;
|
||||
const MAX_DOCUMENTS = 5000;
|
||||
const CHUNK_SIZE = 20;
|
||||
const EXPIRES_AFTER = 7200;
|
||||
@@ -52,12 +52,26 @@
|
||||
'document_property' => array('label' => 'Свойство / артикул', 'payload' => 'property'),
|
||||
);
|
||||
|
||||
protected static $stateOperations = array(
|
||||
'search_include' => array('column'=>'document_in_search','payload'=>'in_search','value'=>'1','before'=>array('0'=>'Вне поиска','1'=>'В поиске')),
|
||||
'search_exclude' => array('column'=>'document_in_search','payload'=>'in_search','value'=>'0','before'=>array('0'=>'Вне поиска','1'=>'В поиске')),
|
||||
'robots_index' => array('column'=>'document_meta_robots','payload'=>'meta_robots','value'=>'index,follow','before'=>array()),
|
||||
'robots_noindex' => array('column'=>'document_meta_robots','payload'=>'meta_robots','value'=>'noindex,nofollow','before'=>array()),
|
||||
'sitemap_include' => array('column'=>'document_in_sitemap','payload'=>'in_sitemap','value'=>'1','before'=>array('0'=>'Не добавляется','1'=>'Добавляется')),
|
||||
'sitemap_exclude' => array('column'=>'document_in_sitemap','payload'=>'in_sitemap','value'=>'0','before'=>array('0'=>'Не добавляется','1'=>'Добавляется')),
|
||||
'technical' => array('column'=>'document_is_technical','payload'=>'is_technical','value'=>'1','before'=>array('0'=>'Обычный','1'=>'Служебный')),
|
||||
'public' => array('column'=>'document_is_technical','payload'=>'is_technical','value'=>'0','before'=>array('0'=>'Обычный','1'=>'Служебный')),
|
||||
'sitemap_frequency' => array('column'=>'document_sitemap_freq','payload'=>'sitemap_frequency','value_input'=>'sitemap_frequency','before'=>array('0'=>'always','1'=>'hourly','2'=>'daily','3'=>'weekly','4'=>'monthly','5'=>'yearly','6'=>'never')),
|
||||
'sitemap_priority' => array('column'=>'document_sitemap_pr','payload'=>'sitemap_priority','value_input'=>'sitemap_priority','before'=>array()),
|
||||
);
|
||||
|
||||
public static function options()
|
||||
{
|
||||
return array(
|
||||
'rubrics' => Model::rubrics(),
|
||||
'document_fields' => self::$documentFields,
|
||||
'products_available' => self::productsAvailable(),
|
||||
'product_descriptions_available' => self::productDescriptionsAvailable(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -65,6 +79,7 @@
|
||||
{
|
||||
$filters = self::filters($input);
|
||||
$operation = self::operation($input, $filters);
|
||||
if ($operation['type'] === 'strip_description_styles') { $filters['scope'] = 'products'; }
|
||||
$matches = self::matches($filters);
|
||||
if (!$matches['ids']) {
|
||||
throw new \InvalidArgumentException('По выбранным условиям документы не найдены');
|
||||
@@ -90,10 +105,10 @@
|
||||
'title' => html_entity_decode((string) $row['document_title'], ENT_QUOTES, 'UTF-8'),
|
||||
'rubric' => html_entity_decode((string) $row['rubric_title'], ENT_QUOTES, 'UTF-8'),
|
||||
'state' => (int) $row['document_status'] === 1 ? 'Опубликован' : 'Черновик',
|
||||
'before' => self::shortValue($change['before']),
|
||||
'after' => self::shortValue($change['after']),
|
||||
'before' => $operation['type'] === 'strip_description_styles' ? mb_substr($change['before'], 0, 1000, 'UTF-8') : self::shortValue($change['before']),
|
||||
'after' => $operation['type'] === 'strip_description_styles' ? mb_substr($change['after'], 0, 1000, 'UTF-8') : self::shortValue($change['after']),
|
||||
'changed' => $change['changed'],
|
||||
'note' => $change['note'],
|
||||
'note' => \App\Common\Language::translateSource($change['note']),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -198,6 +213,25 @@
|
||||
if (!$row) { return false; }
|
||||
|
||||
$type = $operation['type'];
|
||||
if ($type === 'strip_description_styles') {
|
||||
if (!self::productDescriptionsAvailable()) { throw new \InvalidArgumentException('Нет доступа к описаниям товаров'); }
|
||||
$fieldId = self::productDescriptionField($row);
|
||||
if (!$fieldId) { return false; }
|
||||
$current = self::currentValue($row, array('target_type' => 'field', 'field_id' => $fieldId));
|
||||
$next = self::changedValue($current, $operation);
|
||||
if (!$next['changed']) { return false; }
|
||||
$service->patch($documentId, array('fields' => array($fieldId => $next['value'])), $actorId, 'bulk_editor');
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isset($operation['target_type']) && $operation['target_type'] === 'state') {
|
||||
if ($type === 'technical' && Model::isProtectedDocument($documentId)) { return false; }
|
||||
$current = (string) $row[$operation['target']];
|
||||
if ($current === (string) $operation['value']) { return false; }
|
||||
$service->save($documentId, array($operation['payload'] => $operation['value']), $actorId, 'bulk_editor');
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($type === 'publish' || $type === 'unpublish') {
|
||||
if (Model::isProtectedDocument($documentId)) { return false; }
|
||||
$status = $type === 'publish' ? 1 : 0;
|
||||
@@ -250,12 +284,37 @@
|
||||
protected static function operation(array $input, array $filters)
|
||||
{
|
||||
$type = isset($input['operation']) ? (string) $input['operation'] : '';
|
||||
$allowed = array('fill', 'set', 'clear', 'replace', 'move', 'publish', 'unpublish', 'recalculate');
|
||||
$allowed = array_merge(
|
||||
array('fill', 'set', 'clear', 'replace', 'move', 'publish', 'unpublish', 'recalculate', 'strip_description_styles'),
|
||||
array_keys(self::$stateOperations)
|
||||
);
|
||||
if (!in_array($type, $allowed, true)) {
|
||||
throw new \InvalidArgumentException('Выберите действие');
|
||||
}
|
||||
|
||||
$operation = array('type' => $type, 'label' => self::operationLabel($type));
|
||||
if ($type === 'strip_description_styles') {
|
||||
if (!self::productDescriptionsAvailable()) { throw new \InvalidArgumentException('Нет доступа к описаниям товаров'); }
|
||||
return array_merge($operation, array('target_type' => 'product_description', 'target_label' => 'Описание товара'));
|
||||
}
|
||||
|
||||
if (isset(self::$stateOperations[$type])) {
|
||||
$config = self::$stateOperations[$type];
|
||||
$value = isset($config['value']) ? (string) $config['value'] : trim(isset($input[$config['value_input']]) ? (string) $input[$config['value_input']] : '');
|
||||
if ($type === 'sitemap_frequency' && !array_key_exists($value, $config['before'])) {
|
||||
throw new \InvalidArgumentException('Выберите частоту обновления sitemap');
|
||||
}
|
||||
|
||||
if ($type === 'sitemap_priority' && (!is_numeric($value) || (float) $value < 0 || (float) $value > 1)) {
|
||||
throw new \InvalidArgumentException('Приоритет sitemap должен быть от 0 до 1');
|
||||
}
|
||||
|
||||
return array_merge($operation, $config, array(
|
||||
'target_type' => 'state', 'target' => $config['column'], 'value' => $value,
|
||||
'target_label' => self::operationTargetLabel($type),
|
||||
));
|
||||
}
|
||||
|
||||
if (in_array($type, array('move', 'publish', 'unpublish', 'recalculate'), true)) {
|
||||
if ($type === 'move') {
|
||||
$targetRubricId = isset($input['target_rubric_id']) ? (int) $input['target_rubric_id'] : 0;
|
||||
@@ -346,9 +405,9 @@
|
||||
$currentValues = array();
|
||||
$ids = array();
|
||||
foreach ($rows as $row) { $ids[] = (int) $row['Id']; }
|
||||
if (isset($operation['target_type']) && $operation['target_type'] === 'document') {
|
||||
if (isset($operation['target_type']) && in_array($operation['target_type'], array('document', 'state'), true)) {
|
||||
$column = (string) $operation['target'];
|
||||
if (!isset(self::$documentFields[$column])) {
|
||||
if ($operation['target_type'] === 'document' && !isset(self::$documentFields[$column])) {
|
||||
throw new \InvalidArgumentException('Поле документа недоступно для массового изменения');
|
||||
}
|
||||
|
||||
@@ -359,6 +418,12 @@
|
||||
foreach ($valueRows ?: array() as $valueRow) {
|
||||
$currentValues[(int) $valueRow['Id']] = html_entity_decode((string) $valueRow['current_value'], ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
} elseif (isset($operation['target_type']) && $operation['target_type'] === 'product_description') {
|
||||
foreach (array_chunk($ids, 500) as $chunk) {
|
||||
$valueRows = DB::query('SELECT p.product_id,' . \App\Modules\Products\ProductRoles::valueSql('description')
|
||||
. ' current_value FROM ' . CatalogTables::table('catalog_product_index') . ' p WHERE p.product_id IN %li AND p.is_deleted=0', $chunk)->getAll();
|
||||
foreach ($valueRows ?: array() as $valueRow) { $currentValues[(int) $valueRow['product_id']] = (string) $valueRow['current_value']; }
|
||||
}
|
||||
} elseif (isset($operation['target_type']) && $operation['target_type'] === 'field') {
|
||||
$valueRows = DB::query(
|
||||
'SELECT df.document_id,CONCAT(COALESCE(df.field_value,\'\'),COALESCE(dft.field_value,\'\')) current_value'
|
||||
@@ -403,12 +468,23 @@
|
||||
}
|
||||
|
||||
if ($operation['type'] === 'move') {
|
||||
return array('before' => (string) $row['rubric_title'], 'after' => (string) $operation['target_rubric_title'], 'changed' => (int) $row['rubric_id'] !== (int) $operation['target_rubric_id'], 'note' => 'Совпадающие поля переносятся по системному имени');
|
||||
return array('before' => (string) $row['rubric_title'], 'after' => (string) $operation['target_rubric_title'], 'changed' => (int) $row['rubric_id'] !== (int) $operation['target_rubric_id'], 'note' => 'Переносятся только поля с одинаковыми системными именами и типами. Значения остальных полей не сохранятся в новой рубрике.');
|
||||
}
|
||||
|
||||
if ($operation['target_type'] === 'state') {
|
||||
if ($operation['type'] === 'technical' && Model::isProtectedDocument((int) $row['Id'])) {
|
||||
return array('before'=>'Системный документ','after'=>'Без изменений','changed'=>false,'note'=>'Главную и страницу 404 нельзя сделать служебными');
|
||||
}
|
||||
|
||||
$current = self::currentValue($row, $operation);
|
||||
$before = isset($operation['before'][$current]) ? $operation['before'][$current] : $current;
|
||||
$after = isset($operation['before'][(string) $operation['value']]) ? $operation['before'][(string) $operation['value']] : (string) $operation['value'];
|
||||
return array('before'=>$before,'after'=>$after,'changed'=>$current !== (string) $operation['value'],'note'=>'');
|
||||
}
|
||||
|
||||
$current = self::currentValue($row, $operation);
|
||||
$next = self::changedValue($current, $operation);
|
||||
return array('before' => $current, 'after' => $next['value'], 'changed' => $next['changed'], 'note' => $next['changed'] ? '' : 'Значение уже соответствует действию');
|
||||
return array('before' => $current, 'after' => $next['value'], 'changed' => $next['changed'], 'note' => isset($next['removed']) ? 'Удалится атрибутов style: ' . $next['removed'] : ($next['changed'] ? '' : 'Значение уже соответствует действию'));
|
||||
}
|
||||
|
||||
protected static function currentValue(array $row, array $operation)
|
||||
@@ -417,7 +493,12 @@
|
||||
return (string) $row['__bulk_current'];
|
||||
}
|
||||
|
||||
if ($operation['target_type'] === 'document') {
|
||||
if ($operation['target_type'] === 'product_description') {
|
||||
$fieldId = self::productDescriptionField($row);
|
||||
return $fieldId ? self::currentValue($row, array('target_type' => 'field', 'field_id' => $fieldId)) : '';
|
||||
}
|
||||
|
||||
if ($operation['target_type'] === 'document' || $operation['target_type'] === 'state') {
|
||||
if (!array_key_exists($operation['target'], $row)) {
|
||||
$value = DB::query(
|
||||
'SELECT `' . $operation['target'] . '` FROM ' . ContentTables::table('documents') . ' WHERE Id=%i',
|
||||
@@ -444,6 +525,11 @@
|
||||
{
|
||||
$current = (string) $current;
|
||||
$type = $operation['type'];
|
||||
if ($type === 'strip_description_styles') {
|
||||
$result = \App\Helpers\Html::removeInlineStyles($current);
|
||||
return array('value' => $result['html'], 'changed' => $result['removed'] > 0, 'removed' => $result['removed']);
|
||||
}
|
||||
|
||||
if ($type === 'fill') {
|
||||
$value = trim($current) === '' ? (string) $operation['value'] : $current;
|
||||
} elseif ($type === 'clear') {
|
||||
@@ -532,17 +618,51 @@
|
||||
}
|
||||
}
|
||||
|
||||
protected static function productDescriptionsAvailable()
|
||||
{
|
||||
$module = \App\Common\ModuleManager::get('products');
|
||||
return $module && !empty($module['enabled']) && \App\Common\Permission::check('manage_products')
|
||||
&& class_exists('App\\Modules\\Products\\ProductRoles') && self::productsAvailable();
|
||||
}
|
||||
|
||||
protected static function productDescriptionField(array $row)
|
||||
{
|
||||
$product = DB::query('SELECT rubric_id FROM ' . CatalogTables::table('catalog_product_index')
|
||||
. ' WHERE product_id=%i AND is_deleted=0', (int) $row['Id'])->getAssoc();
|
||||
if (!$product || (int) $product['rubric_id'] !== (int) $row['rubric_id']) { return 0; }
|
||||
$roles = \App\Modules\Products\ProductRoles::forRubric((int) $row['rubric_id']);
|
||||
return isset($roles['description']) ? (int) $roles['description'] : 0;
|
||||
}
|
||||
|
||||
protected static function operationLabel($type)
|
||||
{
|
||||
$labels = array(
|
||||
'fill' => 'Заполнить пустые', 'set' => 'Установить значение', 'clear' => 'Очистить',
|
||||
'strip_description_styles' => 'Удалить стили из описаний товаров',
|
||||
'replace' => 'Найти и заменить', 'move' => 'Перенести в рубрику',
|
||||
'publish' => 'Опубликовать', 'unpublish' => 'Снять с публикации',
|
||||
'recalculate' => 'Пересчитать поля и индексы',
|
||||
);
|
||||
'publish' => 'Опубликовать', 'unpublish' => 'Снять с публикации',
|
||||
'recalculate' => 'Пересчитать поля и индексы',
|
||||
'search_include' => 'Включить во внутренний поиск', 'search_exclude' => 'Исключить из внутреннего поиска',
|
||||
'robots_index' => 'Разрешить индексацию поисковиками', 'robots_noindex' => 'Запретить индексацию поисковиками',
|
||||
'sitemap_include' => 'Добавить в sitemap', 'sitemap_exclude' => 'Исключить из sitemap',
|
||||
'technical' => 'Сделать служебными', 'public' => 'Сделать обычными',
|
||||
'sitemap_frequency' => 'Изменить частоту sitemap', 'sitemap_priority' => 'Изменить приоритет sitemap',
|
||||
);
|
||||
return isset($labels[$type]) ? $labels[$type] : $type;
|
||||
}
|
||||
|
||||
protected static function operationTargetLabel($type)
|
||||
{
|
||||
$labels = array(
|
||||
'search_include'=>'Внутренний поиск','search_exclude'=>'Внутренний поиск',
|
||||
'robots_index'=>'Meta robots','robots_noindex'=>'Meta robots',
|
||||
'sitemap_include'=>'Участие в sitemap','sitemap_exclude'=>'Участие в sitemap',
|
||||
'technical'=>'Публичный доступ','public'=>'Публичный доступ',
|
||||
'sitemap_frequency'=>'Частота sitemap','sitemap_priority'=>'Приоритет sitemap',
|
||||
);
|
||||
return isset($labels[$type]) ? $labels[$type] : '';
|
||||
}
|
||||
|
||||
protected static function shortValue($value)
|
||||
{
|
||||
$value = trim(preg_replace('/\s+/u', ' ', strip_tags((string) $value)));
|
||||
|
||||
@@ -442,6 +442,7 @@
|
||||
AdminAssets::addScript($this->base() . '/modules/Documents/assets/documents.js', 50);
|
||||
return $this->render('@documents/bulk-editor.twig', array(
|
||||
'bulk_options' => BulkEditor::options(),
|
||||
'bulk_clean_descriptions' => Request::getStr('operation', '') === 'strip_description_styles',
|
||||
));
|
||||
}
|
||||
|
||||
@@ -587,9 +588,11 @@
|
||||
$snapshot = (new DocumentSnapshotRepository())->find($id);
|
||||
DocumentSaveEvents::after('create', 'adminx', $id, $rubricId, Auth::id(), $input, $fieldValues, array(), is_array($snapshot) ? $snapshot : array());
|
||||
$nextMediaDraftToken = DocumentMediaDraft::issue(Auth::id(), $id);
|
||||
$editorState = Model::editorState($id);
|
||||
return $this->success('Документ создан', array('data' => array(
|
||||
'id' => $id,
|
||||
'document_version' => Model::documentVersion($id),
|
||||
'document_version' => $editorState ? $editorState['version'] : Model::documentVersion($id),
|
||||
'editor_state' => $editorState,
|
||||
'snapshot_warning' => $snapshotError,
|
||||
'media_draft_token' => $nextMediaDraftToken,
|
||||
), 'redirect' => $this->base() . '/documents/' . $id . '/edit'));
|
||||
@@ -734,9 +737,11 @@
|
||||
$snapshot = (new DocumentSnapshotRepository())->find($id);
|
||||
DocumentSaveEvents::after('update', 'adminx', $id, (int) $doc['rubric_id'], Auth::id(), $input, $fieldValues, $doc, is_array($snapshot) ? $snapshot : array());
|
||||
$mediaCleanup = DocumentMediaReplacement::cleanup($mediaReplacement, $fieldValues);
|
||||
$editorState = Model::editorState($id);
|
||||
return $this->success('Документ сохранён', array('data' => array(
|
||||
'id' => $id,
|
||||
'document_version' => Model::documentVersion($id),
|
||||
'document_version' => $editorState ? $editorState['version'] : Model::documentVersion($id),
|
||||
'editor_state' => $editorState,
|
||||
'snapshot_warning' => $snapshotError,
|
||||
'media_cleanup' => $mediaCleanup,
|
||||
'media_draft_token' => DocumentMediaDraft::issue(Auth::id(), $id),
|
||||
|
||||
@@ -226,8 +226,8 @@
|
||||
'document_title', 'document_alias', 'document_alias_header', 'document_alias_history',
|
||||
'document_short_alias', 'document_breadcrumb_title', 'document_excerpt',
|
||||
'document_meta_keywords', 'document_meta_description', 'document_meta_robots',
|
||||
'document_sitemap_freq', 'document_sitemap_pr', 'document_tags', 'document_property',
|
||||
'guid', 'document_status', 'document_in_search', 'document_parent', 'rubric_tmpl_id',
|
||||
'document_sitemap_freq', 'document_sitemap_pr', 'document_in_sitemap', 'document_tags', 'document_property',
|
||||
'guid', 'document_status', 'document_in_search', 'document_is_technical', 'document_parent', 'rubric_tmpl_id',
|
||||
'document_linked_navi_id', 'document_position', 'document_published', 'document_expire',
|
||||
'document_author_id',
|
||||
) as $key) {
|
||||
|
||||
@@ -111,7 +111,7 @@
|
||||
$countArgs = array_merge(array('SELECT COUNT(*) FROM ' . self::documentsTable() . ' d' . $where), $args);
|
||||
$total = (int) call_user_func_array(array('DB', 'query'), $countArgs)->getValue();
|
||||
|
||||
$sql = 'SELECT d.*, r.rubric_title, r.rubric_alias,(' . $score . ') AS search_relevance'
|
||||
$sql = 'SELECT d.*, r.rubric_title, r.rubric_alias,COALESCE(r.rubric_is_technical,0) rubric_is_technical,(' . $score . ') AS search_relevance'
|
||||
. ' FROM ' . self::documentsTable() . ' d'
|
||||
. ' LEFT JOIN ' . self::rubricsTable() . ' r ON r.Id = d.rubric_id'
|
||||
. $where
|
||||
@@ -190,7 +190,7 @@
|
||||
public static function one($id)
|
||||
{
|
||||
$row = DB::query(
|
||||
'SELECT d.*, r.rubric_title, r.rubric_alias FROM ' . self::documentsTable() . ' d'
|
||||
'SELECT d.*, r.rubric_title, r.rubric_alias,COALESCE(r.rubric_is_technical,0) rubric_is_technical FROM ' . self::documentsTable() . ' d'
|
||||
. ' LEFT JOIN ' . self::rubricsTable() . ' r ON r.Id = d.rubric_id'
|
||||
. ' WHERE d.Id = %i LIMIT 1',
|
||||
(int) $id
|
||||
@@ -222,6 +222,8 @@
|
||||
'guid' => '',
|
||||
'document_status' => 1,
|
||||
'document_in_search' => 1,
|
||||
'document_is_technical' => $rubric && !empty($rubric['rubric_is_technical']) ? 1 : 0,
|
||||
'document_in_sitemap' => 1,
|
||||
'document_author_id' => 1,
|
||||
'document_parent' => 0,
|
||||
'rubric_tmpl_id' => 0,
|
||||
@@ -624,8 +626,9 @@
|
||||
foreach (array(
|
||||
'document_title', 'document_alias', 'document_alias_header', 'document_alias_history',
|
||||
'document_short_alias', 'document_breadcrumb_title', 'document_excerpt', 'document_meta_keywords',
|
||||
'document_meta_description', 'document_meta_robots', 'document_sitemap_freq', 'document_sitemap_pr',
|
||||
'document_tags', 'document_property', 'guid', 'document_status', 'document_in_search',
|
||||
'document_meta_description', 'document_meta_robots', 'document_sitemap_freq', 'document_sitemap_pr',
|
||||
'document_in_sitemap', 'document_tags', 'document_property', 'guid', 'document_status', 'document_in_search',
|
||||
'document_is_technical',
|
||||
'document_parent', 'rubric_tmpl_id', 'document_linked_navi_id', 'document_position',
|
||||
'document_author_id',
|
||||
) as $key) {
|
||||
@@ -658,6 +661,10 @@
|
||||
$data['document_alias_header'] = 301;
|
||||
}
|
||||
|
||||
if ($id > 0 && self::isProtectedDocument($id)) {
|
||||
$data['document_is_technical'] = 0;
|
||||
}
|
||||
|
||||
$data['rubric_id'] = $rubricId;
|
||||
$data['document_changed'] = $now;
|
||||
$data['document_version'] = $existing ? max(1, (int) $existing['document_version']) + 1 : 1;
|
||||
@@ -721,6 +728,23 @@
|
||||
)->getValue());
|
||||
}
|
||||
|
||||
public static function editorState($id)
|
||||
{
|
||||
$row = DB::query('SELECT Id,document_title,document_status,document_deleted,document_changed,document_version FROM '
|
||||
. self::documentsTable() . ' WHERE Id=%i LIMIT 1', (int) $id)->getAssoc();
|
||||
if (!$row) { return null; }
|
||||
$label = $row['document_deleted'] ? 'Удалён' : ($row['document_status'] ? 'Опубликован' : 'Черновик');
|
||||
$label = \App\Common\Language::translateSource($label);
|
||||
return array(
|
||||
'title' => self::decode($row['document_title']),
|
||||
'version' => max(1, (int) $row['document_version']),
|
||||
'state_label' => $label,
|
||||
'state_badge' => $row['document_deleted'] ? 'gray' : ($row['document_status'] ? 'green' : 'amber'),
|
||||
'meta' => 'ID ' . (int) $row['Id'] . ', ' . $label . \App\Common\Language::translateSource(', изменён:')
|
||||
. ' ' . date('d.m.Y H:i', (int) $row['document_changed']),
|
||||
);
|
||||
}
|
||||
|
||||
public static function markChanged($id)
|
||||
{
|
||||
self::touchDocument((int) $id);
|
||||
@@ -944,6 +968,7 @@
|
||||
$source['document_deleted'] = '0';
|
||||
$source['document_count_print'] = 0;
|
||||
$source['document_count_view'] = 0;
|
||||
$source['module_catalog'] = '';
|
||||
$source['document_author_id'] = self::legacyAuthorId($authorId);
|
||||
$source['document_changed'] = time();
|
||||
$source['document_version'] = 1;
|
||||
@@ -1458,13 +1483,15 @@
|
||||
'document_meta_keywords' => trim($get('document_meta_keywords')),
|
||||
'document_meta_description' => trim($get('document_meta_description')),
|
||||
'document_meta_robots' => self::robotsValue($get('document_meta_robots')),
|
||||
'document_sitemap_freq' => self::sitemapFreqValue($get('document_sitemap_freq')),
|
||||
'document_sitemap_pr' => self::sitemapPrValue($get('document_sitemap_pr')),
|
||||
'document_sitemap_freq' => self::sitemapFreqValue($get('document_sitemap_freq')),
|
||||
'document_sitemap_pr' => self::sitemapPrValue($get('document_sitemap_pr')),
|
||||
'document_in_sitemap' => (int) $get('document_in_sitemap') === 1 ? 1 : 0,
|
||||
'document_tags' => trim($get('document_tags')),
|
||||
'document_property' => trim($get('document_property')),
|
||||
'guid' => substr(trim($get('guid')), 0, 100),
|
||||
'document_status' => (int) $get('document_status') === 1 ? '1' : '0',
|
||||
'document_in_search' => (int) $get('document_in_search') === 1 ? '1' : '0',
|
||||
'document_status' => (int) $get('document_status') === 1 ? '1' : '0',
|
||||
'document_in_search' => (int) $get('document_in_search') === 1 ? '1' : '0',
|
||||
'document_is_technical' => (int) $get('document_is_technical') === 1 ? 1 : 0,
|
||||
'document_parent' => (int) $get('document_parent'),
|
||||
'rubric_tmpl_id' => (int) $get('rubric_tmpl_id'),
|
||||
'document_linked_navi_id' => (int) $get('document_linked_navi_id'),
|
||||
@@ -1662,6 +1689,10 @@
|
||||
$row['document_status'] = (int) $row['document_status'];
|
||||
$row['document_deleted'] = (int) $row['document_deleted'];
|
||||
$row['document_in_search'] = (int) $row['document_in_search'];
|
||||
$row['document_is_technical'] = isset($row['document_is_technical']) ? (int) $row['document_is_technical'] : 0;
|
||||
$row['document_in_sitemap'] = isset($row['document_in_sitemap']) ? (int) $row['document_in_sitemap'] : 1;
|
||||
$row['rubric_is_technical'] = isset($row['rubric_is_technical']) ? (int) $row['rubric_is_technical'] : 0;
|
||||
$row['is_technical_effective'] = $row['document_is_technical'] || $row['rubric_is_technical'];
|
||||
$row['document_published'] = (int) $row['document_published'];
|
||||
$row['document_expire'] = (int) $row['document_expire'];
|
||||
$row['document_changed'] = (int) $row['document_changed'];
|
||||
@@ -1730,6 +1761,9 @@
|
||||
DB::Insert(self::docFieldsTable(), array(
|
||||
'rubric_field_id' => (int) $field['Id'],
|
||||
'document_id' => (int) $documentId,
|
||||
'field_value' => '',
|
||||
'field_number_value' => 0,
|
||||
'document_in_search' => '1',
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1774,7 +1808,7 @@
|
||||
'editor' => $editor,
|
||||
'editor_kind' => $kind,
|
||||
'parsed' => $type === 'youtube' ? $parsed : self::viewValue($kind, $parsed, $raw),
|
||||
'options' => self::fieldOptions($row['rubric_field_default'], $type, $settings),
|
||||
'options' => self::fieldOptions($row['rubric_field_default'], $type, $settings, $raw),
|
||||
'media_upload_dir' => $isDocumentMedia ? self::mediaUploadDir($row, $documentId, $mediaDraftToken) : '',
|
||||
'media_target_dir' => $mediaTargetDir,
|
||||
'media_picker_dir' => $isDocumentMedia && (int) $documentId > 0 ? $mediaTargetDir : '/uploads',
|
||||
@@ -2426,18 +2460,33 @@
|
||||
return '';
|
||||
}
|
||||
|
||||
protected static function fieldOptions($default, $type = '', array $settings = array())
|
||||
protected static function fieldOptions($default, $type = '', array $settings = array(), $value = '')
|
||||
{
|
||||
$default = (string) $default;
|
||||
$type = (string) $type;
|
||||
if (isset($settings['option_source']) && $settings['option_source'] === 'directory') {
|
||||
$plugin = FieldRegistry::get($type);
|
||||
if ($plugin && is_callable(array($plugin, 'optionMap'))) {
|
||||
$context = new FieldContext($value, array('rubric_field_type' => $type,
|
||||
'rubric_field_default' => $default, 'rubric_field_settings' => json_encode($settings)), 'edit');
|
||||
$out = array();
|
||||
foreach ($plugin->optionMap($context) as $key => $label) {
|
||||
$out[] = array('value' => (string) $key, 'label' => (string) $label);
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($settings['options']) && is_array($settings['options'])) {
|
||||
$out = array();
|
||||
$isList = array_keys($settings['options']) === range(0, count($settings['options']) - 1);
|
||||
foreach ($settings['options'] as $key => $option) {
|
||||
if (is_array($option)) {
|
||||
$value = isset($option['value']) ? (string) $option['value'] : (isset($option['key']) ? (string) $option['key'] : (string) $key);
|
||||
$label = isset($option['label']) ? (string) $option['label'] : (isset($option['title']) ? (string) $option['title'] : $value);
|
||||
} else {
|
||||
$value = is_int($key) ? (string) $option : (string) $key;
|
||||
$value = $isList ? (string) $option : (string) $key;
|
||||
$label = (string) $option;
|
||||
}
|
||||
|
||||
@@ -2711,11 +2760,16 @@
|
||||
|
||||
protected static function clearDocumentCache($documentId)
|
||||
{
|
||||
ContentCacheInvalidator::document($documentId, false);
|
||||
DB::afterCommit(function () use ($documentId) { ContentCacheInvalidator::document($documentId, false); });
|
||||
}
|
||||
|
||||
protected static function buildDocumentSnapshot($documentId)
|
||||
{
|
||||
if (DB::$transaction_in_progress) {
|
||||
DB::afterCommit(function () use ($documentId) { ContentCacheInvalidator::document($documentId, true); });
|
||||
return null;
|
||||
}
|
||||
|
||||
return ContentCacheInvalidator::document($documentId, true);
|
||||
}
|
||||
|
||||
|
||||
@@ -230,6 +230,7 @@
|
||||
'document_parent' => 'Родитель', 'rubric_tmpl_id' => 'Шаблон', 'document_linked_navi_id' => 'Навигация',
|
||||
'document_position' => 'Позиция', 'document_published' => 'Дата публикации', 'document_expire' => 'Дата окончания',
|
||||
'document_author_id' => 'Автор', 'document_sitemap_freq' => 'Sitemap: частота', 'document_sitemap_pr' => 'Sitemap: приоритет',
|
||||
'document_in_sitemap' => 'Sitemap: участие', 'document_is_technical' => 'Служебный документ',
|
||||
);
|
||||
$out = array();
|
||||
foreach ($document as $key => $value) {
|
||||
@@ -238,8 +239,12 @@
|
||||
$value = (int) $value > 0 ? date('d.m.Y H:i:s', (int) $value) : 'не задано';
|
||||
} elseif ($key === 'document_status') {
|
||||
$value = (int) $value === 1 ? 'Опубликован' : 'Черновик';
|
||||
} elseif ($key === 'document_in_search') {
|
||||
$value = (int) $value === 1 ? 'В поиске' : 'Скрыт';
|
||||
} elseif ($key === 'document_in_search') {
|
||||
$value = (int) $value === 1 ? 'В поиске' : 'Скрыт';
|
||||
} elseif ($key === 'document_in_sitemap') {
|
||||
$value = (int) $value === 1 ? 'Добавляется' : 'Не добавляется';
|
||||
} elseif ($key === 'document_is_technical') {
|
||||
$value = (int) $value === 1 ? 'Служебный' : 'Обычный';
|
||||
}
|
||||
|
||||
$out[] = array('key' => $key, 'title' => $labels[$key], 'value' => (string) $value, 'value_preview' => self::shorten((string) $value, 420));
|
||||
|
||||
@@ -1243,6 +1243,11 @@
|
||||
.documents-bulk-controls .field {
|
||||
min-width: 0;
|
||||
}
|
||||
.documents-bulk-progress-actions [hidden],
|
||||
.documents-bulk-controls .field[hidden],
|
||||
[data-bulk-technical-help][hidden] {
|
||||
display: none;
|
||||
}
|
||||
.documents-bulk-search,
|
||||
.documents-bulk-value {
|
||||
grid-column: span 2;
|
||||
@@ -1270,6 +1275,23 @@
|
||||
margin-top: 1px;
|
||||
font-size: 16px;
|
||||
}
|
||||
.documents-bulk-technical-help {
|
||||
margin: 0 16px 16px;
|
||||
}
|
||||
.documents-bulk-technical-help b,
|
||||
.documents-bulk-technical-help span {
|
||||
display: block;
|
||||
}
|
||||
.documents-bulk-technical-help span {
|
||||
margin-top: 2px;
|
||||
}
|
||||
.documents-technical-alert b,
|
||||
.documents-technical-alert span {
|
||||
display: block;
|
||||
}
|
||||
.documents-technical-alert span {
|
||||
margin-top: 2px;
|
||||
}
|
||||
.documents-bulk-step-footer,
|
||||
.documents-bulk-run {
|
||||
display: flex;
|
||||
@@ -1316,6 +1338,15 @@
|
||||
color: var(--text-muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
.documents-bulk-html-preview {
|
||||
display: block;
|
||||
max-height: 140px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.documents-bulk-value-cell {
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
@@ -2654,22 +2685,25 @@
|
||||
}
|
||||
.documents-value-row {
|
||||
display: grid;
|
||||
grid-template-columns: 34px minmax(0, 1fr) 34px;
|
||||
grid-template-columns: 106px minmax(0, 1fr) 34px;
|
||||
gap: 10px;
|
||||
align-items: start;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
padding: 12px;
|
||||
border-radius: var(--radius-lg);
|
||||
background: var(--bg-soft);
|
||||
box-shadow: inset 0 0 0 1px var(--border-default);
|
||||
}
|
||||
.documents-value-row-tools,
|
||||
.documents-value-row-tools {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 34px);
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
.documents-value-row-fields {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.documents-value-row-fields {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.documents-value-row-list_single .documents-value-row-fields {
|
||||
@@ -2687,6 +2721,22 @@
|
||||
}
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.documents-value-row {
|
||||
grid-template-columns: minmax(0, 1fr) 34px;
|
||||
}
|
||||
.documents-value-row-tools {
|
||||
grid-column: 1;
|
||||
grid-row: 2;
|
||||
justify-content: start;
|
||||
}
|
||||
.documents-value-row-fields {
|
||||
grid-column: 1 / -1;
|
||||
grid-row: 1;
|
||||
}
|
||||
.documents-value-remove {
|
||||
grid-column: 2;
|
||||
grid-row: 2;
|
||||
}
|
||||
.documents-value-row-packages .documents-value-row-fields {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
@@ -1289,7 +1289,7 @@
|
||||
if (host) { allowed[String(host.getAttribute('data-rubric-field-id'))] = true; }
|
||||
});
|
||||
document.querySelectorAll('.ax-document-field[data-rubric-field-id]').forEach(function (field) {
|
||||
var hide = (limited || tokens.length > 0) && !allowed[String(field.getAttribute('data-rubric-field-id'))];
|
||||
var hide = limited && !allowed[String(field.getAttribute('data-rubric-field-id'))];
|
||||
field.classList.toggle('is-catalog-hidden', hide);
|
||||
});
|
||||
var empty = catalog.querySelector('[data-document-catalog-empty]');
|
||||
@@ -1377,9 +1377,11 @@
|
||||
});
|
||||
},
|
||||
|
||||
submit: function (stay) {
|
||||
submit: function (stay, reviewed) {
|
||||
if (!this.form || this.submitting) { return; }
|
||||
var self = this;
|
||||
if (!reviewed && Adminx.RichEditor && Adminx.RichEditor.reviewBeforeSave
|
||||
&& Adminx.RichEditor.reviewBeforeSave(this.form, function () { self.submit(stay, true); })) { return; }
|
||||
var id = parseInt(this.field('id').value, 10) || 0;
|
||||
this.clearErrors();
|
||||
this.syncEditors();
|
||||
@@ -1426,6 +1428,7 @@
|
||||
self.refreshMediaDraft(payload.data.media_draft_token, payload.data.id || id);
|
||||
}
|
||||
self.resetMediaReplacements();
|
||||
self.refreshSavedHeading(payload.data && payload.data.editor_state);
|
||||
if (self.form.getAttribute('data-quick-edit') === '1') {
|
||||
self.refreshQuickEditOpener(!stay);
|
||||
return;
|
||||
@@ -1622,7 +1625,10 @@
|
||||
}
|
||||
control.value = saved[Math.min(index, saved.length - 1)] || '';
|
||||
if (control._adminxCodeMirror) { control._adminxCodeMirror.setValue(control.value); }
|
||||
if (control._adminxTiptap) { control._adminxTiptap.commands.setContent(control.value || '<p></p>'); }
|
||||
if (control._adminxTiptap) {
|
||||
if (Adminx.RichEditor && Adminx.RichEditor.replaceHtml) { Adminx.RichEditor.replaceHtml(control, control.value); }
|
||||
else { control._adminxTiptap.commands.setContent(control.value || '<p></p>'); }
|
||||
}
|
||||
});
|
||||
});
|
||||
this.form.querySelectorAll('[data-document-term-input]').forEach(function (field) {
|
||||
@@ -1677,14 +1683,22 @@
|
||||
if (note) { note.remove(); }
|
||||
var factId = document.querySelector('[data-document-fact-id]');
|
||||
if (factId) { factId.textContent = String(id); }
|
||||
var titleField = this.field('document_title');
|
||||
},
|
||||
|
||||
refreshSavedHeading: function (state) {
|
||||
if (!state) { return; }
|
||||
var heading = document.querySelector('[data-document-edit-heading]');
|
||||
var title = titleField ? titleField.value.trim() : '';
|
||||
if (heading && title) { heading.textContent = title; }
|
||||
var status = this.field('document_status');
|
||||
var meta = document.querySelector('[data-document-edit-meta]');
|
||||
if (meta) { meta.textContent = 'ID ' + id + ', ' + (status && status.value === '1' ? 'опубликован' : 'черновик') + ', сохранён только что'; }
|
||||
if (title) { document.title = title + ' · AVE.cms'; }
|
||||
if (heading) { heading.textContent = state.title; }
|
||||
if (meta) { meta.textContent = state.meta; }
|
||||
document.querySelectorAll('[data-document-state-badge]').forEach(function (badge) {
|
||||
badge.classList.remove('badge-blue', 'badge-green', 'badge-amber', 'badge-gray');
|
||||
if (['blue', 'green', 'amber', 'gray'].indexOf(state.state_badge) !== -1) {
|
||||
badge.classList.add('badge-' + state.state_badge);
|
||||
}
|
||||
badge.textContent = state.state_label;
|
||||
});
|
||||
document.title = state.title + ' · AVE.cms';
|
||||
},
|
||||
|
||||
setSaving: function (saving) {
|
||||
@@ -3669,8 +3683,12 @@
|
||||
var help = root.querySelector('[data-bulk-target-help]');
|
||||
if (!help || !target) { return; }
|
||||
var selected = target.options[target.selectedIndex];
|
||||
var message = selected ? String(selected.getAttribute('data-help') || '') : '';
|
||||
if (selected && selected.value === 'document_title' && scope && scope.value === 'products') {
|
||||
var editsField = operation && ['fill', 'set', 'clear', 'replace'].indexOf(operation.value) !== -1;
|
||||
var message = editsField && selected ? String(selected.getAttribute('data-help') || '') : '';
|
||||
if (operation && operation.value === 'strip_description_styles') {
|
||||
message = Adminx.tr('Только поле с ролью «Описание товара». Будут удалены атрибуты style, включая отступы, цвета и размеры текста. Другие поля, классы, заголовки и блоки <style> не изменяются. HTML будет нормализован при разборе.');
|
||||
}
|
||||
if (editsField && selected && selected.value === 'document_title' && scope && scope.value === 'products') {
|
||||
message = 'Это заголовок документа в панели. Название товара на сайте обычно берётся из поля рубрики, помеченного «витрина: название товара на сайте».';
|
||||
}
|
||||
var text = help.querySelector('span');
|
||||
@@ -3701,11 +3719,20 @@
|
||||
|
||||
function updateOperation() {
|
||||
var value = operation ? operation.value : '';
|
||||
if (scope) {
|
||||
Array.prototype.forEach.call(scope.options || [], function (option) {
|
||||
option.disabled = value === 'strip_description_styles' && option.value !== 'products';
|
||||
});
|
||||
if (value === 'strip_description_styles') { scope.value = 'products'; }
|
||||
}
|
||||
var editsField = ['fill', 'set', 'clear', 'replace'].indexOf(value) !== -1;
|
||||
setVisibility('[data-bulk-target-wrap]', editsField);
|
||||
setVisibility('[data-bulk-search-wrap]', value === 'replace');
|
||||
setVisibility('[data-bulk-value-wrap]', value === 'fill' || value === 'set' || value === 'replace');
|
||||
setVisibility('[data-bulk-rubric-target-wrap]', value === 'move');
|
||||
setVisibility('[data-bulk-value-wrap]', value === 'fill' || value === 'set' || value === 'replace');
|
||||
setVisibility('[data-bulk-rubric-target-wrap]', value === 'move');
|
||||
setVisibility('[data-bulk-sitemap-frequency-wrap]', value === 'sitemap_frequency');
|
||||
setVisibility('[data-bulk-sitemap-priority-wrap]', value === 'sitemap_priority');
|
||||
setVisibility('[data-bulk-technical-help]', value === 'technical' || value === 'public');
|
||||
updateTargetHelp();
|
||||
}
|
||||
|
||||
@@ -3753,6 +3780,17 @@
|
||||
token = plan.token || '';
|
||||
var rows = root.querySelector('[data-bulk-preview-rows]');
|
||||
rows.replaceChildren();
|
||||
var htmlPreview = plan.operation && plan.operation.type === 'strip_description_styles';
|
||||
function valueCell(value) {
|
||||
var td = cell(htmlPreview ? '' : value, 'documents-bulk-value-cell');
|
||||
if (htmlPreview) {
|
||||
var code = document.createElement('code');
|
||||
code.className = 'documents-bulk-html-preview';
|
||||
code.textContent = value || '';
|
||||
td.appendChild(code);
|
||||
}
|
||||
return td;
|
||||
}
|
||||
(plan.sample || []).forEach(function (item) {
|
||||
var tr = document.createElement('tr');
|
||||
var identity = document.createElement('td');
|
||||
@@ -3764,10 +3802,15 @@
|
||||
identity.appendChild(meta);
|
||||
tr.appendChild(identity);
|
||||
tr.appendChild(cell(item.rubric));
|
||||
tr.appendChild(cell(item.before, 'documents-bulk-value-cell'));
|
||||
tr.appendChild(cell(item.after, 'documents-bulk-value-cell'));
|
||||
tr.appendChild(valueCell(item.before));
|
||||
tr.appendChild(valueCell(item.after));
|
||||
var result = cell(item.changed ? 'Изменится' : (item.note || 'Без изменений'));
|
||||
result.className = item.changed ? 'documents-bulk-result is-changed' : 'documents-bulk-result is-skipped';
|
||||
if (item.changed && item.note) {
|
||||
var note = document.createElement('small');
|
||||
note.textContent = item.note;
|
||||
result.appendChild(note);
|
||||
}
|
||||
tr.appendChild(result);
|
||||
rows.appendChild(tr);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="documents_bulk_strip_description_styles">Remove styles from product descriptions</phrase>
|
||||
<phrase data="documents_bulk_description_styles_help">Only the field assigned to the product description role. Removes style attributes, including spacing, colors and font sizes. Other fields, classes, headings and <style> elements are unchanged. HTML is normalized during parsing.</phrase>
|
||||
<phrase data="documents_bulk_move_warning">Only fields with matching aliases and types are transferred. Values of other fields will not be retained in the destination rubric.</phrase>
|
||||
<phrase data="documents_bulk_title">Bulk editor</phrase>
|
||||
<phrase data="documents_bulk_intro">Checks changes before starting and processes documents in small batches.</phrase>
|
||||
<phrase data="documents_bulk_notice_title">Review first, then apply</phrase>
|
||||
|
||||
@@ -1,302 +1,48 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="auto_003cc12783448df3">x</phrase>
|
||||
<phrase data="auto_0156bf1b8aac8565">Add more...</phrase>
|
||||
<phrase data="auto_02b4ebb5dc50bca5">The address of the document will be written into the link field.</phrase>
|
||||
<phrase data="auto_02fdd4b8923613d6">Up to 10 characters, optional.</phrase>
|
||||
<phrase data="auto_04c0389bc0db2353">Token copied</phrase>
|
||||
<phrase data="auto_080887ebc7bb5402"><button class="btn btn-ghost btn-icon btn-sm documents-media-remove" type="button" data-document-media-remove data-tooltip="Delete" aria-label="Delete"><i class="ti ti-trash"></i></button></phrase>
|
||||
<phrase data="auto_0957de938411c15b">field</phrase>
|
||||
<phrase data="auto_0af969e08c220502">Clear all field lines?</phrase>
|
||||
<phrase data="auto_0db49b55557f2bde">Parameter</phrase>
|
||||
<phrase data="auto_0e7fbe3404b67fe3">Rebuild JSON snapshots?</phrase>
|
||||
<phrase data="auto_0f9ccee053fe3b6b">New</phrase>
|
||||
<phrase data="auto_0ff730d95f9c5bc3">click to select</phrase>
|
||||
<phrase data="auto_122f4893d3d0d802">Failed to check alias</phrase>
|
||||
<phrase data="auto_1291e1971ba28ee6">API token created</phrase>
|
||||
<phrase data="auto_12bfabff3d7dc01c">Add a keyword</phrase>
|
||||
<phrase data="auto_18337ef195f7d88d"><div class="modal-body"><div class="input-wrap documents-relation-search"><i class="ti ti-search"></i><input class="input" type="search" placeholder="ID, title or alias" data-relation-search></div><div class="documents-picker-status" data-relation-status>Loading...</div><div class="documents-relation-list" data-relation-list></div></div></phrase>
|
||||
<phrase data="auto_1894f01f2cfa4702">JSON snapshot</phrase>
|
||||
<phrase data="auto_1a7725e697463fd8">to</phrase>
|
||||
<phrase data="auto_1af72c14888c4574">Creation preset</phrase>
|
||||
<phrase data="auto_1bc16af35fa47103">uh</phrase>
|
||||
<phrase data="auto_1d00a5603a94c17d">Teaser ID/link</phrase>
|
||||
<phrase data="auto_1d402bc8ffda29cd">Internal server error. Please refresh the page and try again.</phrase>
|
||||
<phrase data="auto_1f864100c5c97f02"><button class="btn btn-ghost btn-icon btn-sm" type="button" data-document-media-down data-tooltip="Below" aria-label="Below"><i class="ti ti-arrow-down"></i></button></phrase>
|
||||
<phrase data="auto_22dc89ab84f07324">"><button class="btn btn-secondary btn-icon btn-sm" type="button" data-document-media-pick data-tooltip="Select file" aria-label="Select file"><i class="ti ti-</phrase>
|
||||
<phrase data="auto_230b5877294e9726">ts</phrase>
|
||||
<phrase data="auto_23289c89f8c038a0">The document ID will be written in the field.</phrase>
|
||||
<phrase data="auto_242f64ddfe84899b">after saving</phrase>
|
||||
<phrase data="auto_25a9845975119103">Creation preset saved</phrase>
|
||||
<phrase data="auto_25dc101484dbd55c">Failed to load list</phrase>
|
||||
<phrase data="auto_285cc4001478d568">h</phrase>
|
||||
<phrase data="auto_28c993e4935524d8">h</phrase>
|
||||
<phrase data="auto_28fb6167ec0a79fe"><section class="documents-revision-system"><div class="documents-revision-subhead"><i class="ti ti-settings"></i><b>Basic settings</b><span></phrase>
|
||||
<phrase data="auto_292688e9915e161b">[link]" data-media-key="link" value="" placeholder="Link or document" data-document-media-url data-document-picker-type="all"></phrase>
|
||||
<phrase data="auto_29f3b29df0d0e54f">Restore</phrase>
|
||||
<phrase data="auto_2a9790fd6fab2922"><button class="btn btn-secondary btn-icon btn-sm" type="button" data-document-media-doc-pick data-tooltip="Select document" aria-label="Select document"><i class="ti ti-file-search"></i></button></div></phrase>
|
||||
<phrase data="auto_2ba58b00b4c52021"></span><label class="documents-revision-group-check"><input type="checkbox" data-document-revision-group="field" checked><span>All</span></label></div></phrase>
|
||||
<phrase data="auto_2c501dc73177148a">ID, name or alias</phrase>
|
||||
<phrase data="auto_2e31dae95f35e3b8">Select file</phrase>
|
||||
<phrase data="auto_2ec20105a2757791">Column 3</phrase>
|
||||
<phrase data="auto_2f1256a9610f7d64">Redirect saved</phrase>
|
||||
<phrase data="auto_2ff1fe42207df255">The secret is ready to be copied.</phrase>
|
||||
<phrase data="auto_301361625f901825">The server returned an incorrect response.</phrase>
|
||||
<phrase data="auto_30278b05221dd957">Refresh page</phrase>
|
||||
<phrase data="auto_32b74a3c47908c1e">Untitled</phrase>
|
||||
<phrase data="auto_33392e5848b4a8eb">JSON snapshots reassembled:</phrase>
|
||||
<phrase data="auto_336d12a4f96485a3"><button class="btn btn-ghost btn-icon btn-sm" type="button" data-document-media-up data-tooltip="Above" aria-label="Above"><i class="ti ti-arrow-up"></i></button></phrase>
|
||||
<phrase data="auto_359282f9ef75e654">Document ID</phrase>
|
||||
<phrase data="auto_35de32df9d942d9a">Note added</phrase>
|
||||
<phrase data="auto_3697bef0b3fc93f5">new</phrase>
|
||||
<phrase data="auto_3812a04b189ec1fd">new</phrase>
|
||||
<phrase data="auto_39704f311a86cd23">Draft</phrase>
|
||||
<phrase data="auto_3de49828e86a4016">Title</phrase>
|
||||
<phrase data="auto_3e096d0063299173">Revision deleted</phrase>
|
||||
<phrase data="auto_3e25fbc59741a10a">Document title</phrase>
|
||||
<phrase data="auto_3e670a1ec591883c">Files uploaded</phrase>
|
||||
<phrase data="auto_3eb77d3c13c51f92">Select revision</phrase>
|
||||
<phrase data="auto_3f039532d65bb5e3">Rebuild JSON</phrase>
|
||||
<phrase data="auto_4044fbc87708b9ad">Clear daily statistics?</phrase>
|
||||
<phrase data="auto_40785832c27c3a51">Column 1</phrase>
|
||||
<phrase data="auto_42ba924b3732dc07">fields</phrase>
|
||||
<phrase data="auto_433e4b40a403cdb0">th</phrase>
|
||||
<phrase data="auto_447d642f14fb2c8c">There are no matching files in the folder</phrase>
|
||||
<phrase data="auto_46551a5e6e43e854">Statistics cleared</phrase>
|
||||
<phrase data="auto_48be85b47e187f3c">not created yet</phrase>
|
||||
<phrase data="auto_4a05d8619dedc462">Copy</phrase>
|
||||
<phrase data="auto_4b4c88ed13b23b15">Redirect removed</phrase>
|
||||
<phrase data="auto_4d60d98f499d1580">Audits</phrase>
|
||||
<phrase data="auto_4f566fb5e3df4276">I</phrase>
|
||||
<phrase data="auto_516cbe2af24391af">l</phrase>
|
||||
<phrase data="auto_51b4eac98af84251">a</phrase>
|
||||
<phrase data="auto_51f784cde1916288">b</phrase>
|
||||
<phrase data="auto_522e27d7402089bc">Document saved</phrase>
|
||||
<phrase data="auto_53e908b396e3a6b3"><span class="badge badge-gray">not created</span></phrase>
|
||||
<phrase data="auto_54a8375d14dfdab5">Failed to read folder</phrase>
|
||||
<phrase data="auto_56ac0cff0f4a358f">Note deleted</phrase>
|
||||
<phrase data="auto_576895a59897535b">File not selected</phrase>
|
||||
<phrase data="auto_577021b5ac1fd915">f</phrase>
|
||||
<phrase data="auto_57afad1302f9645e">o</phrase>
|
||||
<phrase data="auto_588c8feeb973dcb1"><div><dt>File</dt><dd class="mono"></phrase>
|
||||
<phrase data="auto_59ddef8a55503c83">kg</phrase>
|
||||
<phrase data="auto_5a3b4bcf55400711">r</phrase>
|
||||
<phrase data="auto_5bd0d9fe0580526f">. The window must be left open until completion.</phrase>
|
||||
<phrase data="auto_5c019fa5d03ca5cf">in the section</phrase>
|
||||
<phrase data="auto_5e6c96299a2f11e9">s</phrase>
|
||||
<phrase data="auto_5e6d6b07b27b7a7c">All view_count lines will be removed. General document counters will remain unchanged.</phrase>
|
||||
<phrase data="auto_5f9eaa37c4e2ccff"><button class="btn btn-secondary btn-icon btn-sm" type="button" data-document-media-pick data-tooltip="Select file" aria-label="Select file"><i class="ti ti-paperclip"></i></button></phrase>
|
||||
<phrase data="auto_600363a73de5f3a5">Rebuild</phrase>
|
||||
<phrase data="auto_60512114c18fd5ed"><span class="badge badge-amber">needs reassembly</span></phrase>
|
||||
<phrase data="auto_619742ac4a834c45">doc.</phrase>
|
||||
<phrase data="auto_63b1fa390e91f75c">0 B</phrase>
|
||||
<phrase data="auto_65b7f1673713a00c">d</phrase>
|
||||
<phrase data="auto_66d207b9ebe9e4e3"><div class="documents-term-status is-error"><i class="ti ti-alert-circle"></i><span>Failed to load options</span></div></phrase>
|
||||
<phrase data="auto_6702cc12ca25aff1"><div class="empty-state">There are no revisions yet. The first snapshot will appear after saving the document.</div></phrase>
|
||||
<phrase data="auto_691245657a52bdce"><div><label class="documents-revision-check" aria-label="Restore</phrase>
|
||||
<phrase data="auto_6972375800d3e590">Clear the field?</phrase>
|
||||
<phrase data="auto_698ace159126e252">Column 2</phrase>
|
||||
<phrase data="auto_6b595786e068b5bc">Alias can be left empty</phrase>
|
||||
<phrase data="auto_6baaabf049b42cca">e</phrase>
|
||||
<phrase data="auto_6bee957a1f3ef55d">Length</phrase>
|
||||
<phrase data="auto_6c190c23240564f5">f</phrase>
|
||||
<phrase data="auto_6e408d3c9c3156bf">Delete "</phrase>
|
||||
<phrase data="auto_6e52ded051aa402d">Withdrawn</phrase>
|
||||
<phrase data="auto_6f658622a374b8d6"></p></div><button class="modal-close" type="button" data-relation-close aria-label="Close"><i class="ti ti-x"></i></button></div></phrase>
|
||||
<phrase data="auto_6fe63eee472a5a93"><span class="badge badge-green">relevant</span></phrase>
|
||||
<phrase data="auto_707a724dce1fa0d4">URL copied</phrase>
|
||||
<phrase data="auto_72c618d46424c93a">There are no saved values yet</phrase>
|
||||
<phrase data="auto_736a75710565c2f2">[description]" data-media-key="description" rows="2" placeholder="Description"></textarea></phrase>
|
||||
<phrase data="auto_75285ce97dc1dc97"><button class="btn btn-ghost btn-icon btn-sm" type="button" data-document-value-down data-tooltip="Below" aria-label="Below"><i class="ti ti-arrow-down"></i></button></phrase>
|
||||
<phrase data="auto_781e545c1063d5db">The integration will immediately lose access. It will be impossible to return this token.</phrase>
|
||||
<phrase data="auto_7845e83aad6bffff">Errors found:</phrase>
|
||||
<phrase data="auto_7a4f40b5797415a7">Category template: /</phrase>
|
||||
<phrase data="auto_7a9b21737266b2d1">, errors:</phrase>
|
||||
<phrase data="auto_7bd54e89985213b9">Template</phrase>
|
||||
<phrase data="auto_7c3bb087be98e4e9">Failed to load statistics</phrase>
|
||||
<phrase data="auto_7dcc70f455f9f122">API token revoked</phrase>
|
||||
<phrase data="auto_7f09659cde925652">Find or add a tag</phrase>
|
||||
<phrase data="auto_7f7328fc7d7316b8">n</phrase>
|
||||
<phrase data="auto_80a2c74df6ffb08d">Open the desired folder and confirm your selection. All suitable files from it will be added to the field.</phrase>
|
||||
<phrase data="auto_80c97478d2179d1c"><div><dt>State</dt><dd></phrase>
|
||||
<phrase data="auto_83c8e08533872aff"><div class="empty-state">Loading...</div></phrase>
|
||||
<phrase data="auto_84b96b359e9c61d3">The contents of the snapshot will appear after selecting a revision.</phrase>
|
||||
<phrase data="auto_86ea33aef5e95d4f">Delete</phrase>
|
||||
<phrase data="auto_8922542f90c16aee">Copied</phrase>
|
||||
<phrase data="auto_8bf2ee2944fdd73f">optional</phrase>
|
||||
<phrase data="auto_8c34e8bce7d519b3">The description will appear after filling out the meta description.</phrase>
|
||||
<phrase data="auto_8d333d8b91196c4b">Documents</phrase>
|
||||
<phrase data="auto_8d5d38d878604c11">The document has been restored</phrase>
|
||||
<phrase data="auto_8e8ca8428150664e">g</phrase>
|
||||
<phrase data="auto_8ff9429d66687894">No matches</phrase>
|
||||
<phrase data="auto_919be7c1e27ba64c"><button class="btn btn-ghost btn-icon btn-sm" type="button" data-document-value-up data-tooltip="Above" aria-label="Above"><i class="ti ti-arrow-up"></i></button></phrase>
|
||||
<phrase data="auto_9541be7605dbe971">Permissions for one external integration.</phrase>
|
||||
<phrase data="auto_96664ee8380d446c">The document has changed</phrase>
|
||||
<phrase data="auto_9729bca62f6c558e">Request Error</phrase>
|
||||
<phrase data="auto_97c557fb133f1f95">fields</phrase>
|
||||
<phrase data="auto_98b2073ed1815f28">Clear</phrase>
|
||||
<phrase data="auto_9b16ca539e602189">Revoke</phrase>
|
||||
<phrase data="auto_9bf756bd3124a21d">Changes saved</phrase>
|
||||
<phrase data="auto_9c4c0897f8ec6cf2">[title]" data-media-key="title" value="" placeholder="Image title"></phrase>
|
||||
<phrase data="auto_9c7449bfd16b63a0">Remove</phrase>
|
||||
<phrase data="auto_9caf4a95f812be6a">n</phrase>
|
||||
<phrase data="auto_9d1e4bc060f5da40">Added from folder:</phrase>
|
||||
<phrase data="auto_9d809f884b63cdec">Edit</phrase>
|
||||
<phrase data="auto_9da304d709611b05">Failed to load revisions</phrase>
|
||||
<phrase data="auto_9f0b990967c8a2ad">Meaning</phrase>
|
||||
<phrase data="auto_9f3b3c3b78133faa">Select document</phrase>
|
||||
<phrase data="auto_a15870f87e67e329"><div><dt>Formed by</dt><dd></phrase>
|
||||
<phrase data="auto_a18928c7baf57b4e">Fields only</phrase>
|
||||
<phrase data="auto_a2e9f606da125a72">b</phrase>
|
||||
<phrase data="auto_a37cb7b62a6f1b65">The category does not have a path template: the document alias is used from the root of the site.</phrase>
|
||||
<phrase data="auto_a45e66bc42d77b08">Failed to generate alias</phrase>
|
||||
<phrase data="auto_a59e2c2429fe7a88">and</phrase>
|
||||
<phrase data="auto_a5ecb551ebd318c2">Height,</phrase>
|
||||
<phrase data="auto_a63e1ce2e55b8d0a">No image selected</phrase>
|
||||
<phrase data="auto_a690b9dead4d8d8d"><div><dt>Size</dt><dd></phrase>
|
||||
<phrase data="auto_a7774650638b586d">JSON snapshot rebuilt</phrase>
|
||||
<phrase data="auto_a78e4bb6eb8c9ced">Document revisions</phrase>
|
||||
<phrase data="auto_a8504d513adfb6f5">Heading</phrase>
|
||||
<phrase data="auto_a90ed3357338f605">Loading...</phrase>
|
||||
<phrase data="auto_ab30701c85ebee86">Remove document</phrase>
|
||||
<phrase data="auto_ac3008315dc50b25">Add from this folder</phrase>
|
||||
<phrase data="auto_ae008e22ec3a8627">All lines in this field will be removed from the document after saving.</phrase>
|
||||
<phrase data="auto_af962c31c15d28d8"><button class="btn btn-ghost btn-icon btn-sm documents-drag-handle" type="button" data-doc-drag draggable="true" data-tooltip="Drag" aria-label="Drag"><i class="ti ti-grip-vertical"></i></button></phrase>
|
||||
<phrase data="auto_b0a419827426861b">Preset deleted</phrase>
|
||||
<phrase data="auto_b0d827d33fc8eb3f">Pictures</phrase>
|
||||
<phrase data="auto_b1c30d9335b4ffb7">/ + document alias. The date is taken from the publication.</phrase>
|
||||
<phrase data="auto_b279170b217c1e48"><div><dt>Fields</dt><dd class="mono"></phrase>
|
||||
<phrase data="auto_b2ac54889c1e667e">Batch rebuild stopped</phrase>
|
||||
<phrase data="auto_b36631e2d2874351"><article class="documents-revision-field documents-revision-system-field"><div><label class="documents-revision-check" aria-label="Restore</phrase>
|
||||
<phrase data="auto_b383b6f9be5e7ca2">Failed to get snapshot status</phrase>
|
||||
<phrase data="auto_b40bbca36d2d172e">with</phrase>
|
||||
<phrase data="auto_b5251271237d718b">These files are already in the field</phrase>
|
||||
<phrase data="auto_b92a4704544f84aa">The pictures will be sequentially reassembled to</phrase>
|
||||
<phrase data="auto_b9917824e609b5b3">pictures</phrase>
|
||||
<phrase data="auto_baa96cc9f67a7eb8">yu</phrase>
|
||||
<phrase data="auto_be1aff65661f854c">[name]" data-media-key="name" value="" placeholder="File name"></phrase>
|
||||
<phrase data="auto_be4a59e132257571">Revoke an API token?</phrase>
|
||||
<phrase data="auto_be7ec45710267c5c"><section class="documents-revision-content"><div class="documents-revision-subhead"><i class="ti ti-forms"></i><b>Category fields</b><span></phrase>
|
||||
<phrase data="auto_bea15c7bbd9e167c">e</phrase>
|
||||
<phrase data="auto_beed168817322eeb">from</phrase>
|
||||
<phrase data="auto_bf6379458cca6658">m</phrase>
|
||||
<phrase data="auto_c13875d6c76e5c2e">w</phrase>
|
||||
<phrase data="auto_c2b70c3bb20678a7">Failed to apply filters</phrase>
|
||||
<phrase data="auto_c52083faa73d3829">Field</phrase>
|
||||
<phrase data="auto_c5eb26618a7ede98">Read only</phrase>
|
||||
<phrase data="auto_c7fca87d8dd9b0e6">Click to find document</phrase>
|
||||
<phrase data="auto_c9d8ea6476aa730d">Add "</phrase>
|
||||
<phrase data="auto_cccd51a8c6aa88c1"><div class="documents-term-status"><i class="ti ti-loader-2"></i><span>Looking for matches...</span></div></phrase>
|
||||
<phrase data="auto_ccfe048a5551ed0f">preset</phrase>
|
||||
<phrase data="auto_cdd3b42f2a48df2f">Delete preset</phrase>
|
||||
<phrase data="auto_ceebfda5155965db">Failed to generate short alias</phrase>
|
||||
<phrase data="auto_cf0fc49836b59906">can be left blank</phrase>
|
||||
<phrase data="auto_cf412de9896e972b">Select at least one resolution</phrase>
|
||||
<phrase data="auto_d0888e0521387c25">Width,</phrase>
|
||||
<phrase data="auto_d164037dc0f1bd06">Delete revision</phrase>
|
||||
<phrase data="auto_d2264bee0979ddf6"><div><dt>Status</dt><dd>Loading...</dd></div></phrase>
|
||||
<phrase data="auto_d6951b2c8c477f98">All elements of this field will be removed from the document after saving.</phrase>
|
||||
<phrase data="auto_d6b08d92a7694cd4">Weight,</phrase>
|
||||
<phrase data="auto_d77df87cd6098c73">History of field values</phrase>
|
||||
<phrase data="auto_d7907f4d435df378">Additionally</phrase>
|
||||
<phrase data="auto_d944cde8b15c4d8b">at</phrase>
|
||||
<phrase data="auto_d9c83b31f5cb2376">Failed to check short alias</phrase>
|
||||
<phrase data="auto_da97cf5fe3fc4c42">Checking...</phrase>
|
||||
<phrase data="auto_db4d819570e77e56">draft</phrase>
|
||||
<phrase data="auto_dcedec8acc4af7ca">Assignment document</phrase>
|
||||
<phrase data="auto_dd0ec9a1c7140562">Add files from a folder</phrase>
|
||||
<phrase data="auto_defc150c8003aa92">Revisions deleted</phrase>
|
||||
<phrase data="auto_df5763ef792cf2f4">cm</phrase>
|
||||
<phrase data="auto_e01aed78c667a5aa"><button class="btn btn-ghost btn-icon btn-sm documents-value-remove" type="button" data-document-value-remove data-tooltip="Delete" aria-label="Delete"><i class="ti ti-trash"></i></button></phrase>
|
||||
<phrase data="auto_e4cedbc81a3c0d4e">ъ</phrase>
|
||||
<phrase data="auto_e576260a6a03f359">t</phrase>
|
||||
<phrase data="auto_e76f1ce35ab97dfb"></span><label class="documents-revision-group-check"><input type="checkbox" data-document-revision-group="document" checked><span>All</span></label></div></phrase>
|
||||
<phrase data="auto_e83e7fbf2312ab9e">The document has already been changed. Refresh the page.</phrase>
|
||||
<phrase data="auto_e94209605c9c0a4e"><button class="documents-media-thumb" type="button" data-document-media-pick aria-label="Select file"><span><i class="ti ti-</phrase>
|
||||
<phrase data="auto_ec6be72560e6078a">The story is still empty</phrase>
|
||||
<phrase data="auto_eeb60e75b96656e7">Incorrect answer</phrase>
|
||||
<phrase data="auto_f0b532724126bbe8">Clear all field elements?</phrase>
|
||||
<phrase data="auto_f26e5c0c72082089">Find or add a keyword</phrase>
|
||||
<phrase data="auto_f3d123e46297531d">in</phrase>
|
||||
<phrase data="auto_f42c85cd57ba4aa0">Stay</phrase>
|
||||
<phrase data="auto_f6069600bcb07eea"><div class="modal-footer"><div class="mf-left documents-picker-count" data-relation-count></div><button class="btn btn-ghost" type="button" data-relation-close>Close</button></div></phrase>
|
||||
<phrase data="auto_f61de80bf0ca15a4">No document selected</phrase>
|
||||
<phrase data="auto_f7286439b109e428">New redirect</phrase>
|
||||
<phrase data="auto_f7806fce80e51b40">Old URL</phrase>
|
||||
<phrase data="auto_f914c65278294e4a"><div class="modal-header"><span class="dialog-icon info"><i class="ti ti-file-search"></i></span><div style="flex:1"><h3>Select document</h3><p class="text-secondary" style="margin-top:4px"></phrase>
|
||||
<phrase data="auto_fa9f0524f3a0531e">Add a tag</phrase>
|
||||
<phrase data="auto_fc8b3939cc9dc467">The path will be written in the document field.</phrase>
|
||||
<phrase data="auto_fda74d41e3311f87">A newer version is already saved on the server. Refresh the page, check the changes, and save the document again.</phrase>
|
||||
<phrase data="auto_ffec67789fb1fcdc">sch</phrase>
|
||||
<phrase data="documents_bulk_action">Action</phrase>
|
||||
<phrase data="documents_bulk_action_fallback">Action</phrase>
|
||||
<phrase data="documents_bulk_documents_suffix"> documents.</phrase>
|
||||
<phrase data="documents_bulk_errors">errors</phrase>
|
||||
<phrase data="documents_bulk_processed">processed</phrase>
|
||||
<phrase data="documents_bulk_unchanged">unchanged</phrase>
|
||||
<phrase data="runtime_05d4ae78b6f1bfee">n</phrase>
|
||||
<phrase data="runtime_0918b4ba92684eaa">Title</phrase>
|
||||
<phrase data="runtime_0940401102b8a3fe">t</phrase>
|
||||
<phrase data="runtime_11cef8141437f8a6">ъ</phrase>
|
||||
<phrase data="runtime_15f2ccabeb425c29">th</phrase>
|
||||
<phrase data="runtime_1cc10a3947f7c245">d</phrase>
|
||||
<phrase data="runtime_1d51ebe0fc45e38e">Fields only</phrase>
|
||||
<phrase data="runtime_259f56cb715ba3a3">e</phrase>
|
||||
<phrase data="runtime_3051067c6324c63f">h</phrase>
|
||||
<phrase data="runtime_30fbc377ae9122ed">e</phrase>
|
||||
<phrase data="runtime_3164696756227147">Note added</phrase>
|
||||
<phrase data="runtime_34c6fbb62da8ce5c">n</phrase>
|
||||
<phrase data="runtime_37d43a57a463add5">yu</phrase>
|
||||
<phrase data="runtime_40831c5d98a57dfc">h</phrase>
|
||||
<phrase data="runtime_446cdc8e3c0d7efc">s</phrase>
|
||||
<phrase data="runtime_46b0d3855548054a">JSON snapshot rebuilt</phrase>
|
||||
<phrase data="runtime_4f60bd4e24e7dc7f">w</phrase>
|
||||
<phrase data="runtime_50338c005c41fb4e">o</phrase>
|
||||
<phrase data="runtime_5225a95b111d47bf">to</phrase>
|
||||
<phrase data="runtime_53b10ee4405f56d6">not created yet</phrase>
|
||||
<phrase data="runtime_557f4cd2c6d3c150">cm</phrase>
|
||||
<phrase data="runtime_61095f9d62dfe291">The document has been restored</phrase>
|
||||
<phrase data="runtime_6228f1454b196ffd">API token revoked</phrase>
|
||||
<phrase data="runtime_65fd24f1cb37fec4">Draft</phrase>
|
||||
<phrase data="runtime_72a81659de042887">Revisions deleted</phrase>
|
||||
<phrase data="runtime_734dbc2b54ab6c95">r</phrase>
|
||||
<phrase data="runtime_754309a41e0df98a">f</phrase>
|
||||
<phrase data="runtime_7592b7ec4eba966a">ts</phrase>
|
||||
<phrase data="runtime_7b0ff8a2e5fdd66d">m</phrase>
|
||||
<phrase data="runtime_823c4eb3e895adc9">a</phrase>
|
||||
<phrase data="runtime_85011fce4419ee63">Field #</phrase>
|
||||
<phrase data="runtime_894f97c52af9e5ac">Note deleted</phrase>
|
||||
<phrase data="runtime_9aa032336a8e122c">b</phrase>
|
||||
<phrase data="runtime_9b21f5cf014c9efb">I</phrase>
|
||||
<phrase data="runtime_9b6276c9a4ac5507">Document saved</phrase>
|
||||
<phrase data="runtime_a1f5d39a12e8f6be">with</phrase>
|
||||
<phrase data="runtime_ab1f4be7e5d6fd8b">g</phrase>
|
||||
<phrase data="runtime_ae51ade91d2b85b7">Revision deleted</phrase>
|
||||
<phrase data="runtime_b8012cb642c887a0">in</phrase>
|
||||
<phrase data="runtime_b95d78565f154f82">b</phrase>
|
||||
<phrase data="runtime_bb69a96efca3303e">x</phrase>
|
||||
<phrase data="runtime_bbb369f210d2969f">sch</phrase>
|
||||
<phrase data="runtime_beee80c256b458da">at</phrase>
|
||||
<phrase data="runtime_bf0d18ef68a8a34e">can be left blank</phrase>
|
||||
<phrase data="runtime_c08fb476eca49399">kg</phrase>
|
||||
<phrase data="runtime_c5412ba2cc2fc45a">Creation preset saved</phrase>
|
||||
<phrase data="runtime_c78364c5d0f27706">B</phrase>
|
||||
<phrase data="runtime_cdd02bd8b5684812">Redirect removed</phrase>
|
||||
<phrase data="runtime_d92fff560eb5495e">l</phrase>
|
||||
<phrase data="runtime_dd48804aa38b03e1">Preset deleted</phrase>
|
||||
<phrase data="runtime_dd591284d827e17f">f</phrase>
|
||||
<phrase data="runtime_e1c88af54b9fced2">Document #</phrase>
|
||||
<phrase data="runtime_e35c8bb151d3530d">Redirect saved</phrase>
|
||||
<phrase data="runtime_e93c3d6287d39cc3">API token created</phrase>
|
||||
<phrase data="runtime_ee71f8405f87d786">uh</phrase>
|
||||
<phrase data="runtime_eead37caf818d0fa">and</phrase>
|
||||
<phrase data="runtime_f4019994d4e75a2a">after saving</phrase>
|
||||
<phrase data="runtime_f9a506077fa0d961">New</phrase>
|
||||
<phrase data="runtime_fff8b34d92dab340">Template</phrase>
|
||||
<phrase data="auto_f8af664b7ab2ef75">Remove all items?</phrase>
|
||||
<phrase data="auto_10403ca9b11a0b49">After saving, the items will be removed from the document. Unused files can be restored from the media trash.</phrase>
|
||||
<phrase data="auto_5ede041b60096d58">Remove the image?</phrase>
|
||||
<phrase data="auto_c5b3cd090f16f479">After saving, the image will be removed from the document. The unused file can be restored from the media trash.</phrase>
|
||||
<phrase data="auto_e26c8664b60bfa9a">Remove the image from the document?</phrase>
|
||||
<phrase data="auto_02e536f7b2d5cec8">The document was saved, but some old files were not moved to the trash.</phrase>
|
||||
</language>
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="documents_bulk_strip_description_styles">Удалить стили из описаний товаров</phrase>
|
||||
<phrase data="documents_bulk_description_styles_help">Только поле с ролью «Описание товара». Будут удалены атрибуты style, включая отступы, цвета и размеры текста. Другие поля, классы, заголовки и блоки <style> не изменяются. HTML будет нормализован при разборе.</phrase>
|
||||
<phrase data="documents_bulk_move_warning">Переносятся только поля с одинаковыми системными именами и типами. Значения остальных полей не сохранятся в новой рубрике.</phrase>
|
||||
<phrase data="documents_bulk_title">Массовый редактор</phrase>
|
||||
<phrase data="documents_bulk_intro">Проверяет изменения до запуска и обрабатывает документы небольшими пакетами.</phrase>
|
||||
<phrase data="documents_bulk_notice_title">Сначала проверка, затем применение</phrase>
|
||||
|
||||
@@ -1,302 +1,48 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="auto_003cc12783448df3">х</phrase>
|
||||
<phrase data="auto_0156bf1b8aac8565">Добавить ещё…</phrase>
|
||||
<phrase data="auto_02b4ebb5dc50bca5">В поле-ссылку будет записан адрес документа.</phrase>
|
||||
<phrase data="auto_02fdd4b8923613d6">До 10 символов, необязательно.</phrase>
|
||||
<phrase data="auto_04c0389bc0db2353">Токен скопирован</phrase>
|
||||
<phrase data="auto_080887ebc7bb5402"><button class="btn btn-ghost btn-icon btn-sm documents-media-remove" type="button" data-document-media-remove data-tooltip="Удалить" aria-label="Удалить"><i class="ti ti-trash"></i></button></phrase>
|
||||
<phrase data="auto_0957de938411c15b">поле</phrase>
|
||||
<phrase data="auto_0af969e08c220502">Очистить все строки поля?</phrase>
|
||||
<phrase data="auto_0db49b55557f2bde">Параметр</phrase>
|
||||
<phrase data="auto_0e7fbe3404b67fe3">Пересобрать JSON-снимки?</phrase>
|
||||
<phrase data="auto_0f9ccee053fe3b6b">Новый</phrase>
|
||||
<phrase data="auto_0ff730d95f9c5bc3">нажмите, чтобы выбрать</phrase>
|
||||
<phrase data="auto_122f4893d3d0d802">Не удалось проверить alias</phrase>
|
||||
<phrase data="auto_1291e1971ba28ee6">API-токен создан</phrase>
|
||||
<phrase data="auto_12bfabff3d7dc01c">Добавить ключевое слово</phrase>
|
||||
<phrase data="auto_18337ef195f7d88d"><div class="modal-body"><div class="input-wrap documents-relation-search"><i class="ti ti-search"></i><input class="input" type="search" placeholder="ID, название или alias" data-relation-search></div><div class="documents-picker-status" data-relation-status>Загрузка...</div><div class="documents-relation-list" data-relation-list></div></div></phrase>
|
||||
<phrase data="auto_1894f01f2cfa4702">JSON-снимок</phrase>
|
||||
<phrase data="auto_1a7725e697463fd8">к</phrase>
|
||||
<phrase data="auto_1af72c14888c4574">Пресет создания</phrase>
|
||||
<phrase data="auto_1bc16af35fa47103">э</phrase>
|
||||
<phrase data="auto_1d00a5603a94c17d">ID тизера / ссылка</phrase>
|
||||
<phrase data="auto_1d402bc8ffda29cd">Внутренняя ошибка сервера. Обновите страницу и повторите попытку.</phrase>
|
||||
<phrase data="auto_1f864100c5c97f02"><button class="btn btn-ghost btn-icon btn-sm" type="button" data-document-media-down data-tooltip="Ниже" aria-label="Ниже"><i class="ti ti-arrow-down"></i></button></phrase>
|
||||
<phrase data="auto_22dc89ab84f07324">"><button class="btn btn-secondary btn-icon btn-sm" type="button" data-document-media-pick data-tooltip="Выбрать файл" aria-label="Выбрать файл"><i class="ti ti-</phrase>
|
||||
<phrase data="auto_230b5877294e9726">ц</phrase>
|
||||
<phrase data="auto_23289c89f8c038a0">В поле будет записан ID документа.</phrase>
|
||||
<phrase data="auto_242f64ddfe84899b">после сохранения</phrase>
|
||||
<phrase data="auto_25a9845975119103">Пресет создания сохранён</phrase>
|
||||
<phrase data="auto_25dc101484dbd55c">Не удалось загрузить список</phrase>
|
||||
<phrase data="auto_285cc4001478d568">ч</phrase>
|
||||
<phrase data="auto_28c993e4935524d8">з</phrase>
|
||||
<phrase data="auto_28fb6167ec0a79fe"><section class="documents-revision-system"><div class="documents-revision-subhead"><i class="ti ti-settings"></i><b>Основные настройки</b><span></phrase>
|
||||
<phrase data="auto_292688e9915e161b">[link]" data-media-key="link" value="" placeholder="Ссылка или документ" data-document-media-url data-document-picker-type="all"></phrase>
|
||||
<phrase data="auto_29f3b29df0d0e54f">Восстановить</phrase>
|
||||
<phrase data="auto_2a9790fd6fab2922"><button class="btn btn-secondary btn-icon btn-sm" type="button" data-document-media-doc-pick data-tooltip="Выбрать документ" aria-label="Выбрать документ"><i class="ti ti-file-search"></i></button></div></phrase>
|
||||
<phrase data="auto_2ba58b00b4c52021"></span><label class="documents-revision-group-check"><input type="checkbox" data-document-revision-group="field" checked><span>Все</span></label></div></phrase>
|
||||
<phrase data="auto_2c501dc73177148a">ID, название или alias</phrase>
|
||||
<phrase data="auto_2e31dae95f35e3b8">Выбрать файл</phrase>
|
||||
<phrase data="auto_2ec20105a2757791">Колонка 3</phrase>
|
||||
<phrase data="auto_2f1256a9610f7d64">Редирект сохранён</phrase>
|
||||
<phrase data="auto_2ff1fe42207df255">Секрет готов к копированию.</phrase>
|
||||
<phrase data="auto_301361625f901825">Сервер вернул некорректный ответ.</phrase>
|
||||
<phrase data="auto_30278b05221dd957">Обновить страницу</phrase>
|
||||
<phrase data="auto_32b74a3c47908c1e">Без названия</phrase>
|
||||
<phrase data="auto_33392e5848b4a8eb">JSON-снимки пересобраны:</phrase>
|
||||
<phrase data="auto_336d12a4f96485a3"><button class="btn btn-ghost btn-icon btn-sm" type="button" data-document-media-up data-tooltip="Выше" aria-label="Выше"><i class="ti ti-arrow-up"></i></button></phrase>
|
||||
<phrase data="auto_359282f9ef75e654">ID документа</phrase>
|
||||
<phrase data="auto_35de32df9d942d9a">Заметка добавлена</phrase>
|
||||
<phrase data="auto_3697bef0b3fc93f5">новый</phrase>
|
||||
<phrase data="auto_3812a04b189ec1fd">новое</phrase>
|
||||
<phrase data="auto_39704f311a86cd23">Черновик</phrase>
|
||||
<phrase data="auto_3de49828e86a4016">Название</phrase>
|
||||
<phrase data="auto_3e096d0063299173">Ревизия удалена</phrase>
|
||||
<phrase data="auto_3e25fbc59741a10a">Заголовок документа</phrase>
|
||||
<phrase data="auto_3e670a1ec591883c">Файлы загружены</phrase>
|
||||
<phrase data="auto_3eb77d3c13c51f92">Выберите ревизию</phrase>
|
||||
<phrase data="auto_3f039532d65bb5e3">Пересобрать JSON</phrase>
|
||||
<phrase data="auto_4044fbc87708b9ad">Очистить подневную статистику?</phrase>
|
||||
<phrase data="auto_40785832c27c3a51">Колонка 1</phrase>
|
||||
<phrase data="auto_42ba924b3732dc07">поля</phrase>
|
||||
<phrase data="auto_433e4b40a403cdb0">й</phrase>
|
||||
<phrase data="auto_447d642f14fb2c8c">В папке нет подходящих файлов</phrase>
|
||||
<phrase data="auto_46551a5e6e43e854">Статистика очищена</phrase>
|
||||
<phrase data="auto_48be85b47e187f3c">ещё не создан</phrase>
|
||||
<phrase data="auto_4a05d8619dedc462">Копировать</phrase>
|
||||
<phrase data="auto_4b4c88ed13b23b15">Редирект удалён</phrase>
|
||||
<phrase data="auto_4d60d98f499d1580">Ревизии</phrase>
|
||||
<phrase data="auto_4f566fb5e3df4276">я</phrase>
|
||||
<phrase data="auto_516cbe2af24391af">л</phrase>
|
||||
<phrase data="auto_51b4eac98af84251">а</phrase>
|
||||
<phrase data="auto_51f784cde1916288">ь</phrase>
|
||||
<phrase data="auto_522e27d7402089bc">Документ сохранён</phrase>
|
||||
<phrase data="auto_53e908b396e3a6b3"><span class="badge badge-gray">не создан</span></phrase>
|
||||
<phrase data="auto_54a8375d14dfdab5">Не удалось прочитать папку</phrase>
|
||||
<phrase data="auto_56ac0cff0f4a358f">Заметка удалена</phrase>
|
||||
<phrase data="auto_576895a59897535b">Файл не выбран</phrase>
|
||||
<phrase data="auto_577021b5ac1fd915">ф</phrase>
|
||||
<phrase data="auto_57afad1302f9645e">о</phrase>
|
||||
<phrase data="auto_588c8feeb973dcb1"><div><dt>Файл</dt><dd class="mono"></phrase>
|
||||
<phrase data="auto_59ddef8a55503c83">кг</phrase>
|
||||
<phrase data="auto_5a3b4bcf55400711">р</phrase>
|
||||
<phrase data="auto_5bd0d9fe0580526f">. Окно нужно оставить открытым до завершения.</phrase>
|
||||
<phrase data="auto_5c019fa5d03ca5cf">в рубрике</phrase>
|
||||
<phrase data="auto_5e6c96299a2f11e9">ы</phrase>
|
||||
<phrase data="auto_5e6d6b07b27b7a7c">Все строки view_count будут удалены. Общие счётчики документов останутся без изменений.</phrase>
|
||||
<phrase data="auto_5f9eaa37c4e2ccff"><button class="btn btn-secondary btn-icon btn-sm" type="button" data-document-media-pick data-tooltip="Выбрать файл" aria-label="Выбрать файл"><i class="ti ti-paperclip"></i></button></phrase>
|
||||
<phrase data="auto_600363a73de5f3a5">Пересобрать</phrase>
|
||||
<phrase data="auto_60512114c18fd5ed"><span class="badge badge-amber">нужна пересборка</span></phrase>
|
||||
<phrase data="auto_619742ac4a834c45">док.</phrase>
|
||||
<phrase data="auto_63b1fa390e91f75c">0 Б</phrase>
|
||||
<phrase data="auto_65b7f1673713a00c">д</phrase>
|
||||
<phrase data="auto_66d207b9ebe9e4e3"><div class="documents-term-status is-error"><i class="ti ti-alert-circle"></i><span>Не удалось загрузить варианты</span></div></phrase>
|
||||
<phrase data="auto_6702cc12ca25aff1"><div class="empty-state">Ревизий пока нет. Первый снимок появится после сохранения документа.</div></phrase>
|
||||
<phrase data="auto_691245657a52bdce"><div><label class="documents-revision-check" aria-label="Восстановить</phrase>
|
||||
<phrase data="auto_6972375800d3e590">Очистить поле?</phrase>
|
||||
<phrase data="auto_698ace159126e252">Колонка 2</phrase>
|
||||
<phrase data="auto_6b595786e068b5bc">Alias можно оставить пустым</phrase>
|
||||
<phrase data="auto_6baaabf049b42cca">ё</phrase>
|
||||
<phrase data="auto_6bee957a1f3ef55d">Длина,</phrase>
|
||||
<phrase data="auto_6c190c23240564f5">ж</phrase>
|
||||
<phrase data="auto_6e408d3c9c3156bf">Удалить «</phrase>
|
||||
<phrase data="auto_6e52ded051aa402d">Отозван</phrase>
|
||||
<phrase data="auto_6f658622a374b8d6"></p></div><button class="modal-close" type="button" data-relation-close aria-label="Закрыть"><i class="ti ti-x"></i></button></div></phrase>
|
||||
<phrase data="auto_6fe63eee472a5a93"><span class="badge badge-green">актуален</span></phrase>
|
||||
<phrase data="auto_707a724dce1fa0d4">URL скопирован</phrase>
|
||||
<phrase data="auto_72c618d46424c93a">Сохранённых значений пока нет</phrase>
|
||||
<phrase data="auto_736a75710565c2f2">[description]" data-media-key="description" rows="2" placeholder="Описание"></textarea></phrase>
|
||||
<phrase data="auto_75285ce97dc1dc97"><button class="btn btn-ghost btn-icon btn-sm" type="button" data-document-value-down data-tooltip="Ниже" aria-label="Ниже"><i class="ti ti-arrow-down"></i></button></phrase>
|
||||
<phrase data="auto_781e545c1063d5db">Интеграция сразу потеряет доступ. Вернуть этот токен будет невозможно.</phrase>
|
||||
<phrase data="auto_7845e83aad6bffff">Найдено ошибок:</phrase>
|
||||
<phrase data="auto_7a4f40b5797415a7">Шаблон рубрики: /</phrase>
|
||||
<phrase data="auto_7a9b21737266b2d1">, ошибок:</phrase>
|
||||
<phrase data="auto_7bd54e89985213b9">Шаблон</phrase>
|
||||
<phrase data="auto_7c3bb087be98e4e9">Не удалось загрузить статистику</phrase>
|
||||
<phrase data="auto_7dcc70f455f9f122">API-токен отозван</phrase>
|
||||
<phrase data="auto_7f09659cde925652">Найти или добавить тег</phrase>
|
||||
<phrase data="auto_7f7328fc7d7316b8">н</phrase>
|
||||
<phrase data="auto_80a2c74df6ffb08d">Откройте нужную папку и подтвердите выбор. В поле добавятся все подходящие файлы из неё.</phrase>
|
||||
<phrase data="auto_80c97478d2179d1c"><div><dt>Состояние</dt><dd></phrase>
|
||||
<phrase data="auto_83c8e08533872aff"><div class="empty-state">Загрузка...</div></phrase>
|
||||
<phrase data="auto_84b96b359e9c61d3">Содержимое снимка появится после выбора ревизии.</phrase>
|
||||
<phrase data="auto_86ea33aef5e95d4f">Удалить</phrase>
|
||||
<phrase data="auto_8922542f90c16aee">Скопировано</phrase>
|
||||
<phrase data="auto_8bf2ee2944fdd73f">необязательно</phrase>
|
||||
<phrase data="auto_8c34e8bce7d519b3">Описание появится после заполнения meta description.</phrase>
|
||||
<phrase data="auto_8d333d8b91196c4b">Документов</phrase>
|
||||
<phrase data="auto_8d5d38d878604c11">Документ восстановлен</phrase>
|
||||
<phrase data="auto_8e8ca8428150664e">г</phrase>
|
||||
<phrase data="auto_8ff9429d66687894">Совпадений нет</phrase>
|
||||
<phrase data="auto_919be7c1e27ba64c"><button class="btn btn-ghost btn-icon btn-sm" type="button" data-document-value-up data-tooltip="Выше" aria-label="Выше"><i class="ti ti-arrow-up"></i></button></phrase>
|
||||
<phrase data="auto_9541be7605dbe971">Права доступа для одной внешней интеграции.</phrase>
|
||||
<phrase data="auto_96664ee8380d446c">Документ изменился</phrase>
|
||||
<phrase data="auto_9729bca62f6c558e">Ошибка запроса</phrase>
|
||||
<phrase data="auto_97c557fb133f1f95">полей</phrase>
|
||||
<phrase data="auto_98b2073ed1815f28">Очистить</phrase>
|
||||
<phrase data="auto_9b16ca539e602189">Отозвать</phrase>
|
||||
<phrase data="auto_9bf756bd3124a21d">Изменения сохранены</phrase>
|
||||
<phrase data="auto_9c4c0897f8ec6cf2">[title]" data-media-key="title" value="" placeholder="Заголовок изображения"></phrase>
|
||||
<phrase data="auto_9c7449bfd16b63a0">Убрать</phrase>
|
||||
<phrase data="auto_9caf4a95f812be6a">п</phrase>
|
||||
<phrase data="auto_9d1e4bc060f5da40">Добавлено из папки:</phrase>
|
||||
<phrase data="auto_9d809f884b63cdec">Изменить</phrase>
|
||||
<phrase data="auto_9da304d709611b05">Не удалось загрузить ревизии</phrase>
|
||||
<phrase data="auto_9f0b990967c8a2ad">Значение</phrase>
|
||||
<phrase data="auto_9f3b3c3b78133faa">Выбрать документ</phrase>
|
||||
<phrase data="auto_a15870f87e67e329"><div><dt>Сформирован</dt><dd></phrase>
|
||||
<phrase data="auto_a18928c7baf57b4e">Только поля</phrase>
|
||||
<phrase data="auto_a2e9f606da125a72">б</phrase>
|
||||
<phrase data="auto_a37cb7b62a6f1b65">У рубрики нет шаблона пути: alias документа используется от корня сайта.</phrase>
|
||||
<phrase data="auto_a45e66bc42d77b08">Не удалось сгенерировать alias</phrase>
|
||||
<phrase data="auto_a59e2c2429fe7a88">и</phrase>
|
||||
<phrase data="auto_a5ecb551ebd318c2">Высота,</phrase>
|
||||
<phrase data="auto_a63e1ce2e55b8d0a">Изображение не выбрано</phrase>
|
||||
<phrase data="auto_a690b9dead4d8d8d"><div><dt>Размер</dt><dd></phrase>
|
||||
<phrase data="auto_a7774650638b586d">JSON-снимок пересобран</phrase>
|
||||
<phrase data="auto_a78e4bb6eb8c9ced">Ревизии документа</phrase>
|
||||
<phrase data="auto_a8504d513adfb6f5">Заголовок</phrase>
|
||||
<phrase data="auto_a90ed3357338f605">Загрузка...</phrase>
|
||||
<phrase data="auto_ab30701c85ebee86">Убрать документ</phrase>
|
||||
<phrase data="auto_ac3008315dc50b25">Добавить из этой папки</phrase>
|
||||
<phrase data="auto_ae008e22ec3a8627">Все строки этого поля будут удалены из документа после сохранения.</phrase>
|
||||
<phrase data="auto_af962c31c15d28d8"><button class="btn btn-ghost btn-icon btn-sm documents-drag-handle" type="button" data-doc-drag draggable="true" data-tooltip="Перетащить" aria-label="Перетащить"><i class="ti ti-grip-vertical"></i></button></phrase>
|
||||
<phrase data="auto_b0a419827426861b">Пресет удалён</phrase>
|
||||
<phrase data="auto_b0d827d33fc8eb3f">Снимки</phrase>
|
||||
<phrase data="auto_b1c30d9335b4ffb7">/ + alias документа. Дата берётся из публикации.</phrase>
|
||||
<phrase data="auto_b279170b217c1e48"><div><dt>Поля</dt><dd class="mono"></phrase>
|
||||
<phrase data="auto_b2ac54889c1e667e">Пакетная пересборка остановлена</phrase>
|
||||
<phrase data="auto_b36631e2d2874351"><article class="documents-revision-field documents-revision-system-field"><div><label class="documents-revision-check" aria-label="Восстановить</phrase>
|
||||
<phrase data="auto_b383b6f9be5e7ca2">Не удалось получить статус снимка</phrase>
|
||||
<phrase data="auto_b40bbca36d2d172e">с</phrase>
|
||||
<phrase data="auto_b5251271237d718b">Эти файлы уже есть в поле</phrase>
|
||||
<phrase data="auto_b92a4704544f84aa">Снимки будут последовательно пересобраны для</phrase>
|
||||
<phrase data="auto_b9917824e609b5b3">снимков</phrase>
|
||||
<phrase data="auto_baa96cc9f67a7eb8">ю</phrase>
|
||||
<phrase data="auto_be1aff65661f854c">[name]" data-media-key="name" value="" placeholder="Название файла"></phrase>
|
||||
<phrase data="auto_be4a59e132257571">Отозвать API-токен?</phrase>
|
||||
<phrase data="auto_be7ec45710267c5c"><section class="documents-revision-content"><div class="documents-revision-subhead"><i class="ti ti-forms"></i><b>Поля рубрики</b><span></phrase>
|
||||
<phrase data="auto_bea15c7bbd9e167c">е</phrase>
|
||||
<phrase data="auto_beed168817322eeb">из</phrase>
|
||||
<phrase data="auto_bf6379458cca6658">м</phrase>
|
||||
<phrase data="auto_c13875d6c76e5c2e">ш</phrase>
|
||||
<phrase data="auto_c2b70c3bb20678a7">Не удалось применить фильтры</phrase>
|
||||
<phrase data="auto_c52083faa73d3829">Поле</phrase>
|
||||
<phrase data="auto_c5eb26618a7ede98">Только чтение</phrase>
|
||||
<phrase data="auto_c7fca87d8dd9b0e6">Нажмите, чтобы найти документ</phrase>
|
||||
<phrase data="auto_c9d8ea6476aa730d">Добавить «</phrase>
|
||||
<phrase data="auto_cccd51a8c6aa88c1"><div class="documents-term-status"><i class="ti ti-loader-2"></i><span>Ищем совпадения…</span></div></phrase>
|
||||
<phrase data="auto_ccfe048a5551ed0f">пресет</phrase>
|
||||
<phrase data="auto_cdd3b42f2a48df2f">Удалить пресет</phrase>
|
||||
<phrase data="auto_ceebfda5155965db">Не удалось сгенерировать короткий алиас</phrase>
|
||||
<phrase data="auto_cf0fc49836b59906">можно оставить пустым</phrase>
|
||||
<phrase data="auto_cf412de9896e972b">Выберите хотя бы одно разрешение</phrase>
|
||||
<phrase data="auto_d0888e0521387c25">Ширина,</phrase>
|
||||
<phrase data="auto_d164037dc0f1bd06">Удалить ревизию</phrase>
|
||||
<phrase data="auto_d2264bee0979ddf6"><div><dt>Состояние</dt><dd>Загрузка...</dd></div></phrase>
|
||||
<phrase data="auto_d6951b2c8c477f98">Все элементы этого поля будут удалены из документа после сохранения.</phrase>
|
||||
<phrase data="auto_d6b08d92a7694cd4">Вес,</phrase>
|
||||
<phrase data="auto_d77df87cd6098c73">История значений полей</phrase>
|
||||
<phrase data="auto_d7907f4d435df378">Дополнительно</phrase>
|
||||
<phrase data="auto_d944cde8b15c4d8b">у</phrase>
|
||||
<phrase data="auto_d9c83b31f5cb2376">Не удалось проверить короткий alias</phrase>
|
||||
<phrase data="auto_da97cf5fe3fc4c42">Проверка...</phrase>
|
||||
<phrase data="auto_db4d819570e77e56">черновик</phrase>
|
||||
<phrase data="auto_dcedec8acc4af7ca">Документ назначения</phrase>
|
||||
<phrase data="auto_dd0ec9a1c7140562">Добавить файлы из папки</phrase>
|
||||
<phrase data="auto_defc150c8003aa92">Ревизии удалены</phrase>
|
||||
<phrase data="auto_df5763ef792cf2f4">см</phrase>
|
||||
<phrase data="auto_e01aed78c667a5aa"><button class="btn btn-ghost btn-icon btn-sm documents-value-remove" type="button" data-document-value-remove data-tooltip="Удалить" aria-label="Удалить"><i class="ti ti-trash"></i></button></phrase>
|
||||
<phrase data="auto_e4cedbc81a3c0d4e">ъ</phrase>
|
||||
<phrase data="auto_e576260a6a03f359">т</phrase>
|
||||
<phrase data="auto_e76f1ce35ab97dfb"></span><label class="documents-revision-group-check"><input type="checkbox" data-document-revision-group="document" checked><span>Все</span></label></div></phrase>
|
||||
<phrase data="auto_e83e7fbf2312ab9e">Документ уже изменён. Обновите страницу.</phrase>
|
||||
<phrase data="auto_e94209605c9c0a4e"><button class="documents-media-thumb" type="button" data-document-media-pick aria-label="Выбрать файл"><span><i class="ti ti-</phrase>
|
||||
<phrase data="auto_ec6be72560e6078a">История пока пустая</phrase>
|
||||
<phrase data="auto_eeb60e75b96656e7">Некорректный ответ</phrase>
|
||||
<phrase data="auto_f0b532724126bbe8">Очистить все элементы поля?</phrase>
|
||||
<phrase data="auto_f26e5c0c72082089">Найти или добавить ключевое слово</phrase>
|
||||
<phrase data="auto_f3d123e46297531d">в</phrase>
|
||||
<phrase data="auto_f42c85cd57ba4aa0">Остаться</phrase>
|
||||
<phrase data="auto_f6069600bcb07eea"><div class="modal-footer"><div class="mf-left documents-picker-count" data-relation-count></div><button class="btn btn-ghost" type="button" data-relation-close>Закрыть</button></div></phrase>
|
||||
<phrase data="auto_f61de80bf0ca15a4">Документ не выбран</phrase>
|
||||
<phrase data="auto_f7286439b109e428">Новый редирект</phrase>
|
||||
<phrase data="auto_f7806fce80e51b40">Старый URL</phrase>
|
||||
<phrase data="auto_f914c65278294e4a"><div class="modal-header"><span class="dialog-icon info"><i class="ti ti-file-search"></i></span><div style="flex:1"><h3>Выбрать документ</h3><p class="text-secondary" style="margin-top:4px"></phrase>
|
||||
<phrase data="auto_fa9f0524f3a0531e">Добавить тег</phrase>
|
||||
<phrase data="auto_fc8b3939cc9dc467">Путь будет записан в поле документа.</phrase>
|
||||
<phrase data="auto_fda74d41e3311f87">На сервере уже сохранена более новая версия. Обновите страницу, проверьте изменения и сохраните документ повторно.</phrase>
|
||||
<phrase data="auto_ffec67789fb1fcdc">щ</phrase>
|
||||
<phrase data="documents_bulk_action">Действие</phrase>
|
||||
<phrase data="documents_bulk_action_fallback">Действие</phrase>
|
||||
<phrase data="documents_bulk_documents_suffix"> документов.</phrase>
|
||||
<phrase data="documents_bulk_errors">ошибок</phrase>
|
||||
<phrase data="documents_bulk_processed">обработано</phrase>
|
||||
<phrase data="documents_bulk_unchanged">без изменений</phrase>
|
||||
<phrase data="runtime_05d4ae78b6f1bfee">н</phrase>
|
||||
<phrase data="runtime_0918b4ba92684eaa">Название</phrase>
|
||||
<phrase data="runtime_0940401102b8a3fe">т</phrase>
|
||||
<phrase data="runtime_11cef8141437f8a6">ъ</phrase>
|
||||
<phrase data="runtime_15f2ccabeb425c29">й</phrase>
|
||||
<phrase data="runtime_1cc10a3947f7c245">д</phrase>
|
||||
<phrase data="runtime_1d51ebe0fc45e38e">Только поля</phrase>
|
||||
<phrase data="runtime_259f56cb715ba3a3">е</phrase>
|
||||
<phrase data="runtime_3051067c6324c63f">з</phrase>
|
||||
<phrase data="runtime_30fbc377ae9122ed">ё</phrase>
|
||||
<phrase data="runtime_3164696756227147">Заметка добавлена</phrase>
|
||||
<phrase data="runtime_34c6fbb62da8ce5c">п</phrase>
|
||||
<phrase data="runtime_37d43a57a463add5">ю</phrase>
|
||||
<phrase data="runtime_40831c5d98a57dfc">ч</phrase>
|
||||
<phrase data="runtime_446cdc8e3c0d7efc">ы</phrase>
|
||||
<phrase data="runtime_46b0d3855548054a">JSON-снимок пересобран</phrase>
|
||||
<phrase data="runtime_4f60bd4e24e7dc7f">ш</phrase>
|
||||
<phrase data="runtime_50338c005c41fb4e">о</phrase>
|
||||
<phrase data="runtime_5225a95b111d47bf">к</phrase>
|
||||
<phrase data="runtime_53b10ee4405f56d6">ещё не создан</phrase>
|
||||
<phrase data="runtime_557f4cd2c6d3c150">см</phrase>
|
||||
<phrase data="runtime_61095f9d62dfe291">Документ восстановлен</phrase>
|
||||
<phrase data="runtime_6228f1454b196ffd">API-токен отозван</phrase>
|
||||
<phrase data="runtime_65fd24f1cb37fec4">Черновик</phrase>
|
||||
<phrase data="runtime_72a81659de042887">Ревизии удалены</phrase>
|
||||
<phrase data="runtime_734dbc2b54ab6c95">р</phrase>
|
||||
<phrase data="runtime_754309a41e0df98a">ф</phrase>
|
||||
<phrase data="runtime_7592b7ec4eba966a">ц</phrase>
|
||||
<phrase data="runtime_7b0ff8a2e5fdd66d">м</phrase>
|
||||
<phrase data="runtime_823c4eb3e895adc9">а</phrase>
|
||||
<phrase data="runtime_85011fce4419ee63">Поле #</phrase>
|
||||
<phrase data="runtime_894f97c52af9e5ac">Заметка удалена</phrase>
|
||||
<phrase data="runtime_9aa032336a8e122c">б</phrase>
|
||||
<phrase data="runtime_9b21f5cf014c9efb">я</phrase>
|
||||
<phrase data="runtime_9b6276c9a4ac5507">Документ сохранён</phrase>
|
||||
<phrase data="runtime_a1f5d39a12e8f6be">с</phrase>
|
||||
<phrase data="runtime_ab1f4be7e5d6fd8b">г</phrase>
|
||||
<phrase data="runtime_ae51ade91d2b85b7">Ревизия удалена</phrase>
|
||||
<phrase data="runtime_b8012cb642c887a0">в</phrase>
|
||||
<phrase data="runtime_b95d78565f154f82">ь</phrase>
|
||||
<phrase data="runtime_bb69a96efca3303e">х</phrase>
|
||||
<phrase data="runtime_bbb369f210d2969f">щ</phrase>
|
||||
<phrase data="runtime_beee80c256b458da">у</phrase>
|
||||
<phrase data="runtime_bf0d18ef68a8a34e">можно оставить пустым</phrase>
|
||||
<phrase data="runtime_c08fb476eca49399">кг</phrase>
|
||||
<phrase data="runtime_c5412ba2cc2fc45a">Пресет создания сохранён</phrase>
|
||||
<phrase data="runtime_c78364c5d0f27706">Б</phrase>
|
||||
<phrase data="runtime_cdd02bd8b5684812">Редирект удалён</phrase>
|
||||
<phrase data="runtime_d92fff560eb5495e">л</phrase>
|
||||
<phrase data="runtime_dd48804aa38b03e1">Пресет удалён</phrase>
|
||||
<phrase data="runtime_dd591284d827e17f">ж</phrase>
|
||||
<phrase data="runtime_e1c88af54b9fced2">Документ #</phrase>
|
||||
<phrase data="runtime_e35c8bb151d3530d">Редирект сохранён</phrase>
|
||||
<phrase data="runtime_e93c3d6287d39cc3">API-токен создан</phrase>
|
||||
<phrase data="runtime_ee71f8405f87d786">э</phrase>
|
||||
<phrase data="runtime_eead37caf818d0fa">и</phrase>
|
||||
<phrase data="runtime_f4019994d4e75a2a">после сохранения</phrase>
|
||||
<phrase data="runtime_f9a506077fa0d961">Новый</phrase>
|
||||
<phrase data="runtime_fff8b34d92dab340">Шаблон</phrase>
|
||||
<phrase data="auto_f8af664b7ab2ef75">Удалить все элементы?</phrase>
|
||||
<phrase data="auto_10403ca9b11a0b49">После сохранения элементы исчезнут из документа. Неиспользуемые файлы можно будет восстановить из корзины медиа.</phrase>
|
||||
<phrase data="auto_5ede041b60096d58">Удалить изображение?</phrase>
|
||||
<phrase data="auto_c5b3cd090f16f479">После сохранения изображение исчезнет из документа. Неиспользуемый файл можно будет восстановить из корзины медиа.</phrase>
|
||||
<phrase data="auto_e26c8664b60bfa9a">Удалить изображение из документа?</phrase>
|
||||
<phrase data="auto_02e536f7b2d5cec8">Документ сохранён, но часть старых файлов не перемещена в корзину.</phrase>
|
||||
</language>
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
ALTER TABLE `{{prefix}}_documents`
|
||||
ADD COLUMN IF NOT EXISTS `document_is_technical` TINYINT UNSIGNED NOT NULL DEFAULT 0 AFTER `document_in_search`,
|
||||
ADD COLUMN IF NOT EXISTS `document_in_sitemap` TINYINT UNSIGNED NOT NULL DEFAULT 1 AFTER `document_sitemap_pr`,
|
||||
ADD KEY IF NOT EXISTS `idx_public_visibility` (`document_is_technical`,`document_in_sitemap`);
|
||||
@@ -17,7 +17,7 @@
|
||||
return array(
|
||||
'code' => 'documents',
|
||||
'name' => 'Документы',
|
||||
'version' => '0.3.9',
|
||||
'version' => '0.4.11',
|
||||
|
||||
'permissions' => array(
|
||||
'key' => 'documents',
|
||||
@@ -131,6 +131,7 @@
|
||||
array('id' => '014_document_relation_edges', 'file' => 'migrations/014_document_relation_edges.sql'),
|
||||
array('id' => '015_document_creation_presets', 'file' => 'migrations/015_document_creation_presets.sql'),
|
||||
array('id' => '016_reconcile_document_content_columns', 'file' => 'migrations/016_reconcile_document_content_columns.php'),
|
||||
array('id' => '017_document_public_visibility', 'file' => 'migrations/017_document_public_visibility.sql'),
|
||||
),
|
||||
|
||||
'view_globals' => array(
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<label class="product-package-field product-package-field-title"><span>Грузовое место</span><input class="input" name="title" value="{{ package.title|default('')|e('html_attr') }}" placeholder="Коробка 1" aria-label="Название грузового места"></label>
|
||||
<label class="product-package-field"><span>Количество</span><input class="input" type="number" name="quantity" min="1" max="999" step="1" value="{{ package.quantity }}" aria-label="Количество"></label>
|
||||
<label class="product-package-field"><span>Вес, кг</span><input class="input" type="number" name="weight_kg" min="0" step="0.001" value="{{ package.weight_kg|default('') }}" placeholder="0" aria-label="Вес в килограммах"></label>
|
||||
<label class="product-package-field"><span>Длина, см</span><input class="input" type="number" name="length_cm" min="0" step="0.1" value="{{ package.length_cm|default('') }}" placeholder="0" aria-label="Длина в сантиметрах"></label>
|
||||
<label class="product-package-field"><span>Ширина, см</span><input class="input" type="number" name="width_cm" min="0" step="0.1" value="{{ package.width_cm|default('') }}" placeholder="0" aria-label="Ширина в сантиметрах"></label>
|
||||
<label class="product-package-field"><span>Высота, см</span><input class="input" type="number" name="height_cm" min="0" step="0.1" value="{{ package.height_cm|default('') }}" placeholder="0" aria-label="Высота в сантиметрах"></label>
|
||||
@@ -242,12 +242,7 @@
|
||||
<div class="product-package-list" data-package-list>
|
||||
{% for package in shipping_profile.packages %}
|
||||
<div class="product-package-row" data-package-row>
|
||||
<input class="input" name="title" value="{{ package.title|e('html_attr') }}" aria-label="Название грузового места">
|
||||
<input class="input" type="number" name="quantity" min="1" max="999" step="1" value="{{ package.quantity }}" aria-label="Количество">
|
||||
<input class="input" type="number" name="weight_kg" min="0" step="0.001" value="{{ package.weight_kg }}" aria-label="Вес в килограммах">
|
||||
<input class="input" type="number" name="length_cm" min="0" step="0.1" value="{{ package.length_cm }}" aria-label="Длина в сантиметрах">
|
||||
<input class="input" type="number" name="width_cm" min="0" step="0.1" value="{{ package.width_cm }}" aria-label="Ширина в сантиметрах">
|
||||
<input class="input" type="number" name="height_cm" min="0" step="0.1" value="{{ package.height_cm }}" aria-label="Высота в сантиметрах">
|
||||
{% include '@documents/_product_package_fields.twig' with {package: package} only %}
|
||||
<button class="btn btn-ghost btn-icon btn-sm ax-act ax-act-danger" type="button" data-package-remove data-tooltip="Удалить грузовое место" aria-label="Удалить грузовое место"><i class="ti ti-trash"></i></button>
|
||||
</div>
|
||||
{% endfor %}
|
||||
@@ -259,6 +254,6 @@
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<template data-package-template><div class="product-package-row" data-package-row><input class="input" name="title" value="" placeholder="Коробка 1" aria-label="Название грузового места"><input class="input" type="number" name="quantity" min="1" max="999" step="1" value="1" aria-label="Количество"><input class="input" type="number" name="weight_kg" min="0" step="0.001" value="" placeholder="0" aria-label="Вес в килограммах"><input class="input" type="number" name="length_cm" min="0" step="0.1" value="" placeholder="0" aria-label="Длина в сантиметрах"><input class="input" type="number" name="width_cm" min="0" step="0.1" value="" placeholder="0" aria-label="Ширина в сантиметрах"><input class="input" type="number" name="height_cm" min="0" step="0.1" value="" placeholder="0" aria-label="Высота в сантиметрах"><button class="btn btn-ghost btn-icon btn-sm ax-act ax-act-danger" type="button" data-package-remove data-tooltip="Удалить грузовое место" aria-label="Удалить грузовое место"><i class="ti ti-trash"></i></button></div></template>
|
||||
<template data-package-template><div class="product-package-row" data-package-row>{% include '@documents/_product_package_fields.twig' with {package: {quantity: 1}} only %}<button class="btn btn-ghost btn-icon btn-sm ax-act ax-act-danger" type="button" data-package-remove data-tooltip="Удалить грузовое место" aria-label="Удалить грузовое место"><i class="ti ti-trash"></i></button></div></template>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
@@ -42,9 +42,9 @@
|
||||
<div class="documents-bulk-controls">
|
||||
{% if bulk_options.products_available %}
|
||||
<label class="field"><span>Контур</span><select class="select" name="scope">
|
||||
<option value="all">Документы и товары</option>
|
||||
<option value="all"{{ not bulk_clean_descriptions ? ' selected' : '' }}>Документы и товары</option>
|
||||
<option value="documents">Только обычные документы</option>
|
||||
<option value="products">Только товары</option>
|
||||
<option value="products"{{ bulk_clean_descriptions ? ' selected' : '' }}>Только товары</option>
|
||||
</select></label>
|
||||
{% else %}
|
||||
<input type="hidden" name="scope" value="all">
|
||||
@@ -57,7 +57,7 @@
|
||||
</select></label>
|
||||
<label class="field"><span>Состояние</span><select class="select" name="state">
|
||||
<option value="">Опубликованные и черновики</option>
|
||||
<option value="active">Только опубликованные</option>
|
||||
<option value="active"{{ bulk_clean_descriptions ? ' selected' : '' }}>Только опубликованные</option>
|
||||
<option value="draft">Только черновики</option>
|
||||
</select></label>
|
||||
<label class="field documents-bulk-search"><span>Поиск</span><span class="input-wrap"><i class="ti ti-search"></i><input class="input" type="search" name="q" placeholder="ID, название или alias"></span></label>
|
||||
@@ -78,10 +78,21 @@
|
||||
<option value="set">Установить значение</option>
|
||||
<option value="clear">Очистить значение</option>
|
||||
<option value="replace">Найти и заменить</option>
|
||||
{% if bulk_options.product_descriptions_available %}<option value="strip_description_styles"{{ bulk_clean_descriptions ? ' selected' : '' }}>Удалить стили из описаний товаров</option>{% endif %}
|
||||
<option value="move">Перенести в другую рубрику</option>
|
||||
<option value="publish">Опубликовать</option>
|
||||
<option value="unpublish">Снять с публикации</option>
|
||||
<option value="recalculate">Пересчитать поля и индексы</option>
|
||||
<option value="publish">Опубликовать</option>
|
||||
<option value="unpublish">Снять с публикации</option>
|
||||
<option value="technical">Сделать служебными</option>
|
||||
<option value="public">Сделать обычными</option>
|
||||
<option value="search_include">Включить во внутренний поиск</option>
|
||||
<option value="search_exclude">Исключить из внутреннего поиска</option>
|
||||
<option value="robots_index">Разрешить индексацию поисковиками</option>
|
||||
<option value="robots_noindex">Запретить индексацию поисковиками</option>
|
||||
<option value="sitemap_include">Добавить в sitemap</option>
|
||||
<option value="sitemap_exclude">Исключить из sitemap</option>
|
||||
<option value="sitemap_frequency">Изменить частоту sitemap</option>
|
||||
<option value="sitemap_priority">Изменить приоритет sitemap</option>
|
||||
<option value="recalculate">Пересчитать поля и индексы</option>
|
||||
</select></label>
|
||||
|
||||
<label class="field" data-bulk-target-wrap hidden><span>Поле</span><select class="select" name="target" data-bulk-target>
|
||||
@@ -96,16 +107,25 @@
|
||||
<label class="field" data-bulk-search-wrap hidden><span>Что найти</span><input class="input" type="text" name="search" placeholder="Точное вхождение"></label>
|
||||
<label class="field documents-bulk-value" data-bulk-value-wrap hidden><span>Новое значение</span><textarea class="textarea" name="value" rows="3" placeholder="Введите значение"></textarea></label>
|
||||
|
||||
<label class="field" data-bulk-rubric-target-wrap hidden><span>Новая рубрика</span><select class="select" name="target_rubric_id">
|
||||
<label class="field" data-bulk-rubric-target-wrap hidden><span>Новая рубрика</span><select class="select" name="target_rubric_id">
|
||||
<option value="0">Выберите рубрику</option>
|
||||
{% for rubric in bulk_options.rubrics %}
|
||||
<option value="{{ rubric.Id }}">{{ rubric.rubric_title }}</option>
|
||||
{% endfor %}
|
||||
</select></label>
|
||||
</select></label>
|
||||
|
||||
<label class="field" data-bulk-sitemap-frequency-wrap hidden><span>Частота обновления</span><select class="select" name="sitemap_frequency">
|
||||
<option value="0">always</option><option value="1">hourly</option><option value="2">daily</option>
|
||||
<option value="3" selected>weekly</option><option value="4">monthly</option><option value="5">yearly</option><option value="6">never</option>
|
||||
</select></label>
|
||||
<label class="field" data-bulk-sitemap-priority-wrap hidden><span>Приоритет</span><select class="select" name="sitemap_priority">
|
||||
{% for pr in [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1] %}<option value="{{ pr }}"{{ pr == 0.5 ? ' selected' : '' }}>{{ pr }}</option>{% endfor %}
|
||||
</select></label>
|
||||
</div>
|
||||
<div class="documents-bulk-target-help" data-bulk-target-help hidden>
|
||||
<div class="documents-bulk-target-help" data-bulk-target-help hidden>
|
||||
<i class="ti ti-info-circle"></i><span></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="alert alert-info documents-bulk-technical-help" data-bulk-technical-help hidden><i class="ti ti-tool alert-ic"></i><div><b class="alert-title">Служебный документ не удаляется</b><span>Он остаётся доступен запросам, полям и связям, но не открывается отдельной страницей и автоматически исключается из поиска, sitemap и SEO-проверок.</span></div></div>
|
||||
<div class="documents-bulk-step-footer">
|
||||
<span class="text-secondary"><i class="ti ti-info-circle"></i>Ничего не сохранится до подтверждения результата проверки.</span>
|
||||
<button class="btn btn-primary" type="submit" data-bulk-preview><i class="ti ti-eye"></i>Проверить изменения</button>
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
</div>
|
||||
|
||||
<div class="documents-editor-workspace" data-document-workspace data-active-panel="main" data-catalog-mode="{{ catalog_mode ? '1' : '0' }}" data-is-new="{{ is_new ? '1' : '0' }}">
|
||||
{% if catalog_mode and product_context_links %}{% include '@catalog/_context-links.twig' with {context_links: product_context_links} %}{% endif %}
|
||||
<div class="documents-workspace-navigation">
|
||||
<div class="tabs documents-workspace-tabs" role="tablist" aria-label="{{ catalog_mode ? 'Разделы товара' : 'Разделы документа' }}">
|
||||
<button class="tab is-active" type="button" role="tab" aria-selected="true" data-document-workspace-tab="main"><i class="ti ti-file-description"></i>Основное</button>
|
||||
@@ -175,7 +176,7 @@
|
||||
<span class="icon-tile documents-head-icon" style="--tile-bg:var(--sec-soft);--tile-fg:var(--sec)"><i class="ti ti-file-text"></i></span>
|
||||
<h2>Основное</h2>
|
||||
</div>
|
||||
<span class="badge badge-{{ document.state_badge }}">{{ document.state_label }}</span>
|
||||
<span class="badge badge-{{ document.state_badge }}" data-document-state-badge>{{ document.state_label }}</span>
|
||||
</div>
|
||||
<div class="documents-card-body">
|
||||
<div class="form-grid">
|
||||
@@ -301,7 +302,10 @@
|
||||
<div class="documents-card-body">
|
||||
<div class="form-grid">
|
||||
<label class="field col-6"><span class="field-label">Статус</span><select class="select" name="document_status"><option value="1"{{ document.document_status == 1 ? ' selected' : '' }}>Опубликован</option><option value="0"{{ document.document_status == 0 ? ' selected' : '' }}>Черновик</option></select></label>
|
||||
<label class="field col-6"><span class="field-label">Поиск</span><select class="select" name="document_in_search"><option value="1"{{ document.document_in_search == 1 ? ' selected' : '' }}>В поиске</option><option value="0"{{ document.document_in_search == 0 ? ' selected' : '' }}>Скрыт</option></select></label>
|
||||
<label class="field col-6"><span class="field-label">Поиск</span><select class="select" name="document_in_search"><option value="1"{{ document.document_in_search == 1 ? ' selected' : '' }}>В поиске</option><option value="0"{{ document.document_in_search == 0 ? ' selected' : '' }}>Скрыт</option></select></label>
|
||||
<label class="field col-6"><span class="field-label">Публичный доступ</span><select class="select" name="document_is_technical"><option value="0"{{ not document.document_is_technical ? ' selected' : '' }}>Обычный документ</option><option value="1"{{ document.document_is_technical ? ' selected' : '' }}>Служебный документ</option></select><span class="field-hint">Служебный документ доступен полям, связям и запросам, но не открывается отдельной страницей.</span></label>
|
||||
<label class="field col-6"><span class="field-label">Sitemap</span><select class="select" name="document_in_sitemap"><option value="1"{{ document.document_in_sitemap ? ' selected' : '' }}>Добавлять</option><option value="0"{{ not document.document_in_sitemap ? ' selected' : '' }}>Не добавлять</option></select></label>
|
||||
{% if document.rubric_is_technical %}<div class="alert alert-info documents-technical-alert col-12"><i class="ti ti-tool alert-ic"></i><div><b class="alert-title">Рубрика служебная</b><span>Публичный URL этого документа скрыт настройкой рубрики независимо от переключателя выше.</span></div></div>{% endif %}
|
||||
<label class="field col-12"><span class="field-label">Автор</span><select class="select" name="document_author_id">{% for author in authors %}<option value="{{ author.id }}"{{ document.document_author_id == author.id ? ' selected' : '' }}>{{ author.name }}{% if not author.active %} · отключён{% endif %}</option>{% endfor %}</select></label>
|
||||
<div class="field col-12">
|
||||
<span class="field-label">Родительский документ</span>
|
||||
|
||||
@@ -145,7 +145,7 @@
|
||||
<header>
|
||||
{% if can_manage %}<input type="checkbox" value="{{ item.Id }}" data-document-check aria-label="Выбрать документ #{{ item.Id }}">{% endif %}
|
||||
<div class="documents-admin-card-title"><a href="{{ ADMINX_BASE }}/documents/{{ item.Id }}/edit">{{ item.document_title }}</a><small>#{{ item.Id }}</small>{{ document_ui.public_link(item) }}</div>
|
||||
<span class="badge badge-{{ item.state_badge }}">{{ item.state_label }}</span>
|
||||
<span class="badge badge-{{ item.state_badge }}">{{ item.state_label }}</span>{% if item.is_technical_effective %}<span class="badge badge-gray"><i class="ti ti-tool"></i>Служебный</span>{% endif %}
|
||||
</header>
|
||||
<div class="documents-admin-card-body">
|
||||
{% if admin_view.mode == 'custom' %}
|
||||
@@ -237,7 +237,8 @@
|
||||
</td>
|
||||
<td class="documents-cell-state">
|
||||
<div class="documents-badges">
|
||||
<span class="badge badge-{{ item.state_badge }}">{{ item.state_label }}</span>
|
||||
<span class="badge badge-{{ item.state_badge }}">{{ item.state_label }}</span>
|
||||
{% if item.is_technical_effective %}<span class="badge badge-gray"><i class="ti ti-tool"></i>Служебный</span>{% endif %}
|
||||
{% if item.document_in_search %}<span class="badge badge-blue documents-search-flag"><i class="ti ti-search"></i>В поиске</span>{% endif %}
|
||||
{% if item.Id == 1 %}<span class="badge badge-amber">system</span>{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -233,6 +233,9 @@
|
||||
border: none;
|
||||
min-height: 260px;
|
||||
}
|
||||
.events-mobile-label {
|
||||
display: none;
|
||||
}
|
||||
.events-table-day td {
|
||||
padding: 9px 14px;
|
||||
background: var(--background-muted);
|
||||
@@ -247,18 +250,147 @@
|
||||
gap: 8px;
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.events-summary {
|
||||
display: none;
|
||||
}
|
||||
.events-tabs {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.events-table-wrap {
|
||||
max-height: none;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
overflow: visible;
|
||||
}
|
||||
.events-table,
|
||||
.events-table tbody,
|
||||
.events-table tr,
|
||||
.events-table th,
|
||||
.events-table td {
|
||||
.events-table-wrap .table.table-compact.events-table {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
table-layout: auto;
|
||||
}
|
||||
.events-table colgroup,
|
||||
.events-table thead {
|
||||
display: none;
|
||||
}
|
||||
.events-table tbody {
|
||||
display: block;
|
||||
}
|
||||
.events-table .events-row {
|
||||
position: relative;
|
||||
display: grid;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 8px 12px;
|
||||
padding: 12px 14px 12px 17px;
|
||||
border-bottom: 1px solid var(--border-default);
|
||||
}
|
||||
.events-table .events-row:last-of-type {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.events-table .events-row::before {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
bottom: 12px;
|
||||
left: 0;
|
||||
width: 3px;
|
||||
border-radius: 3px;
|
||||
background: var(--event-state-color, var(--gray-300));
|
||||
content: "";
|
||||
}
|
||||
.events-table .events-row td {
|
||||
display: block;
|
||||
width: auto;
|
||||
min-width: 0;
|
||||
height: auto;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
}
|
||||
.events-table .events-row.has-open-details {
|
||||
background: var(--background-muted);
|
||||
}
|
||||
.events-row td:first-child::before {
|
||||
display: none;
|
||||
}
|
||||
.events-cell-state {
|
||||
grid-column: 1;
|
||||
grid-row: 1;
|
||||
}
|
||||
.events-cell-time {
|
||||
grid-column: 2;
|
||||
grid-row: 1;
|
||||
align-self: center;
|
||||
font-size: 11px !important;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.events-cell-actor,
|
||||
.events-cell-message {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.events-cell-actor {
|
||||
display: flex !important;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
grid-row: 2;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px !important;
|
||||
}
|
||||
.events-cell-message {
|
||||
grid-row: 3;
|
||||
padding-top: 2px !important;
|
||||
}
|
||||
.events-cell-message .events-message {
|
||||
line-height: 1.45;
|
||||
}
|
||||
.events-cell-message .text-xs {
|
||||
margin-top: 3px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.events-cell-ip {
|
||||
display: flex !important;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
grid-column: 1;
|
||||
grid-row: 4;
|
||||
color: var(--text-muted);
|
||||
font-size: 11px !important;
|
||||
}
|
||||
.events-cell-actions {
|
||||
grid-column: 2;
|
||||
grid-row: 4;
|
||||
justify-self: end;
|
||||
}
|
||||
.events-mobile-label {
|
||||
display: inline;
|
||||
color: var(--text-muted);
|
||||
font-family: var(--font-family);
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.events-details-row,
|
||||
.events-details-row td {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
.events-details-row[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.events-details-row td {
|
||||
padding: 0 14px 12px 17px !important;
|
||||
border-bottom: 1px solid var(--border-default);
|
||||
}
|
||||
.events-details {
|
||||
max-height: 280px;
|
||||
overflow: auto;
|
||||
padding: 10px;
|
||||
}
|
||||
.events-table-day,
|
||||
.events-table-day td {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
.events-table-day td {
|
||||
padding: 8px 14px;
|
||||
}
|
||||
.events-filter,
|
||||
.events-filter .input-wrap,
|
||||
|
||||
@@ -35,9 +35,11 @@
|
||||
if (hidden) {
|
||||
details.removeAttribute('hidden');
|
||||
button.classList.add('active');
|
||||
row.classList.add('has-open-details');
|
||||
} else {
|
||||
details.setAttribute('hidden', 'hidden');
|
||||
button.classList.remove('active');
|
||||
row.classList.remove('has-open-details');
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
return array(
|
||||
'code' => 'events',
|
||||
'name' => 'Системные события',
|
||||
'version' => '0.1.1',
|
||||
'version' => '0.1.3',
|
||||
|
||||
'permissions' => array(
|
||||
'key' => 'events',
|
||||
@@ -49,7 +49,7 @@
|
||||
'icon' => 'ti ti-history',
|
||||
'permission' => 'view_events',
|
||||
'group' => 'Система',
|
||||
'sort_order' => 35,
|
||||
'sort_order' => 99,
|
||||
'match' => array(
|
||||
'/events',
|
||||
),
|
||||
|
||||
@@ -110,15 +110,15 @@
|
||||
<tbody>
|
||||
{% for row in rows %}
|
||||
<tr class="events-row {{ row.state_class }}">
|
||||
<td class="mono text-muted">{{ row.time_display }}</td>
|
||||
<td><span class="badge {{ row.source_type_badge }} events-source-kind">{{ row.source_type_label }}</span></td>
|
||||
<td><div class="events-referrer-source">{{ row.source_name }}</div></td>
|
||||
<td>
|
||||
<td class="mono text-muted events-cell-time">{{ row.time_display }}</td>
|
||||
<td class="events-cell-state"><span class="badge {{ row.source_type_badge }} events-source-kind">{{ row.source_type_label }}</span></td>
|
||||
<td class="events-cell-actor"><span class="events-mobile-label">Источник</span><div class="events-referrer-source">{{ row.source_name }}</div></td>
|
||||
<td class="events-cell-message">
|
||||
<div class="events-message mono">{{ row.message }}</div>
|
||||
{% if row.url %}<div class="text-muted text-xs events-referrer-url">{{ row.url }}</div>{% endif %}
|
||||
</td>
|
||||
<td><span class="badge badge-gray events-hit-count">{{ row.hits }}</span></td>
|
||||
<td>
|
||||
<td class="events-cell-ip"><span class="events-mobile-label">Переходы</span><span class="badge badge-gray events-hit-count">{{ row.hits }}</span></td>
|
||||
<td class="events-cell-actions">
|
||||
{% if row.details_text %}
|
||||
<button class="btn btn-ghost btn-icon btn-sm" type="button" data-events-details data-tooltip="Детали" aria-label="Детали"><i class="ti ti-chevron-down"></i></button>
|
||||
{% endif %}
|
||||
@@ -170,15 +170,15 @@
|
||||
</tr>
|
||||
{% endif %}
|
||||
<tr class="events-row {{ row.state_class }}">
|
||||
<td class="mono text-muted">{{ row.time_display }}</td>
|
||||
<td><span class="badge {{ row.state_badge }} events-state"><i class="{{ row.state_icon }}"></i>{{ row.state_label }}</span></td>
|
||||
<td>{{ row.actor }}</td>
|
||||
<td>
|
||||
<td class="mono text-muted events-cell-time">{{ row.time_display }}</td>
|
||||
<td class="events-cell-state"><span class="badge {{ row.state_badge }} events-state"><i class="{{ row.state_icon }}"></i>{{ row.state_label }}</span></td>
|
||||
<td class="events-cell-actor"><span class="events-mobile-label">Пользователь</span>{{ row.actor }}</td>
|
||||
<td class="events-cell-message">
|
||||
<div class="events-message">{{ row.message }}</div>
|
||||
{% if row.url %}<div class="mono text-muted text-xs">{{ row.url }}</div>{% endif %}
|
||||
</td>
|
||||
<td class="mono text-muted">{{ row.ip }}</td>
|
||||
<td>
|
||||
<td class="mono text-muted events-cell-ip">{% if row.ip %}<span class="events-mobile-label">IP</span>{{ row.ip }}{% endif %}</td>
|
||||
<td class="events-cell-actions">
|
||||
{% if row.details_text %}
|
||||
<button class="btn btn-ghost btn-icon btn-sm" type="button" data-events-details data-tooltip="Детали" aria-label="Детали"><i class="ti ti-chevron-down"></i></button>
|
||||
{% endif %}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="auto_0f0b8f55edcc806d">Users</phrase>
|
||||
<phrase data="auto_1240ef2fb91174ca">" will be deleted along with the assignment of rights.</phrase>
|
||||
<phrase data="auto_5ea67f9e32546482">Role "</phrase>
|
||||
<phrase data="auto_721da5d070ce0d16">Failed to delete</phrase>
|
||||
@@ -8,4 +9,5 @@
|
||||
<phrase data="auto_8b064896cc26e067">Delete role?</phrase>
|
||||
<phrase data="auto_c00aca49199296d7">Network error</phrase>
|
||||
<phrase data="auto_e02d4b658f2984f4">New role</phrase>
|
||||
<phrase data="runtime_845595d6e899ecb0">Users</phrase>
|
||||
</language>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="auto_0f0b8f55edcc806d">Пользователи</phrase>
|
||||
<phrase data="auto_1240ef2fb91174ca">» будет удалена вместе с назначением прав.</phrase>
|
||||
<phrase data="auto_5ea67f9e32546482">Роль «</phrase>
|
||||
<phrase data="auto_721da5d070ce0d16">Не удалось удалить</phrase>
|
||||
@@ -8,4 +9,5 @@
|
||||
<phrase data="auto_8b064896cc26e067">Удалить роль?</phrase>
|
||||
<phrase data="auto_c00aca49199296d7">Ошибка сети</phrase>
|
||||
<phrase data="auto_e02d4b658f2984f4">Новая роль</phrase>
|
||||
<phrase data="runtime_845595d6e899ecb0">Пользователи</phrase>
|
||||
</language>
|
||||
|
||||
@@ -129,7 +129,12 @@
|
||||
{
|
||||
return Lock::run('media-trash', function () use ($token) {
|
||||
$entry = self::entry($token);
|
||||
$payload = self::itemsRoot() . '/' . $entry['token'] . '/payload';
|
||||
self::removeTree($payload);
|
||||
clearstatcache(true, $payload);
|
||||
if (file_exists($payload)) { throw new \RuntimeException('Не удалось удалить файлы корзины. Проверьте права доступа.'); }
|
||||
self::removeTree(self::itemsRoot() . '/' . $entry['token']);
|
||||
if (is_dir(self::itemsRoot() . '/' . $entry['token'])) { throw new \RuntimeException('Не удалось удалить запись корзины. Проверьте права доступа.'); }
|
||||
AuditLog::record('media.purged', array('actor_id' => Auth::id(), 'target_type' => 'media', 'meta' => array('path' => $entry['path'], 'token' => $entry['token'])));
|
||||
return $entry;
|
||||
});
|
||||
|
||||
@@ -1036,3 +1036,11 @@ button.media-thumb {
|
||||
color: var(--text-secondary, #667085);
|
||||
font-size: 13px;
|
||||
}
|
||||
.media-trash-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid var(--border-default);
|
||||
}
|
||||
|
||||
@@ -59,10 +59,12 @@
|
||||
var audit = e.target.closest('[data-media-audit-run]');
|
||||
var trashRestore = e.target.closest('[data-media-trash-restore]');
|
||||
var trashPurge = e.target.closest('[data-media-trash-purge]');
|
||||
var trashClear = e.target.closest('[data-media-trash-clear]');
|
||||
|
||||
if (audit) { self.runAudit(audit); return; }
|
||||
if (trashRestore) { self.restoreTrash(trashRestore); return; }
|
||||
if (trashPurge) { self.purgeTrash(trashPurge); return; }
|
||||
if (trashClear) { self.clearTrash(trashClear); return; }
|
||||
if (folder) { self.createFolder(); return; }
|
||||
if (rename) { self.rename(rename); return; }
|
||||
if (del) { self.remove(del); return; }
|
||||
@@ -401,6 +403,35 @@
|
||||
});
|
||||
},
|
||||
|
||||
clearTrash: function (button) {
|
||||
var self = this;
|
||||
if (self.clearingTrash) return;
|
||||
var items = Array.from(document.querySelectorAll('[data-media-trash-purge]'));
|
||||
if (!items.length) return;
|
||||
Adminx.Confirm.open({kind: 'danger', title: 'Очистить корзину медиа?',
|
||||
message: 'Все объекты, показанные в корзине, будут удалены окончательно. Восстановить их будет нельзя.',
|
||||
confirmLabel: 'Удалить навсегда', confirmClass: 'btn-danger', onConfirm: function () {
|
||||
self.clearingTrash = true;
|
||||
var done = 0, progress = document.querySelector('[data-media-trash-progress]');
|
||||
document.querySelectorAll('[data-media-trash-clear], [data-media-trash-purge], [data-media-trash-restore]').forEach(function (el) { el.disabled = true; });
|
||||
function step() {
|
||||
progress.textContent = done + ' / ' + items.length;
|
||||
if (done === items.length) { window.location.reload(); return Promise.resolve(); }
|
||||
var item = items[done];
|
||||
return Adminx.Ajax.post(self.base() + '/media/trash/' + encodeURIComponent(item.getAttribute('data-media-trash-purge')) + '/purge', new FormData(document.getElementById('mediaActionForm'))).then(function (payload) {
|
||||
var data = payload.data || {};
|
||||
if (!data.success) throw new Error(data.message || Adminx.tr('Не удалось очистить корзину'));
|
||||
item.closest('tr').remove(); done++; return step();
|
||||
});
|
||||
}
|
||||
step().catch(function (error) {
|
||||
self.clearingTrash = false;
|
||||
document.querySelectorAll('[data-media-trash-clear], [data-media-trash-purge], [data-media-trash-restore]').forEach(function (el) { el.disabled = false; });
|
||||
Adminx.Toast.show(error.message || 'Ошибка сети', 'error');
|
||||
});
|
||||
}});
|
||||
},
|
||||
|
||||
clearThumbnails: function (button) {
|
||||
var self = this;
|
||||
var name = button.getAttribute('data-name') || button.getAttribute('data-path') || '';
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="media_trash_clear">Empty trash</phrase>
|
||||
<phrase data="media_trash_clear_confirm">Empty media trash?</phrase>
|
||||
<phrase data="media_trash_clear_warning">All items currently shown in the trash will be permanently deleted. This cannot be undone.</phrase>
|
||||
<phrase data="media_trash_clear_error">Could not empty trash</phrase>
|
||||
<phrase data="media_trash_files_error">Could not delete trashed files. Check filesystem permissions.</phrase>
|
||||
<phrase data="media_trash_entry_error">Could not delete trash metadata. Check filesystem permissions.</phrase>
|
||||
</language>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="media_trash_clear">Очистить корзину</phrase>
|
||||
<phrase data="media_trash_clear_confirm">Очистить корзину медиа?</phrase>
|
||||
<phrase data="media_trash_clear_warning">Все объекты, показанные в корзине, будут удалены окончательно. Восстановить их будет нельзя.</phrase>
|
||||
<phrase data="media_trash_clear_error">Не удалось очистить корзину</phrase>
|
||||
<phrase data="media_trash_files_error">Не удалось удалить файлы корзины. Проверьте права доступа.</phrase>
|
||||
<phrase data="media_trash_entry_error">Не удалось удалить запись корзины. Проверьте права доступа.</phrase>
|
||||
</language>
|
||||
@@ -19,7 +19,7 @@
|
||||
return array(
|
||||
'code' => 'media',
|
||||
'name' => 'Медиа',
|
||||
'version' => '0.6.4',
|
||||
'version' => '0.6.5',
|
||||
|
||||
'permissions' => array(
|
||||
'key' => 'media',
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
</div>
|
||||
<div class="section-header ax-panel-header"><div class="section-icon"><i class="ti ti-trash"></i></div><div><div class="section-eyebrow">Медиа</div><h2>Удалённые файлы и папки</h2><p class="section-desc">Восстановление возвращает объект по исходному пути. Окончательное удаление необратимо.</p></div></div>
|
||||
<div class="card ax-list-card media-trash-card">
|
||||
{% if items and can_manage %}<div class="media-trash-toolbar"><button class="btn btn-danger" type="button" data-media-trash-clear><i class="ti ti-trash"></i>Очистить корзину</button><span class="text-secondary" data-media-trash-progress role="status" aria-live="polite"></span></div>{% endif %}
|
||||
<div class="table-scroll"><table class="table"><thead><tr><th>Объект</th><th>Тип</th><th>Удалён</th><th class="table-actions"></th></tr></thead><tbody>
|
||||
{% for item in items %}<tr><td><b>{{ item.name }}</b><small class="table-subtitle mono">{{ item.path }}</small></td><td>{{ item.type == 'folder' ? 'Папка' : 'Файл' }}</td><td>{{ item.deleted_label }}</td><td class="table-actions"><div class="cluster">
|
||||
<button class="btn btn-ghost btn-icon ax-act ax-act-restore" type="button" data-media-trash-restore="{{ item.token }}" data-name="{{ item.name }}" data-tooltip="Восстановить" aria-label="Восстановить"><i class="ti ti-restore"></i></button>
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Adminx\Support\ModuleExtensions;
|
||||
use App\Adminx\Support\InterfaceSettings;
|
||||
use App\Common\AdminLocation;
|
||||
use App\Common\ModuleManager;
|
||||
use App\Common\ModuleMigrator;
|
||||
@@ -115,6 +116,11 @@
|
||||
|
||||
if (!empty($item['has_dashboard'])) {
|
||||
ModuleSettings::set('adminx_dashboard_enabled', (bool) $dashboardEnabled, $code, 'bool');
|
||||
InterfaceSettings::setModuleDashboardVisibility(
|
||||
$code,
|
||||
(bool) $dashboardEnabled,
|
||||
ModuleExtensions::dashboardDefinitions()
|
||||
);
|
||||
}
|
||||
|
||||
return self::one($code);
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
return array(
|
||||
'code' => 'modules',
|
||||
'name' => 'Модули',
|
||||
'version' => '0.2.0',
|
||||
'version' => '0.2.1',
|
||||
|
||||
'settings' => array(
|
||||
'repository_enabled' => array('label' => 'Удалённый каталог модулей', 'type' => 'bool', 'default' => false, 'group' => 'modules_repository'),
|
||||
|
||||
@@ -441,7 +441,7 @@
|
||||
}
|
||||
|
||||
foreach ($defaults as $key => $value) {
|
||||
if (!isset($input[$key]) || trim((string) $input[$key]) === '') {
|
||||
if (!array_key_exists($key, $input)) {
|
||||
$input[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user