mirror of
https://github.com/avecms/AVE.cms.git
synced 2026-12-04 00:45:07 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a26157716 | ||
|
|
3a7c4a5fbb | ||
|
|
86a41e4adc | ||
|
|
5dad4a1cf1 | ||
|
|
95c92e7142 | ||
|
|
b21858a4e5 | ||
|
|
33fe774e1a | ||
|
|
7098eb9d6e | ||
|
|
918c989f91 |
@@ -22,10 +22,14 @@
|
||||
/tmp/
|
||||
/uploads/
|
||||
/storage/backups/
|
||||
/storage/database-restore/
|
||||
/storage/importprice/
|
||||
/storage/imports/
|
||||
/storage/jobs/
|
||||
/storage/logs/
|
||||
/storage/media-trash/
|
||||
/storage/releases/
|
||||
/storage/reports/
|
||||
/storage/runtime/
|
||||
/storage/secrets/
|
||||
/storage/tmp/
|
||||
|
||||
@@ -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.
|
||||
|
||||
+565
@@ -0,0 +1,565 @@
|
||||
# История изменений AVE.cms
|
||||
|
||||
Здесь собраны заметные для пользователей изменения AVE.cms 3.3, начиная со
|
||||
сборки 0.30. Внутренние рефакторинги, тестовые файлы и служебные изменения
|
||||
сборщика перечислены только тогда, когда они влияют на установку, обновление
|
||||
или поведение системы.
|
||||
|
||||
Часть возможностей распространяется отдельными модулями. Такие изменения
|
||||
помечены как изменения каталога модулей и не означают, что модуль автоматически
|
||||
установлен вместе с чистым ядром.
|
||||
|
||||
## Не выпущено
|
||||
|
||||
## 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
|
||||
|
||||
### Публичный сайт и вход
|
||||
|
||||
- Неизвестный адрес снова показывает назначенную страницу 404, а не содержимое
|
||||
главной страницы. HTTP-статус 404 и метаданные сохранены.
|
||||
- Публичная регистрация и вход могут работать только по телефону: email больше
|
||||
не требуется, номер форматируется по маске, а доступные способы входа
|
||||
определяются настройками системы.
|
||||
- Настройки телефонного входа и подсказки в кабинете приведены к одному набору
|
||||
разрешённых способов авторизации.
|
||||
|
||||
### Пользователи сайта
|
||||
|
||||
- В разделе пользователей сайта форма учитывает регистрацию без email и
|
||||
корректно показывает телефон как основной идентификатор.
|
||||
|
||||
### Выпуск
|
||||
|
||||
- Для build 0.40 подготовлены чистая core-сборка, компактный установщик и
|
||||
накопительное обновление с build 0.20.
|
||||
|
||||
## 3.3 build 0.39 — 25 августа 2026
|
||||
|
||||
### Документы и публичные шаблоны
|
||||
|
||||
- Карта публичных шаблонов показывает, из каких штатных компонентов AVE.cms
|
||||
собираются основные типы страниц и где каждый компонент редактируется.
|
||||
- Поля оформленных информационных страниц снова доступны в редакторе документа,
|
||||
включая подписи, адреса и содержимое карт на странице контактов.
|
||||
- Исправлено сохранение документа из режима исходного HTML-кода редактора.
|
||||
- Публичный адрес под названием документа в таблице стал активной ссылкой и
|
||||
открывается в новой вкладке.
|
||||
- Существующий документ можно сохранять со своим URL, даже если рядом с ним
|
||||
позднее появился системный маршрут установленного модуля.
|
||||
|
||||
### Рубрики и темы
|
||||
|
||||
- Дополнительные шаблоны рубрики открываются в полноразмерной рабочей панели,
|
||||
поддерживают проверку и корректно возвращаются из полноэкранного режима.
|
||||
- Из редактора дополнительного шаблона можно перейти к связанному документу.
|
||||
- Улучшено отображение представлений и публичных шаблонов в разделе темы.
|
||||
|
||||
### Поиск
|
||||
|
||||
- Поиск распознаёт артикулы без разделителя между буквами и цифрами, сохраняет
|
||||
правила русской и английской раскладки и учитывает управляемые синонимы.
|
||||
- Добавлена осторожная коррекция опечаток с подсказкой «Возможно, вы искали»;
|
||||
исходный запрос пользователя не заменяется без объяснения.
|
||||
- Переиндексация получила более устойчивый пошаговый прогресс и словарь
|
||||
поисковых вариантов.
|
||||
|
||||
### Каталог модулей
|
||||
|
||||
- Модуль слайдеров добавлен в публичный каталог: слайды, ссылки, навигация,
|
||||
адаптивные изображения и внешний вид управляются из панели.
|
||||
- Галереи получили обновлённый публичный просмотр изображений.
|
||||
- Модуль SMS-входа получил журнал событий и расширенную диагностику отправки.
|
||||
- Обновлены модули поиска и связанных материалов.
|
||||
- Торговые, проектные и служебные модули по-прежнему исключены из публичной
|
||||
core-сборки и каталога.
|
||||
|
||||
### Выпуск
|
||||
|
||||
- Для build 0.39 подготовлены чистая core-сборка, компактный установщик и
|
||||
накопительное обновление с build 0.20.
|
||||
|
||||
## 3.3 build 0.38 — 5 августа 2026
|
||||
|
||||
### Поля документов
|
||||
|
||||
- Описание поля снова поддерживает безопасную HTML-разметку и показывается
|
||||
редактору под полем документа.
|
||||
- Для подсказок можно использовать выделение, уменьшенный текст, переносы,
|
||||
ссылки и списки. Скрипты и опасные HTML-атрибуты автоматически удаляются.
|
||||
|
||||
### Пользователи и безопасность
|
||||
|
||||
- В карточке пользователя появились активные сеансы с возможностью завершить
|
||||
отдельный сеанс или все остальные устройства.
|
||||
- Неудачные попытки входа записываются в аудит и доступны для контроля.
|
||||
- Поддержан временный пароль с обязательной сменой при следующем входе.
|
||||
- Усилены проверки API-токенов, внешних адресов, возврата после авторизации и
|
||||
публичных форм.
|
||||
- Антиспам получил автоматические блокировки и уведомления о всплесках.
|
||||
|
||||
### Медиа и публичное оформление
|
||||
|
||||
- Медиатека получила безопасную корзину, анализ использования файлов и
|
||||
восстановление удалённых объектов.
|
||||
- В редакторе документа можно заменить изображения его папки без отдельного
|
||||
перехода в медиатеку.
|
||||
- Исправлена очистка и повторная генерация миниатюр.
|
||||
- Публичные представления модулей доступны для редактирования в активной теме
|
||||
с проверкой шаблона, ревизиями и возвратом к поставке модуля.
|
||||
|
||||
### Поиск и работа с контентом
|
||||
|
||||
- Поиск документов и товаров учитывает русскую и английскую запись, неверную
|
||||
раскладку, формы слов и приоритет точного совпадения.
|
||||
- Модуль поиска получил управляемые синонимы, области выдачи и редактируемые
|
||||
публичные шаблоны.
|
||||
- Массовый редактор документов безопасно обновляет только выбранные поля и
|
||||
корректно инвалидирует публичный кеш.
|
||||
- Улучшены быстрые переходы из публичного режима редактирования к реальным
|
||||
разделам панели.
|
||||
|
||||
### Модули
|
||||
|
||||
- A/B-тесты показывают достаточность выборки и статистическую достоверность
|
||||
результата, а не только проценты конверсии.
|
||||
- Рейтинги получили просмотр и модерацию отдельных голосов.
|
||||
- Задачи Todo и Канбан поддерживают сроки, исполнителей, видимость и связь с
|
||||
документами.
|
||||
- Всплывающие окна получили защиту от повторного учёта событий и уведомления.
|
||||
- В публичный каталог добавлены кросспостинг, импорт документов и безопасное
|
||||
сравнение локальной и рабочей систем.
|
||||
- Встроенные разделы панели, включая медиатеку, больше не показываются как
|
||||
отдельные устанавливаемые модули.
|
||||
- Из публичного каталога исключены закрытые и проектные расширения, инструменты
|
||||
разработчика, товарный контур и служебные помощники выпуска.
|
||||
|
||||
### Выпуск и диагностика
|
||||
|
||||
- Помощник выпуска проверяет миграции отдельно устанавливаемых модулей отдельно
|
||||
от миграций чистого ядра.
|
||||
- Мониторинг здоровья, планировщик и каталоги обновлений получили дополнительные
|
||||
уведомления о требующих внимания состояниях.
|
||||
- Для build 0.38 опубликованы чистая core-сборка, установщик и накопительное
|
||||
обновление с build 0.20.
|
||||
- Чистая сборка по-прежнему не содержит торговые, проектные и закрытые модули.
|
||||
|
||||
## 3.3 build 0.37 — 30 июля 2026
|
||||
|
||||
### Медиа
|
||||
|
||||
- Добавлены именованные виды изображений: администратор может заранее задать
|
||||
назначение, размеры и способ кадрирования изображения.
|
||||
- В редакторе изображения появилось действие «Подогнать под вид».
|
||||
- Для вида изображения можно создавать WebP-двойник.
|
||||
|
||||
### Рубрики
|
||||
|
||||
- Удаление рубрики стало обратимым: удалённые рубрики помещаются в корзину.
|
||||
- Из корзины рубрику можно восстановить или удалить окончательно.
|
||||
- Ревизии схемы рубрики переведены на общий механизм хранения истории.
|
||||
|
||||
### Пользователи
|
||||
|
||||
- Глобальный поиск теперь находит пользователей панели.
|
||||
- В таблицу пользователей добавлена дата последнего входа.
|
||||
- Поиск пользователей корректно работает с кириллицей.
|
||||
- Защищён текущий публичный аккаунт: пользователь не может случайно отключить
|
||||
или удалить собственную учётную запись во время работы.
|
||||
- Для публичных аккаунтов добавлено управляемое удаление с проверкой прав и
|
||||
защитой связанных данных.
|
||||
|
||||
### Исправления
|
||||
|
||||
- Начальная установка создаёт таблицы для видов изображений.
|
||||
- Улучшена совместимость панели каталога, рубрик и тем с модульными ресурсами.
|
||||
|
||||
## 3.3 build 0.36 — 30 июля 2026
|
||||
|
||||
### Каталог
|
||||
|
||||
- Редактор разделов каталога получил наглядное древовидное представление.
|
||||
- Порядок и вложенность разделов можно менять перетаскиванием.
|
||||
- Исправлено выделение активного раздела и обновление дерева после операций.
|
||||
- Улучшена работа с большими деревьями и длинными названиями разделов.
|
||||
|
||||
### Товарные фиды
|
||||
|
||||
- Переработан интерфейс создания и редактирования фидов.
|
||||
- Добавлены понятные настройки источника, разделов, полей и правил выгрузки.
|
||||
- Улучшены проверка конфигурации и формирование публичного файла фида.
|
||||
- Модуль товарных фидов поставляется отдельно через каталог модулей.
|
||||
|
||||
## 3.3 build 0.35 — 30 июля 2026
|
||||
|
||||
### Поиск
|
||||
|
||||
- Добавлен единый механизм провайдеров глобального поиска. Разделы и модули
|
||||
могут добавлять собственные типы результатов без изменения поискового ядра.
|
||||
- Поиск документов учитывает раскладку клавиатуры, транслитерацию, части слов
|
||||
и приоритет совпадения.
|
||||
- Результаты получили единый формат заголовков, пояснений, ссылок и иконок.
|
||||
|
||||
### Диагностика контента
|
||||
|
||||
- Добавлена безопасная интроспекция страницы: система может определить
|
||||
используемые документы, рубрики, запросы, блоки, навигацию и представления.
|
||||
- Диагностика сообщает о недостающих связях и шаблонах без выполнения
|
||||
пользовательского PHP-кода.
|
||||
- Публичный отладчик получил более точные сведения о составе страницы.
|
||||
|
||||
### Ревизии
|
||||
|
||||
- Создан общий механизм JSON-ревизий для административных сущностей.
|
||||
- Блоки, шаблоны, рубрики и представления используют единый формат снимков,
|
||||
сравнения и восстановления.
|
||||
|
||||
### Интеграции и безопасность
|
||||
|
||||
- Исходящие HTTP-запросы получили единый журнал с временем выполнения,
|
||||
результатом и безопасно очищенными диагностическими данными.
|
||||
- Усилена проверка внешних адресов и защита от обращения к запрещённым сетевым
|
||||
ресурсам.
|
||||
- Старые MD5-пароли публичных пользователей автоматически заменяются
|
||||
современным хешем после успешного входа.
|
||||
- Усилена проверка локальных адресов возврата после авторизации.
|
||||
- API-токены получили более строгую проверку областей доступа.
|
||||
|
||||
### Модули
|
||||
|
||||
- Планировщик поддерживает длительные задания, разбитые на небольшие шаги.
|
||||
- Поиск и похожие документы могут выполнять переиндексацию через планировщик.
|
||||
- В каталог модулей добавлен MCP-мост для управляемого доступа внешних
|
||||
инструментов к разрешённым данным AVE.cms.
|
||||
- Для платёжных модулей и модуля магазина добавлен журнал обращений и проверка
|
||||
фактического статуса платежа. Эти возможности не входят в чистое ядро.
|
||||
|
||||
## 3.3 build 0.34 — 29 июля 2026
|
||||
|
||||
### Модель контента
|
||||
|
||||
- Справочники стали отдельной сущностью для повторно используемых значений
|
||||
полей без создания лишних публичных документов.
|
||||
- Добавлены двусторонние связи документов.
|
||||
- Добавлены вычисляемые поля.
|
||||
- Появилась библиотека готовых наборов полей для быстрого создания рубрик.
|
||||
- Визуальная карта сайта показывает основные сущности и их связи.
|
||||
|
||||
### Управление
|
||||
|
||||
- Добавлена командная палитра и глобальный административный поиск.
|
||||
- Аудит действий стал нагляднее: события проще фильтровать и просматривать по
|
||||
времени и пользователям.
|
||||
- Улучшена страница диагностики и готовности сайта.
|
||||
|
||||
### Представления
|
||||
|
||||
- Для публичных представлений добавлены ревизии и безопасный предпросмотр.
|
||||
- Модуль A/B-тестов умеет проверять разные варианты представлений.
|
||||
|
||||
### Надёжность
|
||||
|
||||
- Добавлен модуль надёжных исходящих событий: неотправленные события
|
||||
сохраняются, повторяются и доступны в журнале.
|
||||
- Добавлен модуль автоматического прогрева кеша.
|
||||
- Миграция из старых версий получила полную и выборочную схемы переноса,
|
||||
предварительный анализ таблиц и пошаговый прогресс.
|
||||
|
||||
## 3.3 build 0.33 — 28 июля 2026
|
||||
|
||||
### Публичный сайт
|
||||
|
||||
- Добавлен раздел управления публичным сайтом со структурой, размещениями и
|
||||
представлениями.
|
||||
- Представление можно назначить документу, рубрике, запросу или другому
|
||||
поддерживаемому источнику без жёсткой привязки разметки в PHP-коде.
|
||||
- Добавлены предпросмотр и история изменений представлений.
|
||||
- Карта размещений показывает, какой компонент и шаблон формируют конкретную
|
||||
часть страницы.
|
||||
|
||||
### Контент
|
||||
|
||||
- Документы, рубрики, запросы, блоки и навигация получили единые контракты
|
||||
сохранения и вывода.
|
||||
- Зависимости тегов контента учитываются при обновлении и очистке кеша.
|
||||
- Выбор документов вынесен в общий репозиторий и используется разными
|
||||
редакторами панели.
|
||||
- Улучшено объяснение условий запросов и предпросмотр результата.
|
||||
|
||||
### Совместимость
|
||||
|
||||
- Нативная система представлений добавлена без принудительной замены
|
||||
существующих шаблонов публичного сайта.
|
||||
- Модули поиска, похожих документов, галерей, комментариев и других публичных
|
||||
компонентов адаптированы к общему механизму вывода.
|
||||
|
||||
## 3.3 build 0.32 — 27 июля 2026
|
||||
|
||||
### Чистое ядро
|
||||
|
||||
- Проектные настройки и оформление конкретного сайта отделены от публичной
|
||||
core-сборки.
|
||||
- Локальные примеры и тестовые данные исключены из Git и релизных архивов.
|
||||
- В чистой сборке сохраняются только ядро, установщик, базовая тема и
|
||||
системная документация.
|
||||
|
||||
### Разработка
|
||||
|
||||
- Исходный PHP-код приведён к единому стилю AVE.cms с проверкой совместимости
|
||||
с PHP 7.3.
|
||||
- Добавлены правила для безопасного хранения runtime-каталогов и локальных
|
||||
файлов после установки.
|
||||
|
||||
## 3.3 build 0.31 — 27 июля 2026
|
||||
|
||||
### Установка модулей
|
||||
|
||||
- Архивы модулей публикуются вместе с корректным описанием зависимостей.
|
||||
- Установщик пакета проверяет и устанавливает необходимые зависимости в
|
||||
правильном порядке.
|
||||
|
||||
### Обновления
|
||||
|
||||
- Резервная копия перед обновлением ограничивается таблицами, которых
|
||||
действительно касается миграция.
|
||||
- Исправлена область резервирования миграций пользователей и сохранённых
|
||||
представлений.
|
||||
- Обновлено описание чистой публичной сборки и порядка установки.
|
||||
|
||||
## 3.3 build 0.30 — 27 июля 2026
|
||||
|
||||
### Языки панели
|
||||
|
||||
- Панель управления получила русскую и английскую локализацию.
|
||||
- Язык можно выбрать при установке и позднее изменить в профиле.
|
||||
- Переведены системные разделы, сообщения, элементы интерфейса и клиентские
|
||||
уведомления.
|
||||
|
||||
### Справка
|
||||
|
||||
- Добавлена английская версия пользовательской справки по установке, полям,
|
||||
контенту, API, модулям, хукам, отладке и работе с базой данных.
|
||||
- Справка открывается на выбранном языке панели.
|
||||
|
||||
### Установщик и пакеты
|
||||
|
||||
- Мастер установки стал локализованным.
|
||||
- Пакеты демонстрационных сайтов могут объявлять необходимые модули и
|
||||
устанавливать их как зависимости.
|
||||
- Инструменты сборки проверяют языковые файлы и состав модульных архивов.
|
||||
+571
-327
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
# AVE.cms
|
||||
|
||||
**AVE.cms 3.3 build 0.35** — модульная система управления сайтами на PHP.
|
||||
**AVE.cms 3.3 build 0.44** — модульная система управления сайтами на PHP.
|
||||
Она подходит для проектов, в которых структуру содержимого нужно собирать из
|
||||
собственных рубрик, полей, документов, запросов, блоков и шаблонов, не
|
||||
привязываясь к заранее заданному типу сайта.
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Common\Permission;
|
||||
use App\Common\Language;
|
||||
|
||||
/**
|
||||
* Реестр провайдеров административного поиска.
|
||||
@@ -140,7 +141,7 @@
|
||||
|
||||
return array(
|
||||
'type' => self::code(isset($row['type']) ? $row['type'] : $providerCode),
|
||||
'group' => self::text(isset($row['group']) ? $row['group'] : 'Результаты', 80),
|
||||
'group' => Language::translateSource(self::text(isset($row['group']) ? $row['group'] : 'Результаты', 80)),
|
||||
'title' => $title,
|
||||
'subtitle' => self::text(isset($row['subtitle']) ? $row['subtitle'] : '', 300),
|
||||
'url' => $url,
|
||||
|
||||
@@ -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,13 +76,16 @@
|
||||
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 сохраняет изменения и оставляет редактор открытым; ревизии позволяют вернуться к прошлой версии.'), 'Смена рубрики существующего документа запрещена без отдельной миграции полей.'),
|
||||
self::item('#^/documents#', 'Документы', 'Основной реестр страниц и товарных карточек сайта, построенных на рубриках и их полях.', array('Фильтруйте документы по рубрике, состоянию и названию.', 'Публикацию, копирование и удаление можно выполнять из списка или пакетно.', 'Удалённый документ сначала попадает в корзину и только затем может быть удалён окончательно.'), 'Документ №1 и системная страница 404 защищены от окончательного удаления.', 'content/documents'),
|
||||
self::item('#^/public-site/presentations$#', 'Представления', 'Создаёт повторно используемое оформление карточек, списков, слайдеров и других результатов.', array('Черновик проверяется на реальном материале и не меняет публичный сайт.', 'Публикация фиксирует версию, а назначение выбирает место и режим применения.', 'Представление меняет внешний вид готовых данных, но не заменяет рубрику, запрос, блок или модуль.'), 'Для совместимости каждое новое назначение начинает работу в режиме «Текущий вывод».', 'content/public-site'),
|
||||
self::item('#^/public-site/template-map$#', 'Карта шаблонов', 'Показывает фактическую цепочку сборки обычных страниц, списков, каталога и товаров.', array('Общий шаблон создаёт внешний каркас страницы.', 'Шаблон рубрики размещает поля, блоки, запросы и модульные теги.', 'Тема оформляет только подключённые компоненты, если не включён отдельный режим оболочки темы.'), 'Карта работает только на чтение; каждая кнопка открывает штатный редактор выбранного слоя.', 'content/public-site'),
|
||||
self::item('#^/public-site/map$#', 'Визуальная карта сайта', 'Показывает деревья меню, связанные страницы и опубликованные документы вне навигации.', array('Уровни строятся из действующих пунктов навигации.', 'Ссылка документа открывает его штатный редактор.', 'Документ вне меню может использоваться запросом, каталогом или прямой ссылкой.'), 'Карта является обзором и ничего не публикует.', 'content/public-site'),
|
||||
self::item('#^/public-site/placements$#', 'Размещения компонентов', 'Показывает, в каких сохранённых шаблонах используются блоки, подборки, навигации и модульные теги.', array('Вкладка «Размещения» показывает каждое найденное место отдельно.', 'Вкладка «Где используется» объединяет одинаковые компоненты и показывает число связей.', 'Кнопки справа открывают конкретный исходный шаблон и конкретный подключённый компонент.'), 'Карта предназначена для поиска связей и ничего не меняет на публичном сайте.', 'content/public-site'),
|
||||
self::item('#^/public-site/templates$#', 'Шаблоны публичного сайта', 'Редактирует общие файловые Twig-компоненты активной темы.', array('Список материалов имеет системный резерв.', 'Оболочка страницы и остальные компоненты темы редактируются без поиска файла вручную.', 'Сохранение проверяет Twig, создаёт ревизию и очищает публичный кеш.'), 'Шаблоны рубрик, запросов и блоков остаются в собственных разделах.', 'content/public-site'),
|
||||
self::item('#^/public-site(?:/.*)?$#', 'Публичный сайт', 'Показывает, из каких базовых компонентов собирается сайт и где используется каждый из них.', array('Раздел является картой и не дублирует редакторы шаблонов, рубрик, запросов, блоков и меню.', 'Представления — дополнительный способ оформить уже подготовленные данные.', 'Диагностика сообщает только о явных пробелах в обязательных настройках.'), 'Начните со вкладки «Структура», а содержимое меняйте в штатном редакторе нужного компонента.', 'content/public-site'),
|
||||
|
||||
self::item('#^/catalog/products/shipping$#', 'Доставка и упаковка', 'Показывает готовность товарных данных к расчёту доставки и позволяет редактировать грузовые места без открытия документа.', array('Каждое грузовое место хранит количество, вес и три габарита.', 'Расчёт включается отдельно и использует только полностью заполненную упаковку.', 'Фильтр помогает быстро найти товары без размеров или с выключенным расчётом.'), 'Вес и размеры указываются для одного грузового места; количество умножает итоговые показатели.'),
|
||||
@@ -91,6 +94,7 @@
|
||||
self::item('#^/catalog/variant-groups(?:/.*)?$#', 'Группы вариантов', 'Объединяет отдельные товары с собственными URL и артикулами в одну карточку публичного листинга.', array('Основной вариант представляет группу до выбора цвета или исполнения.', 'Порядок вариантов определяет порядок переключателей на публичной карточке.', 'Выключенный вариант остаётся документом, но не предлагается покупателю.'), 'Каждый вариант должен сохранять собственные цену, остаток, URL и артикул.'),
|
||||
self::item('#^/catalog/card-templates$#', 'Карточки товаров', 'Управляет Twig-разметкой и CSS товарной карточки отдельно для разных мест публичного сайта.', array('Черновик можно проверять на живых данных товара без публикации.', 'Контексты назначают представление главной странице, каталогу и другим листингам.', 'Ревизии сохраняют историю черновиков и опубликованных версий.'), 'Публичный сайт меняется только после публикации представления и включения нативного режима нужного контекста.'),
|
||||
self::item('#^/catalog/filter-templates$#', 'Шаблоны фильтров', 'Управляет Twig-разметкой, CSS и клиентским поведением фасетов товарного каталога.', array('Алгоритм выборки остаётся в каталоге, а шаблон отвечает за представление.', 'Черновик можно проверить до публикации.', 'Теги шаблона выводят название фильтра, варианты и рассчитанные количества товаров.'), 'После публикации проверьте выбор, сброс и повторное применение нескольких фильтров.'),
|
||||
self::item('#^/catalog/public-templates$#', 'Публичные шаблоны товаров', 'Редактирует разметку страницы товара, вариантов, рекомендаций и комплектов в активной теме.', array('Если override отсутствует, редактор показывает резервный шаблон модуля.', 'Первое сохранение создаёт файл в активной теме и подключает пространство products_public.', 'Список данных под редактором объясняет доступные Twig-переменные и вставляет их в код.'), 'Сохранение меняет публичный сайт сразу; предыдущие версии остаются в ревизиях темы.', 'content/catalog'),
|
||||
self::item('#^/catalog/\d+/\d+$#', 'Конструктор каталога', 'Связывает поле типа catalog с деревом разделов, документами, полями и публичными фильтрами.', array('Разделы задают структуру каталога и набор доступных полей.', 'Условия фильтров определяют SQL-ограничения публичной выборки.', 'Порядок полей и фильтров меняется перетаскиванием и сохраняется сразу.'), 'Изменения структуры влияют на редактор документов и публичный каталог.'),
|
||||
self::item('#^/catalog#', 'Каталог', 'Управляет структурами каталогов, товарным индексом, фильтрами и связью с документами.', array('Каждый каталог создаётся для конкретного поля рубрики типа catalog.', 'Товары являются документами и не дублируются в отдельной основной таблице.', 'Для вариантов одного товара используются группы вариантов.'), 'Начинайте с выбора каталога, затем настраивайте разделы, поля и фильтры.', 'content/catalog'),
|
||||
|
||||
@@ -103,16 +107,21 @@
|
||||
self::item('#^/navigation#', 'Навигация', 'Создаёт меню сайта: шаблоны уровней, пункты, вложенность, условия показа и связи с документами.', array('Каждая навигация имеет собственный тег для вставки в шаблон.', 'Пункты можно сортировать и переносить между уровнями.', 'Связанный документ позволяет не вводить URL вручную.'), 'После изменения структуры очищается кеш соответствующей навигации.', 'content/navigation'),
|
||||
self::item('#^/requests#', 'Запросы', 'Формирует выборки документов по рубрикам и полям, а затем выводит их через шаблоны элементов и списка.', array('Условия определяют, какие документы попадут в результат.', 'Основной и постраничный шаблоны отвечают только за представление.', 'External/AJAX-флаги разрешают прямой вызов запроса и требуют осторожности.'), 'Проверяйте запрос после изменения условий: он может использоваться сразу в нескольких страницах.', 'content/requests'),
|
||||
self::item('#^/media#', 'Медиа и файлы', 'Управляет файлами в uploads: загрузкой, папками, изображениями, превью и конвертацией WebP.', array('Сетка и список показывают одни и те же физические файлы.', 'Редактор изображений создаёт производные файлы для crop и resize.', 'При удалении исходника удаляются его превью и связанная WebP-копия.'), 'Не размещайте служебные PHP-файлы в uploads; раздел предназначен только для пользовательских медиа.', 'media'),
|
||||
self::item('#^/certificates(?:/.*)?$#', 'Сертификаты', 'Хранит документы соответствия и связывает их с товарами или другими материалами.', array('Срок действия помогает заранее находить документы, которые требуют проверки.', 'Файл выбирается из медиатеки и остаётся доступен независимо от карточки связи.', 'Связанные товары используют один сертификат без дублирования файла.'), 'Истёкший срок снимает отметку о действующем сертификате, но сам товар автоматически не удаляет.'),
|
||||
self::item('#^/ipra(?:/.*)?$#', 'ИПРА', 'Управляет программами реабилитации и связанными назначениями для работы с клиентами.', array('Запись связывается с пользователем сайта и хранит рабочие сроки.', 'Статус отражает текущий этап обработки, а не публичность документа.', 'Перед изменением назначения проверьте связанные обращения и заказы.'), 'Медицинские и персональные данные должны быть доступны только ролям, которым они необходимы.'),
|
||||
self::item('#^/registrations(?:/.*)?$#', 'Регистрационные удостоверения', 'Ведёт реестр РУ и связи с товарами, чтобы показывать актуальный признак регистрации.', array('Один номер можно связать с несколькими товарами.', 'Дата окончания используется для контроля актуальности отметки.', 'Файл удостоверения выбирается из общей медиатеки.'), 'Окончание срока убирает признак действующего РУ; доступность товара определяется отдельно.'),
|
||||
self::item('#^/service(?:/.*)?$#', 'Сервисное обслуживание', 'Хранит сервисные обращения, сроки, ответственных и историю работ по оборудованию.', array('Карточка объединяет клиента, оборудование и текущее состояние обращения.', 'Смена статуса фиксирует этап работы и остаётся в истории.', 'Сроки помогают находить просроченные обращения.'), 'Не удаляйте завершённые обращения, если история нужна для гарантийного обслуживания.'),
|
||||
self::item('#^/system/release-assistant(?:/.*)?$#', 'Помощник выпуска', 'Проверяет состав локального релиза, версии модулей, миграции и готовность архивов перед ручной публикацией.', array('Предварительная проверка ничего не публикует и не меняет рабочий сайт.', 'В отчёте отдельно показаны изменённые файлы, таблицы и версии модулей.', 'Сборку запускают только после устранения ошибок проверки.'), 'Раздел предназначен для владельца исходного проекта и не включается в обычную публичную сборку.'),
|
||||
|
||||
self::item('#^/system/orders#', 'Заказы и корзина', 'Обрабатывает заказы, состояния оплаты и доставки, шаблоны корзины и брошенные сессии покупателей.', array('Карточка заказа фиксирует товары, цены и выбранные варианты на момент оформления.', 'Способы оплаты настраиваются во вкладке «Оплата», реквизиты провайдеров — во вкладке «Gateways».', 'Брошенные корзины очищаются по сроку хранения и доступны для диагностики.'), 'Отмена и возврат могут влиять на платёжный шлюз — проверяйте итоговый статус операции.'),
|
||||
self::item('#^/system/customers#', 'Пользователи сайта', 'Управляет публичными аккаунтами, регистрацией, OAuth-гейтами и полями профиля.', array('Email-регистрация, восстановление доступа и создание аккаунта после заказа входят в ядро.', 'Дополнительные поля независимо подключаются к регистрации и личному кабинету.', 'Подключённые OAuth-гейты открывают ту же публичную сессию, что и обычная форма входа.', 'Отключение аккаунта запрещает вход, но сохраняет связанные данные.'), 'Email остаётся основным идентификатором; дополнительные способы входа поставляются отдельными модулями.'),
|
||||
self::item('#^/system/customers#', 'Пользователи сайта', 'Управляет публичными аккаунтами, регистрацией, OAuth-гейтами и полями профиля.', array('Регистрацию можно разрешить по email, телефону или обоими способами.', 'Телефонный аккаунт не требует email; адрес можно добавить и подтвердить позже.', 'Дополнительные поля независимо подключаются к регистрации и личному кабинету.', 'Подключённые OAuth-гейты открывают ту же публичную сессию, что и обычная форма входа.', 'Отключение аккаунта запрещает вход, но сохраняет связанные данные.'), 'Для регистрации по телефону установите и настройте SMS-провайдер; без него телефонная форма не показывается.'),
|
||||
self::item('#^/content/contacts/forms/\d+$#', 'Конструктор формы', 'Настраивает поля, шаблон формы, получателей, письмо и поведение после отправки.', array('Теги полей доступны в шаблоне формы и письма.', 'Получатели задаются по одному на строку.', 'История обращений хранит отправленные значения и ответы менеджеров.'), 'После изменения шаблона отправьте тестовое обращение и проверьте письмо.'),
|
||||
self::item('#^/content/contacts#', 'Формы и обращения', 'Управляет публичными формами обратной связи и журналом сообщений посетителей.', array('Форма состоит из полей, шаблонов и почтовых настроек.', 'История позволяет менять статус обращения и отвечать посетителю.', 'Копирование формы создаёт независимый набор настроек.'), 'Проверяйте адреса получателей и настройки системной почты перед публикацией формы.'),
|
||||
self::item('#^/content/rss#', 'RSS-каналы', 'Публикует документы выбранной рубрики в XML-ленте по настраиваемому адресу /rss/{alias}.', array('Заголовок и описание можно брать из полей рубрики.', 'Количество элементов ограничивает размер выдаваемой ленты.', 'Префикс /rss/ зарезервирован и не может использоваться документами.'), 'После изменения алиаса обновите внешние подписки и проверьте XML из списка.'),
|
||||
self::item('#^/content/feeds#', 'Товарные фиды', 'Формирует управляемые XML/YML-выгрузки товаров для партнеров и торговых площадок.', array('Категории определяют товарную выборку, исключения применяются после дочерних разделов.', 'Поля XML и характеристики связываются с индексом каталога или полями товарной рубрики.', 'Предпросмотр не меняет кеш, а пересоздание атомарно публикует новый файл.'), 'Не меняйте закрепленные legacy URL у действующих партнеров; редактируйте связанную конфигурацию фида.'),
|
||||
self::item('#^/content/price-import#', 'Импорт цен', 'Обновляет цены товаров из XLSX после обязательного предварительного просмотра изменений.', array('Сначала загрузите файл или получите его по настроенной HTTPS-ссылке.', 'Выберите лист и сформируйте предварительный просмотр.', 'Применение изменяет только подтверждённые строки и записывает результат в историю.'), 'Не применяйте импорт, если предварительный просмотр показывает неожиданные товары или пустые цены.'),
|
||||
|
||||
self::item('#^/users#', 'Пользователи', 'Управляет сотрудниками, которые могут входить в панель управления, их ролями и активностью.', array('Роль определяет доступные разделы и действия.', 'Отключённый пользователь не может войти, но сохраняется в журнале действий.', 'Нельзя отключить или удалить собственную активную учётную запись.'), 'Публичные аккаунты находятся в отдельном разделе «Пользователи сайта».', 'administration/users'),
|
||||
self::item('#^/users#', 'Пользователи', 'Управляет сотрудниками, которые могут входить в панель управления, их ролями, паролями и активными сессиями.', array('Роль определяет доступные разделы и действия.', 'Во вкладке «Сессии и входы» видны устройства, IP и неудачные попытки входа.', 'Временный пароль можно потребовать сменить при следующем входе.', 'Отключение учётной записи завершает все её активные сессии.', 'Нельзя отключить или удалить собственную активную учётную запись.'), 'Публичные аккаунты находятся в отдельном разделе «Пользователи сайта».', 'administration/users'),
|
||||
self::item('#^/roles#', 'Роли и права', 'Определяет набор разрешений для администраторов и разграничивает доступ к функциям системы.', array('Права сгруппированы по модулям и назначаются роли целиком.', 'Системная роль admin всегда имеет полный доступ.', 'Роль с назначенными пользователями нельзя удалить.'), 'После изменения роли права применяются при следующей проверке доступа пользователя.'),
|
||||
self::item('#^/settings/main$#', 'Основные настройки', 'Управляет публичным доступом, параметрами сайта, почты, документов и вывода.', array('Режим разработки возвращает посетителям временную страницу 503 и закрывает динамические маршруты от индексации.', 'Сотрудник с отдельным правом продолжает видеть документы, модули и API.', 'Поля сгруппированы по назначению, а тип значения проверяется перед сохранением.', 'Секреты устанавливаемых модулей не должны храниться в общих настройках.'), 'Перед открытием сайта переключите публичный доступ и проверьте страницу в отдельном браузере без авторизации.'),
|
||||
self::item('#^/settings/interface$#', 'Настройка интерфейса', 'Определяет порядок и видимость пунктов левого меню и виджетов дашборда.', array('Перетаскивание меняет порядок только для панели управления.', 'Скрытие пункта не отменяет право роли и не блокирует прямой URL.', 'Виджеты установленных модулей появляются в списке автоматически.'), 'Доступ к функциям всегда ограничивайте через роли и права, а не только через видимость меню.'),
|
||||
@@ -125,27 +134,27 @@
|
||||
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('Карточки и порядок сохраняются без перезагрузки.', 'Колонки можно настроить под собственный процесс.', 'Каждый сотрудник работает со своей доской.'), 'Не используйте канбан как журнал системных ошибок: для них предназначены события и Todo.'),
|
||||
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('Задачу можно создать из выпадающего списка в шапке на любой странице панели управления.', 'Чекбокс сразу сохраняет состояние без перезагрузки.', 'Каждый пользователь видит только собственные задачи.'), 'Удаление задачи необратимо; выполненные пункты можно вернуть в работу обычным чекбоксом.'),
|
||||
self::item('#^/todo$#', 'Todo', 'Хранит рабочие задачи сотрудников со сроками и связями с документами.', array('Задачу можно создать из выпадающего списка в шапке на любой странице панели управления.', 'Ответственный видит назначенную задачу и может отметить её выполненной.', 'Режим «Команда» открывает задачу всем сотрудникам с правом просмотра Todo.', 'Связанный документ открывается прямо из строки задачи.'), 'Изменять и удалять задачу может её создатель; выполнение доступно создателю и ответственному.'),
|
||||
self::item('#^/modules/search#', 'Поиск по сайту', 'Индексирует опубликованные документы и формирует обычную страницу результатов и JSON для живого поиска.', array('Области позволяют отдельно искать по товарам, новостям, статьям и другим наборам рубрик.', 'Алгоритм определяет разбор строки и вес точного совпадения, заголовка и содержимого.', 'Штатный HTML можно заменить шаблонами модуля или существующим запросом документов.'), 'После изменения рубрик или индексируемых полей выполните полную переиндексацию.', 'modules/search'),
|
||||
self::item('#^/modules/commerceml#', 'Обмен с 1С', 'Принимает CommerceML по защищённому адресу и сопоставляет товары 1С с документами товарной рубрики.', array('Для каждой интеграции создайте отдельный профиль с логином, паролем и рубрикой.', 'Поля внешнего ID, артикула, цены и остатка выбираются из полей назначенной рубрики.', 'Пробный XML можно загрузить из списка профилей и проверить результат в журнале обменов.'), 'Создание неизвестных товаров выключено по умолчанию: сначала проверьте сопоставление на существующих документах.'),
|
||||
self::item('#^/modules/experiments#', 'A/B-тесты', 'Распределяет посетителей между вариантами и собирает показы и конверсии без смешивания вариантов в общем кеше.', array('Код эксперимента используется в шаблонном теге, API и атрибутах отслеживания конверсии.', 'Вес вариантов задаёт распределение внутри выбранного охвата аудитории.', 'Черновик не участвует в публичном выводе; перед запуском проверьте каждый вариант.'), 'Изменение цены штатным вариантом влияет только на представление и не меняет сумму заказа.'),
|
||||
self::item('#^/modules/experiments#', 'A/B-тесты', 'Распределяет посетителей между вариантами и проверяет, достаточно ли данных для вывода.', array('Код эксперимента используется в шаблонном теге, API и атрибутах отслеживания конверсии.', 'Вес вариантов задаёт распределение внутри выбранного охвата аудитории.', 'Минимум показов защищает от слишком раннего выбора победителя.', 'После набора выборки панель показывает погрешность, достоверность и устойчивый вариант.'), 'Не останавливайте тест по одному проценту конверсии: дождитесь состояния с достоверным результатом.'),
|
||||
self::item('#^/modules/popups#', 'Всплывающие окна', 'Управляет кампаниями поп-апов, условиями показа, A/B-вариантами и собранными заявками.', array('Сценарий определяет момент показа: задержку, прокрутку или попытку ухода.', 'Пути включения и исключения принимают по одному шаблону на строку; символ * заменяет произвольную часть.', 'HTML вариантов контролируется проектом, а заявки обрабатываются на отдельной вкладке.'), 'Проверьте кампанию на тестовом URL и мобильном экране до включения автоматической вставки.'),
|
||||
self::item('#^/modules/reviews#', 'Отзывы', 'Собирает оценки и отзывы к документам, позволяет модерировать публикацию и отвечать от имени компании.', array('Состояние определяет, попадёт ли отзыв в публичный список.', 'Признак подтверждённой покупки устанавливается только после проверки заказа.', 'Ответ компании сохраняется вместе с отзывом и выводится его публичным шаблоном.'), 'Удаление отзыва необратимо; спорный материал безопаснее сначала отклонить.', 'modules/reviews'),
|
||||
self::item('#^/modules/reviews#', 'Отзывы', 'Собирает оценки и отзывы к документам, позволяет модерировать публикацию и отвечать от имени компании.', array('Состояние определяет, попадёт ли отзыв в публичный список.', 'Признак подтверждённой покупки устанавливается только после проверки заказа.', 'Выберите несколько строк, чтобы опубликовать, отклонить, вернуть на модерацию или удалить их одним действием.', 'Ответ компании сохраняется вместе с отзывом и выводится его публичным шаблоном.'), 'Удаление отзыва необратимо; спорный материал безопаснее сначала отклонить.', 'modules/reviews'),
|
||||
self::item('#^/modules/scheduler#', 'Планировщик', 'Собирает фоновые задачи установленных модулей в единый реестр, запускает их по расписанию и хранит журнал.', array('Защищённый URL добавляется в планировщик хостинга с интервалом в одну минуту.', 'Cron-выражение и активность каждой задачи меняются прямо в таблице.', 'Ручной запуск использует тот же обработчик и попадает в общий журнал.'), 'После смены секретного URL обновите задание на хостинге: старый адрес сразу перестанет работать.'),
|
||||
self::item('#^/modules/search-analytics#', 'Поисковые запросы', 'Показывает реальные поисковые фразы посетителей, частоту запросов и случаи пустой выдачи.', array('Фильтр по области разделяет спрос по новостям, товарам, статьям и другим настроенным областям.', 'Состояние и заметка позволяют отмечать разобранные запросы и планировать новый контент.', 'Показатель «Результатов сейчас» помогает проверить, исправлена ли нулевая выдача.'), 'Очистка истории удаляет аналитические данные, но не затрагивает поисковый индекс.'),
|
||||
self::item('#^/modules/system-health#', 'Мониторинг здоровья', 'Проверяет доступность базы данных, диска, фоновых задач и заданных внешних HTTPS-сервисов.', array('Текущий снимок показывает независимый результат каждой инфраструктурной проверки.', 'История помогает отличить разовый сбой от повторяющейся проблемы.', 'Для внешнего сервиса задаются ожидаемый HTTP-статус и ограниченный таймаут.'), 'Мониторинг фиксирует рабочее состояние, но не заменяет приёмочный чек-лист перед запуском сайта.'),
|
||||
self::item('#^/modules/traffic-analytics#', 'Источники трафика', 'Группирует входящие переходы по UTM-меткам, источникам, кампаниям и посадочным страницам.', array('Период и фильтры одинаково применяются к сводке, таблицам и CSV-экспорту.', 'UTM-конструктор собирает ссылку в браузере и не сохраняет введённые значения.', 'Один вход посетителя на ту же страницу за день агрегируется без хранения IP.'), 'Перед очисткой выбранного периода выгрузите CSV, если данные нужны для отчётности.'),
|
||||
self::item('#^/modules/antispam#', 'Антиспам', 'Настраивает профили защиты публичных форм и показывает журнал отклонённых отправок.', array('Профиль объединяет лимиты, проверку скрытого поля и анализ содержимого для конкретной формы.', 'Журнал объясняет, какое правило остановило запрос, и помогает скорректировать чувствительность.', 'Доверенные исключения применяйте только к контролируемым интеграциям.'), 'Не ослабляйте общий профиль из-за одного ложного срабатывания: создайте отдельный профиль для нужной формы.'),
|
||||
self::item('#^/modules/interactions#', 'Взаимодействия', 'Хранит общий журнал оценок, реакций и голосов, который используют прикладные модули.', array('Канал определяет допустимые действия и типы объектов.', 'Агрегаты ускоряют публичный вывод счётчиков и рейтингов.', 'Пересчёт восстанавливает агрегаты из исходного журнала действий.'), 'Обычно этот раздел не вставляется в шаблон напрямую: публичный интерфейс предоставляют рейтинги, опросы и комментарии.'),
|
||||
self::item('#^/modules/ratings#', 'Рейтинги', 'Добавляет на документы и другие разрешённые объекты настраиваемую шкалу оценок.', array('Документы включают страницы, товары, новости и статьи, построенные на рубриках.', 'Тег [mod_rating] использует текущий документ; явная цель задаётся типом и ID.', 'Кнопки тегов вставляют доступные значения в HTML-шаблон рейтинга.'), 'Голоса и итоговые значения хранятся в модуле «Взаимодействия».'),
|
||||
self::item('#^/modules/comments#', 'Комментарии', 'Управляет древовидными обсуждениями, премодерацией, антиспамом и публичными шаблонами.', array('Разрешите только те типы объектов, на которых действительно нужны обсуждения.', 'Шаблоны списка, комментария и формы имеют собственные наборы тегов.', 'Публикация, скрытие и отметка спама выполняются из общего журнала.'), 'Оценка комментариев использует отдельный канал модуля «Взаимодействия».'),
|
||||
self::item('#^/modules/ratings#', 'Рейтинги', 'Добавляет на документы и другие разрешённые объекты настраиваемую шкалу оценок.', array('Документы включают страницы, товары, новости и статьи, построенные на рубриках.', 'Тег [mod_rating] использует текущий документ; явная цель задаётся типом и ID.', 'Список голосов позволяет удалить ошибочную оценку или сбросить рейтинг объекта.', 'После модерации среднее значение пересчитывается автоматически.'), 'Удаление голосов необратимо и записывается в аудит; сам документ при этом не изменяется.'),
|
||||
self::item('#^/modules/comments#', 'Комментарии', 'Управляет древовидными обсуждениями, премодерацией, антиспамом и публичными шаблонами.', array('Разрешите только те типы объектов, на которых действительно нужны обсуждения.', 'Шаблоны списка, комментария и формы имеют собственные наборы тегов.', 'Публикация, скрытие и отметка спама выполняются из общего журнала.', 'Выбор строк позволяет обработать до 500 комментариев одним массовым действием.'), 'Оценка комментариев использует отдельный канал модуля «Взаимодействия».'),
|
||||
self::item('#^/modules/polls#', 'Опросы', 'Создаёт одиночные и множественные голосования с расписанием, доступом и управляемыми результатами.', array('Для публикации вставьте [mod_poll:ID] в документ, блок или шаблон.', 'Архив опросов доступен по настраиваемому публичному URL.', 'Шаблоны опроса, варианта, результата и архива имеют разные наборы тегов.'), 'Удаление опроса также удаляет варианты ответа и собранные голоса.'),
|
||||
self::item('#^/modules/galleries#', 'Галереи', 'Собирает изображения медиатеки в упорядоченные сетки и слайдеры с собственными публичными URL.', array('Файлы остаются в медиатеке; галерея хранит только связи, подписи и порядок.', 'Тег [mod_gallery:ID] выводит коллекцию в документе, блоке или шаблоне.', 'Отдельные шаблоны управляют оболочкой галереи и разметкой одного изображения.'), 'Удаление галереи не удаляет исходные файлы и созданные для них превью.'),
|
||||
self::item('#^/modules/banners#', 'Баннеры', 'Управляет рекламными местами, ротацией изображений, расписанием и внутренней статистикой переходов.', array('Стабильный код места используется в теге [mod_banner:КОД].', 'Вес влияет только на стратегию «По весу»; равномерная ротация выбирает материал с меньшим числом показов.', 'Изображения выбираются из общей медиатеки и не удаляются вместе с баннером.'), 'Нулевой лимит означает отсутствие ограничения; сброс статистики необратим.'),
|
||||
|
||||
@@ -26,10 +26,12 @@
|
||||
'core.update' => 'Установка подписанного обновления ядра',
|
||||
'stored_php.execute' => 'Выполнение сохранённого PHP-кода',
|
||||
'stored_php.write' => 'Сохранение PHP-кода, исполняемого runtime',
|
||||
'stored_html.write' => 'Сохранение HTML форм и разметки, исполняемых в публичной странице',
|
||||
'theme_assets.write' => 'Изменение исполняемых CSS/JavaScript и файлов публичной темы',
|
||||
'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'),
|
||||
@@ -86,6 +88,12 @@
|
||||
'POST /modules/legacy-migration/runs/{id}/rollback' => array('legacy_migration.execute', 'run_legacy_migration'),
|
||||
'POST /modules/legacy-migration/runs/{id}/files' => array('legacy_migration.execute', 'run_legacy_migration'),
|
||||
'POST /database/backup/restore' => array('database.restore', 'manage_database'),
|
||||
'POST /modules/popups/{id}' => array('stored_html.write', 'manage_popup_code'),
|
||||
'POST /modules/popups/{id}/delete' => array('stored_html.write', 'manage_popup_code'),
|
||||
'POST /modules/popups/settings' => array('stored_html.write', 'manage_popup_code'),
|
||||
'POST /modules/experiments/{id}' => array('stored_html.write', 'manage_experiment_code'),
|
||||
'POST /modules/experiments/{id}/delete' => array('stored_html.write', 'manage_experiment_code'),
|
||||
'POST /modules/experiments/settings' => array('stored_html.write', 'manage_experiment_code'),
|
||||
);
|
||||
|
||||
public static function validate(array $route)
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------------
|
||||
| AVE.cms
|
||||
|--------------------------------------------------------------------------------------
|
||||
| @package AVE.cms
|
||||
| @file adminx/Support/ViewOverrideEditor.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\Support;
|
||||
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Common\Twig;
|
||||
use App\Adminx\Themes\Model;
|
||||
use App\Frontend\ThemeAssets;
|
||||
use App\Helpers\Json;
|
||||
|
||||
/** Safe editor for a fixed set of public Twig view overrides. */
|
||||
class ViewOverrideEditor
|
||||
{
|
||||
protected $namespace;
|
||||
protected $fallbackRoot;
|
||||
protected $fallbackPrefix;
|
||||
protected $definitions;
|
||||
|
||||
public function __construct($namespace, $fallbackRoot, $fallbackPrefix, array $definitions)
|
||||
{
|
||||
$namespace = trim((string) $namespace);
|
||||
if (!preg_match('/^[A-Za-z][A-Za-z0-9_]{0,63}$/', $namespace)) {
|
||||
throw new \InvalidArgumentException('Некорректное пространство публичных шаблонов');
|
||||
}
|
||||
|
||||
$this->namespace = $namespace;
|
||||
$this->fallbackRoot = rtrim(str_replace('\\', '/', (string) $fallbackRoot), '/');
|
||||
$this->fallbackPrefix = trim(str_replace('\\', '/', (string) $fallbackPrefix), '/');
|
||||
$this->definitions = $this->normalizeDefinitions($definitions);
|
||||
}
|
||||
|
||||
public function all()
|
||||
{
|
||||
$out = array();
|
||||
foreach ($this->definitions as $code => $definition) {
|
||||
$out[] = $this->describe($code, $definition);
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function one($code)
|
||||
{
|
||||
$code = trim((string) $code);
|
||||
if ($code === '' || !isset($this->definitions[$code])) {
|
||||
$code = (string) key($this->definitions);
|
||||
}
|
||||
|
||||
return $this->describe($code, $this->definitions[$code], true);
|
||||
}
|
||||
|
||||
public function save($code, $content, $authorId, $action = 'public-view')
|
||||
{
|
||||
$this->assertCode($code);
|
||||
$item = $this->one($code);
|
||||
$syntax = $this->lint($content, $code);
|
||||
if (empty($syntax['ok'])) {
|
||||
throw new \InvalidArgumentException($syntax['message']);
|
||||
}
|
||||
|
||||
Model::saveFile($item['theme'], $item['theme_path'], (string) $content, (int) $authorId, $action);
|
||||
$this->ensureNamespace($item['theme'], (int) $authorId);
|
||||
return $this->one($item['code']);
|
||||
}
|
||||
|
||||
public function deleteOverride($code, $authorId)
|
||||
{
|
||||
$this->assertCode($code);
|
||||
$item = $this->one($code);
|
||||
if (empty($item['has_fallback'])) {
|
||||
throw new \RuntimeException('Для этого шаблона нет резервной версии');
|
||||
}
|
||||
|
||||
if (empty($item['has_theme_file'])) {
|
||||
throw new \RuntimeException('Переопределение темы не найдено');
|
||||
}
|
||||
|
||||
Model::deletePath($item['theme'], $item['theme_path'], (int) $authorId);
|
||||
return $this->one($item['code']);
|
||||
}
|
||||
|
||||
public function lint($content, $code = 'template')
|
||||
{
|
||||
$content = (string) $content;
|
||||
if (trim($content) === '') {
|
||||
return array('ok' => false, 'message' => 'Twig-шаблон не может быть пустым');
|
||||
}
|
||||
|
||||
try {
|
||||
ThemeAssets::registerViewOverrides();
|
||||
Twig::twig()->createTemplate($content, 'public_view_' . preg_replace('/[^a-z0-9_]/i', '_', (string) $code));
|
||||
} catch (\Throwable $e) {
|
||||
return array('ok' => false, 'message' => 'Ошибка Twig: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
return array('ok' => true, 'message' => 'Twig-синтаксис корректен');
|
||||
}
|
||||
|
||||
protected function describe($code, array $definition, $includeContent = false)
|
||||
{
|
||||
$theme = ThemeAssets::currentTheme();
|
||||
$themePath = 'views/' . $this->namespace . '/' . $definition['file'];
|
||||
$themeFile = BASEPATH . '/templates/' . $theme . '/' . $themePath;
|
||||
$fallbackFile = $this->fallbackRoot !== '' ? $this->fallbackRoot . '/' . $definition['file'] : '';
|
||||
$manifest = ThemeAssets::manifest($theme);
|
||||
$namespaceEnabled = in_array($this->namespace, isset($manifest['view_overrides']) ? $manifest['view_overrides'] : array(), true);
|
||||
$hasThemeFile = is_file($themeFile) && is_readable($themeFile);
|
||||
$hasFallback = $fallbackFile !== '' && is_file($fallbackFile) && is_readable($fallbackFile);
|
||||
$activeOverride = $namespaceEnabled && $hasThemeFile;
|
||||
$source = $activeOverride ? 'theme' : ($hasThemeFile ? 'theme_disabled' : ($hasFallback ? 'fallback' : 'missing'));
|
||||
$item = array_merge($definition, array(
|
||||
'code' => $code,
|
||||
'namespace' => $this->namespace,
|
||||
'theme' => $theme,
|
||||
'theme_path' => $themePath,
|
||||
'fallback_path' => $this->fallbackPrefix !== '' ? $this->fallbackPrefix . '/' . $definition['file'] : '',
|
||||
'has_theme_file' => $hasThemeFile,
|
||||
'has_fallback' => $hasFallback,
|
||||
'can_delete_override' => $hasThemeFile && $hasFallback,
|
||||
'namespace_enabled' => $namespaceEnabled,
|
||||
'active_override' => $activeOverride,
|
||||
'source' => $source,
|
||||
'source_label' => $activeOverride ? 'Активная тема' : ($hasThemeFile ? 'Файл темы отключён' : ($hasFallback ? 'Резерв компонента' : 'Файл отсутствует')),
|
||||
'modified_label' => $hasThemeFile ? date('d.m.Y H:i', (int) filemtime($themeFile)) : ($hasFallback ? date('d.m.Y H:i', (int) filemtime($fallbackFile)) : ''),
|
||||
));
|
||||
|
||||
if ($includeContent) {
|
||||
$sourceFile = $hasThemeFile ? $themeFile : $fallbackFile;
|
||||
$item['content'] = $sourceFile !== '' && is_file($sourceFile) ? (string) file_get_contents($sourceFile) : '';
|
||||
$item['fallback_content'] = $hasFallback ? (string) file_get_contents($fallbackFile) : '';
|
||||
}
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
protected function ensureNamespace($theme, $authorId)
|
||||
{
|
||||
$manifest = ThemeAssets::manifest($theme);
|
||||
$overrides = isset($manifest['view_overrides']) && is_array($manifest['view_overrides'])
|
||||
? $manifest['view_overrides']
|
||||
: array();
|
||||
if (in_array($this->namespace, $overrides, true)) { return; }
|
||||
|
||||
$overrides[] = $this->namespace;
|
||||
$manifest['view_overrides'] = array_values(array_unique($overrides));
|
||||
Model::saveFile(
|
||||
$theme,
|
||||
ThemeAssets::MANIFEST,
|
||||
Json::encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n",
|
||||
(int) $authorId,
|
||||
'public-view-namespace'
|
||||
);
|
||||
}
|
||||
|
||||
protected function assertCode($code)
|
||||
{
|
||||
if (!isset($this->definitions[trim((string) $code)])) {
|
||||
throw new \InvalidArgumentException('Публичный шаблон не найден');
|
||||
}
|
||||
}
|
||||
|
||||
protected function normalizeDefinitions(array $definitions)
|
||||
{
|
||||
$out = array();
|
||||
foreach ($definitions as $code => $definition) {
|
||||
$code = trim((string) $code);
|
||||
$file = isset($definition['file']) ? ThemeAssets::normalizePath($definition['file']) : '';
|
||||
if (!preg_match('/^[a-z][a-z0-9_-]{0,63}$/', $code) || $file === '' || substr($file, -5) !== '.twig') {
|
||||
throw new \InvalidArgumentException('Некорректное описание публичного шаблона');
|
||||
}
|
||||
|
||||
$definition['file'] = $file;
|
||||
$definition['title'] = isset($definition['title']) ? (string) $definition['title'] : $code;
|
||||
$definition['description'] = isset($definition['description']) ? (string) $definition['description'] : '';
|
||||
$definition['icon'] = isset($definition['icon']) ? (string) $definition['icon'] : 'ti ti-template';
|
||||
$definition['group'] = isset($definition['group']) ? (string) $definition['group'] : '';
|
||||
$definition['variables'] = isset($definition['variables']) && is_array($definition['variables']) ? $definition['variables'] : array();
|
||||
$out[$code] = $definition;
|
||||
}
|
||||
|
||||
if (!$out) { throw new \InvalidArgumentException('Реестр публичных шаблонов пуст'); }
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------------
|
||||
| AVE.cms
|
||||
|--------------------------------------------------------------------------------------
|
||||
| @package AVE.cms
|
||||
| @file adminx/Support/WorkItemContext.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\Support;
|
||||
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Common\SystemTables;
|
||||
use App\Common\Permission;
|
||||
use App\Content\ContentTables;
|
||||
use App\Content\Documents\DocumentPickerRepository;
|
||||
use DB;
|
||||
|
||||
/** Shared assignee and document context for panel work items. */
|
||||
class WorkItemContext
|
||||
{
|
||||
public static function users()
|
||||
{
|
||||
$rows = DB::query(
|
||||
'SELECT id,name,email FROM ' . SystemTables::table('users')
|
||||
. ' WHERE is_active=1 ORDER BY name,email,id'
|
||||
)->getAll();
|
||||
$result = array();
|
||||
foreach ($rows ?: array() as $row) {
|
||||
$result[] = array(
|
||||
'id' => (int) $row['id'],
|
||||
'name' => trim((string) $row['name']) !== '' ? (string) $row['name'] : (string) $row['email'],
|
||||
'email' => (string) $row['email'],
|
||||
);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public static function assignee($userId)
|
||||
{
|
||||
$userId = max(0, (int) $userId);
|
||||
if ($userId < 1) { return 0; }
|
||||
return (int) DB::query(
|
||||
'SELECT id FROM ' . SystemTables::table('users') . ' WHERE id=%i AND is_active=1 LIMIT 1',
|
||||
$userId
|
||||
)->getValue();
|
||||
}
|
||||
|
||||
public static function documents($query, $limit = 20)
|
||||
{
|
||||
if (!Permission::check('view_documents')) { return array(); }
|
||||
return (new DocumentPickerRepository())->search($query, array(), $limit);
|
||||
}
|
||||
|
||||
public static function target($type, $id)
|
||||
{
|
||||
if (!Permission::check('view_documents')) { return array('', 0); }
|
||||
$type = strtolower(trim((string) $type));
|
||||
$id = max(0, (int) $id);
|
||||
if ($type !== 'document' || $id < 1) { return array('', 0); }
|
||||
$exists = (int) DB::query(
|
||||
'SELECT Id FROM ' . ContentTables::table('documents') . ' WHERE Id=%i AND document_deleted!=%s LIMIT 1',
|
||||
$id,
|
||||
'1'
|
||||
)->getValue();
|
||||
return $exists > 0 ? array('document', $exists) : array('', 0);
|
||||
}
|
||||
|
||||
public static function decorateTargets(array &$items)
|
||||
{
|
||||
if (!Permission::check('view_documents')) { return; }
|
||||
$ids = array();
|
||||
foreach ($items as $item) {
|
||||
if (isset($item['target_type'], $item['target_id']) && $item['target_type'] === 'document' && (int) $item['target_id'] > 0) {
|
||||
$ids[(int) $item['target_id']] = (int) $item['target_id'];
|
||||
}
|
||||
}
|
||||
|
||||
$documents = array();
|
||||
if ($ids) {
|
||||
$rows = DB::query(
|
||||
'SELECT Id,document_title,document_alias FROM ' . ContentTables::table('documents')
|
||||
. ' WHERE Id IN (' . implode(',', $ids) . ') AND document_deleted!=%s',
|
||||
'1'
|
||||
)->getAll();
|
||||
foreach ($rows ?: array() as $row) { $documents[(int) $row['Id']] = $row; }
|
||||
}
|
||||
|
||||
foreach ($items as &$item) {
|
||||
$item['target_title'] = '';
|
||||
$item['target_alias'] = '';
|
||||
$item['target_url'] = '';
|
||||
$id = isset($item['target_id']) ? (int) $item['target_id'] : 0;
|
||||
if (!isset($documents[$id])) { continue; }
|
||||
$item['target_title'] = htmlspecialchars_decode((string) $documents[$id]['document_title'], ENT_QUOTES);
|
||||
$item['target_alias'] = (string) $documents[$id]['document_alias'];
|
||||
$item['target_url'] = rtrim(ADMINX_BASE, '/') . '/documents/' . $id . '/edit';
|
||||
}
|
||||
|
||||
unset($item);
|
||||
}
|
||||
|
||||
public static function dueAt($value)
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
if ($value === '') { return 0; }
|
||||
$timestamp = strtotime($value);
|
||||
return $timestamp === false ? 0 : max(0, (int) $timestamp);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -5088,6 +5373,30 @@ ul.sortable {
|
||||
flex: 0 0 auto;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.media-picker-manage {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.media-picker-manage[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.media-picker-folder-form {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.media-picker-folder-form[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.media-picker-folder-form .input-wrap {
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
.media-picker-folder-form .btn-icon {
|
||||
min-width: 40px;
|
||||
}
|
||||
.media-picker-url {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
@@ -5279,6 +5588,20 @@ ul.sortable {
|
||||
.media-picker-tools .media-picker-search {
|
||||
flex-basis: calc(100% - 50px);
|
||||
}
|
||||
.media-picker-manage {
|
||||
width: 100%;
|
||||
}
|
||||
.media-picker-manage .btn-primary {
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
.media-picker-folder-form {
|
||||
align-items: stretch;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.media-picker-folder-form .input-wrap {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
.media-picker-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
+170
-8
@@ -221,6 +221,87 @@
|
||||
}
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ //
|
||||
// Простые формы модулей: стандартный Ajax-контракт без отдельного JS.
|
||||
// ------------------------------------------------------------------ //
|
||||
Adminx.initAjaxForms = function () {
|
||||
document.addEventListener('submit', function (event) {
|
||||
var form = event.target.closest ? event.target.closest('form[data-ax-ajax-form]') : null;
|
||||
if (!form || form.getAttribute('data-ax-submitting') === '1') { return; }
|
||||
event.preventDefault();
|
||||
|
||||
var submit = event.submitter || form.querySelector('button[type="submit"],input[type="submit"]');
|
||||
var data = new FormData(form);
|
||||
if (submit && submit.name && !data.has(submit.name)) { data.append(submit.name, submit.value || '1'); }
|
||||
|
||||
form.setAttribute('data-ax-submitting', '1');
|
||||
form.setAttribute('aria-busy', 'true');
|
||||
if (submit) { submit.disabled = true; }
|
||||
Adminx.Loader.show();
|
||||
|
||||
Adminx.Ajax.request(form.getAttribute('action') || window.location.href, {
|
||||
method: (form.getAttribute('method') || 'POST').toUpperCase(),
|
||||
body: data
|
||||
}).then(function (payload) {
|
||||
var response = Adminx.Ajax.handle(payload);
|
||||
if (payload.ok && response.success !== false) {
|
||||
form.dispatchEvent(new CustomEvent('adminx:form-saved', { bubbles: true, detail: response }));
|
||||
if (form.hasAttribute('data-ax-reset-on-success')) { form.reset(); }
|
||||
}
|
||||
}).catch(function (error) {
|
||||
Adminx.Toast.show(error && error.message ? error.message : Adminx.t('server_unavailable', 'Сервер недоступен. Повторите попытку.'), 'error');
|
||||
}).then(function () {
|
||||
Adminx.Loader.hide();
|
||||
form.removeAttribute('data-ax-submitting');
|
||||
form.removeAttribute('aria-busy');
|
||||
if (submit) { submit.disabled = false; }
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ //
|
||||
// Пакетная загрузка обходит серверный max_file_uploads без изменения php.ini.
|
||||
// ------------------------------------------------------------------ //
|
||||
Adminx.Upload = {
|
||||
BATCH_SIZE: 20,
|
||||
|
||||
files: function (url, files, makeData, onProgress) {
|
||||
files = Array.prototype.slice.call(files || []);
|
||||
if (!files.length) { return Promise.resolve({ files: [], batches: 0, total: 0 }); }
|
||||
|
||||
var self = this;
|
||||
var uploaded = [];
|
||||
var batches = Math.ceil(files.length / self.BATCH_SIZE);
|
||||
var run = function (batch) {
|
||||
if (batch >= batches) {
|
||||
return Promise.resolve({ files: uploaded, batches: batches, total: files.length });
|
||||
}
|
||||
|
||||
var start = batch * self.BATCH_SIZE;
|
||||
var chunk = files.slice(start, start + self.BATCH_SIZE);
|
||||
var data = makeData(chunk, batch, batches);
|
||||
return Adminx.Ajax.post(url, data).then(function (payload) {
|
||||
var response = payload.data || {};
|
||||
if (!payload.ok || response.success === false) {
|
||||
var error = new Error(response.message || 'Не удалось загрузить файлы');
|
||||
error.uploaded = uploaded.slice();
|
||||
error.batch = batch;
|
||||
throw error;
|
||||
}
|
||||
|
||||
var result = response.data || {};
|
||||
uploaded = uploaded.concat(result.files || []);
|
||||
if (typeof onProgress === 'function') {
|
||||
onProgress(Math.min(start + chunk.length, files.length), files.length, uploaded.length, response);
|
||||
}
|
||||
return run(batch + 1);
|
||||
});
|
||||
};
|
||||
|
||||
return run(0);
|
||||
}
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ //
|
||||
Adminx.Sidebar = {
|
||||
KEY: 'adminx-sidebar',
|
||||
@@ -407,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 вручную (над триггером),
|
||||
@@ -575,6 +703,8 @@
|
||||
// cancelLabel, onConfirm });
|
||||
// ------------------------------------------------------------------ //
|
||||
Adminx.Confirm = {
|
||||
active: null,
|
||||
|
||||
ICONS: {
|
||||
info: ['info', 'ti-info-circle'],
|
||||
success: ['success', 'ti-circle-check'],
|
||||
@@ -584,6 +714,11 @@
|
||||
|
||||
open: function (cfg) {
|
||||
cfg = cfg || {};
|
||||
if (this.active) {
|
||||
this.active.focus();
|
||||
return false;
|
||||
}
|
||||
|
||||
var kind = this.ICONS[cfg.kind] ? cfg.kind : 'warning';
|
||||
var ic = this.ICONS[kind];
|
||||
|
||||
@@ -615,21 +750,46 @@
|
||||
requestAnimationFrame(function () { overlay.classList.add('show'); });
|
||||
|
||||
var self = this;
|
||||
var close = function () {
|
||||
var previousFocus = document.activeElement;
|
||||
var confirmButton = modal.querySelector('[data-ok]');
|
||||
var settled = false;
|
||||
var finish = function (confirmed) {
|
||||
if (settled) { return; }
|
||||
settled = true;
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
self.active = null;
|
||||
overlay.classList.remove('show');
|
||||
setTimeout(function () { overlay.remove(); document.removeEventListener('keydown', onKey); }, 180);
|
||||
setTimeout(function () {
|
||||
overlay.remove();
|
||||
if (!confirmed && previousFocus && document.contains(previousFocus)) {
|
||||
previousFocus.focus();
|
||||
}
|
||||
}, 180);
|
||||
if (confirmed && typeof cfg.onConfirm === 'function') {
|
||||
cfg.onConfirm();
|
||||
}
|
||||
};
|
||||
var onKey = function (e) {
|
||||
if (e.key !== 'Escape' && e.key !== 'Enter') { return; }
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (typeof e.stopImmediatePropagation === 'function') { e.stopImmediatePropagation(); }
|
||||
finish(e.key === 'Enter');
|
||||
};
|
||||
var onKey = function (e) { if (e.key === 'Escape') { close(); } };
|
||||
|
||||
overlay.addEventListener('click', function (e) {
|
||||
if (e.target === overlay || e.target.closest('[data-cancel]')) { close(); return; }
|
||||
if (e.target === overlay || e.target.closest('[data-cancel]')) { finish(false); return; }
|
||||
if (e.target.closest('[data-ok]')) {
|
||||
close();
|
||||
if (typeof cfg.onConfirm === 'function') { cfg.onConfirm(); }
|
||||
finish(true);
|
||||
}
|
||||
});
|
||||
document.addEventListener('keydown', onKey);
|
||||
modal.querySelector('[data-ok]').focus();
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
this.active = {
|
||||
focus: function () { confirmButton.focus(); },
|
||||
close: function () { finish(false); }
|
||||
};
|
||||
confirmButton.focus();
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -864,10 +1024,12 @@
|
||||
Adminx.Sidebar.init();
|
||||
Adminx.Theme.init();
|
||||
Adminx.Dropdown.init();
|
||||
Adminx.NotificationPreferences.init();
|
||||
Adminx.SidebarUser.init();
|
||||
Adminx.Tabs.init();
|
||||
Adminx.Drawer.init();
|
||||
Adminx.Tooltip.init();
|
||||
Adminx.initAjaxForms();
|
||||
Adminx.initLogout();
|
||||
Adminx.initCopyTag();
|
||||
Adminx.initSectionHelp();
|
||||
|
||||
@@ -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
@@ -47,8 +47,14 @@
|
||||
+ '<div class="media-picker-tools">'
|
||||
+ '<div class="input-wrap media-picker-search"><i class="ti ti-search"></i><input class="input" type="search" placeholder="' + placeholder + '" data-mp-search></div>'
|
||||
+ '<button class="btn btn-ghost btn-icon" type="button" data-mp-up data-tooltip="На уровень выше" aria-label="На уровень выше"><i class="ti ti-arrow-up"></i></button>'
|
||||
+ '<div class="media-picker-manage" data-mp-manage hidden>'
|
||||
+ '<button class="btn btn-secondary btn-icon" type="button" data-mp-folder-toggle data-tooltip="Создать папку" aria-label="Создать папку"><i class="ti ti-folder-plus"></i></button>'
|
||||
+ '<button class="btn btn-primary" type="button" data-mp-upload><i class="ti ti-upload"></i>' + (type === 'image' ? 'Загрузить изображения' : 'Загрузить файлы') + '</button>'
|
||||
+ '<input type="file" data-mp-upload-input multiple hidden' + (type === 'image' ? ' accept="image/*"' : '') + '>'
|
||||
+ '</div>'
|
||||
+ (onUrl ? '<button class="btn btn-ghost btn-sm" type="button" data-mp-url-toggle><i class="ti ti-link"></i>По ссылке</button>' : '')
|
||||
+ '</div>'
|
||||
+ '<div class="media-picker-folder-form" data-mp-folder-form hidden><span class="input-wrap"><i class="ti ti-folder"></i><input class="input" type="text" maxlength="120" placeholder="Название новой папки" data-mp-folder-name></span><button class="btn btn-primary btn-sm" type="button" data-mp-folder-create><i class="ti ti-check"></i>Создать</button><button class="btn btn-ghost btn-icon btn-sm" type="button" data-mp-folder-cancel aria-label="Отмена" data-tooltip="Отмена"><i class="ti ti-x"></i></button></div>'
|
||||
+ (onUrl ? '<div class="media-picker-url" data-mp-url hidden><input class="input" type="url" placeholder="https://…" data-mp-url-input><button class="btn btn-primary btn-sm" type="button" data-mp-url-apply><i class="ti ti-check"></i>Вставить</button></div>' : '')
|
||||
+ '<div class="media-picker-crumbs" data-mp-crumbs></div>'
|
||||
+ '<div class="media-picker-status" data-mp-status>Загрузка…</div>'
|
||||
@@ -63,12 +69,16 @@
|
||||
document.body.appendChild(overlay);
|
||||
window.requestAnimationFrame(function () { overlay.classList.add('show'); });
|
||||
|
||||
var state = { dir: options.dir || '/uploads', parent: '', page: 1, pages: 1, q: '', type: type };
|
||||
var state = { dir: options.dir || '/uploads', parent: '', page: 1, pages: 1, q: '', type: type, canManage: false, busy: false };
|
||||
var grid = overlay.querySelector('[data-mp-grid]');
|
||||
var crumbs = overlay.querySelector('[data-mp-crumbs]');
|
||||
var status = overlay.querySelector('[data-mp-status]');
|
||||
var count = overlay.querySelector('[data-mp-count]');
|
||||
var search = overlay.querySelector('[data-mp-search]');
|
||||
var manage = overlay.querySelector('[data-mp-manage]');
|
||||
var uploadInput = overlay.querySelector('[data-mp-upload-input]');
|
||||
var folderForm = overlay.querySelector('[data-mp-folder-form]');
|
||||
var folderName = overlay.querySelector('[data-mp-folder-name]');
|
||||
var timer = null;
|
||||
|
||||
function close() {
|
||||
@@ -89,6 +99,8 @@
|
||||
var folders = data.folders || [];
|
||||
var files = data.files || [];
|
||||
renderCrumbs(data.breadcrumbs || []);
|
||||
state.canManage = !!data.can_manage;
|
||||
manage.hidden = !state.canManage;
|
||||
grid.innerHTML = '';
|
||||
folders.forEach(function (folder) {
|
||||
var folderMeta = state.q
|
||||
@@ -111,6 +123,74 @@
|
||||
overlay.querySelector('[data-mp-up]').disabled = !state.parent;
|
||||
}
|
||||
|
||||
function responseData(payload) {
|
||||
var response = payload && payload.data ? payload.data : {};
|
||||
if (!payload || !payload.ok || response.success === false) {
|
||||
throw new Error(response.message || (response.error && response.error.message) || 'Не удалось выполнить действие');
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
function setBusy(value, message) {
|
||||
state.busy = !!value;
|
||||
manage.querySelectorAll('button').forEach(function (button) { button.disabled = state.busy; });
|
||||
status.hidden = !message;
|
||||
if (message) { status.textContent = message; }
|
||||
}
|
||||
|
||||
function clearSearch() {
|
||||
state.q = '';
|
||||
search.value = '';
|
||||
}
|
||||
|
||||
function createFolder() {
|
||||
var name = folderName.value.trim();
|
||||
if (!name || state.busy) { folderName.focus(); return; }
|
||||
var data = new FormData();
|
||||
data.set('_csrf', Adminx.csrf());
|
||||
data.set('dir', state.dir);
|
||||
data.set('name', name);
|
||||
setBusy(true, 'Создаём папку…');
|
||||
Adminx.Ajax.post(base + '/media/folders', data).then(responseData).then(function (response) {
|
||||
var result = response.data || {};
|
||||
folderForm.hidden = true;
|
||||
folderName.value = '';
|
||||
clearSearch();
|
||||
Adminx.Toast.show(response.message || 'Папка создана', 'success');
|
||||
load(result.path || state.dir, 1);
|
||||
}).catch(function (error) {
|
||||
setBusy(false, '');
|
||||
Adminx.Toast.show(error.message || 'Не удалось создать папку', 'error');
|
||||
folderName.focus();
|
||||
});
|
||||
}
|
||||
|
||||
function upload(files) {
|
||||
if (!files || !files.length || state.busy) { return; }
|
||||
setBusy(true, 'Подготовка к загрузке: ' + files.length + '…');
|
||||
Adminx.Upload.files(base + '/media/upload', files, function (chunk) {
|
||||
var data = new FormData();
|
||||
data.set('_csrf', Adminx.csrf());
|
||||
data.set('dir', state.dir);
|
||||
chunk.forEach(function (file) { data.append('files[]', file); });
|
||||
return data;
|
||||
}, function (processed, total) {
|
||||
status.textContent = 'Загружено: ' + processed + ' из ' + total + '…';
|
||||
}).then(function (result) {
|
||||
uploadInput.value = '';
|
||||
clearSearch();
|
||||
Adminx.Toast.show('Загружено файлов: ' + result.files.length, 'success');
|
||||
load(state.dir, 1);
|
||||
}).catch(function (error) {
|
||||
uploadInput.value = '';
|
||||
setBusy(false, '');
|
||||
var uploaded = error && error.uploaded ? error.uploaded.length : 0;
|
||||
var message = error.message || 'Не удалось загрузить файлы';
|
||||
if (uploaded) { message += '. До ошибки загружено: ' + uploaded; }
|
||||
Adminx.Toast.show(message, 'error');
|
||||
});
|
||||
}
|
||||
|
||||
function load(dir, page) {
|
||||
state.dir = dir || state.dir;
|
||||
state.page = page || 1;
|
||||
@@ -131,9 +211,10 @@
|
||||
state.parent = data.parent_dir || '';
|
||||
state.page = data.page || 1;
|
||||
state.pages = data.pages || 1;
|
||||
setBusy(false, '');
|
||||
render(data);
|
||||
})
|
||||
.catch(function () { status.textContent = 'Не удалось загрузить медиа'; status.hidden = false; });
|
||||
.catch(function () { setBusy(false, ''); status.textContent = 'Не удалось загрузить медиа'; status.hidden = false; });
|
||||
}
|
||||
|
||||
overlay.addEventListener('click', function (e) {
|
||||
@@ -146,6 +227,10 @@
|
||||
if (e.target.closest('[data-mp-prev]') && state.page > 1) { load(state.dir, state.page - 1); }
|
||||
if (e.target.closest('[data-mp-next]') && state.page < state.pages) { load(state.dir, state.page + 1); }
|
||||
if (e.target.closest('[data-mp-up]') && state.parent) { load(state.parent, 1); }
|
||||
if (e.target.closest('[data-mp-folder-toggle]')) { folderForm.hidden = !folderForm.hidden; if (!folderForm.hidden) { folderName.focus(); } return; }
|
||||
if (e.target.closest('[data-mp-folder-cancel]')) { folderForm.hidden = true; folderName.value = ''; return; }
|
||||
if (e.target.closest('[data-mp-folder-create]')) { createFolder(); return; }
|
||||
if (e.target.closest('[data-mp-upload]')) { uploadInput.click(); return; }
|
||||
if (onUrl) {
|
||||
if (e.target.closest('[data-mp-url-toggle]')) {
|
||||
var box = overlay.querySelector('[data-mp-url]');
|
||||
@@ -163,6 +248,10 @@
|
||||
window.clearTimeout(timer);
|
||||
timer = window.setTimeout(function () { state.q = search.value.trim(); load(state.dir, 1); }, 220);
|
||||
});
|
||||
folderName.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter') { e.preventDefault(); createFolder(); }
|
||||
});
|
||||
uploadInput.addEventListener('change', function () { upload(uploadInput.files); });
|
||||
document.addEventListener('keydown', onKey);
|
||||
load(state.dir, 1);
|
||||
search.focus();
|
||||
|
||||
@@ -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,32 +440,58 @@ 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;
|
||||
}
|
||||
},
|
||||
|
||||
bindForm: function (textarea, editor) {
|
||||
var form = textarea.closest('form');
|
||||
var self = this;
|
||||
if (!form) { return; }
|
||||
form.addEventListener('submit', function () {
|
||||
var root = textarea.closest('.rich-editor');
|
||||
if (root && root.classList.contains('rich-editor-source-open') && root._richSourceEditor) {
|
||||
root._richSourceEditor.save();
|
||||
textarea.value = root._richSourceEditor.getValue();
|
||||
return;
|
||||
}
|
||||
if (textarea.getAttribute('data-rich-editor-dirty') === '1') {
|
||||
textarea.value = editor.getHTML();
|
||||
}
|
||||
self.syncTextarea(textarea, editor);
|
||||
});
|
||||
},
|
||||
|
||||
syncTextarea: function (textarea, editor) {
|
||||
var root;
|
||||
if (!textarea) { return ''; }
|
||||
root = textarea.closest('.rich-editor');
|
||||
if (root && root.classList.contains('rich-editor-source-open') && root._richSourceEditor) {
|
||||
root._richSourceEditor.save();
|
||||
textarea.value = root._richSourceEditor.getValue();
|
||||
textarea.setAttribute('data-rich-editor-dirty', '1');
|
||||
return textarea.value;
|
||||
}
|
||||
if (editor && textarea.getAttribute('data-rich-editor-dirty') === '1') {
|
||||
textarea.value = editor.getHTML();
|
||||
}
|
||||
return textarea.value;
|
||||
},
|
||||
|
||||
openSource: function (editor) {
|
||||
var root = editor.view.dom.closest('.rich-editor');
|
||||
if (!root || !window.CodeMirror) { return; }
|
||||
@@ -319,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;
|
||||
}
|
||||
@@ -343,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;
|
||||
});
|
||||
},
|
||||
|
||||
+50
-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,19 @@
|
||||
|
||||
$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()) {
|
||||
Response::json(array(
|
||||
'success' => false,
|
||||
'message' => 'Сначала смените временный пароль.',
|
||||
'redirect' => ADMINX_BASE . '/account/password',
|
||||
), 428);
|
||||
}
|
||||
|
||||
Request::redirect(ADMINX_BASE . '/account/password');
|
||||
}
|
||||
|
||||
//-- Пункты меню для layout: фильтр по правам + активный пункт + абсолютный href.
|
||||
$navFlat = [];
|
||||
@@ -195,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; }
|
||||
@@ -208,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) {
|
||||
@@ -225,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,
|
||||
@@ -237,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);
|
||||
@@ -245,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>
|
||||
|
||||
@@ -57,6 +57,16 @@
|
||||
$login = Request::postStr('login');
|
||||
$password = (string) Request::post('password', '');
|
||||
$remember = Request::postBool('remember', false);
|
||||
$identityKey = 'admin-login-user:' . hash('sha256', mb_strtolower(trim($login), 'UTF-8'));
|
||||
$ipKey = 'admin-login-ip:' . Request::ip();
|
||||
if (RateLimiter::tooManyAttempts($identityKey, 5) || RateLimiter::tooManyAttempts($ipKey, 20)) {
|
||||
$this->auditLoginFailure($login, 'rate_limit');
|
||||
$wait = max(RateLimiter::availableIn($identityKey), RateLimiter::availableIn($ipKey));
|
||||
return $this->render('@auth/login.twig', array(
|
||||
'error' => 'Слишком много попыток входа. Повторите через ' . max(1, $wait) . ' сек.',
|
||||
'login_prev' => $login,
|
||||
));
|
||||
}
|
||||
|
||||
//-- Современный Auth API (SystemTables users: email/password_hash/role).
|
||||
//-- Вход по email или логину; запоминание — по флажку.
|
||||
@@ -68,19 +78,20 @@
|
||||
$result = Auth::attempt($login, $password, $options);
|
||||
|
||||
if (is_array($result)) {
|
||||
Session::regenerateCsrf();
|
||||
$this->redirect($this->base() . '/');
|
||||
return null;
|
||||
return $this->loginCompleted($result, $identityKey, $ipKey);
|
||||
}
|
||||
|
||||
//-- Legacy-пароль (перенесённые пользователи, md5(md5(pass+salt))):
|
||||
//-- проверяем и молча перехешируем в bcrypt при первом входе.
|
||||
if ($this->legacyLogin($login, $password, $options)) {
|
||||
Session::regenerateCsrf();
|
||||
$this->redirect($this->base() . '/');
|
||||
return null;
|
||||
$legacyUser = $this->legacyLogin($login, $password, $options);
|
||||
if (is_array($legacyUser)) {
|
||||
return $this->loginCompleted($legacyUser, $identityKey, $ipKey);
|
||||
}
|
||||
|
||||
RateLimiter::hit($identityKey, 600);
|
||||
RateLimiter::hit($ipKey, 600);
|
||||
$this->auditLoginFailure($login, isset($result) ? (string) $result : 'failed');
|
||||
|
||||
$messages = [
|
||||
1 => AdminLocale::text('auth_err_required', 'Введите логин или email и пароль.'),
|
||||
2 => AdminLocale::text('auth_err_invalid', 'Неверный логин или пароль.'),
|
||||
@@ -96,6 +107,61 @@
|
||||
]);
|
||||
}
|
||||
|
||||
/** GET /account/password — mandatory temporary-password replacement. */
|
||||
public function passwordForm(array $params = array())
|
||||
{
|
||||
$user = Auth::user();
|
||||
if (!$user) { $this->redirect($this->base() . '/login'); return null; }
|
||||
|
||||
return $this->render('@auth/password.twig', array(
|
||||
'error' => '',
|
||||
'user' => $user,
|
||||
));
|
||||
}
|
||||
|
||||
/** POST /account/password — finish a forced password change. */
|
||||
public function changePassword(array $params = array())
|
||||
{
|
||||
$user = Auth::user();
|
||||
if (!$user) { $this->redirect($this->base() . '/login'); return null; }
|
||||
try {
|
||||
$this->verifyCsrf();
|
||||
} catch (\RuntimeException $e) {
|
||||
return $this->render('@auth/password.twig', array(
|
||||
'error' => 'Сессия устарела, обновите страницу и попробуйте снова.', 'user' => $user,
|
||||
));
|
||||
}
|
||||
|
||||
$current = (string) Request::post('current_password', '');
|
||||
$password = (string) Request::post('password', '');
|
||||
$confirm = (string) Request::post('password_confirm', '');
|
||||
$error = '';
|
||||
if (!password_verify($current, (string) $user['password_hash'])) {
|
||||
$error = 'Текущий пароль указан неверно.';
|
||||
} elseif (mb_strlen($password, 'UTF-8') < 8) {
|
||||
$error = 'Новый пароль должен содержать не меньше 8 символов.';
|
||||
} elseif (!hash_equals($password, $confirm)) {
|
||||
$error = 'Новые пароли не совпадают.';
|
||||
} elseif (password_verify($password, (string) $user['password_hash'])) {
|
||||
$error = 'Новый пароль должен отличаться от временного.';
|
||||
}
|
||||
|
||||
if ($error !== '') {
|
||||
return $this->render('@auth/password.twig', array('error' => $error, 'user' => $user));
|
||||
}
|
||||
|
||||
\App\Adminx\Users\Model::completePasswordChange((int) $user['id'], $password);
|
||||
AuditLog::record('auth.password_changed', array(
|
||||
'actor_id' => (int) $user['id'],
|
||||
'actor_name' => isset($user['name']) ? (string) $user['name'] : '',
|
||||
'target_type' => 'user',
|
||||
'target_id' => (int) $user['id'],
|
||||
));
|
||||
Session::regenerateCsrf();
|
||||
$this->redirect($this->base() . '/');
|
||||
return null;
|
||||
}
|
||||
|
||||
/** POST /locale — смена только языка интерфейса Adminx. */
|
||||
public function language(array $params = array())
|
||||
{
|
||||
@@ -181,7 +247,36 @@
|
||||
$arr['password_hash'] = $hash;
|
||||
Auth::login($arr, $options);
|
||||
|
||||
return true;
|
||||
return $arr;
|
||||
}
|
||||
|
||||
protected function loginCompleted(array $user, $identityKey, $ipKey)
|
||||
{
|
||||
RateLimiter::clear($identityKey);
|
||||
RateLimiter::clear($ipKey);
|
||||
\App\Adminx\Users\Model::recordSuccessfulLogin((int) $user['id']);
|
||||
AuditLog::record('auth.login_succeeded', array(
|
||||
'actor_id' => (int) $user['id'],
|
||||
'actor_name' => isset($user['name']) ? (string) $user['name'] : '',
|
||||
'target_type' => 'user',
|
||||
'target_id' => (int) $user['id'],
|
||||
));
|
||||
Session::regenerateCsrf();
|
||||
$this->redirect($this->base() . (!empty($user['must_change_password']) ? '/account/password' : '/'));
|
||||
return null;
|
||||
}
|
||||
|
||||
protected function auditLoginFailure($identifier, $reason)
|
||||
{
|
||||
$user = \App\Adminx\Users\Model::findByIdentifier((string) $identifier);
|
||||
AuditLog::record('auth.login_failed', array(
|
||||
'target_type' => 'user',
|
||||
'target_id' => $user ? (int) $user->id : null,
|
||||
'meta' => array(
|
||||
'identifier' => mb_substr(trim((string) $identifier), 0, 190, 'UTF-8'),
|
||||
'reason' => (string) $reason,
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
/** POST /logout — выход (ajax + CSRF). */
|
||||
|
||||
@@ -13,4 +13,13 @@
|
||||
<phrase data="auto_94d6ba09fac4d9d6">The session is out of date, please refresh the page and try again.</phrase>
|
||||
<phrase data="auto_941abeff84af0919">Too many tries. Repeat after</phrase>
|
||||
<phrase data="auto_5a6373e98b6ebb55">The account has been disabled.</phrase>
|
||||
<phrase data="auth_temp_password_title">Temporary password change</phrase>
|
||||
<phrase data="auth_temp_password_heading">Change your temporary password</phrase>
|
||||
<phrase data="auth_temp_password_intro">The control panel will open after the password is changed.</phrase>
|
||||
<phrase data="auth_temp_password_for">For</phrase>
|
||||
<phrase data="auth_temp_password_current">Temporary password</phrase>
|
||||
<phrase data="auth_temp_password_new">New password</phrase>
|
||||
<phrase data="auth_temp_password_hint">At least 6 characters; the password must differ from the temporary one.</phrase>
|
||||
<phrase data="auth_temp_password_confirm">Repeat the new password</phrase>
|
||||
<phrase data="auth_temp_password_save">Save new password</phrase>
|
||||
</language>
|
||||
|
||||
@@ -13,4 +13,9 @@
|
||||
<phrase data="runtime_4ffa62424067c80f">Too many tries. Repeat after</phrase>
|
||||
<phrase data="runtime_7cc36c1848c1e707">The account has been disabled.</phrase>
|
||||
<phrase data="runtime_46a81a92e59e6d10">sec.</phrase>
|
||||
<phrase data="auth_login_rate_limited">Too many login attempts. Try again in</phrase>
|
||||
<phrase data="auth_current_password_invalid">The current password is incorrect.</phrase>
|
||||
<phrase data="auth_new_password_short">The new password must contain at least 6 characters.</phrase>
|
||||
<phrase data="auth_new_password_mismatch">The new passwords do not match.</phrase>
|
||||
<phrase data="auth_new_password_same">The new password must differ from the temporary one.</phrase>
|
||||
</language>
|
||||
|
||||
@@ -13,4 +13,13 @@
|
||||
<phrase data="auto_94d6ba09fac4d9d6">Сессия устарела, обновите страницу и попробуйте снова.</phrase>
|
||||
<phrase data="auto_941abeff84af0919">Слишком много попыток. Повторите через</phrase>
|
||||
<phrase data="auto_5a6373e98b6ebb55">Учётная запись отключена.</phrase>
|
||||
<phrase data="auth_temp_password_title">Смена временного пароля</phrase>
|
||||
<phrase data="auth_temp_password_heading">Смените временный пароль</phrase>
|
||||
<phrase data="auth_temp_password_intro">После смены откроется панель управления.</phrase>
|
||||
<phrase data="auth_temp_password_for">Для</phrase>
|
||||
<phrase data="auth_temp_password_current">Временный пароль</phrase>
|
||||
<phrase data="auth_temp_password_new">Новый пароль</phrase>
|
||||
<phrase data="auth_temp_password_hint">Минимум 6 символов, пароль должен отличаться от временного.</phrase>
|
||||
<phrase data="auth_temp_password_confirm">Повторите новый пароль</phrase>
|
||||
<phrase data="auth_temp_password_save">Сохранить новый пароль</phrase>
|
||||
</language>
|
||||
|
||||
@@ -13,4 +13,9 @@
|
||||
<phrase data="runtime_4ffa62424067c80f">Слишком много попыток. Повторите через</phrase>
|
||||
<phrase data="runtime_7cc36c1848c1e707">Учётная запись отключена.</phrase>
|
||||
<phrase data="runtime_46a81a92e59e6d10">сек.</phrase>
|
||||
<phrase data="auth_login_rate_limited">Слишком много попыток входа. Повторите через</phrase>
|
||||
<phrase data="auth_current_password_invalid">Текущий пароль указан неверно.</phrase>
|
||||
<phrase data="auth_new_password_short">Новый пароль должен содержать не меньше 6 символов.</phrase>
|
||||
<phrase data="auth_new_password_mismatch">Новые пароли не совпадают.</phrase>
|
||||
<phrase data="auth_new_password_same">Новый пароль должен отличаться от временного.</phrase>
|
||||
</language>
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
return [
|
||||
'code' => 'auth',
|
||||
'name' => 'Доступ',
|
||||
'version' => '0.1.0',
|
||||
'version' => '0.2.1',
|
||||
|
||||
'public_routes' => [
|
||||
'/login',
|
||||
@@ -34,6 +34,8 @@
|
||||
array('GET', '/login', array(\App\Adminx\Auth\Controller::class, 'form')),
|
||||
array('POST', '/login', array(\App\Adminx\Auth\Controller::class, 'login')),
|
||||
array('POST', '/locale', array(\App\Adminx\Auth\Controller::class, 'language')),
|
||||
array('GET', '/account/password', array(\App\Adminx\Auth\Controller::class, 'passwordForm'), array('permission' => 'admin_panel')),
|
||||
array('POST', '/account/password', array(\App\Adminx\Auth\Controller::class, 'changePassword'), array('permission' => 'admin_panel')),
|
||||
array('POST', '/reauth', array(\App\Adminx\Auth\Controller::class, 'reauth'), array('permission' => 'admin_panel')),
|
||||
array('POST', '/logout', array(\App\Adminx\Auth\Controller::class, 'logout')),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
{% extends '@adminx/auth.twig' %}
|
||||
{% block title %}{{ lang.auth_temp_password_title|default('Смена временного пароля') }}{% endblock %}
|
||||
{% block content %}
|
||||
<div class="auth-wrap">
|
||||
<div class="card auth-card">
|
||||
<div class="auth-head">
|
||||
<h1 class="auth-logo-h"><img class="auth-logo" src="{{ asset_ver(ADMINX_BASE ~ '/assets/img/logo.svg') }}" alt="AVE.cms" width="132" height="47"></h1>
|
||||
<h1>{{ lang.auth_temp_password_heading|default('Смените временный пароль') }}</h1>
|
||||
<p class="text-secondary">{{ lang.auth_temp_password_for|default('Для') }} {{ user.name|default(user.email) }}. {{ lang.auth_temp_password_intro|default('После смены откроется панель управления.') }}</p>
|
||||
</div>
|
||||
{% if error %}<div class="alert alert-danger" role="alert"><i class="ti ti-alert-triangle"></i><span>{{ error }}</span></div>{% endif %}
|
||||
<form method="post" action="{{ ADMINX_BASE }}/account/password" class="auth-form">
|
||||
<input type="hidden" name="_csrf" value="{{ csrf_token }}">
|
||||
<div class="field"><label for="currentPassword">{{ lang.auth_temp_password_current|default('Временный пароль') }}</label><input class="input" type="password" id="currentPassword" name="current_password" autocomplete="current-password" autofocus required></div>
|
||||
<div class="field"><label for="newPassword">{{ lang.auth_temp_password_new|default('Новый пароль') }}</label><input class="input" type="password" id="newPassword" name="password" minlength="8" autocomplete="new-password" required><span class="field-hint">{{ lang.auth_temp_password_hint|default('Минимум 8 символов, пароль должен отличаться от временного.') }}</span></div>
|
||||
<div class="field"><label for="passwordConfirm">{{ lang.auth_temp_password_confirm|default('Повторите новый пароль') }}</label><input class="input" type="password" id="passwordConfirm" name="password_confirm" minlength="8" autocomplete="new-password" required></div>
|
||||
<button class="btn btn-primary btn-block" type="submit"><i class="ti ti-key"></i>{{ lang.auth_temp_password_save|default('Сохранить новый пароль') }}</button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="auth-foot text-muted text-xs">AVE.cms · {{ lang.app_admin_panel|default('Панель управления') }}</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -133,6 +133,10 @@
|
||||
$row = self::store()->formatRow($row, $withSnapshot);
|
||||
$snapshot = $row['snapshot'];
|
||||
$text = $withSnapshot && is_array($snapshot) && isset($snapshot['sysblock_text']) ? (string) $snapshot['sysblock_text'] : '';
|
||||
$current = $withSnapshot ? Model::raw((int) $row['block_id']) : array();
|
||||
$comparison = $withSnapshot && is_array($snapshot)
|
||||
? JsonRevisionStore::compareSnapshots($current ? Model::snapshot($current) : array(), $snapshot)
|
||||
: array();
|
||||
|
||||
return array(
|
||||
'id' => (int) $row['id'],
|
||||
@@ -152,6 +156,7 @@
|
||||
'text_size_label' => $withSnapshot ? JsonRevisionStore::formatBytes(strlen($text)) : '',
|
||||
'snapshot' => $snapshot,
|
||||
'code' => $text,
|
||||
'comparison' => $comparison,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -720,6 +720,8 @@
|
||||
var fields = document.querySelector('[data-revision-fields]');
|
||||
var restore = document.querySelector('[data-revision-restore]');
|
||||
var remove = document.querySelector('[data-revision-delete]');
|
||||
var comparison = item.comparison || {};
|
||||
var changed = comparison.summary ? parseInt(comparison.summary.total_changed || 0, 10) : 0;
|
||||
var clear = document.querySelector('[data-revisions-clear]');
|
||||
|
||||
if (title) { title.textContent = 'Ревизии: ' + (row.dataset.name || ('#' + row.dataset.id)); }
|
||||
@@ -831,7 +833,7 @@
|
||||
|
||||
if (title) { title.textContent = '#' + item.id + ' · ' + (item.action_label || item.action || 'Ревизия'); }
|
||||
if (meta) {
|
||||
meta.textContent = (item.created_label || '-') + (item.author_name ? ' · ' + item.author_name : '') + (item.text_size_label ? ' · ' + item.text_size_label : '');
|
||||
meta.textContent = (item.created_label || '-') + (item.author_name ? ' · ' + item.author_name : '') + (item.text_size_label ? ' · ' + item.text_size_label : '') + ' · ' + (changed ? ('изменений: ' + changed) : 'совпадает с текущим');
|
||||
}
|
||||
if (fields) {
|
||||
fields.innerHTML =
|
||||
@@ -845,7 +847,7 @@
|
||||
(String(snapshot.sysblock_visual) === '1' ? ', visual' : '') +
|
||||
'</em></span>';
|
||||
}
|
||||
if (restore) { restore.disabled = !this.currentRevisionId; }
|
||||
if (restore) { restore.disabled = !this.currentRevisionId || !changed; }
|
||||
if (remove) {
|
||||
remove.disabled = !this.currentRevisionId;
|
||||
if (this.currentRevisionId) { remove.setAttribute('data-revision-delete', String(this.currentRevisionId)); }
|
||||
|
||||
@@ -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.3',
|
||||
'version' => '0.1.6',
|
||||
|
||||
'permissions' => array(
|
||||
'key' => 'blocks',
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
use App\Adminx\Support\CodeEditor;
|
||||
use App\Adminx\Support\SavedViews;
|
||||
use App\Content\PaymentPrograms;
|
||||
use App\Content\Documents\DocumentMediaDraft;
|
||||
use App\Content\ProductShipping;
|
||||
use App\Frontend\ThemeAssets;
|
||||
use App\Adminx\Packages\Products\AttributeNormalization;
|
||||
@@ -48,7 +49,10 @@
|
||||
use App\Adminx\Packages\Products\ProductRelations;
|
||||
use App\Adminx\Packages\Products\ProductCollections;
|
||||
use App\Adminx\Packages\Products\ProductDemands;
|
||||
use App\Adminx\Packages\Products\ProductDuplicator;
|
||||
use App\Adminx\Packages\Products\QualitySnapshot;
|
||||
use App\Adminx\Packages\Products\ProductReadiness;
|
||||
use App\Adminx\Packages\Products\PublicViewTemplates;
|
||||
use App\Adminx\Packages\Products\ShippingPackageTemplates;
|
||||
use App\Adminx\Packages\Products\VariantGroups;
|
||||
use App\Adminx\Packages\Commerce\Promotions;
|
||||
@@ -87,38 +91,56 @@
|
||||
'state' => Request::getStr('state', ''),
|
||||
'issue' => Request::getStr('issue', ''),
|
||||
'payment' => Request::getStr('payment', ''),
|
||||
'view' => Request::getStr('view', 'table') === 'cards' ? 'cards' : 'table',
|
||||
'page' => Request::getInt('page', 1),
|
||||
'per_page' => Request::getInt('per_page', 25),
|
||||
);
|
||||
$statsSnapshot = Model::productStatsSnapshot();
|
||||
return $this->render('@products/products.twig', array(
|
||||
'result' => Model::products($filters),
|
||||
'stats' => Model::productStats(),
|
||||
'stats' => $statsSnapshot['stats'],
|
||||
'stats_loaded' => $statsSnapshot['loaded'],
|
||||
'filters' => $filters,
|
||||
'saved_views' => SavedViews::all('catalog_products', Auth::id(), $this->savedViewFields('products')),
|
||||
'can_manage' => Permission::check('manage_products'),
|
||||
'can_copy' => Permission::check('manage_products') && Permission::check('manage_documents'),
|
||||
'can_toggle' => Permission::check('manage_products') && Permission::check('manage_documents'),
|
||||
));
|
||||
}
|
||||
|
||||
public function productStats(array $params = array())
|
||||
{
|
||||
if (!Permission::check('view_products')) { return $this->error('Недостаточно прав', array(), 403); }
|
||||
$stats = Model::productStats();
|
||||
$stats['indexed_label'] = !empty($stats['indexed_at']) ? date('d.m H:i', (int) $stats['indexed_at']) : '—';
|
||||
return $this->success('', array('data' => array('stats' => $stats)));
|
||||
}
|
||||
|
||||
public function productQuality(array $params = array())
|
||||
{
|
||||
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();
|
||||
$stats = Model::productStats();
|
||||
$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();
|
||||
foreach ($issues as $item) { $allowed[(string) $item['code']] = true; }
|
||||
$issue = Request::getStr('issue', '');
|
||||
if ($issue !== '' && !isset($allowed[$issue])) { $issue = ''; }
|
||||
$state = Request::getStr('state', '');
|
||||
if (!in_array($state, array('', 'active', 'inactive'), true)) { $state = ''; }
|
||||
$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' => $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,
|
||||
@@ -126,6 +148,30 @@
|
||||
'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,
|
||||
));
|
||||
}
|
||||
|
||||
public function refreshProductQualitySnapshot(array $params = array())
|
||||
{
|
||||
if (($error = $this->csrfGuard()) !== null) { return $error; }
|
||||
if (!Permission::check('view_products')) { return $this->error('Недостаточно прав', array(), 403); }
|
||||
|
||||
try {
|
||||
$snapshot = QualitySnapshot::refresh();
|
||||
} catch (\Throwable $e) {
|
||||
error_log('[products.quality] ' . $e->getMessage());
|
||||
return $this->error('Не удалось рассчитать качество товаров', array(), 500);
|
||||
}
|
||||
|
||||
return $this->success('Сводка качества обновлена', array(
|
||||
'data' => array(
|
||||
'generated_label' => (string) $snapshot['generated_label'],
|
||||
'quality_total' => (int) $snapshot['stats']['quality_total'],
|
||||
'required' => (int) $snapshot['required'],
|
||||
'score' => (int) $snapshot['stats']['score'],
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
@@ -475,6 +521,55 @@
|
||||
));
|
||||
}
|
||||
|
||||
public function publicTemplates(array $params = array())
|
||||
{
|
||||
if (!Permission::check('view_products')) { return $this->renderStatus('@adminx/404.twig', array('title' => 'Недостаточно прав'), 403); }
|
||||
$this->publicTemplateAssets();
|
||||
return $this->render('@themes/view-overrides.twig', array(
|
||||
'page_title' => 'Публичные шаблоны товаров',
|
||||
'page_description' => 'Каталог, карточки, страница товара, сравнение и обращения в активной теме.',
|
||||
'back_url' => '/catalog/products',
|
||||
'back_label' => 'Товары',
|
||||
'route_base' => '/catalog/public-templates',
|
||||
'list_title' => 'Публичный вывод',
|
||||
'tabs_template' => '@products/_tabs.twig',
|
||||
'product_tab' => 'public_templates',
|
||||
'templates' => PublicViewTemplates::all(),
|
||||
'selected' => PublicViewTemplates::one(Request::getStr('template', '')),
|
||||
'can_manage' => Permission::check('manage_products') && Permission::check('manage_themes'),
|
||||
'can_view_themes' => Permission::check('view_themes'),
|
||||
));
|
||||
}
|
||||
|
||||
public function lintPublicTemplate(array $params = array())
|
||||
{
|
||||
if (($error = $this->publicTemplateGuard(false)) !== null) { return $error; }
|
||||
$result = PublicViewTemplates::lint(Request::postStr('content', ''));
|
||||
return !empty($result['ok'])
|
||||
? $this->success($result['message'], array('data' => $result))
|
||||
: $this->error($result['message'], array('content' => $result['message']), 422);
|
||||
}
|
||||
|
||||
public function savePublicTemplate(array $params = array())
|
||||
{
|
||||
if (($error = $this->publicTemplateGuard()) !== null) { return $error; }
|
||||
$code = isset($params['code']) ? (string) $params['code'] : '';
|
||||
try { $item = PublicViewTemplates::save($code, Request::postStr('content', ''), Auth::id()); }
|
||||
catch (\Throwable $e) { return $this->error($e->getMessage(), array(), 422); }
|
||||
$this->audit('catalog.public_template_saved', null, array('theme' => $item['theme'], 'path' => $item['theme_path']));
|
||||
return $this->success('Шаблон активной темы сохранён', array('data' => $item));
|
||||
}
|
||||
|
||||
public function deletePublicTemplate(array $params = array())
|
||||
{
|
||||
if (($error = $this->publicTemplateGuard()) !== null) { return $error; }
|
||||
$code = isset($params['code']) ? (string) $params['code'] : '';
|
||||
try { $item = PublicViewTemplates::deleteOverride($code, Auth::id()); }
|
||||
catch (\Throwable $e) { return $this->error($e->getMessage(), array(), 422); }
|
||||
$this->audit('catalog.public_template_override_deleted', null, array('theme' => $item['theme'], 'path' => $item['theme_path']));
|
||||
return $this->success('Переопределение удалено, используется шаблон модуля', array('data' => $item));
|
||||
}
|
||||
|
||||
public function cardTemplate(array $params = array())
|
||||
{
|
||||
if (!Permission::check('view_products')) { return $this->error('Недостаточно прав', array(), 403); }
|
||||
@@ -536,7 +631,7 @@
|
||||
if (!$syntax['ok']) { return $this->error($syntax['message'], array('draft_markup' => $syntax['message']), 422); }
|
||||
try {
|
||||
$this->bootPublicCatalogPreview();
|
||||
$catalog = \App\Modules\Products\Repository::fromDocumentId(Request::postInt('preview_catalog_id', 0));
|
||||
$catalog = \App\Modules\Products\Repository::forFilterPreviewFromDocumentId(Request::postInt('preview_catalog_id', 0));
|
||||
if (!$catalog) { throw new \RuntimeException('Выберите раздел каталога с настроенными фильтрами'); }
|
||||
$result = \App\Modules\Products\FilterTemplateRenderer::preview($catalog, $markup, $css);
|
||||
$html = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
||||
@@ -729,13 +824,14 @@
|
||||
if (!Permission::check('view_products')) { return $this->renderStatus('@adminx/404.twig', array('title' => 'Недостаточно прав'), 403); }
|
||||
$this->attributeAssets();
|
||||
$view = Request::getStr('view', 'overview');
|
||||
if (!in_array($view, array('overview', 'normalization', 'attributes', 'sets', 'migration', 'sections'), true)) { $view = 'overview'; }
|
||||
if (!in_array($view, array('overview', 'normalization', 'attributes', 'sets', 'filters', 'migration', 'sections'), true)) { $view = 'overview'; }
|
||||
return $this->render('@products/attributes.twig', array(
|
||||
'view' => $view, 'stats' => Attributes::stats(), 'value_types' => Attributes::valueTypes(),
|
||||
'attributes' => Attributes::all(Request::getStr('q', ''), Request::getStr('status', '')),
|
||||
'product_attributes' => $view === 'migration' ? Attributes::all('', 'active', 'product') : array(),
|
||||
'sets' => Attributes::sets(), 'legacy_fields' => $view === 'migration' ? Attributes::legacyFields() : array(),
|
||||
'sections' => $view === 'sections' ? Attributes::sections() : array(),
|
||||
'section_filters' => $view === 'filters' ? Attributes::sectionFilterEditor(Request::getInt('section_id', 0)) : array(),
|
||||
'normalization' => $view === 'normalization' ? AttributeNormalization::audit() : array(),
|
||||
'overview' => $view === 'overview' ? Attributes::overview() : array(),
|
||||
'filters' => array('q'=>Request::getStr('q',''),'status'=>Request::getStr('status','')),
|
||||
@@ -866,6 +962,19 @@
|
||||
if(($error=$this->productGuard())!==null){return $error;}try{$data=Attributes::saveSection((int)$params['id'],Request::postAll(),Auth::id());}catch(\Throwable $e){return $this->error($e->getMessage(),array(),422);}return $this->success('Режим раздела сохранён',array('data'=>$data));
|
||||
}
|
||||
|
||||
public function saveAttributeSectionFilters(array $params = array())
|
||||
{
|
||||
if (($error = $this->productGuard()) !== null) { return $error; }
|
||||
$id = isset($params['id']) ? (int) $params['id'] : 0;
|
||||
try { $data = Attributes::saveSectionFilters($id, Request::postAll(), Auth::id()); }
|
||||
catch (\Throwable $e) { return $this->error($e->getMessage(), array(), 422); }
|
||||
$this->audit('catalog.attribute_section_filters_saved', $id, $data);
|
||||
return $this->success('Фильтры раздела сохранены', array(
|
||||
'redirect' => $this->base() . '/catalog/attributes?view=filters§ion_id=' . $id,
|
||||
'data' => $data,
|
||||
));
|
||||
}
|
||||
|
||||
public function rebuildAttributeShadow(array $params = array())
|
||||
{
|
||||
if(($error=$this->productGuard())!==null){return $error;}try{$data=Attributes::rebuildShadowIndex((int)$params['id']);}catch(\Throwable $e){return $this->error($e->getMessage(),array(),422);}$this->audit('catalog.attribute_shadow_rebuilt',(int)$params['id'],$data);return $this->success('Теневой индекс раздела перестроен',array('data'=>$data));
|
||||
@@ -981,6 +1090,7 @@
|
||||
$search = Request::getStr('q', '');
|
||||
return $this->render('@products/variant-group.twig', array(
|
||||
'group' => $group, 'search' => $search,
|
||||
'focus_product_id' => Request::getInt('focus', 0),
|
||||
'variant_fields' => VariantGroups::fields((int) $group['id']),
|
||||
'variant_attributes' => VariantGroups::nativeAttributes(),
|
||||
'package_templates' => ShippingPackageTemplates::all(),
|
||||
@@ -1100,11 +1210,12 @@
|
||||
public function copyVariantProduct(array $params = array())
|
||||
{
|
||||
if (($error = $this->productGuard()) !== null) { return $error; }
|
||||
if (!Request::postBool('confirmed', false)) { return $this->error('Подтвердите создание варианта', array(), 409); }
|
||||
$sourceId = (int) $params['product'];
|
||||
$newId = 0;
|
||||
try {
|
||||
$newId = DocumentsModel::copy($sourceId, Auth::id());
|
||||
Model::reindexDocument($newId);
|
||||
$copy = ProductDuplicator::copy($sourceId, Auth::id());
|
||||
$newId = (int) $copy['id'];
|
||||
VariantGroups::add((int) $params['id'], $newId);
|
||||
} catch (\Throwable $e) {
|
||||
if ($newId > 0) { try { DocumentsModel::delete($newId); DocumentsModel::purge($newId); } catch (\Throwable $cleanupError) {} }
|
||||
@@ -1112,7 +1223,49 @@
|
||||
}
|
||||
|
||||
$this->audit('catalog.variant_copied', (int) $params['id'], array('source_id' => $sourceId, 'product_id' => $newId));
|
||||
return $this->success('Вариант создан копированием', array('redirect' => $this->base() . '/catalog/products/' . $newId . '/edit'));
|
||||
return $this->success('Вариант создан копированием', array(
|
||||
'redirect' => $this->base() . '/catalog/products/' . $newId . '/edit?variant_group=' . (int) $params['id'],
|
||||
));
|
||||
}
|
||||
|
||||
public function copyProduct(array $params = array())
|
||||
{
|
||||
if (($error = $this->guardPermission('manage_products', 'manage_documents')) !== null) { return $error; }
|
||||
if (!Request::postBool('confirmed', false)) { return $this->error('Подтвердите создание копии товара', array(), 409); }
|
||||
$sourceId = isset($params['id']) ? (int) $params['id'] : 0;
|
||||
try {
|
||||
$copy = ProductDuplicator::copy($sourceId, Auth::id());
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage(), array(), 422);
|
||||
}
|
||||
|
||||
$this->audit('catalog.product_copied', (int) $copy['id'], array(
|
||||
'source_id' => $sourceId,
|
||||
'attributes' => (int) $copy['attributes'],
|
||||
'shipping' => !empty($copy['shipping']),
|
||||
));
|
||||
return $this->success('Копия товара создана', array(
|
||||
'id' => (int) $copy['id'],
|
||||
'redirect' => $this->base() . '/catalog/products/' . (int) $copy['id'] . '/edit',
|
||||
));
|
||||
}
|
||||
|
||||
public function toggleProduct(array $params = array())
|
||||
{
|
||||
if (($error = $this->guardPermission('manage_products', 'manage_documents')) !== null) { return $error; }
|
||||
$productId = isset($params['id']) ? (int) $params['id'] : 0;
|
||||
if (!Model::product($productId)) { return $this->error('Товар не найден', array(), 404); }
|
||||
try {
|
||||
$status = DocumentsModel::toggleStatus($productId);
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage(), array(), 422);
|
||||
}
|
||||
|
||||
if ($status === false) { return $this->error('Товар не найден', array(), 404); }
|
||||
$this->audit('catalog.product_status_changed', $productId, array('status' => (int) $status));
|
||||
return $this->success($status ? 'Товар опубликован' : 'Товар снят с публикации', array(
|
||||
'data' => array('status' => (int) $status),
|
||||
));
|
||||
}
|
||||
|
||||
public function deleteVariantGroup(array $params = array())
|
||||
@@ -1161,7 +1314,23 @@
|
||||
VariantGroups::add($groupId, $productId);
|
||||
} catch (\Throwable $e) { return $this->error($e->getMessage(), array(), 422); }
|
||||
$this->audit('catalog.variant_group_created_from_product', $groupId, array('product_id' => $productId));
|
||||
return $this->success('Группа вариантов создана', array('redirect' => $this->base() . '/catalog/variant-groups/' . $groupId));
|
||||
return $this->success('Группа вариантов создана', array('redirect' => $this->variantGroupUrl($groupId, $productId)));
|
||||
}
|
||||
|
||||
public function attachProductVariantGroup(array $params = array())
|
||||
{
|
||||
if (($error = $this->productGuard()) !== null) { return $error; }
|
||||
$productId = isset($params['id']) ? (int) $params['id'] : 0;
|
||||
$groupId = Request::postInt('group_id', 0);
|
||||
if (!Model::product($productId)) { return $this->error('Товар не найден', array(), 404); }
|
||||
if ($groupId <= 0) { return $this->error('Выберите группу вариантов', array(), 422); }
|
||||
if (VariantGroups::membership($productId)) { return $this->error('Товар уже состоит в группе', array(), 422); }
|
||||
try { VariantGroups::add($groupId, $productId); }
|
||||
catch (\Throwable $e) { return $this->error($e->getMessage(), array(), 422); }
|
||||
$this->audit('catalog.variant_added_from_product', $groupId, array('product_id' => $productId));
|
||||
return $this->success('Товар добавлен в группу вариантов', array(
|
||||
'redirect' => $this->variantGroupUrl($groupId, $productId),
|
||||
));
|
||||
}
|
||||
|
||||
public function editProduct(array $params = array())
|
||||
@@ -1179,26 +1348,45 @@
|
||||
CodeEditor::useRichEditor();
|
||||
$this->attributeAssets();
|
||||
$variantGroup = VariantGroups::membership($id);
|
||||
$returnUrl = $this->base() . '/catalog/products';
|
||||
$returnLabel = 'Товары';
|
||||
$returnGroupId = Request::getInt('variant_group', 0);
|
||||
if ($variantGroup && $returnGroupId === (int) $variantGroup['id']) {
|
||||
$returnUrl = $this->variantGroupUrl((int) $variantGroup['id'], $id);
|
||||
$returnLabel = 'Группа вариантов';
|
||||
}
|
||||
|
||||
$shippingProfile = ProductShipping::profile($id);
|
||||
$nativeAttributes = Attributes::productEditor($id);
|
||||
$searchAliasesAvailable = $this->productSearchAliasesAvailable();
|
||||
$mediaDraftToken = DocumentMediaDraft::issue(Auth::id(), $id);
|
||||
return $this->render('@documents/edit.twig', array(
|
||||
'document' => $document,
|
||||
'field_groups' => DocumentsModel::fieldsForDocument($id),
|
||||
'field_groups' => DocumentsModel::fieldsForDocument($id, $mediaDraftToken),
|
||||
'media_draft_token' => $mediaDraftToken,
|
||||
'rubrics' => DocumentsModel::rubrics(),
|
||||
'templates' => DocumentsModel::rubricTemplates((int) $document['rubric_id']),
|
||||
'navigation_items' => DocumentsModel::navigationItems(),
|
||||
'authors' => DocumentsModel::authors(),
|
||||
'is_new' => false, 'can_manage' => true,
|
||||
'is_new' => false, 'can_manage' => true, 'quick_edit' => Request::getBool('quick_edit', false),
|
||||
'actor_id' => Auth::id(),
|
||||
'catalog_mode' => true, 'product' => $product, 'variant_group' => $variantGroup,
|
||||
'variant_groups' => $variantGroup ? array() : VariantGroups::all(),
|
||||
'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),
|
||||
'can_manage_product_promotions' => Permission::check('manage_orders'),
|
||||
'return_url' => $this->base() . '/catalog/products',
|
||||
'product_search_aliases_available' => $searchAliasesAvailable,
|
||||
'product_search_aliases' => $searchAliasesAvailable
|
||||
? \App\Modules\Search\DocumentAliases::forDocument($id)
|
||||
: array(),
|
||||
'return_url' => $returnUrl,
|
||||
'return_label' => $returnLabel,
|
||||
'product_copy_url' => $this->base() . '/catalog/products/' . $id . '/copy',
|
||||
'submit_url' => $this->base() . '/documents/' . $id,
|
||||
));
|
||||
}
|
||||
@@ -1308,6 +1496,47 @@
|
||||
if(($error=$this->productGuard())!==null){return $error;}$productId=isset($params['id'])?(int)$params['id']:0;if(!Model::product($productId)){return $this->error('Товар не найден',array(),404);}try{$data=Attributes::saveProductValues($productId,Request::postAll(),Auth::id());}catch(\Throwable $e){return $this->error($e->getMessage(),array(),422);}$this->audit('catalog.product_attributes_saved',$productId,$data);return $this->success('Характеристики товара сохранены',array('data'=>$data));
|
||||
}
|
||||
|
||||
public function saveProductSearchAliases(array $params = array())
|
||||
{
|
||||
if (($error = $this->productGuard()) !== null) { return $error; }
|
||||
$productId = isset($params['id']) ? (int) $params['id'] : 0;
|
||||
if (!Model::product($productId)) { return $this->error('Товар не найден', array(), 404); }
|
||||
if (!$this->productSearchAliasesAvailable()) {
|
||||
return $this->error('Обновите и включите модуль «Поиск по сайту»', array(), 409);
|
||||
}
|
||||
|
||||
try {
|
||||
$aliases = \App\Modules\Search\DocumentAliases::saveDocument(
|
||||
$productId,
|
||||
(array) Request::post('aliases', array()),
|
||||
Auth::id()
|
||||
);
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage(), array(), 422);
|
||||
}
|
||||
|
||||
$this->audit('catalog.product_search_aliases_saved', $productId, array('count' => count($aliases)));
|
||||
return $this->success('Поисковые названия сохранены', array('data' => array('aliases' => $aliases)));
|
||||
}
|
||||
|
||||
public function productSearchAliasSuggestions(array $params = array())
|
||||
{
|
||||
if (!Permission::check('manage_products')) {
|
||||
return $this->error('Недостаточно прав', array(), 403);
|
||||
}
|
||||
|
||||
if (!$this->productSearchAliasesAvailable()) {
|
||||
return $this->error('Обновите и включите модуль «Поиск по сайту»', array(), 409);
|
||||
}
|
||||
|
||||
$query = Request::getStr('q', '');
|
||||
$documentId = Request::getInt('document_id', 0);
|
||||
$items = mb_strlen(trim($query), 'UTF-8') >= 2
|
||||
? \App\Modules\Search\DocumentAliases::suggestions($query, $documentId, 12)
|
||||
: array();
|
||||
return $this->success('', array('data' => array('items' => $items)));
|
||||
}
|
||||
|
||||
public function copyProductShippingToVariants(array $params = array())
|
||||
{
|
||||
if (($error = $this->productGuard()) !== null) { return $error; }
|
||||
@@ -1410,14 +1639,24 @@
|
||||
|
||||
$allowed = Model::productRubrics();
|
||||
$rubricId = Request::getInt('rubric_id', 0);
|
||||
if (!in_array($rubricId, $allowed, true)) { $rubricId = !empty($allowed) ? (int) reset($allowed) : 0; }
|
||||
if ($rubricId <= 0) { return $this->renderStatus('@adminx/404.twig', array('title' => 'Товарная рубрика не настроена'), 404); }
|
||||
if (!$allowed) { return $this->renderStatus('@adminx/404.twig', array('title' => 'Товарная рубрика не настроена'), 404); }
|
||||
if (!in_array($rubricId, $allowed, true)) {
|
||||
$this->assets();
|
||||
return $this->render('@products/product-create.twig', array(
|
||||
'rubrics' => Model::productRubricOptions(),
|
||||
'return_url' => $this->base() . '/catalog/products',
|
||||
));
|
||||
}
|
||||
|
||||
$document = DocumentsModel::blank($rubricId);
|
||||
$mediaDraftToken = DocumentMediaDraft::issue(Auth::id(), 0);
|
||||
AdminAssets::addStyle($this->base() . '/modules/Documents/assets/documents.css', 50);
|
||||
AdminAssets::addScript($this->base() . '/modules/Documents/assets/documents.js', 50);
|
||||
CodeEditor::useRichEditor(); $this->assets();
|
||||
return $this->render('@documents/edit.twig', array(
|
||||
'document' => $document, 'field_groups' => DocumentsModel::fieldsForRubric($rubricId, 0),
|
||||
'document' => $document,
|
||||
'field_groups' => DocumentsModel::fieldsForRubric($rubricId, 0, $mediaDraftToken),
|
||||
'media_draft_token' => $mediaDraftToken,
|
||||
'rubrics' => array_values(array_filter(DocumentsModel::rubrics(), function ($rubric) use ($allowed) { return in_array((int) $rubric['Id'], $allowed, true); })),
|
||||
'templates' => DocumentsModel::rubricTemplates($rubricId), 'navigation_items' => DocumentsModel::navigationItems(),
|
||||
'authors' => DocumentsModel::authors(), 'is_new' => true, 'can_manage' => true,
|
||||
@@ -1462,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(),
|
||||
@@ -1474,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);
|
||||
}
|
||||
|
||||
@@ -1588,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()),
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -1664,7 +1936,7 @@
|
||||
{
|
||||
return $scope === 'quality'
|
||||
? array('q', 'issue', 'state', 'per_page')
|
||||
: array('q', 'state', 'issue', 'payment', 'per_page');
|
||||
: array('q', 'state', 'issue', 'payment', 'per_page', 'view');
|
||||
}
|
||||
|
||||
protected function quickEditData()
|
||||
@@ -1690,10 +1962,21 @@
|
||||
'quick_profiles_available' => QuickEditorProfiles::available());
|
||||
}
|
||||
|
||||
protected function variantGroupUrl($groupId, $productId = 0)
|
||||
{
|
||||
$url = $this->base() . '/catalog/variant-groups/' . (int) $groupId;
|
||||
if ((int) $productId > 0) {
|
||||
$url .= '?focus=' . (int) $productId . '#variant-' . (int) $productId;
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
protected function assets()
|
||||
{
|
||||
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')) {
|
||||
@@ -1716,6 +1999,16 @@
|
||||
&& is_file(BASEPATH . '/modules/products/admin/module.php');
|
||||
}
|
||||
|
||||
protected function productSearchAliasesAvailable()
|
||||
{
|
||||
$module = ModuleManager::get('search');
|
||||
return is_array($module)
|
||||
&& !empty($module['installed'])
|
||||
&& !empty($module['enabled'])
|
||||
&& class_exists('App\\Modules\\Search\\DocumentAliases')
|
||||
&& \App\Modules\Search\DocumentAliases::available();
|
||||
}
|
||||
|
||||
protected function attributeAssets()
|
||||
{
|
||||
$this->assets();
|
||||
@@ -1754,6 +2047,24 @@
|
||||
AdminAssets::addScript('/modules/products/admin/assets/card-templates.js', 56);
|
||||
}
|
||||
|
||||
protected function publicTemplateAssets()
|
||||
{
|
||||
$this->assets();
|
||||
CodeEditor::useCodeMirror('htmlmixed');
|
||||
AdminAssets::addStyle(ADMINX_BASE . '/modules/Themes/assets/view-overrides.css', 56);
|
||||
AdminAssets::addScript(ADMINX_BASE . '/modules/Themes/assets/view-overrides.js', 56);
|
||||
}
|
||||
|
||||
protected function publicTemplateGuard($requireThemePermission = true)
|
||||
{
|
||||
if (($error = $this->productGuard()) !== null) { return $error; }
|
||||
if ($requireThemePermission && !Permission::check('manage_themes')) {
|
||||
return $this->error('Для изменения публичной разметки требуется право управления темами', array(), 403);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected function audit($action, $targetId = null, array $meta = array())
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -257,8 +303,8 @@
|
||||
|
||||
protected static function filterTemplateSettings(array $input, $submitted = false)
|
||||
{
|
||||
$zero = isset($input['zero_behavior']) ? (string) $input['zero_behavior'] : 'disable';
|
||||
if (!in_array($zero, array('show', 'disable', 'hide'), true)) { $zero = 'disable'; }
|
||||
$zero = isset($input['zero_behavior']) ? (string) $input['zero_behavior'] : 'hide';
|
||||
if (!in_array($zero, array('show', 'disable', 'hide'), true)) { $zero = 'hide'; }
|
||||
return array(
|
||||
'show_counts' => $submitted ? !empty($input['show_counts']) : (!array_key_exists('show_counts', $input) || !empty($input['show_counts'])),
|
||||
'zero_behavior' => $zero,
|
||||
@@ -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 {
|
||||
@@ -519,6 +604,47 @@
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Разделы каталога, доступные как родители в редакторе документа. */
|
||||
public static function searchParentDocuments($query, $limit = 30)
|
||||
{
|
||||
$query = trim((string) $query);
|
||||
$limit = max(1, min(50, (int) $limit));
|
||||
$sql = 'SELECT i.id AS catalog_item_id,i.name,i.status AS catalog_status,i.document_id,d.rubric_id,'
|
||||
. ' d.document_title,d.document_alias,r.rubric_title'
|
||||
. ' FROM ' . self::itemsTable() . ' i'
|
||||
. ' INNER JOIN ' . self::documentsTable() . ' d ON d.Id=i.document_id'
|
||||
. ' LEFT JOIN ' . self::rubricsTable() . ' r ON r.Id=d.rubric_id'
|
||||
. " WHERE i.document_id>0 AND d.document_deleted!='1'";
|
||||
$args = array();
|
||||
if ($query !== '') {
|
||||
$sql .= ' AND (i.name LIKE %ss OR d.document_title LIKE %ss'
|
||||
. ' OR d.document_alias LIKE %ss OR d.Id=%i)';
|
||||
$args[] = $query;
|
||||
$args[] = $query;
|
||||
$args[] = $query;
|
||||
$args[] = (int) $query;
|
||||
}
|
||||
|
||||
$sql .= ' ORDER BY i.level ASC,i.position ASC,i.name ASC LIMIT ' . $limit;
|
||||
$rows = call_user_func_array(array('DB', 'query'), array_merge(array($sql), $args))->getAll();
|
||||
$out = array();
|
||||
foreach ($rows ?: array() as $row) {
|
||||
$out[] = array(
|
||||
'id' => (int) $row['document_id'],
|
||||
'rubric_id' => (int) $row['rubric_id'],
|
||||
'title' => self::decode($row['name']),
|
||||
'alias' => (string) $row['document_alias'],
|
||||
'status' => (int) $row['catalog_status'],
|
||||
'rubric_title' => 'Раздел каталога'
|
||||
. ((int) $row['catalog_status'] === 1 ? '' : ' · выключен')
|
||||
. ' · ' . self::decode($row['rubric_title']),
|
||||
'catalog_item_id' => (int) $row['catalog_item_id'],
|
||||
);
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
public static function parseValue($value)
|
||||
{
|
||||
$data = FieldValueCodec::decodeStructured($value, array());
|
||||
@@ -543,7 +669,35 @@
|
||||
{
|
||||
return self::productsAvailable()
|
||||
? ProductIndexer::stats()
|
||||
: array('total' => 0, 'active' => 0, 'inactive' => 0, 'categories' => 0);
|
||||
: self::emptyProductStats();
|
||||
}
|
||||
|
||||
public static function productQualityStats()
|
||||
{
|
||||
return self::productsAvailable()
|
||||
? ProductIndexer::qualityStats()
|
||||
: self::emptyProductStats();
|
||||
}
|
||||
|
||||
public static function productStatsSnapshot()
|
||||
{
|
||||
$stats = self::productsAvailable() ? ProductIndexer::cachedStats() : self::emptyProductStats();
|
||||
return array(
|
||||
'loaded' => is_array($stats),
|
||||
'stats' => array_merge(self::emptyProductStats(), is_array($stats) ? $stats : array()),
|
||||
);
|
||||
}
|
||||
|
||||
protected static function emptyProductStats()
|
||||
{
|
||||
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_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,
|
||||
);
|
||||
}
|
||||
|
||||
public static function productQualityIssues(array $stats)
|
||||
@@ -561,6 +715,14 @@
|
||||
return self::productsAvailable() ? ProductIndexer::productRubrics() : array();
|
||||
}
|
||||
|
||||
public static function productRubricOptions()
|
||||
{
|
||||
$allowed = array_flip(self::productRubrics());
|
||||
return array_values(array_filter(self::rubricOptions(), function ($rubric) use ($allowed) {
|
||||
return isset($allowed[(int) $rubric['id']]);
|
||||
}));
|
||||
}
|
||||
|
||||
public static function reindexProducts($limit = 0)
|
||||
{
|
||||
return self::productsAvailable()
|
||||
@@ -976,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)
|
||||
@@ -1007,6 +1192,7 @@
|
||||
protected static function clearCache()
|
||||
{
|
||||
DB::clearTags(array('documents', 'requests', 'modules', 'catalog'));
|
||||
(new FeedService())->clearAll();
|
||||
Cache::forgetTag(CacheKey::tag('catalog'));
|
||||
}
|
||||
|
||||
@@ -1047,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();
|
||||
@@ -1087,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',
|
||||
|
||||
@@ -5,11 +5,128 @@
|
||||
overflow-y: hidden;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
.catalog-tree > .catalog-tree-item > .catalog-tree-row {
|
||||
border-top: 1px solid var(--border-strong);
|
||||
.catalog-tree {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
padding: 12px;
|
||||
overflow-x: hidden;
|
||||
background: var(--background-subtle);
|
||||
}
|
||||
.catalog-tree-row {
|
||||
grid-template-columns: 30px 22px minmax(180px, 1fr) 112px 70px 84px;
|
||||
.catalog-tree.is-drag-active {
|
||||
user-select: none;
|
||||
}
|
||||
.catalog-tree.is-order-saving::after {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 4;
|
||||
content: '';
|
||||
cursor: wait;
|
||||
background: rgba(248, 250, 252, 0.36);
|
||||
}
|
||||
.catalog-tree > .catalog-tree-item {
|
||||
width: calc(100% - var(--catalog-indent, 0px));
|
||||
min-width: 0;
|
||||
margin-left: var(--catalog-indent, 0px);
|
||||
}
|
||||
.catalog-tree-row,
|
||||
.catalog-tree > .catalog-tree-item > .catalog-tree-row {
|
||||
display: grid;
|
||||
grid-template-columns: 30px 30px minmax(180px, 1fr) auto 104px 258px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 54px;
|
||||
padding: 7px 9px;
|
||||
border: 0;
|
||||
border-radius: var(--radius-md);
|
||||
outline: 0;
|
||||
background: var(--background-card);
|
||||
box-shadow: inset 0 0 0 1px var(--border-default);
|
||||
cursor: pointer;
|
||||
transition-property: background-color, box-shadow, opacity;
|
||||
transition-duration: 150ms;
|
||||
}
|
||||
.catalog-tree-row:hover {
|
||||
background: var(--blue-50);
|
||||
box-shadow: inset 0 0 0 1px var(--blue-300);
|
||||
}
|
||||
.catalog-tree-row.is-selected {
|
||||
background: var(--blue-50);
|
||||
box-shadow: inset 3px 0 var(--blue-500), inset 0 0 0 1px var(--blue-300);
|
||||
}
|
||||
.catalog-tree-position {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--background-muted);
|
||||
color: var(--text-secondary);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.catalog-tree-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
.catalog-tree-meta .badge {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.catalog-tree-count {
|
||||
min-width: 42px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
text-align: center;
|
||||
}
|
||||
.catalog-tree-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 3px;
|
||||
min-width: 0;
|
||||
}
|
||||
.catalog-tree-actions .btn-icon {
|
||||
width: 40px;
|
||||
min-width: 40px;
|
||||
height: 40px;
|
||||
}
|
||||
.catalog-tree-actions .btn-icon:active {
|
||||
transform: scale(0.96);
|
||||
}
|
||||
.catalog-tree-actions .btn-icon:disabled {
|
||||
opacity: 0.28;
|
||||
cursor: default;
|
||||
}
|
||||
.catalog-action-level {
|
||||
color: var(--blue-600);
|
||||
}
|
||||
.catalog-action-sibling {
|
||||
color: var(--green-600);
|
||||
}
|
||||
.catalog-action-child {
|
||||
color: var(--cyan-700);
|
||||
}
|
||||
.catalog-action-edit {
|
||||
color: var(--blue-600);
|
||||
}
|
||||
.catalog-action-delete {
|
||||
color: var(--red-600);
|
||||
}
|
||||
.catalog-drag {
|
||||
border-radius: var(--radius-sm);
|
||||
outline: 0;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
.catalog-drag:hover,
|
||||
.catalog-drag:focus-visible {
|
||||
background: var(--background-muted);
|
||||
color: var(--blue-600);
|
||||
}
|
||||
.catalog-tree-tools {
|
||||
display: flex;
|
||||
@@ -39,21 +156,53 @@
|
||||
}
|
||||
.catalog-tree-item.is-inactive > .catalog-tree-row {
|
||||
background: var(--amber-50);
|
||||
box-shadow: inset 3px 0 var(--amber-500);
|
||||
box-shadow: inset 3px 0 var(--amber-500), inset 0 0 0 1px var(--amber-200);
|
||||
}
|
||||
.catalog-tree-item.is-drop-target > .catalog-tree-row {
|
||||
background: var(--blue-50);
|
||||
.catalog-tree-row.drag-over-top {
|
||||
box-shadow: inset 0 2px var(--blue-500);
|
||||
}
|
||||
.catalog-tree-item.is-drop-target.is-drop-after > .catalog-tree-row {
|
||||
.catalog-tree-row.drag-over-bottom {
|
||||
box-shadow: inset 0 -2px var(--blue-500);
|
||||
}
|
||||
.catalog-tree-item.is-drop-target.is-drop-inside > .catalog-tree-row {
|
||||
background: var(--blue-50);
|
||||
box-shadow: inset 0 0 0 2px var(--blue-500);
|
||||
.catalog-tree > .catalog-tree-item.is-dragging,
|
||||
.catalog-tree > .catalog-tree-item.is-dragging-child {
|
||||
display: none;
|
||||
}
|
||||
.catalog-tree-item.is-dragging > .catalog-tree-row {
|
||||
opacity: 0.58;
|
||||
.catalog-tree-placeholder {
|
||||
min-height: 52px;
|
||||
border: 1px dashed var(--blue-500);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--blue-50);
|
||||
box-shadow: inset 0 0 0 3px rgba(59, 130, 246, 0.08);
|
||||
}
|
||||
.catalog-tree-ghost {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 3000;
|
||||
max-width: calc(100vw - 24px);
|
||||
box-sizing: border-box;
|
||||
pointer-events: none;
|
||||
opacity: 0.96;
|
||||
box-shadow: 0 14px 34px rgba(15, 23, 42, 0.2);
|
||||
will-change: transform;
|
||||
}
|
||||
.catalog-tree-ghost .catalog-tree-meta,
|
||||
.catalog-tree-ghost .catalog-tree-status,
|
||||
.catalog-tree-ghost .catalog-tree-actions {
|
||||
display: none;
|
||||
}
|
||||
.catalog-tree-ghost {
|
||||
grid-template-columns: 30px 30px minmax(160px, 1fr);
|
||||
}
|
||||
.catalog-tree-dragging,
|
||||
.catalog-tree-dragging * {
|
||||
cursor: grabbing !important;
|
||||
}
|
||||
.catalog-tree.is-filtering .catalog-action-level,
|
||||
.catalog-tree.is-filtering .catalog-drag {
|
||||
opacity: 0.28;
|
||||
pointer-events: none;
|
||||
}
|
||||
.catalog-item-form {
|
||||
display: flex;
|
||||
@@ -590,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;
|
||||
@@ -683,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;
|
||||
@@ -736,13 +992,27 @@
|
||||
.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 {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.catalog-tree-row {
|
||||
grid-template-columns: 30px 18px minmax(140px, 1fr) 60px 70px;
|
||||
.catalog-tree-row,
|
||||
.catalog-tree > .catalog-tree-item > .catalog-tree-row {
|
||||
grid-template-columns: 30px 30px minmax(140px, 1fr) 94px 258px;
|
||||
}
|
||||
.catalog-tree-meta {
|
||||
display: none;
|
||||
}
|
||||
.catalog-tree-status > span {
|
||||
display: none;
|
||||
@@ -773,8 +1043,153 @@
|
||||
margin-top: 3px;
|
||||
}
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.catalog-tree-row {
|
||||
grid-template-columns: 28px minmax(120px, 1fr) 54px 76px;
|
||||
@media (max-width: 760px) {
|
||||
.catalog-tree {
|
||||
padding: 9px;
|
||||
}
|
||||
.catalog-tree > .catalog-tree-item {
|
||||
width: calc(100% - min(var(--catalog-indent, 0px), 80px));
|
||||
margin-left: min(var(--catalog-indent, 0px), 80px);
|
||||
}
|
||||
.catalog-tree-row,
|
||||
.catalog-tree > .catalog-tree-item > .catalog-tree-row {
|
||||
grid-template-columns: 28px 26px minmax(0, 1fr) auto;
|
||||
gap: 6px;
|
||||
padding: 8px;
|
||||
}
|
||||
.catalog-tree-name {
|
||||
grid-column: 3;
|
||||
}
|
||||
.catalog-tree-status {
|
||||
grid-column: 4;
|
||||
}
|
||||
.catalog-tree-actions {
|
||||
grid-column: 1 / -1;
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
.catalog-tree-actions .btn-icon {
|
||||
width: 40px;
|
||||
min-width: 40px;
|
||||
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,23 +2,35 @@
|
||||
'use strict';
|
||||
var Adminx = window.Adminx || (window.Adminx = {});
|
||||
Adminx.Catalog = {
|
||||
itemForm: null, settingsForm: null, dragRow: null, dragParent: null, dragSnapshot: '', dragTarget: null, 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]');
|
||||
if (drawerTab) { self.tab('[data-catalog-drawer-tab]', '[data-catalog-drawer-panel]', drawerTab.getAttribute('data-catalog-drawer-tab')); }
|
||||
if (e.target.closest('[data-catalog-item-new]')) { self.newItem(); }
|
||||
if (e.target.closest('[data-catalog-item-new]')) { self.newItem(0); }
|
||||
var indent = e.target.closest('[data-catalog-item-indent]');
|
||||
if (indent) { self.changeItemLevel(indent.closest('[data-catalog-item]'), parseInt(indent.getAttribute('data-catalog-item-indent'), 10) || 0); return; }
|
||||
var sibling = e.target.closest('[data-catalog-item-sibling]');
|
||||
if (sibling) { var siblingNode = sibling.closest('[data-catalog-item]'); self.newItem(Number(siblingNode.getAttribute('data-parent-id')) || 0); return; }
|
||||
var child = e.target.closest('[data-catalog-item-child]');
|
||||
if (child) { self.newItem(Number(child.getAttribute('data-catalog-item-child')) || 0); return; }
|
||||
var edit = e.target.closest('[data-catalog-item-edit]');
|
||||
if (edit) { self.editItem(edit.getAttribute('data-catalog-item-edit')); }
|
||||
if (edit) { self.editItem(edit.getAttribute('data-catalog-item-edit')); return; }
|
||||
var del = e.target.closest('[data-catalog-item-delete]');
|
||||
if (del) { self.deleteItem(del.getAttribute('data-catalog-item-delete')); }
|
||||
if (del) { self.deleteItem(del.getAttribute('data-catalog-item-delete')); return; }
|
||||
var treeRow = e.target.closest('[data-catalog-builder-item]');
|
||||
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]');
|
||||
@@ -29,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(); }
|
||||
@@ -45,11 +59,50 @@
|
||||
if (this.settingsForm) { this.settingsForm.addEventListener('submit', function (e) { e.preventDefault(); self.saveSettings(false); }); this.updateSettingsGroups(); this.updateCommerceSettings(); }
|
||||
var createForm = document.querySelector('[data-catalog-create]');
|
||||
if (createForm) { createForm.addEventListener('submit', function (e) { e.preventDefault(); self.createCatalog(createForm); }); }
|
||||
document.addEventListener('dragstart', function (e) { self.dragStart(e); });
|
||||
document.addEventListener('dragover', function (e) { self.dragOver(e); });
|
||||
document.addEventListener('drop', function (e) { if (self.dragRow) { e.preventDefault(); } });
|
||||
document.addEventListener('dragend', function () { self.dragEnd(); });
|
||||
document.addEventListener('pointerdown', function (e) { self.treeDragStart(e); });
|
||||
document.addEventListener('pointermove', function (e) { self.treeDragOver(e); });
|
||||
document.addEventListener('pointerup', function (e) { self.treeDrop(e); });
|
||||
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'); },
|
||||
@@ -66,13 +119,17 @@
|
||||
document.querySelectorAll(tabs).forEach(function (el) { var active = el.getAttribute(tabs.indexOf('drawer') >= 0 ? 'data-catalog-drawer-tab' : 'data-catalog-page-tab') === value; el.classList.toggle('is-active', active); el.setAttribute('aria-selected', active ? 'true' : 'false'); });
|
||||
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 () {
|
||||
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"]');
|
||||
if (parent) { parent.value = String(Number(parentId) || 0); }
|
||||
var defaultFields = this.settingsValues('fields_default[]'), defaultFilters = this.settingsValues('filters_default[]');
|
||||
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');
|
||||
},
|
||||
@@ -80,7 +137,7 @@
|
||||
updateSettingsGroups: function () { if (!this.settingsForm) { return; } this.settingsForm.querySelectorAll('[data-catalog-settings-group]').forEach(function (group) { var name = group.getAttribute('data-catalog-settings-group'), selected = group.querySelectorAll('[name="' + name + '"]:checked').length, badge = group.querySelector('[data-catalog-settings-selected]'); group.querySelectorAll('.catalog-choice-row, .catalog-filter-row').forEach(function (row) { var input = row.querySelector('[name="' + name + '"]'); row.classList.toggle('is-selected', !!input && input.checked); }); if (badge) { badge.textContent = 'Включено: ' + selected; badge.classList.toggle('badge-blue', selected > 0); badge.classList.toggle('badge-gray', selected === 0); } }); },
|
||||
updateCommerceSettings: function () { if (!this.settingsForm) { return; } var purpose = this.settingsForm.querySelector('[name="purpose"]'), visible = purpose && purpose.value === 'commerce'; this.settingsForm.querySelectorAll('[data-catalog-commerce-fields]').forEach(function (section) { section.hidden = !visible; }); },
|
||||
editItem: function (id, requestedTab) {
|
||||
var self = this; Adminx.Loader.show();
|
||||
var self = this; this.markSelectedItem(id); Adminx.Loader.show();
|
||||
fetch(this.base() + '/catalog/items/' + encodeURIComponent(id), { headers: { 'Accept': 'application/json' }, credentials: 'same-origin' }).then(this.json).then(function (payload) {
|
||||
self.fill(payload.data || {}); Adminx.Drawer.open('catalogItemDrawer');
|
||||
if (['main', 'fields', 'filters'].indexOf(requestedTab) >= 0) { self.tab('[data-catalog-drawer-tab]', '[data-catalog-drawer-panel]', requestedTab); }
|
||||
@@ -93,20 +150,42 @@
|
||||
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; }
|
||||
var treeItem = document.querySelector('[data-catalog-item][data-id="' + item.id + '"]');
|
||||
this.treeBranch(treeItem).slice(1).forEach(function (child) {
|
||||
var option = this.itemForm.querySelector('[name="parent_id"] option[value="' + child.getAttribute('data-id') + '"]');
|
||||
if (option) { option.disabled = true; }
|
||||
}, this);
|
||||
this.renderConditionContext(item.condition_context || null);
|
||||
document.querySelector('[data-catalog-drawer-title]').textContent = item.name || 'Раздел каталога'; this.tab('[data-catalog-drawer-tab]', '[data-catalog-drawer-panel]', 'main'); this.updateCounts(); this.setState('item', '');
|
||||
document.querySelector('[data-catalog-drawer-title]').textContent = item.name || 'Раздел каталога'; this.markSelectedItem(item.id); this.tab('[data-catalog-drawer-tab]', '[data-catalog-drawer-panel]', 'main'); this.updateCounts(); this.setState('item', '');
|
||||
},
|
||||
checkValues: function (name, values) { var map = {}; values.forEach(function (id) { map[String(id)] = true; }); this.itemForm.querySelectorAll('[name="' + name + '"]').forEach(function (el) { el.checked = !!map[el.value]; }); },
|
||||
updateCounts: function () { ['fields', 'filters'].forEach(function (type) { var count = this.itemForm.querySelectorAll('[name="' + type + '_use[]"]:checked').length; var el = document.querySelector('[data-catalog-' + type + '-count]'); if (el) { el.textContent = count; } this.itemForm.querySelectorAll('[name="' + type + '_use[]"]').forEach(function (toggle) { var row = toggle.closest('.catalog-choice-row, .catalog-filter-row'); if (row) { row.classList.toggle('is-selected', toggle.checked); } }); this.itemForm.querySelectorAll('[data-catalog-field-group="' + type + '"]').forEach(function (group) { var selected = group.querySelectorAll('[name="' + type + '_use[]"]:checked').length; var badge = group.querySelector('[data-catalog-group-selected]'); if (badge) { badge.textContent = 'Включено: ' + selected; badge.classList.toggle('badge-blue', selected > 0); badge.classList.toggle('badge-gray', selected === 0); } }); }, this); var orderButton = this.itemForm.querySelector('[data-catalog-filter-order]'); if (orderButton) { orderButton.disabled = this.filterOrder.length < 2; } this.renderConditionContext(this.conditionContext); },
|
||||
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]');
|
||||
@@ -154,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; if (toggle) { toggle.checked = active; this.updateTreeStatus(toggle); } 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; } },
|
||||
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';
|
||||
@@ -180,12 +304,239 @@
|
||||
var self = this, run = function () { var data = new FormData(); data.append('_csrf', self.csrf()); self.ajax(self.url() + '/items/' + id + '/delete', data, function (payload) { Adminx.Toast.show(payload.message, 'success'); window.location.reload(); }); };
|
||||
if (Adminx.Confirm) { Adminx.Confirm.open({ kind: 'error', title: 'Удалить раздел?', message: 'Будут удалены также все вложенные разделы. Документы останутся.', confirmLabel: 'Удалить', confirmClass: 'btn-danger', onConfirm: run }); } else if (confirm('Удалить раздел и все вложенные?')) { run(); }
|
||||
},
|
||||
search: function (value) { value = String(value || '').trim().toLowerCase(); document.querySelectorAll('[data-catalog-item]').forEach(function (row) { row.classList.toggle('is-filtered', value && row.textContent.toLowerCase().indexOf(value) < 0); }); },
|
||||
dragStart: function (e) { var handle = e.target.closest('.catalog-drag[draggable="true"]'), row = handle ? handle.closest('[data-catalog-item]') : null; if (!row) { e.preventDefault(); return; } this.dragRow = row; this.dragParent = row.parentNode; this.dragSnapshot = this.siblingOrder(this.dragParent); row.classList.add('is-dragging'); e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', row.getAttribute('data-id')); },
|
||||
dragOver: function (e) { if (!this.dragRow) { return; } var target = e.target.closest('[data-catalog-item]'); if (!target || target === this.dragRow || this.dragRow.contains(target)) { return; } var row = target.querySelector(':scope > .catalog-tree-row'), rect = row.getBoundingClientRect(), ratio = (e.clientY - rect.top) / rect.height, mode = ratio < .28 ? 'before' : (ratio > .72 ? 'after' : 'inside'), destination = null, reference = null, parentId = 0; e.preventDefault(); e.dataTransfer.dropEffect = 'move'; if (this.dragTarget && this.dragTarget !== target) { this.dragTarget.classList.remove('is-drop-target', 'is-drop-after', 'is-drop-inside'); } this.dragTarget = target; target.classList.add('is-drop-target'); target.classList.toggle('is-drop-after', mode === 'after'); target.classList.toggle('is-drop-inside', mode === 'inside'); if (mode === 'inside') { destination = target.querySelector(':scope > .catalog-tree-children'); if (!destination) { destination = document.createElement('ol'); destination.className = 'catalog-tree-children'; target.appendChild(destination); } parentId = Number(target.getAttribute('data-id')); } else { destination = target.parentNode; reference = mode === 'before' ? target : target.nextSibling; parentId = Number(target.getAttribute('data-parent-id')); } if (destination !== this.dragRow.parentNode || (reference !== this.dragRow && this.dragRow.nextSibling !== reference)) { destination.insertBefore(this.dragRow, reference); this.dragRow.setAttribute('data-parent-id', String(parentId)); } },
|
||||
dragEnd: function () { if (!this.dragRow) { return; } var changed = this.dragSnapshot !== this.siblingOrder(this.dragParent); this.dragRow.classList.remove('is-dragging'); if (this.dragTarget) { this.dragTarget.classList.remove('is-drop-target', 'is-drop-after', 'is-drop-inside'); } document.querySelectorAll('.catalog-tree-children').forEach(function (list) { if (!list.querySelector(':scope > [data-catalog-item]')) { list.remove(); } }); this.dragRow = null; this.dragParent = null; this.dragTarget = null; this.dragSnapshot = ''; if (changed) { this.saveOrder(); } },
|
||||
siblingOrder: function (parent) { return Array.prototype.filter.call(parent ? parent.children : [], function (el) { return el.matches('[data-catalog-item]'); }).map(function (el) { return el.getAttribute('data-id'); }).join(','); },
|
||||
saveOrder: function () { var rows = []; document.querySelectorAll('[data-catalog-item]').forEach(function (row) { var siblings = Array.prototype.filter.call(row.parentNode.children, function (el) { return el.matches('[data-catalog-item]'); }); rows.push({ id: Number(row.getAttribute('data-id')), parent_id: Number(row.getAttribute('data-parent-id')), position: siblings.indexOf(row) }); }); var data = new FormData(); data.append('_csrf', this.csrf()); data.append('order', JSON.stringify(rows)); this.ajax(this.url() + '/reorder', data, function (payload) { Adminx.Toast.show(payload.message, 'success'); }); },
|
||||
markSelectedItem: function (id) {
|
||||
document.querySelectorAll('[data-catalog-builder-item]').forEach(function (row) {
|
||||
row.classList.toggle('is-selected', String(row.getAttribute('data-catalog-builder-item')) === String(id));
|
||||
});
|
||||
},
|
||||
treeRoot: function () { return document.querySelector('[data-catalog-tree]'); },
|
||||
treeNodes: function () {
|
||||
var root = this.treeRoot();
|
||||
return root ? Array.prototype.filter.call(root.children, function (node) { return node.matches('[data-catalog-item]'); }) : [];
|
||||
},
|
||||
search: function (value) {
|
||||
value = String(value || '').trim().toLowerCase();
|
||||
var nodes = this.treeNodes(), byId = {}, visible = {};
|
||||
nodes.forEach(function (node) { byId[String(node.getAttribute('data-id'))] = node; node.classList.add('is-filtered'); });
|
||||
if (!value) {
|
||||
nodes.forEach(function (node) { node.classList.remove('is-filtered'); });
|
||||
} else {
|
||||
nodes.forEach(function (node) {
|
||||
var name = node.querySelector('.catalog-tree-name');
|
||||
if (!name || name.textContent.toLowerCase().indexOf(value) < 0) { return; }
|
||||
var current = node;
|
||||
while (current && !visible[current.getAttribute('data-id')]) {
|
||||
visible[current.getAttribute('data-id')] = true;
|
||||
current = byId[String(current.getAttribute('data-parent-id'))] || null;
|
||||
}
|
||||
});
|
||||
Object.keys(visible).forEach(function (id) { if (byId[id]) { byId[id].classList.remove('is-filtered'); } });
|
||||
}
|
||||
var root = this.treeRoot();
|
||||
if (root) { root.classList.toggle('is-filtering', !!value); }
|
||||
},
|
||||
treeDragStart: function (e) {
|
||||
var handle = e.target.closest('[data-catalog-drag-handle]');
|
||||
var root = handle ? handle.closest('[data-catalog-tree]') : null;
|
||||
if (!handle || !root || handle.disabled || this.orderSaving || root.classList.contains('is-filtering') || (typeof e.button === 'number' && e.button !== 0)) { return; }
|
||||
this.dragItem = handle.closest('[data-catalog-item]');
|
||||
if (!this.dragItem) { return; }
|
||||
this.dragPointerId = e.pointerId;
|
||||
this.dragStartX = e.clientX;
|
||||
this.dragStartY = e.clientY;
|
||||
this.dragStarted = false;
|
||||
this.dragOrderSnapshot = this.treeOrderSignature();
|
||||
if (handle.setPointerCapture) { handle.setPointerCapture(e.pointerId); }
|
||||
e.preventDefault();
|
||||
},
|
||||
beginTreeDrag: function (e) {
|
||||
if (!this.dragItem || this.dragStarted) { return; }
|
||||
var row = this.dragItem.querySelector('[data-catalog-builder-item]');
|
||||
var firstRect = this.dragItem.getBoundingClientRect();
|
||||
var rowRect = row.getBoundingClientRect();
|
||||
this.dragStarted = true;
|
||||
this.dragGroup = this.treeBranch(this.dragItem);
|
||||
this.dragPlaceholder = document.createElement('li');
|
||||
this.dragPlaceholder.className = 'catalog-tree-placeholder';
|
||||
this.dragPlaceholder.setAttribute('aria-hidden', 'true');
|
||||
var lastRect = this.dragGroup[this.dragGroup.length - 1].getBoundingClientRect();
|
||||
this.dragPlaceholder.style.height = Math.max(52, lastRect.bottom - firstRect.top) + 'px';
|
||||
this.dragItem.parentNode.insertBefore(this.dragPlaceholder, this.dragItem);
|
||||
this.dragGhost = row.cloneNode(true);
|
||||
this.dragGhost.classList.remove('is-selected');
|
||||
this.dragGhost.classList.add('catalog-tree-ghost');
|
||||
this.dragGhost.style.width = Math.min(rowRect.width, 520, Math.max(1, window.innerWidth - 24)) + 'px';
|
||||
document.body.appendChild(this.dragGhost);
|
||||
this.positionTreeDragGhost(e);
|
||||
document.body.classList.add('catalog-tree-dragging');
|
||||
this.treeRoot().classList.add('is-drag-active');
|
||||
this.dragGroup.forEach(function (node, index) { node.classList.add(index === 0 ? 'is-dragging' : 'is-dragging-child'); });
|
||||
},
|
||||
treeDragOver: function (e) {
|
||||
if (!this.dragItem || e.pointerId !== this.dragPointerId) { return; }
|
||||
if (!this.dragStarted) {
|
||||
if (Math.abs(e.clientX - this.dragStartX) < 5 && Math.abs(e.clientY - this.dragStartY) < 5) { return; }
|
||||
this.beginTreeDrag(e);
|
||||
}
|
||||
e.preventDefault();
|
||||
this.positionTreeDragGhost(e);
|
||||
this.scrollTree(e.clientY);
|
||||
var target = null, bottom = false, self = this;
|
||||
this.treeNodes().some(function (node) {
|
||||
if (self.dragGroup.indexOf(node) !== -1 || node.classList.contains('is-filtered')) { return false; }
|
||||
var candidate = node.querySelector('[data-catalog-builder-item]');
|
||||
var rect = candidate ? candidate.getBoundingClientRect() : null;
|
||||
if (!rect || e.clientY >= rect.bottom) { return false; }
|
||||
target = node;
|
||||
bottom = e.clientY > rect.top + rect.height / 2;
|
||||
return true;
|
||||
});
|
||||
document.querySelectorAll('.catalog-tree-row.drag-over-top, .catalog-tree-row.drag-over-bottom').forEach(function (row) { row.classList.remove('drag-over-top', 'drag-over-bottom'); });
|
||||
if (!target) { this.treeRoot().appendChild(this.dragPlaceholder); return; }
|
||||
var targetRow = target.querySelector('[data-catalog-builder-item]');
|
||||
var branch = this.treeBranch(target);
|
||||
var anchor = bottom ? branch[branch.length - 1].nextSibling : target;
|
||||
if (anchor !== this.dragPlaceholder) { target.parentNode.insertBefore(this.dragPlaceholder, anchor); }
|
||||
targetRow.classList.toggle('drag-over-top', !bottom);
|
||||
targetRow.classList.toggle('drag-over-bottom', bottom);
|
||||
},
|
||||
treeDrop: function (e) {
|
||||
if (!this.dragItem || e.pointerId !== this.dragPointerId) { return; }
|
||||
e.preventDefault();
|
||||
if (!this.dragStarted || !this.dragPlaceholder || !this.dragPlaceholder.parentNode) { this.treeDragEnd(); return; }
|
||||
var placeholder = this.dragPlaceholder;
|
||||
this.dragGroup.forEach(function (node) { placeholder.parentNode.insertBefore(node, placeholder); });
|
||||
placeholder.parentNode.removeChild(placeholder);
|
||||
this.dragPlaceholder = null;
|
||||
this.normalizeTreeHierarchy();
|
||||
var changed = this.treeOrderSignature() !== this.dragOrderSnapshot;
|
||||
this.treeDragEnd();
|
||||
if (changed) { this.persistTreeOrder(); }
|
||||
},
|
||||
treeDragEnd: function () {
|
||||
this.dragGroup.forEach(function (node) { node.classList.remove('is-dragging', 'is-dragging-child'); });
|
||||
if (this.dragPlaceholder && this.dragPlaceholder.parentNode) { this.dragPlaceholder.parentNode.removeChild(this.dragPlaceholder); }
|
||||
document.querySelectorAll('.catalog-tree-row.drag-over-top, .catalog-tree-row.drag-over-bottom').forEach(function (row) { row.classList.remove('drag-over-top', 'drag-over-bottom'); });
|
||||
var root = this.treeRoot();
|
||||
if (root) { root.classList.remove('is-drag-active'); }
|
||||
if (this.dragGhost && this.dragGhost.parentNode) { this.dragGhost.parentNode.removeChild(this.dragGhost); }
|
||||
document.body.classList.remove('catalog-tree-dragging');
|
||||
this.dragItem = null;
|
||||
this.dragGroup = [];
|
||||
this.dragPlaceholder = null;
|
||||
this.dragGhost = null;
|
||||
this.dragPointerId = null;
|
||||
this.dragStarted = false;
|
||||
this.dragOrderSnapshot = '';
|
||||
},
|
||||
positionTreeDragGhost: function (e) {
|
||||
if (!this.dragGhost) { return; }
|
||||
var left = Math.min(e.clientX + 14, window.innerWidth - this.dragGhost.offsetWidth - 12);
|
||||
var top = Math.min(e.clientY + 12, window.innerHeight - this.dragGhost.offsetHeight - 12);
|
||||
this.dragGhost.style.transform = 'translate3d(' + Math.max(12, left) + 'px,' + Math.max(12, top) + 'px,0)';
|
||||
},
|
||||
scrollTree: function (clientY) {
|
||||
var edge = 72;
|
||||
if (clientY < edge) { window.scrollBy(0, -Math.ceil((edge - clientY) / 5)); }
|
||||
if (clientY > window.innerHeight - edge) { window.scrollBy(0, Math.ceil((clientY - window.innerHeight + edge) / 5)); }
|
||||
},
|
||||
treeOrderSignature: function () {
|
||||
return this.treeNodes().map(function (node) { return node.getAttribute('data-id') + ':' + node.getAttribute('data-level'); }).join('|');
|
||||
},
|
||||
treeBranch: function (node) {
|
||||
if (!node) { return []; }
|
||||
var branch = [node], level = parseInt(node.getAttribute('data-level'), 10) || 0, next = node.nextElementSibling;
|
||||
while (next) {
|
||||
if (next === this.dragPlaceholder) { next = next.nextElementSibling; continue; }
|
||||
if (!next.matches('[data-catalog-item]') || (parseInt(next.getAttribute('data-level'), 10) || 0) <= level) { break; }
|
||||
branch.push(next);
|
||||
next = next.nextElementSibling;
|
||||
}
|
||||
return branch;
|
||||
},
|
||||
canIndentItem: function (node) {
|
||||
var level = parseInt(node.getAttribute('data-level'), 10) || 0, previous = node.previousElementSibling;
|
||||
while (previous) {
|
||||
if (!previous.matches('[data-catalog-item]')) { previous = previous.previousElementSibling; continue; }
|
||||
var previousLevel = parseInt(previous.getAttribute('data-level'), 10) || 0;
|
||||
if (previousLevel < level) { return false; }
|
||||
if (previousLevel === level) { return true; }
|
||||
previous = previous.previousElementSibling;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
changeItemLevel: function (node, delta) {
|
||||
if (!node || !delta || this.orderSaving) { return; }
|
||||
var root = this.treeRoot();
|
||||
if (root && root.classList.contains('is-filtering')) { Adminx.Toast.show('Очистите поиск перед изменением структуры', 'info'); return; }
|
||||
var level = parseInt(node.getAttribute('data-level'), 10) || 0;
|
||||
if (delta > 0 && !this.canIndentItem(node)) { return; }
|
||||
if (delta < 0 && level === 0) { return; }
|
||||
var shift = delta > 0 ? 1 : -1;
|
||||
this.treeBranch(node).forEach(function (branchNode) {
|
||||
var branchLevel = parseInt(branchNode.getAttribute('data-level'), 10) || 0;
|
||||
branchNode.setAttribute('data-level', String(Math.max(0, branchLevel + shift)));
|
||||
});
|
||||
this.normalizeTreeHierarchy();
|
||||
this.persistTreeOrder();
|
||||
},
|
||||
normalizeTreeHierarchy: function () {
|
||||
var nodes = this.treeNodes(), parents = [], positions = {}, previousLevel = 0, self = this;
|
||||
nodes.forEach(function (node, index) {
|
||||
var level = Math.max(0, parseInt(node.getAttribute('data-level'), 10) || 0);
|
||||
if (index === 0) { level = 0; }
|
||||
if (level > previousLevel + 1) { level = previousLevel + 1; }
|
||||
var parentId = level > 0 && parents[level - 1] ? parents[level - 1] : 0;
|
||||
if (level > 0 && !parentId) { level = 0; parentId = 0; }
|
||||
var id = parseInt(node.getAttribute('data-id'), 10) || 0;
|
||||
var key = String(parentId);
|
||||
var position = positions[key] || 0;
|
||||
positions[key] = position + 1;
|
||||
parents[level] = id;
|
||||
parents.length = level + 1;
|
||||
previousLevel = level;
|
||||
node.setAttribute('data-level', String(level));
|
||||
node.setAttribute('data-parent-id', String(parentId));
|
||||
node.setAttribute('data-position', String(position));
|
||||
node.style.setProperty('--catalog-indent', Math.min(level, 10) * 28 + 'px');
|
||||
var number = node.querySelector('.catalog-tree-position');
|
||||
if (number) { number.textContent = String(position + 1); }
|
||||
var badge = node.querySelector('[data-catalog-level-badge]');
|
||||
if (badge) { badge.textContent = 'уровень ' + (level + 1); }
|
||||
});
|
||||
nodes.forEach(function (node) {
|
||||
var level = parseInt(node.getAttribute('data-level'), 10) || 0;
|
||||
var decrease = node.querySelector('[data-catalog-item-indent="-1"]');
|
||||
var increase = node.querySelector('[data-catalog-item-indent="1"]');
|
||||
if (decrease) { decrease.disabled = level === 0; }
|
||||
if (increase) { increase.disabled = !self.canIndentItem(node); }
|
||||
});
|
||||
},
|
||||
persistTreeOrder: function () {
|
||||
if (this.orderSaving) { return; }
|
||||
this.normalizeTreeHierarchy();
|
||||
var rows = this.treeNodes().map(function (node) {
|
||||
return {
|
||||
id: Number(node.getAttribute('data-id')),
|
||||
parent_id: Number(node.getAttribute('data-parent-id')),
|
||||
position: Number(node.getAttribute('data-position'))
|
||||
};
|
||||
});
|
||||
var data = new FormData(), self = this, root = this.treeRoot();
|
||||
data.append('_csrf', this.csrf());
|
||||
data.append('order', JSON.stringify(rows));
|
||||
this.orderSaving = true;
|
||||
if (root) { root.classList.add('is-order-saving'); }
|
||||
this.ajax(this.url() + '/reorder', data, function (payload) {
|
||||
self.orderSaving = false;
|
||||
if (root) { root.classList.remove('is-order-saving'); }
|
||||
Adminx.Toast.show(payload.message || 'Порядок сохранён', 'success');
|
||||
}, { quiet: true, fail: function () {
|
||||
self.orderSaving = false;
|
||||
if (root) { root.classList.remove('is-order-saving'); }
|
||||
setTimeout(function () { window.location.reload(); }, 400);
|
||||
} });
|
||||
},
|
||||
ajax: function (url, data, done, options) { options = options || {}; if (!options.quiet) { Adminx.Loader.show(); } fetch(url, { method: 'POST', body: data, headers: { 'Accept': 'application/json' }, credentials: 'same-origin' }).then(this.json).then(function (payload) { if (!payload.success) { throw payload; } done(payload); }).catch(function (payload) { if (options.fail) { options.fail(payload); } Adminx.Catalog.error(payload); }).finally(function () { if (!options.quiet) { Adminx.Loader.hide(); } }); },
|
||||
json: function (res) { return res.json().then(function (payload) { if (!res.ok) { throw payload; } return payload; }); },
|
||||
esc: function (value) { var node = document.createElement('div'); node.textContent = String(value == null ? '' : value); return node.innerHTML; },
|
||||
|
||||
@@ -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.2.0',
|
||||
'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>
|
||||
@@ -1,18 +1,19 @@
|
||||
{% extends '@adminx/main.twig' %}
|
||||
{% block title %}{{ catalog.rubric_title }} · Каталог{% endblock %}
|
||||
{% macro rows(items, can_manage) %}
|
||||
{% macro rows(items, can_manage, level) %}
|
||||
{% set level = level|default(0) %}
|
||||
{% for item in items %}
|
||||
<li class="catalog-tree-item{{ item.status ? '' : ' is-inactive' }}" data-catalog-item data-id="{{ item.id }}" data-parent-id="{{ item.parent_id }}" data-filter-count="{{ item.filters_use|length }}">
|
||||
<div class="catalog-tree-row">
|
||||
<button class="catalog-drag" type="button" draggable="{{ can_manage ? 'true' : 'false' }}" aria-label="Перетащить" data-tooltip="Изменить порядок"><i class="ti ti-grip-vertical"></i></button>
|
||||
<span class="catalog-tree-branch"><i class="ti ti-corner-down-right"></i></span>
|
||||
<li class="catalog-tree-item{{ item.status ? '' : ' is-inactive' }}" data-catalog-item data-id="{{ item.id }}" data-parent-id="{{ item.parent_id }}" data-position="{{ item.position }}" data-level="{{ level }}" data-filter-count="{{ item.filters_use|length }}" style="--catalog-indent:{{ level > 10 ? 280 : level * 28 }}px">
|
||||
<div class="catalog-tree-row" data-catalog-builder-item="{{ item.id }}">
|
||||
<button class="catalog-drag" type="button" aria-label="Перетащить раздел" data-tooltip="Перетащить раздел вместе с подразделами" data-catalog-drag-handle{{ can_manage ? '' : ' disabled' }}><i class="ti ti-grip-vertical"></i></button>
|
||||
<span class="catalog-tree-position" data-tooltip="Позиция внутри уровня">{{ item.position + 1 }}</span>
|
||||
<div class="catalog-tree-name"><b>{{ item.name }}</b><small>#{{ item.id }}{% if item.document_id %} · документ #{{ item.document_id }}{% endif %}</small></div>
|
||||
<div class="catalog-tree-meta"><span class="badge badge-gray" data-catalog-level-badge>уровень {{ level + 1 }}</span><span class="catalog-tree-count" data-tooltip="Поля / фильтры">{{ item.fields_use|length }} / {{ item.filters_use|length }}</span></div>
|
||||
<div class="catalog-tree-status"><span data-catalog-item-status-label>{{ item.status ? 'активен' : 'скрыт' }}</span><label class="switch" data-tooltip="{{ item.status ? 'Скрыть раздел' : 'Включить раздел' }}"><input type="checkbox" data-catalog-item-status="{{ item.id }}"{{ item.status ? ' checked' : '' }} aria-label="{{ item.status ? 'Скрыть раздел' : 'Включить раздел' }}"></label></div>
|
||||
<span class="catalog-tree-count" data-tooltip="Поля / фильтры">{{ item.fields_use|length }} / {{ item.filters_use|length }}</span>
|
||||
{% if can_manage %}<div class="catalog-tree-actions"><button class="btn btn-ghost btn-icon btn-sm catalog-action-edit" type="button" data-catalog-item-edit="{{ item.id }}" data-tooltip="Редактировать"><i class="ti ti-edit"></i></button><button class="btn btn-ghost btn-icon btn-sm catalog-action-delete" type="button" data-catalog-item-delete="{{ item.id }}" data-tooltip="Удалить"><i class="ti ti-trash"></i></button></div>{% endif %}
|
||||
{% if can_manage %}<div class="catalog-tree-actions"><button class="btn btn-ghost btn-icon btn-sm catalog-action-level" type="button" data-catalog-item-indent="-1" data-tooltip="Поднять на уровень выше"{{ level == 0 ? ' disabled' : '' }}><i class="ti ti-arrow-left"></i></button><button class="btn btn-ghost btn-icon btn-sm catalog-action-level" type="button" data-catalog-item-indent="1" data-tooltip="Сделать подразделом"><i class="ti ti-arrow-right"></i></button><button class="btn btn-ghost btn-icon btn-sm catalog-action-sibling" type="button" data-catalog-item-sibling="{{ item.id }}" data-tooltip="Добавить рядом"><i class="ti ti-row-insert-bottom"></i></button><button class="btn btn-ghost btn-icon btn-sm catalog-action-child" type="button" data-catalog-item-child="{{ item.id }}" data-tooltip="Добавить подраздел"><i class="ti ti-subtask"></i></button><button class="btn btn-ghost btn-icon btn-sm catalog-action-edit" type="button" data-catalog-item-edit="{{ item.id }}" data-tooltip="Редактировать"><i class="ti ti-edit"></i></button><button class="btn btn-ghost btn-icon btn-sm catalog-action-delete" type="button" data-catalog-item-delete="{{ item.id }}" data-tooltip="Удалить"><i class="ti ti-trash"></i></button></div>{% endif %}
|
||||
</div>
|
||||
{% if item.children %}<ol class="catalog-tree-children">{{ _self.rows(item.children, can_manage) }}</ol>{% endif %}
|
||||
</li>
|
||||
{% if item.children %}{{ _self.rows(item.children, can_manage, level + 1) }}{% endif %}
|
||||
{% endfor %}
|
||||
{% endmacro %}
|
||||
{% block content %}
|
||||
@@ -25,7 +26,7 @@
|
||||
<div class="section-header catalog-panel-header"><div class="section-icon"><i class="ti ti-list-tree"></i></div><div><div class="section-eyebrow">Структура</div><h2>Разделы каталога</h2><p class="section-desc">Порядок и вложенность используются в каталожном поле документа.</p></div></div>
|
||||
<div class="card catalog-card">
|
||||
<div class="catalog-section-head"><div class="catalog-section-title"><span class="icon-tile catalog-head-icon" style="--tile-bg:var(--violet-100);--tile-fg:var(--violet-600)"><i class="ti ti-list-tree"></i></span><div><h2>Дерево разделов</h2><p class="text-secondary">Перетаскивайте строки за маркер слева.</p></div></div><div class="catalog-tree-tools"><label class="input-wrap catalog-tree-search"><i class="ti ti-search"></i><input class="input" type="search" placeholder="Найти раздел" data-catalog-tree-search></label>{% if can_manage %}<button class="btn btn-secondary" type="button" data-catalog-recompile-all><i class="ti ti-refresh"></i>Пересобрать фильтры</button>{% endif %}</div></div>
|
||||
<ol class="catalog-tree" data-catalog-tree>{{ _self.rows(tree, can_manage) }}</ol>
|
||||
<ol class="catalog-tree" data-catalog-tree>{{ _self.rows(tree, can_manage, 0) }}</ol>
|
||||
{% if not tree %}<div class="empty-state">Разделов пока нет.</div>{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
@@ -41,12 +42,12 @@
|
||||
<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">
|
||||
<div class="form-grid catalog-product-card-values">
|
||||
<label class="field col-12"><span class="field-label">Представление</span><select class="select" name="product_card_template_id"><option value="0">Стандартное файловое</option>{% for template in card_template_options %}<option value="{{ template.id }}"{{ settings.product_card_template_id == template.id ? ' selected' : '' }}>{{ template.title }} · {{ template.code }}{% if not template.is_published %} · черновик{% else %} · v{{ template.version }}{% endif %}</option>{% endfor %}</select><span class="field-hint"><a href="{{ ADMINX_BASE }}/catalog/card-templates">Редактировать представления карточек</a>. На сайте используется только опубликованная версия.</span></label>
|
||||
<label class="field col-12"><span class="field-label">Представление</span><select class="select" name="product_card_template_id"><option value="0">Общая «Стандартная карточка»</option>{% for template in card_template_options %}{% if template.id != 1 %}<option value="{{ template.id }}"{{ settings.product_card_template_id == template.id ? ' selected' : '' }}>{{ template.title }} · {{ template.code }}{% if not template.is_published %} · черновик{% else %} · v{{ template.version }}{% endif %}</option>{% endif %}{% endfor %}</select><span class="field-hint"><a href="{{ ADMINX_BASE }}/catalog/card-templates">Редактировать представления карточек</a>. Значение по умолчанию использует опубликованную «Стандартную карточку»; файловый шаблон остаётся резервом, пока её разметка пуста.</span></label>
|
||||
<label class="field col-6"><span class="field-label">Фотографий в слайдере</span><select class="select" name="product_card[max_images]">{% for count in 1..5 %}<option value="{{ count }}"{{ settings.product_card.max_images == count ? ' selected' : '' }}>{{ count }}</option>{% endfor %}</select></label>
|
||||
<label class="field col-6"><span class="field-label">Бесплатная доставка от</span><div class="catalog-product-card-price"><input class="input" type="number" min="0" step="1000" name="product_card[delivery_threshold]" value="{{ settings.product_card.delivery_threshold|number_format(0, '.', '') }}"><span>₽</span></div></label>
|
||||
</div>
|
||||
@@ -65,7 +66,7 @@
|
||||
<div class="form-grid">
|
||||
<label class="field col-5"><span class="field-label">Шаблон</span><select class="select" name="filter_template_id"><option value="0">Не выбран</option>{% for template in filter_template_options %}<option value="{{ template.id }}"{{ settings.filter_template_id == template.id ? ' selected' : '' }}>{{ template.title }} · {{ template.code }}{% if template.is_published %} · v{{ template.version }}{% else %} · черновик{% endif %}</option>{% endfor %}</select><span class="field-hint"><a href="{{ ADMINX_BASE }}/catalog/filter-templates">Редактировать шаблоны фильтров</a></span></label>
|
||||
<label class="field col-4"><span class="field-label">Режим вывода</span><select class="select" name="filter_template_mode"><option value="legacy"{{ settings.filter_template_mode == 'legacy' ? ' selected' : '' }}>Текущий публичный вывод</option><option value="preview"{{ settings.filter_template_mode == 'preview' ? ' selected' : '' }}>Только предпросмотр</option><option value="native"{{ settings.filter_template_mode == 'native' ? ' selected' : '' }}>Опубликованный Twig</option></select><span class="field-hint">«Предпросмотр» не меняет сайт.</span></label>
|
||||
<label class="field col-3"><span class="field-label">Нулевые значения</span><select class="select" name="filter_template[zero_behavior]"><option value="show"{{ settings.filter_template.zero_behavior == 'show' ? ' selected' : '' }}>Показывать</option><option value="disable"{{ settings.filter_template.zero_behavior == 'disable' ? ' selected' : '' }}>Отключать</option><option value="hide"{{ settings.filter_template.zero_behavior == 'hide' ? ' selected' : '' }}>Скрывать</option></select></label>
|
||||
<label class="field col-3"><span class="field-label">Нулевые значения</span><select class="select" name="filter_template[zero_behavior]"><option value="hide"{{ settings.filter_template.zero_behavior == 'hide' ? ' selected' : '' }}>Скрывать</option><option value="disable"{{ settings.filter_template.zero_behavior == 'disable' ? ' selected' : '' }}>Показывать неактивными</option><option value="show"{{ settings.filter_template.zero_behavior == 'show' ? ' selected' : '' }}>Показывать активными</option></select><span class="field-hint">Выбранное значение не скрывается, чтобы фильтр можно было снять.</span></label>
|
||||
<div class="field col-12 catalog-toggle-row"><span><b>Показывать количество товаров</b><small>В Twig значение доступно как <code>option.count</code>.</small></span><label class="switch"><input type="checkbox" name="filter_template[show_counts]" value="1"{{ settings.filter_template.show_counts ? ' checked' : '' }} aria-label="Показывать количество товаров"></label></div>
|
||||
</div>
|
||||
</section>{% endif %}
|
||||
@@ -94,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 !defined('ENV_CMS') || strtolower((string) ENV_CMS) !== 'production';
|
||||
$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.0',
|
||||
'version' => '0.1.3',
|
||||
'registry' => array('dynamic' => true),
|
||||
);
|
||||
}
|
||||
@@ -28,7 +28,7 @@
|
||||
return array(
|
||||
'code' => 'console',
|
||||
'name' => 'PHP-консоль',
|
||||
'version' => '0.1.0',
|
||||
'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>
|
||||
|
||||
|
||||
@@ -19,26 +19,99 @@
|
||||
use App\Common\AdminAssets;
|
||||
use App\Adminx\Support\Roles;
|
||||
use App\Adminx\Support\CodeEditor;
|
||||
use App\Adminx\Support\SavedViews;
|
||||
use App\Common\Auth;
|
||||
use App\Common\Controller as BaseController;
|
||||
use App\Common\Permission;
|
||||
use App\Helpers\Request;
|
||||
use App\Helpers\Response;
|
||||
use App\Helpers\Csv;
|
||||
use App\Common\AuditLog;
|
||||
|
||||
class Controller extends BaseController
|
||||
{
|
||||
public function exportCustomers(array $params = array())
|
||||
{
|
||||
if (!Permission::check('view_customers')) { Response::forbidden(); return ''; }
|
||||
$q = Request::getStr('q', '');
|
||||
AuditLog::record('customers.exported', array('actor_id' => Auth::id(), 'target_type' => 'customers', 'meta' => array('q' => $q)));
|
||||
Csv::download('customers_' . date('Ymd_His') . '.csv', array('ID', 'Имя', 'Фамилия', 'Логин', 'Email', 'Телефон', 'Компания', 'Статус', 'Регистрация', 'Последний вход'), function ($write) use ($q) {
|
||||
$before = 0;
|
||||
do {
|
||||
$rows = Model::exportChunk($q, $before, 500);
|
||||
foreach ($rows as $row) { $before = (int) $row['id']; $write(array($row['id'], $row['firstname'], $row['lastname'], $row['user_name'], $row['email'], $row['phone'], $row['company'], (string) $row['status'] === '1' ? 'Активен' : 'Отключён', (int) $row['reg_time'] > 0 ? date('d.m.Y H:i', (int) $row['reg_time']) : '', (int) $row['last_visit'] > 0 ? date('d.m.Y H:i', (int) $row['last_visit']) : ''));
|
||||
}
|
||||
} while (count($rows) === 500);
|
||||
});
|
||||
return '';
|
||||
}
|
||||
|
||||
public function index(array $params=array())
|
||||
{
|
||||
if(!Permission::check('view_customers')){Response::forbidden();return '';}AdminAssets::addStyle($this->base().'/modules/Customers/assets/customers.css',50);AdminAssets::addScript($this->base().'/modules/Customers/assets/customers.js',50);CodeEditor::useCodeMirror('htmlmixed');
|
||||
$oauthModules=Model::oauthModules();foreach($oauthModules as &$oauthModule){$oauthModule['can_open']=Permission::check($oauthModule['permission']);}unset($oauthModule);
|
||||
$tab=Request::getStr('tab','customers');if(!in_array($tab,array('customers','fields','auth','pages'),true)){$tab='customers';}return $this->render('@customers/index.twig',array('tab'=>$tab,'customers'=>Model::customers(Request::getStr('q','')),'fields'=>Model::fields(),'stats'=>Model::stats(),'auth_settings'=>Model::authSettings(),'checkout_access_template_default'=>\App\Common\PublicAuthSettings::defaultCheckoutAccessTemplate(),'oauth_modules'=>$oauthModules,'customer_groups'=>Model::groups(),'admin_roles'=>Roles::map(),'page_templates'=>Model::pageTemplates(),'auth_forms'=>Model::authFormDefinitions(),'q'=>Request::getStr('q',''),'can_manage'=>Permission::check('manage_customers'),'can_manage_admin_access'=>Permission::check('manage_users')));
|
||||
$authMethods=Model::authMethods();$authMethodStats=array('installed'=>0,'active'=>0);foreach($authMethods as &$authMethod){$authMethod['can_open']=$authMethod['installed']?Permission::check($authMethod['permission']):Permission::check('view_modules');$authMethod['action_url']=$authMethod['installed']?$authMethod['url']:'/modules';$authMethod['action_label']=$authMethod['installed']?'Настроить':'Открыть модули';if($authMethod['installed']){$authMethodStats['installed']++;}if($authMethod['active']){$authMethodStats['active']++;}}unset($authMethod);
|
||||
$tab=Request::getStr('tab','center');if(!in_array($tab,array('center','customers','fields','auth','pages'),true)){$tab='center';}$q=Request::getStr('q','');$segment=Request::getStr('segment','all');return $this->render('@customers/index.twig',array('tab'=>$tab,'customers'=>Model::customers($q),'fields'=>Model::fields(),'stats'=>Model::stats(),'center_customers'=>$tab==='center'?CustomerCenter::listing($q,$segment):array(),'center_stats'=>$tab==='center'?CustomerCenter::stats():array(),'center_segments'=>CustomerCenter::segments(),'duplicate_groups'=>$tab==='center'?CustomerCenter::duplicateGroups():array(),'segment'=>$segment,'saved_views'=>SavedViews::all('customers_center',Auth::id(),array('q','segment')),'auth_settings'=>Model::authSettings(),'checkout_access_template_default'=>\App\Common\PublicAuthSettings::defaultCheckoutAccessTemplate(),'auth_methods'=>$authMethods,'auth_method_stats'=>$authMethodStats,'customer_groups'=>Model::groups(),'admin_roles'=>Roles::map(),'page_templates'=>Model::pageTemplates(),'auth_forms'=>Model::authFormDefinitions(),'q'=>$q,'can_manage'=>Permission::check('manage_customers'),'can_manage_admin_access'=>Permission::check('manage_users'),'current_public_user_id'=>Model::publicIdForSystem(Auth::id())));
|
||||
}
|
||||
|
||||
public function saveSavedView(array $params = array())
|
||||
{
|
||||
if (($error = $this->savedViewGuard()) !== null) { return $error; }
|
||||
$filters = json_decode(Request::postStr('filters', '{}'), true);
|
||||
if (!is_array($filters)) { return $this->error('Некорректный набор фильтров', array(), 422); }
|
||||
try { $views = SavedViews::save('customers_center', Auth::id(), Request::postStr('title', ''), $filters, array('q', 'segment')); }
|
||||
catch (\InvalidArgumentException $e) { return $this->error($e->getMessage(), array(), 422); }
|
||||
return $this->success('Представление сохранено', array('data' => array('views' => $views)));
|
||||
}
|
||||
|
||||
public function deleteSavedView(array $params = array())
|
||||
{
|
||||
if (($error = $this->savedViewGuard()) !== null) { return $error; }
|
||||
try { $views = SavedViews::delete('customers_center', Auth::id(), isset($params['id']) ? $params['id'] : '', array('q', 'segment')); }
|
||||
catch (\InvalidArgumentException $e) { return $this->error($e->getMessage(), array(), 404); }
|
||||
return $this->success('Представление удалено', array('data' => array('views' => $views)));
|
||||
}
|
||||
|
||||
protected function savedViewGuard() { if (($error = $this->csrfGuard()) !== null) { return $error; } return Permission::check('view_customers') ? null : $this->error('Недостаточно прав', array(), 403); }
|
||||
|
||||
public function centerCustomer(array $params = array())
|
||||
{
|
||||
if (!Permission::check('view_customers')) { return $this->error('Недостаточно прав', array(), 403); }
|
||||
$customer = CustomerCenter::detail(isset($params['id']) ? (int) $params['id'] : 0, Auth::id());
|
||||
if (!$customer) { return $this->error('Пользователь не найден', array(), 404); }
|
||||
return $this->success('', array('html' => array('detail' => $this->render('@customers/customer-center-detail.twig', array('customer' => $customer, 'can_manage' => Permission::check('manage_customers'))))));
|
||||
}
|
||||
|
||||
public function addCustomerNote(array $params = array())
|
||||
{
|
||||
if (($error = $this->guard()) !== null) { return $error; }
|
||||
try { CustomerCenter::addNote(isset($params['id']) ? (int) $params['id'] : 0, Auth::id(), Request::postStr('note', '')); }
|
||||
catch (\InvalidArgumentException $e) { return $this->error($e->getMessage(), array(), 422); }
|
||||
catch (\Throwable $e) { error_log('Customer note: ' . $e->getMessage()); return $this->error('Не удалось добавить заметку', array(), 500); }
|
||||
return $this->success('Заметка добавлена');
|
||||
}
|
||||
|
||||
public function mergeCustomers(array $params = array())
|
||||
{
|
||||
if (($error = $this->guard()) !== null) { return $error; }
|
||||
try { $customer = CustomerCenter::merge(Request::postInt('target_id', 0), Request::postInt('source_id', 0), Auth::id()); }
|
||||
catch (\InvalidArgumentException $e) { return $this->error($e->getMessage(), array(), 422); }
|
||||
catch (\Throwable $e) { error_log('Customer merge: ' . $e->getMessage()); return $this->error('Не удалось объединить аккаунты', array(), 500); }
|
||||
return $this->success('Аккаунты объединены', array('data' => array('id' => (int) $customer['user']['id']), 'reload' => true));
|
||||
}
|
||||
|
||||
public function toggle(array $params=array())
|
||||
{
|
||||
if(($e=$this->guard())!==null){return $e;}
|
||||
$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?'Пользователь включён':'Пользователь отключён');
|
||||
}
|
||||
|
||||
public function toggle(array $params=array()){if(($e=$this->guard())!==null){return $e;}return $this->success(Model::toggle(isset($params['id'])?$params['id']:0)?'Пользователь включён':'Пользователь отключён');}
|
||||
public function customer(array $params=array())
|
||||
{
|
||||
if(!Permission::check('view_customers')){return $this->error('Недостаточно прав',array(),403);}
|
||||
$customer=Model::customer(isset($params['id'])?$params['id']:0);
|
||||
$customer=Model::customer(isset($params['id'])?$params['id']:0,Auth::id());
|
||||
return $customer?$this->success('',array('data'=>$customer)):$this->error('Пользователь не найден',array(),404);
|
||||
}
|
||||
|
||||
@@ -46,19 +119,40 @@
|
||||
{
|
||||
if(($e=$this->guard())!==null){return $e;}
|
||||
$id=isset($params['id'])?(int)$params['id']:0;$input=Request::postAll();
|
||||
if(!Permission::check('manage_users')){$current=Model::customer($id);$input['admin_access']=!empty($current['system']['is_active'])?'1':'';$input['admin_role']=!empty($current['system']['role'])?(string)$current['system']['role']:'manager';}
|
||||
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));
|
||||
}
|
||||
|
||||
public function deleteCustomer(array $params = array())
|
||||
{
|
||||
if (($e = $this->guard()) !== null) {
|
||||
return $e;
|
||||
}
|
||||
|
||||
$id = isset($params['id']) ? (int) $params['id'] : 0;
|
||||
try {
|
||||
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));
|
||||
}
|
||||
|
||||
public function saveField(array $params=array()){if(($e=$this->guard())!==null){return $e;}try{$id=Model::saveField(isset($params['id'])?$params['id']:0,Request::postAll());}catch(\Throwable $e){return $this->error($e->getMessage(),array(),422);}return $this->success('Поле сохранено',array('data'=>array('id'=>$id),'reload'=>true));}
|
||||
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');}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------------
|
||||
| AVE.cms
|
||||
|--------------------------------------------------------------------------------------
|
||||
| @package AVE.cms
|
||||
| @file adminx/modules/Customers/CustomerCenter.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\Customers;
|
||||
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Common\DatabaseSchema;
|
||||
use App\Common\SystemTables;
|
||||
use App\Adminx\Support\AdminLocale;
|
||||
use App\Content\BasketTables;
|
||||
use App\Content\ContactsTables;
|
||||
use App\Content\PublicUserTables;
|
||||
use DB;
|
||||
|
||||
/** Read model and safe merge operations for the customer workspace. */
|
||||
class CustomerCenter
|
||||
{
|
||||
public static function listing($query = '', $segment = 'all', $limit = 300)
|
||||
{
|
||||
$query = mb_substr(trim((string) $query), 0, 190, 'UTF-8');
|
||||
$segment = isset(self::segments()[$segment]) ? $segment : 'all';
|
||||
$limit = max(1, min(500, (int) $limit));
|
||||
$users = PublicUserTables::table('users');
|
||||
$orders = BasketTables::table('module_basket_history');
|
||||
$hasOrders = DatabaseSchema::tableExists($orders);
|
||||
$orderJoin = $hasOrders
|
||||
? ' LEFT JOIN (SELECT order_user_id,COUNT(*) orders_count,SUM(order_total) orders_total,MAX(order_published) last_order_at'
|
||||
. ' FROM ' . $orders . ' WHERE order_user_id>0 GROUP BY order_user_id) orders ON orders.order_user_id=u.Id'
|
||||
: '';
|
||||
$sql = 'SELECT u.Id AS id,u.email,u.firstname,u.lastname,u.user_name,u.phone,u.company,u.status,u.reg_time,u.last_visit,'
|
||||
. ($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 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';
|
||||
$args = array_merge($args, array($query, $query, $query, $query, $query, $query));
|
||||
if (ctype_digit($query)) { $sql .= ' OR u.Id=%i'; $args[] = (int) $query; }
|
||||
$sql .= ')';
|
||||
}
|
||||
|
||||
$now = time();
|
||||
if ($segment === 'new') { $sql .= ' AND u.reg_time>=%i'; $args[] = $now - 30 * 86400; }
|
||||
elseif ($segment === 'buyers') { $sql .= $hasOrders ? ' AND COALESCE(orders.orders_count,0)>0' : ' AND 1=0'; }
|
||||
elseif ($segment === 'repeat') { $sql .= $hasOrders ? ' AND COALESCE(orders.orders_count,0)>=2' : ' AND 1=0'; }
|
||||
elseif ($segment === 'vip') { $sql .= $hasOrders ? ' AND COALESCE(orders.orders_total,0)>=100000' : ' AND 1=0'; }
|
||||
elseif ($segment === 'inactive') { $sql .= ' AND (u.last_visit=0 OR u.last_visit<%i)'; $args[] = $now - 180 * 86400; }
|
||||
elseif ($segment === 'without_orders' && $hasOrders) { $sql .= ' AND COALESCE(orders.orders_count,0)=0'; }
|
||||
$sql .= ' ORDER BY orders_total DESC,last_order_at DESC,u.Id DESC LIMIT ' . $limit;
|
||||
$rows = call_user_func_array(array('DB', 'query'), array_merge(array($sql), $args))->getAll() ?: array();
|
||||
foreach ($rows as &$row) {
|
||||
$row['id'] = (int) $row['id'];
|
||||
$row['orders_count'] = (int) $row['orders_count'];
|
||||
$row['orders_total'] = (float) $row['orders_total'];
|
||||
$row['last_order_at'] = (int) $row['last_order_at'];
|
||||
$row['segment_codes'] = self::segmentCodes($row);
|
||||
}
|
||||
|
||||
unset($row);
|
||||
return $rows;
|
||||
}
|
||||
|
||||
public static function stats()
|
||||
{
|
||||
$users = PublicUserTables::table('users');
|
||||
$orders = BasketTables::table('module_basket_history');
|
||||
$result = array(
|
||||
'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)) {
|
||||
$result['buyers'] = (int) DB::query('SELECT COUNT(DISTINCT order_user_id) FROM ' . $orders . ' WHERE order_user_id>0')->getValue();
|
||||
$result['repeat'] = (int) DB::query('SELECT COUNT(*) FROM (SELECT order_user_id FROM ' . $orders . ' WHERE order_user_id>0 GROUP BY order_user_id HAVING COUNT(*)>=2) repeated')->getValue();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public static function segments()
|
||||
{
|
||||
$segments = array('all' => 'Все', 'new' => 'Новые', 'buyers' => 'С заказами', 'repeat' => 'Повторные', 'vip' => 'От 100 000 ₽', 'inactive' => 'Неактивные', 'without_orders' => 'Без заказов');
|
||||
foreach ($segments as &$label) { $label = AdminLocale::translateMarkup($label); }
|
||||
unset($label);
|
||||
return $segments;
|
||||
}
|
||||
|
||||
public static function detail($id, $currentSystemId = 0)
|
||||
{
|
||||
$id = (int) $id;
|
||||
$profile = Model::customer($id, $currentSystemId);
|
||||
if (!$profile) { return null; }
|
||||
$orderData = self::orderData(
|
||||
$id,
|
||||
isset($profile['user']['email']) ? $profile['user']['email'] : '',
|
||||
isset($profile['user']['phone']) ? $profile['user']['phone'] : ''
|
||||
);
|
||||
$profile['summary'] = $orderData['summary'];
|
||||
$profile['orders'] = $orderData['orders'];
|
||||
$profile['contacts'] = self::contacts(isset($profile['user']['email']) ? $profile['user']['email'] : '');
|
||||
$profile['popup_leads'] = self::popupLeads(
|
||||
isset($profile['user']['email']) ? $profile['user']['email'] : '',
|
||||
isset($profile['user']['phone']) ? $profile['user']['phone'] : ''
|
||||
);
|
||||
$profile['quiz_leads'] = self::quizLeads(
|
||||
isset($profile['user']['email']) ? $profile['user']['email'] : '',
|
||||
isset($profile['user']['phone']) ? $profile['user']['phone'] : ''
|
||||
);
|
||||
$profile['identities'] = self::identities($id);
|
||||
$profile['engagement'] = self::engagement($id);
|
||||
$profile['notes'] = self::notes($id);
|
||||
$profile['segments'] = self::segmentCodes(array_merge($profile['user'], $orderData['summary']));
|
||||
return $profile;
|
||||
}
|
||||
|
||||
public static function addNote($userId, $authorId, $text)
|
||||
{
|
||||
$userId = (int) $userId; $authorId = (int) $authorId;
|
||||
$text = trim((string) $text);
|
||||
if (!Model::customer($userId)) { throw new \InvalidArgumentException('Пользователь не найден'); }
|
||||
if ($text === '') { throw new \InvalidArgumentException('Введите текст заметки'); }
|
||||
if (mb_strlen($text, 'UTF-8') > 4000) { throw new \InvalidArgumentException('Заметка не должна превышать 4000 символов'); }
|
||||
if (!DatabaseSchema::tableExists(self::notesTable())) { throw new \RuntimeException('Примените миграцию центра покупателей'); }
|
||||
DB::Insert(self::notesTable(), array('user_id' => $userId, 'author_id' => $authorId, 'note' => $text, 'created_at' => time()));
|
||||
return (int) DB::insertId();
|
||||
}
|
||||
|
||||
public static function merge($targetId, $sourceId, $actorSystemId = 0)
|
||||
{
|
||||
$targetId = (int) $targetId; $sourceId = (int) $sourceId;
|
||||
if ($targetId <= 0 || $sourceId <= 0 || $targetId === $sourceId) { throw new \InvalidArgumentException('Выберите два разных аккаунта'); }
|
||||
$target = Model::customer($targetId, $actorSystemId); $source = Model::customer($sourceId, $actorSystemId);
|
||||
if (!$target || !$source) { throw new \InvalidArgumentException('Один из аккаунтов не найден'); }
|
||||
if (!empty($source['is_current']) || !empty($source['system'])) { throw new \InvalidArgumentException('Нельзя объединить аккаунт, связанный с доступом в панель'); }
|
||||
self::assertIdentityMerge($targetId, $sourceId);
|
||||
DB::startTransaction();
|
||||
try {
|
||||
$sourceUnique = array('email' => null);
|
||||
if (DatabaseSchema::columnExists(PublicUserTables::table('users'), 'phone_normalized')) { $sourceUnique['phone_normalized'] = null; }
|
||||
DB::Update(PublicUserTables::table('users'), $sourceUnique, 'Id=%i', $sourceId);
|
||||
self::mergeCoreProfile($target['user'], $source['user']);
|
||||
self::mergeProfileValues($targetId, $sourceId);
|
||||
self::moveOptionalData($targetId, $sourceId);
|
||||
$identities = PublicUserTables::table('user_identities');
|
||||
if (DatabaseSchema::tableExists($identities)) { DB::Update($identities, array('user_id' => $targetId, 'updated_at' => time()), 'user_id=%i', $sourceId); }
|
||||
if (DatabaseSchema::tableExists(self::notesTable())) { DB::Update(self::notesTable(), array('user_id' => $targetId), 'user_id=%i', $sourceId); }
|
||||
self::addNote($targetId, $actorSystemId, 'Объединён аккаунт #' . $sourceId . '. Контакты источника: ' . trim((string) $source['user']['email'] . ' ' . (string) $source['user']['phone']));
|
||||
DB::Update(PublicUserTables::table('users'), array('status' => '0', 'deleted' => '1', 'del_time' => time()), 'Id=%i', $sourceId);
|
||||
DB::Delete(PublicUserTables::table('users_session'), 'user_id=%i', $sourceId);
|
||||
DB::Delete(PublicUserTables::table('auth_tokens'), 'user_id=%i', $sourceId);
|
||||
DB::commit();
|
||||
} catch (\Throwable $e) { DB::rollback(); throw $e; }
|
||||
return self::detail($targetId, $actorSystemId);
|
||||
}
|
||||
|
||||
public static function duplicateGroups()
|
||||
{
|
||||
$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 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 COALESCE(deleted,0)!='1' AND phone_normalized IS NOT NULL GROUP BY phone_normalized HAVING COUNT(*)>1 LIMIT 30";
|
||||
}
|
||||
|
||||
foreach ($queries as $kind => $sql) {
|
||||
foreach (DB::query($sql)->getAll() ?: array() as $row) {
|
||||
$ids = array_values(array_unique(array_filter(array_map('intval', explode(',', (string) $row['ids'])))));
|
||||
if (count($ids) > 1) { $groups[] = array('kind' => $kind, 'value' => (string) $row['duplicate_value'], 'ids' => $ids, 'target_id' => min($ids)); }
|
||||
}
|
||||
}
|
||||
|
||||
return $groups;
|
||||
}
|
||||
|
||||
/**
|
||||
* Заказы человека: свои по аккаунту плюс гостевые по контактам.
|
||||
*
|
||||
* Оформить заказ можно без входа (`order_user_id = 0`), и такие покупки
|
||||
* раньше не попадали на карточку вовсе. Ищем их так же, как обращения и
|
||||
* заявки — по email и телефону, — но помечаем `matched_by`, чтобы
|
||||
* догадка не выдавалась за подтверждённую принадлежность аккаунту.
|
||||
*/
|
||||
protected static function orderData($userId, $email = '', $phone = '')
|
||||
{
|
||||
$table = BasketTables::table('module_basket_history');
|
||||
$empty = array('summary' => array('orders_count' => 0, 'orders_total' => 0, 'last_order_at' => 0, 'guest_count' => 0), 'orders' => array());
|
||||
if (!DatabaseSchema::tableExists($table)) { return $empty; }
|
||||
|
||||
$where = array('order_user_id=%i');
|
||||
$args = array((int) $userId);
|
||||
$email = trim((string) $email);
|
||||
if ($email !== '') { $where[] = '(order_user_id=0 AND LOWER(order_email)=LOWER(%s))'; $args[] = $email; }
|
||||
$digits = preg_replace('/\D+/', '', (string) $phone);
|
||||
if (strlen($digits) >= 10) {
|
||||
$where[] = "(order_user_id=0 AND RIGHT(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(order_phone,' ',''),'(',''),')',''),'-',''),'+',''),10)=%s)";
|
||||
$args[] = substr($digits, -10);
|
||||
}
|
||||
|
||||
$condition = '(' . implode(' OR ', $where) . ')';
|
||||
$summaryArgs = array_merge(array(
|
||||
'SELECT COUNT(*) orders_count,COALESCE(SUM(order_total),0) orders_total,COALESCE(MAX(order_published),0) last_order_at,'
|
||||
. ' COALESCE(SUM(order_user_id=0),0) guest_count FROM ' . $table . ' WHERE ' . $condition,
|
||||
), $args);
|
||||
$summary = call_user_func_array(array(DB::class, 'query'), $summaryArgs)->getAssoc() ?: array();
|
||||
$listArgs = array_merge(array(
|
||||
'SELECT id,order_id,order_total,order_status,order_pay,order_published,order_user_id FROM ' . $table
|
||||
. ' WHERE ' . $condition . ' ORDER BY order_published DESC,id DESC LIMIT 20',
|
||||
), $args);
|
||||
$rows = call_user_func_array(array(DB::class, 'query'), $listArgs)->getAll() ?: array();
|
||||
foreach ($rows as &$row) {
|
||||
$row['id'] = (int) $row['id'];
|
||||
$row['order_total'] = (float) $row['order_total'];
|
||||
$row['order_published'] = (int) $row['order_published'];
|
||||
$row['matched_by'] = (int) $row['order_user_id'] > 0 ? 'account' : 'contact';
|
||||
}
|
||||
|
||||
unset($row);
|
||||
return array('summary' => array(
|
||||
'orders_count' => isset($summary['orders_count']) ? (int) $summary['orders_count'] : 0,
|
||||
'orders_total' => isset($summary['orders_total']) ? (float) $summary['orders_total'] : 0,
|
||||
'last_order_at' => isset($summary['last_order_at']) ? (int) $summary['last_order_at'] : 0,
|
||||
'guest_count' => isset($summary['guest_count']) ? (int) $summary['guest_count'] : 0,
|
||||
), 'orders' => $rows);
|
||||
}
|
||||
|
||||
protected static function contacts($email)
|
||||
{
|
||||
$table = ContactsTables::table('module_contacts_history'); $email = trim((string) $email);
|
||||
if ($email === '' || !DatabaseSchema::tableExists($table)) { return array(); }
|
||||
return DB::query('SELECT id,form_id,subject,status,date FROM ' . $table . ' WHERE LOWER(email)=LOWER(%s) ORDER BY date DESC,id DESC LIMIT 20', $email)->getAll() ?: array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Заявки из поп-апов сопоставляются по email или телефону.
|
||||
* Модуль устанавливается отдельно, поэтому отсутствие таблицы —
|
||||
* обычное состояние, а не ошибка.
|
||||
*/
|
||||
protected static function popupLeads($email, $phone)
|
||||
{
|
||||
if (!class_exists('App\\Modules\\Popups\\Repository')) { return array(); }
|
||||
try {
|
||||
if (!DatabaseSchema::tableExists(\App\Modules\Popups\Tables::table('leads'))) { return array(); }
|
||||
return \App\Modules\Popups\Repository::leadsForContact($email, $phone, 20);
|
||||
} catch (\Throwable $e) {
|
||||
return array();
|
||||
}
|
||||
}
|
||||
|
||||
/** Заявки из пошагового подбора — тот же принцип, что и у поп-апов. */
|
||||
protected static function quizLeads($email, $phone)
|
||||
{
|
||||
if (!class_exists('App\\Modules\\Quiz\\Repository')) { return array(); }
|
||||
try { return \App\Modules\Quiz\Repository::leadsForContact($email, $phone, 20); }
|
||||
catch (\Throwable $e) { return array(); }
|
||||
}
|
||||
|
||||
protected static function identities($userId)
|
||||
{
|
||||
$table = PublicUserTables::table('user_identities');
|
||||
return DatabaseSchema::tableExists($table) ? (DB::query('SELECT provider,email,created_at,last_login_at FROM ' . $table . ' WHERE user_id=%i ORDER BY provider', (int) $userId)->getAll() ?: array()) : array();
|
||||
}
|
||||
|
||||
protected static function engagement($userId)
|
||||
{
|
||||
$result = array('favorites' => array(), 'viewed' => array());
|
||||
$favorites = BasketTables::table('module_basket_favorites');
|
||||
if (DatabaseSchema::tableExists($favorites)) { $result['favorites'] = array_map('intval', array_column(DB::query('SELECT fav_document_id FROM ' . $favorites . ' WHERE fav_user_id=%i ORDER BY fav_created_at DESC LIMIT 30', (int) $userId)->getAll() ?: array(), 'fav_document_id')); }
|
||||
$viewed = BasketTables::table('module_basket_viewed');
|
||||
if (DatabaseSchema::tableExists($viewed)) { $result['viewed'] = array_map('intval', array_column(DB::query('SELECT viewed_document_id FROM ' . $viewed . ' WHERE viewed_user_id=%i ORDER BY viewed_at DESC LIMIT 30', (int) $userId)->getAll() ?: array(), 'viewed_document_id')); }
|
||||
return $result;
|
||||
}
|
||||
|
||||
protected static function notes($userId)
|
||||
{
|
||||
if (!DatabaseSchema::tableExists(self::notesTable())) { return array(); }
|
||||
return DB::query('SELECT n.*,u.name author_name FROM ' . self::notesTable() . ' n LEFT JOIN ' . SystemTables::table('users') . ' u ON u.id=n.author_id WHERE n.user_id=%i ORDER BY n.created_at DESC,n.id DESC LIMIT 100', (int) $userId)->getAll() ?: array();
|
||||
}
|
||||
|
||||
protected static function segmentCodes(array $row)
|
||||
{
|
||||
$codes = array(); $now = time();
|
||||
if (!empty($row['reg_time']) && (int) $row['reg_time'] >= $now - 30 * 86400) { $codes[] = 'new'; }
|
||||
if (!empty($row['orders_count'])) { $codes[] = 'buyers'; }
|
||||
if (isset($row['orders_count']) && (int) $row['orders_count'] >= 2) { $codes[] = 'repeat'; }
|
||||
if (isset($row['orders_total']) && (float) $row['orders_total'] >= 100000) { $codes[] = 'vip'; }
|
||||
if (empty($row['last_visit']) || (int) $row['last_visit'] < $now - 180 * 86400) { $codes[] = 'inactive'; }
|
||||
if (empty($row['orders_count'])) { $codes[] = 'without_orders'; }
|
||||
return $codes;
|
||||
}
|
||||
|
||||
protected static function assertIdentityMerge($targetId, $sourceId)
|
||||
{
|
||||
$table = PublicUserTables::table('user_identities');
|
||||
if (!DatabaseSchema::tableExists($table)) { return; }
|
||||
$conflict = DB::query('SELECT source.provider FROM ' . $table . ' source INNER JOIN ' . $table . ' target ON target.provider=source.provider AND target.user_id=%i WHERE source.user_id=%i LIMIT 1', (int) $targetId, (int) $sourceId)->getValue();
|
||||
if ($conflict) { throw new \InvalidArgumentException('У обоих аккаунтов подключён один способ входа: ' . $conflict); }
|
||||
}
|
||||
|
||||
protected static function mergeProfileValues($targetId, $sourceId)
|
||||
{
|
||||
$table = PublicUserTables::table('user_profile_values');
|
||||
if (!DatabaseSchema::tableExists($table)) { return; }
|
||||
foreach (DB::query('SELECT field_id,value FROM ' . $table . ' WHERE user_id=%i', (int) $sourceId)->getAll() ?: array() as $row) {
|
||||
$current = DB::query('SELECT value FROM ' . $table . ' WHERE user_id=%i AND field_id=%i', (int) $targetId, (int) $row['field_id'])->getValue();
|
||||
if ($current === null) { DB::Insert($table, array('user_id' => $targetId, 'field_id' => (int) $row['field_id'], 'value' => (string) $row['value'], 'updated_at' => time())); }
|
||||
elseif (trim((string) $current) === '' && trim((string) $row['value']) !== '') { DB::Update($table, array('value' => (string) $row['value'], 'updated_at' => time()), 'user_id=%i AND field_id=%i', $targetId, (int) $row['field_id']); }
|
||||
}
|
||||
|
||||
DB::Delete($table, 'user_id=%i', $sourceId);
|
||||
}
|
||||
|
||||
protected static function mergeCoreProfile(array $target, array $source)
|
||||
{
|
||||
$fields = array('email', 'phone', 'phone_normalized', 'firstname', 'lastname', 'street', 'street_nr', 'zipcode', 'city', 'telefax', 'description', 'company', 'birthday', 'country');
|
||||
$values = array();
|
||||
foreach ($fields as $field) {
|
||||
if (trim(isset($target[$field]) ? (string) $target[$field] : '') === '' && trim(isset($source[$field]) ? (string) $source[$field] : '') !== '') {
|
||||
$values[$field] = $source[$field];
|
||||
}
|
||||
}
|
||||
|
||||
$targetEmail = strtolower(trim(isset($target['email']) ? (string) $target['email'] : ''));
|
||||
$sourceEmail = strtolower(trim(isset($source['email']) ? (string) $source['email'] : ''));
|
||||
if ($targetEmail === '' || ($targetEmail !== '' && $targetEmail === $sourceEmail)) {
|
||||
$values['email_verified_at'] = max(isset($target['email_verified_at']) ? (int) $target['email_verified_at'] : 0, isset($source['email_verified_at']) ? (int) $source['email_verified_at'] : 0);
|
||||
}
|
||||
|
||||
$targetPhone = trim(isset($target['phone_normalized']) ? (string) $target['phone_normalized'] : '');
|
||||
$sourcePhone = trim(isset($source['phone_normalized']) ? (string) $source['phone_normalized'] : '');
|
||||
if ($targetPhone === '' || ($targetPhone !== '' && $targetPhone === $sourcePhone)) {
|
||||
$values['phone_verified_at'] = max(isset($target['phone_verified_at']) ? (int) $target['phone_verified_at'] : 0, isset($source['phone_verified_at']) ? (int) $source['phone_verified_at'] : 0);
|
||||
}
|
||||
|
||||
if ($values) { DB::Update(PublicUserTables::table('users'), $values, 'Id=%i', (int) $target['id']); }
|
||||
}
|
||||
|
||||
protected static function moveOptionalData($targetId, $sourceId)
|
||||
{
|
||||
$orders = BasketTables::table('module_basket_history');
|
||||
if (DatabaseSchema::tableExists($orders)) { DB::Update($orders, array('order_user_id' => $targetId), 'order_user_id=%i', $sourceId); }
|
||||
$favorites = BasketTables::table('module_basket_favorites');
|
||||
if (DatabaseSchema::tableExists($favorites)) {
|
||||
DB::query('INSERT IGNORE INTO ' . $favorites . ' (fav_user_id,fav_document_id,fav_created_at) SELECT %i,fav_document_id,fav_created_at FROM ' . $favorites . ' WHERE fav_user_id=%i', $targetId, $sourceId);
|
||||
DB::Delete($favorites, 'fav_user_id=%i', $sourceId);
|
||||
}
|
||||
|
||||
$viewed = BasketTables::table('module_basket_viewed');
|
||||
if (DatabaseSchema::tableExists($viewed)) {
|
||||
DB::query('INSERT INTO ' . $viewed . ' (viewed_user_id,viewed_document_id,viewed_at) SELECT %i,source.viewed_document_id,source.viewed_at FROM ' . $viewed . ' source WHERE source.viewed_user_id=%i ON DUPLICATE KEY UPDATE viewed_at=GREATEST(' . $viewed . '.viewed_at,VALUES(viewed_at))', $targetId, $sourceId);
|
||||
DB::Delete($viewed, 'viewed_user_id=%i', $sourceId);
|
||||
}
|
||||
}
|
||||
|
||||
protected static function notesTable()
|
||||
{
|
||||
return SystemTables::prefix() . '_customer_notes';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------------
|
||||
| AVE.cms
|
||||
|--------------------------------------------------------------------------------------
|
||||
| @package AVE.cms
|
||||
| @file adminx/modules/Customers/GlobalSearchProvider.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\Customers;
|
||||
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Content\PublicUserTables;
|
||||
use DB;
|
||||
|
||||
class GlobalSearchProvider
|
||||
{
|
||||
public static function search($query, $limit = 8)
|
||||
{
|
||||
$query = trim((string) $query); if ($query === '') { return array(); }
|
||||
$sql = 'SELECT Id,email,firstname,lastname,user_name,phone,company,status FROM ' . PublicUserTables::table('users')
|
||||
. ' 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));
|
||||
$rows = call_user_func_array(array('DB', 'query'), array_merge(array($sql), $args))->getAll() ?: array();
|
||||
$out = array();
|
||||
foreach ($rows as $row) {
|
||||
$title = trim($row['firstname'] . ' ' . $row['lastname']); if ($title === '') { $title = $row['user_name'] ?: ($row['email'] ?: $row['phone']); }
|
||||
$subtitle = '#' . (int) $row['Id']; if ($row['email']) { $subtitle .= ' · ' . $row['email']; } if ((string) $row['status'] !== '1') { $subtitle .= ' · отключён'; }
|
||||
$out[] = array('type' => 'customer', 'group' => 'Пользователи сайта', 'title' => $title, 'subtitle' => $subtitle, 'url' => '/system/customers?tab=customers&q=' . rawurlencode((string) ($row['email'] ?: $row['user_name'])), 'icon' => 'ti ti-user-heart', 'score' => 50);
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@
|
||||
use App\Adminx\Support\Roles;
|
||||
use App\Common\Auth\IdentityLinker;
|
||||
use App\Common\ModuleManager;
|
||||
use App\Common\SystemTables;
|
||||
use App\Content\PublicUserTables;
|
||||
use App\Content\ContentTables;
|
||||
use App\Common\PublicAuthSettings;
|
||||
@@ -34,28 +35,63 @@
|
||||
{
|
||||
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 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 ((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();
|
||||
}
|
||||
|
||||
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)
|
||||
public static function toggle($id, $currentSystemId = 0)
|
||||
{
|
||||
DB::query('UPDATE '.self::table('users')." SET status=IF(status='1','0','1') WHERE Id=%i AND deleted!=%s",(int)$id,'1');
|
||||
$customer = self::customer($id, $currentSystemId);
|
||||
if (!$customer) {
|
||||
throw new \InvalidArgumentException('Пользователь не найден');
|
||||
}
|
||||
|
||||
if (!empty($customer['is_current'])) {
|
||||
throw new \InvalidArgumentException('Нельзя отключить собственную учётную запись');
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public static function customer($id)
|
||||
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();
|
||||
@@ -63,14 +99,43 @@
|
||||
$system=IdentityLinker::systemForPublic((int)$id,(string)$row['email']);
|
||||
return array('user'=>$row,'extra'=>$extra,'system'=>$system?array(
|
||||
'id'=>(int)$system['id'],'role'=>(string)$system['role'],'is_active'=>(int)$system['is_active'],
|
||||
):null);
|
||||
):null,'is_current'=>$system&&(int)$system['id']===(int)$currentSystemId);
|
||||
}
|
||||
|
||||
public static function publicIdForSystem($systemId)
|
||||
{
|
||||
$system = DB::query(
|
||||
'SELECT * FROM ' . SystemTables::table('users') . ' WHERE id = %i LIMIT 1',
|
||||
(int) $systemId
|
||||
)->getAssoc();
|
||||
if (!$system) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$public = IdentityLinker::publicForSystem((array) $system);
|
||||
return $public ? (int) $public['Id'] : 0;
|
||||
}
|
||||
|
||||
public static function updateCustomer($id,array $input,$currentSystemId=0)
|
||||
{
|
||||
$id=(int)$id;
|
||||
$current=self::customer($id);
|
||||
$current=self::customer($id,$currentSystemId);
|
||||
if(!$current){throw new \InvalidArgumentException('Пользователь не найден');}
|
||||
if(!empty($current['is_current'])){
|
||||
$currentSystem=$current['system'];
|
||||
if(isset($input['user_group'])&&(int)$input['user_group']!==(int)$current['user']['user_group']){
|
||||
throw new \InvalidArgumentException('Нельзя изменить собственную публичную группу');
|
||||
}
|
||||
|
||||
if(isset($input['admin_role'])&&(string)$input['admin_role']!==(string)$currentSystem['role']){
|
||||
throw new \InvalidArgumentException('Нельзя изменить собственную роль в панели управления');
|
||||
}
|
||||
|
||||
$input['user_group']=(string)$current['user']['user_group'];
|
||||
$input['status']=(string)$current['user']['status']==='1'?'1':'';
|
||||
$input['admin_access']=!empty($currentSystem['is_active'])?'1':'';
|
||||
$input['admin_role']=(string)$currentSystem['role'];
|
||||
}
|
||||
|
||||
$email=mb_strtolower(trim((string)(isset($input['email'])?$input['email']:'')));
|
||||
$phoneInput=trim((string)(isset($input['phone'])?$input['phone']:''));
|
||||
@@ -88,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();
|
||||
@@ -126,12 +191,49 @@
|
||||
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);
|
||||
}
|
||||
|
||||
public static function deleteCustomer($id, $currentSystemId = 0)
|
||||
{
|
||||
$id = (int) $id;
|
||||
$current = self::customer($id, $currentSystemId);
|
||||
if (!$current) {
|
||||
throw new \InvalidArgumentException('Пользователь не найден');
|
||||
}
|
||||
|
||||
if (!empty($current['is_current'])) {
|
||||
throw new \InvalidArgumentException('Нельзя удалить собственную учётную запись');
|
||||
}
|
||||
|
||||
if (!empty($current['system']['is_active'])) {
|
||||
throw new \InvalidArgumentException('Сначала отключите пользователю доступ к панели управления');
|
||||
}
|
||||
|
||||
DB::startTransaction();
|
||||
try {
|
||||
DB::Update(self::table('users'), array(
|
||||
'status' => '0',
|
||||
'deleted' => '1',
|
||||
'del_time' => time(),
|
||||
), 'Id = %i', $id);
|
||||
self::invalidateCustomerSessions($id);
|
||||
DB::Delete(self::table('user_identities'), 'user_id = %i', $id);
|
||||
DB::commit();
|
||||
} catch (\Throwable $e) {
|
||||
DB::rollback();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function fields()
|
||||
{
|
||||
$rows = DB::query('SELECT * FROM '.self::table('user_profile_fields').' ORDER BY position,id')->getAll() ?: array();
|
||||
@@ -191,7 +293,7 @@
|
||||
return $settings;
|
||||
}
|
||||
|
||||
public static function oauthModules()
|
||||
public static function authMethods()
|
||||
{
|
||||
$definitions = array(
|
||||
array(
|
||||
@@ -217,24 +319,33 @@
|
||||
$items = array();
|
||||
foreach ($definitions as $definition) {
|
||||
$module = ModuleManager::get($definition['module']);
|
||||
if (!$module || empty($module['installed'])) { continue; }
|
||||
$available = $module !== null;
|
||||
$installed = $available && !empty($module['installed']);
|
||||
|
||||
$isPhone = isset($definition['kind']) && $definition['kind'] === 'phone';
|
||||
if ($isPhone) {
|
||||
if ($installed && $isPhone) {
|
||||
$phoneProvider = PhoneProviderRegistry::get($definition['provider']);
|
||||
$isRegistered = $phoneProvider !== null;
|
||||
$config = class_exists('\\App\\Modules\\SmscAuth\\SecretStore')
|
||||
? \App\Modules\SmscAuth\SecretStore::config()
|
||||
: array();
|
||||
$configured = $isRegistered && $phoneProvider->configured();
|
||||
} else {
|
||||
} elseif ($installed) {
|
||||
$isRegistered = in_array($definition['provider'], $registered, true);
|
||||
$config = $isRegistered ? ProviderRegistry::config($definition['provider']) : array();
|
||||
$configured = $isRegistered && ProviderRegistry::configured($definition['provider'], $config);
|
||||
} else {
|
||||
$config = array();
|
||||
$configured = false;
|
||||
}
|
||||
|
||||
$active = !empty($module['enabled']) && $configured && !empty($config['enabled']);
|
||||
if (empty($module['enabled'])) {
|
||||
$moduleEnabled = $installed && !empty($module['enabled']);
|
||||
$active = $moduleEnabled && $configured && !empty($config['enabled']);
|
||||
if (!$available) {
|
||||
$state = array('label' => 'Пакет отсутствует', 'badge' => 'badge-red');
|
||||
} elseif (!$installed) {
|
||||
$state = array('label' => 'Не установлен', 'badge' => 'badge-gray');
|
||||
} elseif (!$moduleEnabled) {
|
||||
$state = array('label' => 'Модуль выключен', 'badge' => 'badge-gray');
|
||||
} elseif (!$configured) {
|
||||
$state = array('label' => 'Нужны ключи', 'badge' => 'badge-amber');
|
||||
@@ -245,7 +356,9 @@
|
||||
}
|
||||
|
||||
$items[] = array_merge($definition, array(
|
||||
'module_enabled' => !empty($module['enabled']),
|
||||
'available' => $available,
|
||||
'installed' => $installed,
|
||||
'module_enabled' => $moduleEnabled,
|
||||
'configured' => $configured,
|
||||
'active' => $active,
|
||||
'allow_registration' => !empty($config['allow_registration']),
|
||||
@@ -317,6 +430,9 @@
|
||||
'profile' => array('label' => 'Профиль', 'description' => 'Контактные и дополнительные поля пользователя.', 'icon' => 'ti-user-circle', 'tile' => 'violet'),
|
||||
'password' => array('label' => 'Смена пароля', 'description' => 'Форма для авторизованного пользователя.', 'icon' => 'ti-lock-cog', 'tile' => 'cyan'),
|
||||
'message' => array('label' => 'Системное сообщение', 'description' => 'Результат регистрации, подтверждения и восстановления.', 'icon' => 'ti-message-circle-check', 'tile' => 'green'),
|
||||
'phone' => array('label' => 'Вход по телефону', 'description' => 'Запрос и проверка одноразового SMS-кода.', 'icon' => 'ti-device-mobile-message', 'tile' => 'cyan'),
|
||||
'oauth' => array('label' => 'Вход через сервисы', 'description' => 'Кнопки входа через подключённые OAuth-модули.', 'icon' => 'ti-brand-openid', 'tile' => 'blue'),
|
||||
'oauth_connections' => array('label' => 'Привязанные сервисы', 'description' => 'Управление внешними способами входа в профиле.', 'icon' => 'ti-plug-connected', 'tile' => 'violet'),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,310 @@
|
||||
.customers-table td:last-child {
|
||||
text-align: right;
|
||||
}
|
||||
.customers-center-kpis {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
.customers-segments {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin: 14px 0;
|
||||
}
|
||||
.customers-segments a {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 40px;
|
||||
padding: 7px 11px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--background-surface);
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
text-decoration: none;
|
||||
}
|
||||
.customers-segments a:hover {
|
||||
border-color: var(--border-strong);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.customers-segments a.is-active {
|
||||
border-color: var(--color-primary);
|
||||
background: var(--blue-50);
|
||||
color: var(--color-primary);
|
||||
font-weight: 700;
|
||||
}
|
||||
.customers-duplicates {
|
||||
display: block;
|
||||
margin: 0 0 14px;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.customers-duplicates > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 13px 15px;
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
}
|
||||
.customers-duplicates > summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
.customers-duplicates > summary > span:first-child {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.customers-duplicates > div {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
padding: 0 14px 14px;
|
||||
}
|
||||
.customers-duplicates article {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--background-surface);
|
||||
}
|
||||
.customers-duplicates article > span:first-child {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.customers-duplicates article b,
|
||||
.customers-duplicates article small {
|
||||
display: block;
|
||||
}
|
||||
.customers-duplicates article small {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.customers-center-list {
|
||||
padding: 0;
|
||||
}
|
||||
.customers-center-table th:nth-child(1) {
|
||||
width: auto;
|
||||
}
|
||||
.customers-center-table th:nth-child(2) {
|
||||
width: 150px;
|
||||
}
|
||||
.customers-center-table th:nth-child(3) {
|
||||
width: 180px;
|
||||
}
|
||||
.customers-center-table th:nth-child(4) {
|
||||
width: 260px;
|
||||
}
|
||||
.customers-center-table td > small,
|
||||
.customers-center-table td > b {
|
||||
display: block;
|
||||
}
|
||||
.customers-center-table td > small {
|
||||
margin-top: 3px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
}
|
||||
.customers-center-table tbody tr[data-customer-center-open] {
|
||||
cursor: pointer;
|
||||
}
|
||||
.customers-center-person {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
.customers-center-person > span,
|
||||
.customers-center-avatar {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex: 0 0 auto;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--blue-100);
|
||||
color: var(--blue-700);
|
||||
font-weight: 800;
|
||||
}
|
||||
.customers-center-person > span {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.customers-center-person > div {
|
||||
min-width: 0;
|
||||
}
|
||||
.customers-center-person b,
|
||||
.customers-center-person small {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.customers-center-person small {
|
||||
margin-top: 3px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
}
|
||||
.customers-center-segment-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
}
|
||||
.customer-center-drawer {
|
||||
width: min(66.666vw, 1280px);
|
||||
max-width: none;
|
||||
}
|
||||
.customer-center-drawer .drawer-footer {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.customers-center-detail {
|
||||
display: grid;
|
||||
align-content: start;
|
||||
gap: 14px;
|
||||
background: var(--background-inset);
|
||||
}
|
||||
.customers-center-profile {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
padding: 18px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--background-surface);
|
||||
}
|
||||
.customers-center-avatar {
|
||||
width: 58px;
|
||||
height: 58px;
|
||||
font-size: 18px;
|
||||
}
|
||||
.customers-center-profile > div:nth-child(2) {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.customers-center-profile h2,
|
||||
.customers-center-profile p {
|
||||
margin: 0;
|
||||
}
|
||||
.customers-center-profile h2 {
|
||||
margin: 3px 0;
|
||||
font-size: 20px;
|
||||
}
|
||||
.customers-center-profile p {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.customers-center-profile .customers-center-segment-list {
|
||||
margin-top: 8px;
|
||||
}
|
||||
.customers-center-detail-kpis {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.customers-center-detail-kpis > span {
|
||||
display: grid;
|
||||
grid-template-columns: 34px minmax(0, 1fr);
|
||||
align-items: center;
|
||||
padding: 11px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--background-surface);
|
||||
}
|
||||
.customers-center-detail-kpis i {
|
||||
display: grid;
|
||||
grid-row: 1/3;
|
||||
place-items: center;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--blue-100);
|
||||
color: var(--blue-600);
|
||||
font-size: 17px;
|
||||
}
|
||||
.customers-center-detail-kpis b,
|
||||
.customers-center-detail-kpis small {
|
||||
display: block;
|
||||
}
|
||||
.customers-center-detail-kpis small {
|
||||
color: var(--text-secondary);
|
||||
font-size: 10px;
|
||||
}
|
||||
.customers-center-detail-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
align-items: start;
|
||||
}
|
||||
.customers-center-detail-grid > .card {
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.customers-center-order-list,
|
||||
.customers-center-contact-list,
|
||||
.customers-center-identities,
|
||||
.customers-center-notes {
|
||||
display: grid;
|
||||
gap: 7px;
|
||||
padding: 12px;
|
||||
}
|
||||
.customers-center-order-list a,
|
||||
.customers-center-contact-list article,
|
||||
.customers-center-identities article {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 9px 10px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--background-inset);
|
||||
color: var(--text-primary);
|
||||
text-decoration: none;
|
||||
}
|
||||
.customers-center-order-list a:hover {
|
||||
background: var(--background-hover);
|
||||
}
|
||||
.customers-center-order-list b,
|
||||
.customers-center-order-list small,
|
||||
.customers-center-identities b,
|
||||
.customers-center-identities small,
|
||||
.customers-center-contact-list b,
|
||||
.customers-center-contact-list small {
|
||||
display: block;
|
||||
}
|
||||
.customers-center-order-list small,
|
||||
.customers-center-identities small,
|
||||
.customers-center-contact-list small {
|
||||
margin-top: 2px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 10.5px;
|
||||
}
|
||||
.customers-center-identities article {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
.customers-center-identities article > i {
|
||||
color: var(--color-primary);
|
||||
font-size: 19px;
|
||||
}
|
||||
.customers-center-notes article {
|
||||
padding: 10px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--background-inset);
|
||||
}
|
||||
.customers-center-notes p {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.customers-center-notes small {
|
||||
display: block;
|
||||
margin-top: 6px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 10.5px;
|
||||
}
|
||||
.customers-center-note-form {
|
||||
display: grid;
|
||||
gap: 9px;
|
||||
padding: 12px;
|
||||
border-top: 1px solid var(--border-default);
|
||||
}
|
||||
.customers-center-note-form .btn {
|
||||
justify-self: end;
|
||||
}
|
||||
.customer-editor-drawer {
|
||||
width: min(66.666vw, 1240px);
|
||||
max-width: none;
|
||||
@@ -97,6 +401,16 @@
|
||||
.customers-editor-access .customers-switch-card:last-child {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.customers-editor-input {
|
||||
width: 100%;
|
||||
}
|
||||
.customers-editor-input .input {
|
||||
width: 100%;
|
||||
}
|
||||
.customers-switch-card.is-locked {
|
||||
opacity: 0.68;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.customers-editor-checkbox {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -797,7 +1111,8 @@
|
||||
@media (max-width: 980px) {
|
||||
.customers-field-builder,
|
||||
.customers-pages-grid,
|
||||
.customers-social-grid {
|
||||
.customers-social-grid,
|
||||
.customers-center-detail-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.customers-profile-preview {
|
||||
@@ -806,6 +1121,10 @@
|
||||
.customers-auth-settings-grid {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
.customers-center-kpis,
|
||||
.customers-center-detail-kpis {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@media (max-width: 980px) {
|
||||
.customers-auth-template-layout {
|
||||
@@ -827,11 +1146,14 @@
|
||||
}
|
||||
.customer-editor-drawer,
|
||||
.customer-field-drawer,
|
||||
.customer-auth-form-drawer {
|
||||
.customer-auth-form-drawer,
|
||||
.customer-center-drawer {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
}
|
||||
.customers-editor-meta {
|
||||
.customers-editor-meta,
|
||||
.customers-center-kpis,
|
||||
.customers-center-detail-kpis {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.customers-switch-grid,
|
||||
@@ -848,11 +1170,14 @@
|
||||
.customers-social-callback {
|
||||
grid-column: auto;
|
||||
}
|
||||
.customers-social-status {
|
||||
.customers-social-status,
|
||||
.customers-center-profile,
|
||||
.customers-duplicates article {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
.customers-social-status > .btn {
|
||||
.customers-social-status > .btn,
|
||||
.customers-center-profile > .btn {
|
||||
align-self: flex-end;
|
||||
}
|
||||
.customers-page-fields .field:nth-child(3),
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
if (event.target.matches('[data-customer-field] [name="type"]')) { self.updateOptionsVisibility(); }
|
||||
if (event.target.matches('[data-auth-show]')) { self.syncAuthFieldRows(); }
|
||||
if (event.target.matches('[data-registration-mode]')) { self.syncAuthMode(); }
|
||||
if (event.target.matches('[data-registration-gate]')) { self.syncRegistrationGate(); }
|
||||
if (event.target.matches('[data-customer-admin-access]')) { self.syncAdminAccess(); }
|
||||
});
|
||||
|
||||
@@ -29,8 +30,14 @@
|
||||
});
|
||||
|
||||
document.addEventListener('click', function (event) {
|
||||
var centerOpen = event.target.closest('[data-customer-center-open]');
|
||||
if (centerOpen) { event.preventDefault(); self.openCustomerCenter(centerOpen.getAttribute('data-url')); return; }
|
||||
var merge = event.target.closest('[data-customer-merge]');
|
||||
if (merge) { event.preventDefault(); self.mergeCustomers(merge); return; }
|
||||
var customerEdit = event.target.closest('[data-customer-edit]');
|
||||
if (customerEdit) { event.preventDefault(); self.openCustomer(customerEdit); return; }
|
||||
var customerDelete = event.target.closest('[data-customer-delete]');
|
||||
if (customerDelete) { event.preventDefault(); self.deleteCustomer(customerDelete); return; }
|
||||
if (event.target.closest('[data-field-new]')) { self.fieldForm(null); }
|
||||
var edit = event.target.closest('[data-field-edit]');
|
||||
if (edit) { self.fieldForm(JSON.parse(edit.closest('[data-field]').getAttribute('data-field'))); }
|
||||
@@ -49,6 +56,13 @@
|
||||
if (checkoutDefault) { self.setCheckoutTemplate(checkoutDefault.getAttribute('data-template') || ''); }
|
||||
});
|
||||
|
||||
document.addEventListener('submit', function (event) {
|
||||
var note = event.target.closest('[data-customer-note]');
|
||||
if (!note) { return; }
|
||||
event.preventDefault();
|
||||
self.request(note.action, new FormData(note)).then(function () { self.openCustomerCenter(note.getAttribute('data-refresh-url'), true); });
|
||||
});
|
||||
|
||||
var form = document.querySelector('[data-customer-field]');
|
||||
if (form) {
|
||||
form.addEventListener('submit', function (event) {
|
||||
@@ -93,6 +107,7 @@
|
||||
});
|
||||
}
|
||||
this.syncAuthFieldRows();
|
||||
this.syncRegistrationGate();
|
||||
this.syncAuthMode();
|
||||
this.initSortable();
|
||||
},
|
||||
@@ -111,6 +126,34 @@
|
||||
});
|
||||
},
|
||||
|
||||
openCustomerCenter: function (url, keepOpen) {
|
||||
var detail = document.querySelector('[data-customer-center-detail]');
|
||||
if (!detail || !url) { return; }
|
||||
detail.innerHTML = '<div class="skeleton" style="height:160px"></div>';
|
||||
if (!keepOpen && Adminx.Drawer) { Adminx.Drawer.open('customerCenterDrawer'); }
|
||||
Adminx.Loader.show();
|
||||
Adminx.Ajax.request(url, { method: 'GET' }).then(function (payload) {
|
||||
Adminx.Loader.hide();
|
||||
if (!payload.ok || !payload.data.success) { throw new Error(payload.data.message || Adminx.tr('Не удалось загрузить карточку')); }
|
||||
detail.innerHTML = payload.data.html && payload.data.html.detail ? payload.data.html.detail : '<div class="empty-state">' + Adminx.tr('Нет данных') + '</div>';
|
||||
}).catch(function (error) { Adminx.Loader.hide(); detail.innerHTML = '<div class="empty-state">' + error.message + '</div>'; Adminx.Toast.show(error.message, 'error'); });
|
||||
},
|
||||
|
||||
mergeCustomers: function (button) {
|
||||
var self = this;
|
||||
var target = Number(button.getAttribute('data-target-id')) || 0;
|
||||
var source = Number(button.getAttribute('data-source-id')) || 0;
|
||||
Adminx.Confirm.open({
|
||||
kind: 'warning', title: Adminx.tr('Объединить аккаунты?'),
|
||||
message: Adminx.tr('Данные исходного аккаунта будут перенесены в основной. Исходный аккаунт будет отключён и удалён.') + ' #' + source + ' → #' + target,
|
||||
confirmLabel: Adminx.tr('Объединить'),
|
||||
onConfirm: function () {
|
||||
var body = new FormData(); body.set('target_id', target); body.set('source_id', source);
|
||||
return self.request(Adminx.base() + '/system/customers/center/merge', body).then(function () { window.location.reload(); });
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
openCustomer: function (button) {
|
||||
var form = document.querySelector('[data-customer-editor]');
|
||||
var self = this;
|
||||
@@ -135,6 +178,7 @@
|
||||
if (!form) { return; }
|
||||
form.reset();
|
||||
form.dataset.id = user.id || '0';
|
||||
form.dataset.current = data.is_current ? '1' : '0';
|
||||
['firstname', 'lastname', 'email', 'user_name', 'phone', 'company', 'birthday', 'description', 'city', 'street', 'street_nr', 'zipcode', 'user_group'].forEach(function (name) {
|
||||
if (form.elements[name]) { form.elements[name].value = user[name] == null ? '' : user[name]; }
|
||||
});
|
||||
@@ -145,6 +189,7 @@
|
||||
form.elements.phone_verified.checked = Number(user.phone_verified_at) > 0;
|
||||
form.elements.admin_access.checked = !!(data.system && Number(data.system.is_active) === 1);
|
||||
form.elements.admin_role.value = data.system && data.system.role ? data.system.role : 'manager';
|
||||
this.syncCurrentAccountProtection();
|
||||
this.syncAdminAccess();
|
||||
Object.keys(extra).forEach(function (id) {
|
||||
var input = form.elements['extra[' + id + ']'];
|
||||
@@ -179,9 +224,51 @@
|
||||
var form = document.querySelector('[data-customer-editor]');
|
||||
var field = form ? form.querySelector('[data-customer-admin-role]') : null;
|
||||
var toggle = form && form.elements.admin_access ? form.elements.admin_access : null;
|
||||
var isCurrent = form && form.dataset.current === '1';
|
||||
var canManage = form && form.dataset.canManageAdminAccess === '1';
|
||||
if (!field || !toggle) { return; }
|
||||
field.hidden = !toggle.checked;
|
||||
if (form.elements.admin_role) { form.elements.admin_role.disabled = !toggle.checked; }
|
||||
if (form.elements.admin_role) { form.elements.admin_role.disabled = !toggle.checked || !canManage || isCurrent; }
|
||||
},
|
||||
|
||||
syncCurrentAccountProtection: function () {
|
||||
var form = document.querySelector('[data-customer-editor]');
|
||||
var isCurrent = form && form.dataset.current === '1';
|
||||
var canManage = form && form.dataset.canManageAdminAccess === '1';
|
||||
var accountHint = form ? form.querySelector('[data-customer-account-hint]') : null;
|
||||
var adminHint = form ? form.querySelector('[data-customer-admin-hint]') : null;
|
||||
var groupHint = form ? form.querySelector('[data-customer-group-hint]') : null;
|
||||
var roleHint = form ? form.querySelector('[data-customer-admin-role-hint]') : null;
|
||||
var accountCard = form ? form.querySelector('[data-customer-account-card]') : null;
|
||||
var adminCard = form ? form.querySelector('[data-customer-admin-card]') : null;
|
||||
if (!form) { return; }
|
||||
form.elements.user_group.disabled = isCurrent;
|
||||
form.elements.status.disabled = isCurrent;
|
||||
form.elements.admin_access.disabled = isCurrent || !canManage;
|
||||
if (accountCard) { accountCard.classList.toggle('is-locked', isCurrent); }
|
||||
if (adminCard) { adminCard.classList.toggle('is-locked', isCurrent || !canManage); }
|
||||
if (accountHint) {
|
||||
accountHint.textContent = isCurrent
|
||||
? 'Собственную учётную запись нельзя отключить.'
|
||||
: 'Может входить на сайт и в личный кабинет.';
|
||||
}
|
||||
if (adminHint) {
|
||||
adminHint.textContent = isCurrent
|
||||
? 'Собственный доступ к панели нельзя отключить.'
|
||||
: (canManage
|
||||
? 'Та же учётная запись сможет работать в административном интерфейсе.'
|
||||
: 'Изменение требует права управления системными пользователями.');
|
||||
}
|
||||
if (groupHint) {
|
||||
groupHint.textContent = isCurrent
|
||||
? 'Собственную публичную группу изменяйте через другого администратора.'
|
||||
: 'Определяет права пользователя на публичной части сайта.';
|
||||
}
|
||||
if (roleHint) {
|
||||
roleHint.textContent = isCurrent
|
||||
? 'Собственную роль изменяйте через другого администратора.'
|
||||
: 'Права роли настраиваются в разделе «Роли и права».';
|
||||
}
|
||||
},
|
||||
|
||||
formatTimestamp: function (value) {
|
||||
@@ -206,6 +293,22 @@
|
||||
});
|
||||
},
|
||||
|
||||
deleteCustomer: function (button) {
|
||||
var self = this;
|
||||
Adminx.Confirm.open({
|
||||
kind: 'error',
|
||||
title: 'Удалить пользователя сайта?',
|
||||
message: 'Аккаунт будет отключён, а его публичные сессии завершены. История заказов и связанные записи сохранятся.',
|
||||
confirmLabel: 'Удалить',
|
||||
confirmClass: 'btn-danger',
|
||||
onConfirm: function () {
|
||||
self.request(button.getAttribute('data-url'), new FormData()).then(function () {
|
||||
window.location.reload();
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
toggleField: function (input) {
|
||||
var self = this;
|
||||
var item = input.closest('[data-field-id]');
|
||||
@@ -292,6 +395,31 @@
|
||||
emailOnly.hidden = mode.value !== 'email';
|
||||
},
|
||||
|
||||
syncRegistrationGate: function () {
|
||||
var gate = document.querySelector('[data-registration-gate]');
|
||||
var hasEmail = gate && gate.value !== 'phone';
|
||||
var phoneOnly = gate && gate.value === 'phone';
|
||||
var emailAndPhone = gate && gate.value === 'email_phone';
|
||||
var description = document.querySelector('[data-auth-email-field-description]');
|
||||
var visibility = document.querySelector('[data-auth-email-visibility]');
|
||||
var required = document.querySelector('[data-auth-email-required]');
|
||||
if (!gate) { return; }
|
||||
document.querySelectorAll('[data-auth-email-registration], [data-auth-email-form-fields], [data-auth-email-settings]').forEach(function (section) {
|
||||
section.hidden = !hasEmail;
|
||||
});
|
||||
if (description) { description.textContent = phoneOnly ? 'Не используется для входа; можно добавить в профиле как контакт' : (emailAndPhone ? 'Запрашивается только при выборе регистрации по email' : 'Логин и канал подтверждения регистрации по email'); }
|
||||
if (visibility) {
|
||||
visibility.textContent = phoneOnly ? 'Только в профиле' : (emailAndPhone ? 'В email-форме' : 'Показывается');
|
||||
visibility.classList.toggle('badge-blue', !phoneOnly);
|
||||
visibility.classList.toggle('badge-gray', phoneOnly);
|
||||
}
|
||||
if (required) {
|
||||
required.textContent = phoneOnly ? 'Необязательно' : (emailAndPhone ? 'По выбору способа' : 'Обязательно');
|
||||
required.classList.toggle('badge-blue', !phoneOnly && !emailAndPhone);
|
||||
required.classList.toggle('badge-gray', phoneOnly || emailAndPhone);
|
||||
}
|
||||
},
|
||||
|
||||
setCheckoutTemplate: function (value) {
|
||||
var form = document.querySelector('[data-customer-auth]');
|
||||
var textarea = form ? form.elements.checkout_access_template : null;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="customers_center_title">Customer center</phrase>
|
||||
<phrase data="customers_center_eyebrow">Customer operations</phrase>
|
||||
<phrase data="customers_center_description">Account, purchases, inquiries, and customer interests are collected in one card.</phrase>
|
||||
<phrase data="customers_center_accounts">Accounts</phrase>
|
||||
<phrase data="customers_center_buyers">Customers</phrase>
|
||||
<phrase data="customers_center_repeat">Repeat customers</phrase>
|
||||
<phrase data="customers_center_duplicates">Duplicate groups</phrase>
|
||||
<phrase data="customers_center_duplicate_warning">Possible duplicates found</phrase>
|
||||
<phrase data="customers_center_duplicate_email">Same email</phrase>
|
||||
<phrase data="customers_center_duplicate_phone">Same phone</phrase>
|
||||
<phrase data="customers_center_open">Open customer card</phrase>
|
||||
<phrase data="customers_center_card">Customer card</phrase>
|
||||
<phrase data="customers_center_card_hint">Profile and interaction history</phrase>
|
||||
<phrase data="customers_center_orders">Orders</phrase>
|
||||
<phrase data="customers_center_login_methods">Login methods</phrase>
|
||||
<phrase data="customers_center_contacts">Inquiries</phrase>
|
||||
<phrase data="customers_center_notes">Manager notes</phrase>
|
||||
<phrase data="customers_center_note_hint">Internal information that is not visible to the customer</phrase>
|
||||
<phrase data="customers_center_note_new">New note</phrase>
|
||||
<phrase data="customers_center_note_added">Note added</phrase>
|
||||
<phrase data="customers_center_merged">Accounts merged</phrase>
|
||||
<phrase data="customers_center_segment_all">All</phrase>
|
||||
<phrase data="customers_center_segment_new">New</phrase>
|
||||
<phrase data="customers_center_segment_buyers">With orders</phrase>
|
||||
<phrase data="customers_center_segment_repeat">Repeat</phrase>
|
||||
<phrase data="customers_center_segment_vip">Over ₽100,000</phrase>
|
||||
<phrase data="customers_center_segment_inactive">Inactive</phrase>
|
||||
<phrase data="customers_center_segment_empty">Without orders</phrase>
|
||||
</language>
|
||||
@@ -2,30 +2,12 @@
|
||||
<language>
|
||||
<phrase data="auto_32b373146ceb643e">Failed to load profile</phrase>
|
||||
<phrase data="auto_3ad78d4634845d06">New field</phrase>
|
||||
<phrase data="auto_453d46b73a83a1f7">The change requires the Manage System Users right.</phrase>
|
||||
<phrase data="auto_51aff18539497f49">User</phrase>
|
||||
<phrase data="auto_533496be720f1840">Can log into the site and personal account.</phrase>
|
||||
<phrase data="auto_54628e7921e2b7ef">Site user</phrase>
|
||||
<phrase data="auto_7851fbc651bc0177">: '&#039;' }[character];
|
||||
});
|
||||
},
|
||||
|
||||
deleteField: function (button) {
|
||||
var self = this;
|
||||
Adminx.Confirm.open({
|
||||
kind: 'error', title: 'Delete field?',
|
||||
message: 'Values of this field for site users will also be deleted.',
|
||||
confirmLabel: 'Delete', confirmClass: 'btn-danger',
|
||||
onConfirm: function () { self.request(button.getAttribute('data-url'), new FormData()).then(function () { window.location.reload(); }); }
|
||||
});
|
||||
},
|
||||
|
||||
toggleField: function (input) {
|
||||
var self = this;
|
||||
var item = input.closest('[data-field-id]');
|
||||
this.request(input.getAttribute('data-url'), new FormData()).then(function (response) {
|
||||
var active = !!Number(response.data && response.data.is_active);
|
||||
input.checked = active;
|
||||
item.classList.toggle('is-disabled', !active);
|
||||
var preview = document.querySelector('[data-preview-field=</phrase>
|
||||
<phrase data="auto_8072db5006172c8c">Role rights are configured in the “Roles and Rights” section.</phrase>
|
||||
<phrase data="auto_de7fb9566c3ab6f8">Action failed</phrase>
|
||||
<phrase data="auto_f0dff5ab4a669f7a">Saved</phrase>
|
||||
<phrase data="auto_f7198a183e197a24">The same account will be able to work in the administrative interface.</phrase>
|
||||
</language>
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="customers_center_title">Центр покупателей</phrase>
|
||||
<phrase data="customers_center_eyebrow">Работа с покупателями</phrase>
|
||||
<phrase data="customers_center_description">Аккаунт, покупки, обращения и интересы человека собраны в одной карточке.</phrase>
|
||||
<phrase data="customers_center_accounts">Аккаунтов</phrase>
|
||||
<phrase data="customers_center_buyers">Покупателей</phrase>
|
||||
<phrase data="customers_center_repeat">Повторных</phrase>
|
||||
<phrase data="customers_center_duplicates">Групп дублей</phrase>
|
||||
<phrase data="customers_center_duplicate_warning">Найдены возможные дубли</phrase>
|
||||
<phrase data="customers_center_duplicate_email">Одинаковый email</phrase>
|
||||
<phrase data="customers_center_duplicate_phone">Одинаковый телефон</phrase>
|
||||
<phrase data="customers_center_open">Открыть карточку</phrase>
|
||||
<phrase data="customers_center_card">Карточка покупателя</phrase>
|
||||
<phrase data="customers_center_card_hint">Профиль и история взаимодействия</phrase>
|
||||
<phrase data="customers_center_orders">Заказы</phrase>
|
||||
<phrase data="customers_center_login_methods">Способы входа</phrase>
|
||||
<phrase data="customers_center_contacts">Обращения</phrase>
|
||||
<phrase data="customers_center_notes">Заметки менеджеров</phrase>
|
||||
<phrase data="customers_center_note_hint">Внутренняя информация, покупатель её не видит</phrase>
|
||||
<phrase data="customers_center_note_new">Новая заметка</phrase>
|
||||
<phrase data="customers_center_note_added">Заметка добавлена</phrase>
|
||||
<phrase data="customers_center_merged">Аккаунты объединены</phrase>
|
||||
<phrase data="customers_center_segment_all">Все</phrase>
|
||||
<phrase data="customers_center_segment_new">Новые</phrase>
|
||||
<phrase data="customers_center_segment_buyers">С заказами</phrase>
|
||||
<phrase data="customers_center_segment_repeat">Повторные</phrase>
|
||||
<phrase data="customers_center_segment_vip">От 100 000 ₽</phrase>
|
||||
<phrase data="customers_center_segment_inactive">Неактивные</phrase>
|
||||
<phrase data="customers_center_segment_empty">Без заказов</phrase>
|
||||
</language>
|
||||
@@ -2,30 +2,12 @@
|
||||
<language>
|
||||
<phrase data="auto_32b373146ceb643e">Не удалось загрузить профиль</phrase>
|
||||
<phrase data="auto_3ad78d4634845d06">Новое поле</phrase>
|
||||
<phrase data="auto_453d46b73a83a1f7">Изменение требует права управления системными пользователями.</phrase>
|
||||
<phrase data="auto_51aff18539497f49">Пользователь</phrase>
|
||||
<phrase data="auto_533496be720f1840">Может входить на сайт и в личный кабинет.</phrase>
|
||||
<phrase data="auto_54628e7921e2b7ef">Пользователь сайта</phrase>
|
||||
<phrase data="auto_7851fbc651bc0177">: '&#039;' }[character];
|
||||
});
|
||||
},
|
||||
|
||||
deleteField: function (button) {
|
||||
var self = this;
|
||||
Adminx.Confirm.open({
|
||||
kind: 'error', title: 'Удалить поле?',
|
||||
message: 'Значения этого поля у пользователей сайта также будут удалены.',
|
||||
confirmLabel: 'Удалить', confirmClass: 'btn-danger',
|
||||
onConfirm: function () { self.request(button.getAttribute('data-url'), new FormData()).then(function () { window.location.reload(); }); }
|
||||
});
|
||||
},
|
||||
|
||||
toggleField: function (input) {
|
||||
var self = this;
|
||||
var item = input.closest('[data-field-id]');
|
||||
this.request(input.getAttribute('data-url'), new FormData()).then(function (response) {
|
||||
var active = !!Number(response.data && response.data.is_active);
|
||||
input.checked = active;
|
||||
item.classList.toggle('is-disabled', !active);
|
||||
var preview = document.querySelector('[data-preview-field=</phrase>
|
||||
<phrase data="auto_8072db5006172c8c">Права роли настраиваются в разделе «Роли и права».</phrase>
|
||||
<phrase data="auto_de7fb9566c3ab6f8">Не удалось выполнить действие</phrase>
|
||||
<phrase data="auto_f0dff5ab4a669f7a">Сохранено</phrase>
|
||||
<phrase data="auto_f7198a183e197a24">Та же учётная запись сможет работать в административном интерфейсе.</phrase>
|
||||
</language>
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------------
|
||||
| AVE.cms
|
||||
|--------------------------------------------------------------------------------------
|
||||
| @package AVE.cms
|
||||
| @file adminx/modules/Customers/migrations/007_customer_center.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\Common\SystemTables;
|
||||
use App\Content\BasketTables;
|
||||
|
||||
return function (array $context) {
|
||||
$notes = SystemTables::prefix() . '_customer_notes';
|
||||
if (!DatabaseSchema::tableExists($notes)) {
|
||||
DB::query('CREATE TABLE `' . $notes . '` ('
|
||||
. '`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,`user_id` INT UNSIGNED NOT NULL,`author_id` INT UNSIGNED NOT NULL DEFAULT 0,'
|
||||
. '`note` TEXT NOT NULL,`created_at` INT UNSIGNED NOT NULL,PRIMARY KEY (`id`),KEY `idx_customer_notes` (`user_id`,`created_at`)'
|
||||
. ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
|
||||
}
|
||||
|
||||
$orders = BasketTables::table('module_basket_history');
|
||||
if (DatabaseSchema::tableExists($orders) && !DatabaseSchema::indexExists($orders, 'idx_order_user_date')) {
|
||||
DB::query('ALTER TABLE `' . $orders . '` ADD KEY `idx_order_user_date` (`order_user_id`,`order_published`)');
|
||||
}
|
||||
|
||||
return 1;
|
||||
};
|
||||
@@ -14,8 +14,10 @@
|
||||
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Adminx\Customers\GlobalSearchProvider;
|
||||
|
||||
return array(
|
||||
'code' => 'customers', 'name' => 'Пользователи сайта', 'version' => '0.3.0',
|
||||
'code' => 'customers', 'name' => 'Пользователи сайта', 'version' => '0.10.4',
|
||||
'permissions' => array('key' => 'customers', 'items' => array(
|
||||
array(
|
||||
'code' => 'view_customers',
|
||||
@@ -45,9 +47,13 @@
|
||||
),
|
||||
),
|
||||
'routes' => array(
|
||||
array('GET', '/system/customers/export', array(\App\Adminx\Customers\Controller::class, 'exportCustomers')),
|
||||
array('GET', '/system/customers', array(\App\Adminx\Customers\Controller::class, 'index')),
|
||||
array('POST', '/system/customers/saved-views', array(\App\Adminx\Customers\Controller::class, 'saveSavedView')),
|
||||
array('POST', '/system/customers/saved-views/{id}/delete', array(\App\Adminx\Customers\Controller::class, 'deleteSavedView')),
|
||||
array('GET', '/system/customers/users/{id}', array(\App\Adminx\Customers\Controller::class, 'customer')),
|
||||
array('POST', '/system/customers/users/{id}', array(\App\Adminx\Customers\Controller::class, 'updateCustomer')),
|
||||
array('POST', '/system/customers/users/{id}/delete', array(\App\Adminx\Customers\Controller::class, 'deleteCustomer')),
|
||||
array('POST', '/system/customers/{id}/toggle', array(\App\Adminx\Customers\Controller::class, 'toggle')),
|
||||
array('POST', '/system/customers/fields/reorder', array(\App\Adminx\Customers\Controller::class, 'reorderFields')),
|
||||
array('POST', '/system/customers/fields/{id}', array(\App\Adminx\Customers\Controller::class, 'saveField')),
|
||||
@@ -58,6 +64,9 @@
|
||||
array('GET', '/system/customers/forms/{key}', array(\App\Adminx\Customers\Controller::class, 'authForm')),
|
||||
array('POST', '/system/customers/forms/{key}', array(\App\Adminx\Customers\Controller::class, 'saveAuthForm')),
|
||||
array('POST', '/system/customers/forms/{key}/reset', array(\App\Adminx\Customers\Controller::class, 'resetAuthForm')),
|
||||
array('GET', '/system/customers/center/{id}', array(\App\Adminx\Customers\Controller::class, 'centerCustomer')),
|
||||
array('POST', '/system/customers/center/{id}/notes', array(\App\Adminx\Customers\Controller::class, 'addCustomerNote')),
|
||||
array('POST', '/system/customers/center/merge', array(\App\Adminx\Customers\Controller::class, 'mergeCustomers')),
|
||||
),
|
||||
'migrations' => array(
|
||||
array('id' => '001_normalize_public_groups', 'file' => 'migrations/001_normalize_public_groups.sql'),
|
||||
@@ -66,6 +75,11 @@
|
||||
array('id' => '004_materialize_public_auth_schema', 'file' => 'migrations/004_materialize_public_auth_schema.sql'),
|
||||
array('id' => '005_checkout_registration', 'file' => 'migrations/005_checkout_registration.sql'),
|
||||
array('id' => '006_phone_identity', 'file' => 'migrations/006_phone_identity.php'),
|
||||
array('id' => '007_customer_center', 'file' => 'migrations/007_customer_center.php'),
|
||||
),
|
||||
'view_globals' => array('module_code' => 'customers'),
|
||||
'admin_extension' => array(
|
||||
'url' => '/system/customers', 'feature' => 'Публичные аккаунты и профили', 'icon' => 'ti ti-user-heart',
|
||||
'search' => array('code' => 'customers', 'provider' => array(GlobalSearchProvider::class, 'search'), 'permission' => 'view_customers', 'priority' => 26, 'limit' => 8),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<section class="customers-center-profile"><div class="customers-center-avatar">{{ (customer.user.firstname|first ~ customer.user.lastname|first)|upper ?: '#' }}</div><div><span class="section-eyebrow">Профиль #{{ customer.user.id }}</span><h2>{{ (customer.user.firstname ~ ' ' ~ customer.user.lastname)|trim ?: customer.user.user_name }}</h2><p>{{ customer.user.email ?: 'Email не указан' }}{% if customer.user.phone %} · {{ customer.user.phone }}{% endif %}</p><div class="customers-center-segment-list">{% set labels={'new':'Новый','buyers':'С заказами','repeat':'Повторный','vip':'От 100 000 ₽','inactive':'Неактивный','without_orders':'Без заказов'} %}{% for code in customer.segments %}<span class="badge {{ code=='vip'?'badge-violet':(code=='repeat'?'badge-green':(code=='inactive'?'badge-gray':'badge-blue')) }}">{{ labels[code] }}</span>{% endfor %}</div></div><a class="btn btn-secondary btn-sm" href="{{ ADMINX_BASE }}/system/customers?tab=customers&q={{ customer.user.id }}"><i class="ti ti-pencil"></i>Редактировать аккаунт</a></section>
|
||||
|
||||
<div class="customers-center-detail-kpis"><span><i class="ti ti-shopping-bag"></i><b>{{ customer.summary.orders_count }}</b><small>заказов</small></span><span><i class="ti ti-currency-rubel"></i><b>{{ customer.summary.orders_total|number_format(0,'.',' ') }} ₽</b><small>общая сумма</small></span><span><i class="ti ti-heart"></i><b>{{ customer.engagement.favorites|length }}</b><small>в избранном</small></span><span><i class="ti ti-history"></i><b>{{ customer.engagement.viewed|length }}</b><small>просмотрено</small></span></div>
|
||||
|
||||
<div class="customers-center-detail-grid">
|
||||
<section class="card ax-list-card"><div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile"><i class="ti ti-shopping-bag"></i></span><div><h3>Заказы</h3><p>Последние покупки пользователя</p></div></div>{% if customer.summary.guest_count %}<span class="badge badge-amber" data-tooltip="Оформлены без входа, найдены по email или телефону">Гостевых: {{ customer.summary.guest_count }}</span>{% endif %}</div><div class="customers-center-order-list">{% for order in customer.orders %}<a href="{{ ADMINX_BASE }}/shop/orders?tab=orders&q={{ order.order_id }}"><span><b>#{{ order.order_id }}</b><small>{{ order.order_published|date('d.m.Y H:i') }}{% if order.matched_by == 'contact' %} · <i class="ti ti-user-question"></i> гостевой{% endif %}</small></span><strong>{{ order.order_total|number_format(0,'.',' ') }} ₽</strong></a>{% else %}<div class="empty-state">Заказов пока нет</div>{% endfor %}</div></section>
|
||||
<section class="card ax-list-card"><div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--cyan-100);--tile-fg:var(--cyan-600)"><i class="ti ti-login"></i></span><div><h3>Способы входа</h3><p>Связанные аккаунты и подтверждения</p></div></div></div><div class="customers-center-identities"><article><i class="ti ti-{{ customer.user.email_verified_at?'mail-check':'mail' }}"></i><span><b>Email</b><small>{{ customer.user.email_verified_at?'подтверждён':'не подтверждён' }}</small></span></article>{% if customer.user.phone %}<article><i class="ti ti-{{ customer.user.phone_verified_at?'phone-check':'phone' }}"></i><span><b>Телефон</b><small>{{ customer.user.phone_verified_at?'подтверждён':'не подтверждён' }}</small></span></article>{% endif %}{% for identity in customer.identities %}<article><i class="ti {{ identity.provider=='yandex'?'ti-brand-yandex':(identity.provider=='vk'?'ti-brand-vk':'ti-key') }}"></i><span><b>{{ identity.provider|upper }}</b><small>последний вход {{ identity.last_login_at?identity.last_login_at|date('d.m.Y'):'—' }}</small></span></article>{% endfor %}</div></section>
|
||||
<section class="card ax-list-card"><div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--amber-100);--tile-fg:var(--amber-600)"><i class="ti ti-message"></i></span><div><h3>Обращения</h3><p>Сообщения контактных форм по email</p></div></div></div><div class="customers-center-contact-list">{% for item in customer.contacts %}<article><span><b>{{ item.subject ?: 'Обращение #' ~ item.id }}</b><small>{{ item.date|date('d.m.Y H:i') }}</small></span><span class="badge {{ item.status=='new'?'badge-amber':(item.status=='replied'?'badge-green':'badge-gray') }}">{{ item.status=='new'?'Новое':(item.status=='replied'?'Отвечено':'Просмотрено') }}</span></article>{% else %}<div class="empty-state">Обращений не найдено</div>{% endfor %}</div></section>
|
||||
{% if customer.popup_leads %}<section class="card ax-list-card"><div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--green-100);--tile-fg:var(--green-600)"><i class="ti ti-user-plus"></i></span><div><h3>Заявки из поп-апов</h3><p>Сопоставлены по email или телефону</p></div></div></div><div class="customers-center-contact-list">{% for item in customer.popup_leads %}<article><span><b>{{ item.campaign_title ?: 'Заявка #' ~ item.id }}</b><small>{{ item.created_at|date('d.m.Y H:i') }}{% if item.phone %} · {{ item.phone }}{% endif %}</small></span><span class="badge {{ item.status=='new'?'badge-amber':(item.status=='spam'?'badge-red':'badge-green') }}">{{ item.status=='new'?'Новая':(item.status=='spam'?'Спам':'Обработана') }}</span></article>{% endfor %}</div></section>{% endif %}
|
||||
{% if customer.quiz_leads %}<section class="card ax-list-card"><div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--cyan-100);--tile-fg:var(--cyan-600)"><i class="ti ti-list-check"></i></span><div><h3>Заявки из подбора</h3><p>Сопоставлены по email или телефону</p></div></div></div><div class="customers-center-contact-list">{% for item in customer.quiz_leads %}<article><span><b>{{ item.quiz_title }}</b><small>{{ item.created_label }} · ответов {{ item.answers_count }} · подошло {{ item.matches_count }}</small></span><span class="badge {{ item.lead_status=='new'?'badge-amber':(item.lead_status=='spam'?'badge-red':'badge-green') }}">{{ item.lead_status=='new'?'Новая':(item.lead_status=='spam'?'Спам':'Обработана') }}</span></article>{% endfor %}</div></section>{% endif %}
|
||||
<section class="card ax-list-card"><div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--violet-100);--tile-fg:var(--violet-600)"><i class="ti ti-note"></i></span><div><h3>Заметки менеджеров</h3><p>Внутренняя информация, покупатель её не видит</p></div></div></div><div class="customers-center-notes">{% for note in customer.notes %}<article><p>{{ note.note }}</p><small>{{ note.author_name ?: 'Система' }} · {{ note.created_at|date('d.m.Y H:i') }}</small></article>{% else %}<div class="empty-state">Заметок пока нет</div>{% endfor %}</div>{% if can_manage %}<form class="customers-center-note-form" action="{{ ADMINX_BASE }}/system/customers/center/{{ customer.user.id }}/notes" data-customer-note data-refresh-url="{{ ADMINX_BASE }}/system/customers/center/{{ customer.user.id }}"><input type="hidden" name="_csrf" value="{{ csrf_token }}"><label class="field"><span class="field-label">Новая заметка</span><textarea class="textarea" name="note" rows="3" maxlength="4000" required></textarea></label><button class="btn btn-primary btn-sm" type="submit"><i class="ti ti-plus"></i>Добавить</button></form>{% endif %}</section>
|
||||
</div>
|
||||
@@ -0,0 +1,19 @@
|
||||
<div class="section-header ax-panel-header customers-center-head"><div class="section-icon"><i class="ti ti-users-group"></i></div><div><div class="section-eyebrow">Работа с покупателями</div><h2>Центр покупателей</h2><p class="section-desc">Аккаунт, покупки, обращения и интересы человека собраны в одной карточке.</p></div><div class="section-header-right"><form class="customers-filter" action="{{ ADMINX_BASE }}/system/customers" data-customers-center-filter><input type="hidden" name="tab" value="center"><input type="hidden" name="segment" value="{{ segment|e }}"><div class="input-wrap"><i class="ti ti-search"></i><input class="input" type="search" name="q" value="{{ q|e }}" placeholder="Имя, email, телефон или ID"></div><button class="btn btn-secondary"><i class="ti ti-search"></i>Найти</button></form>{% set saved_views_form = '[data-customers-center-filter]' %}{% set saved_views_save_url = ADMINX_BASE ~ '/system/customers/saved-views' %}{% set saved_views_delete_url = ADMINX_BASE ~ '/system/customers/saved-views/__ID__/delete' %}{% set saved_views_fields = ['q','segment'] %}{% include '@adminx/_saved_views.twig' %}</div></div>
|
||||
|
||||
<div class="customers-center-kpis">
|
||||
<div class="card stat-tile"><div class="stat-ico"><i class="ti ti-users"></i></div><div><div class="stat-val">{{ center_stats.total|default(0) }}</div><div class="stat-label">Аккаунтов</div></div></div>
|
||||
<div class="card stat-tile"><div class="stat-ico is-green"><i class="ti ti-shopping-bag"></i></div><div><div class="stat-val">{{ center_stats.buyers|default(0) }}</div><div class="stat-label">Покупателей</div></div></div>
|
||||
<div class="card stat-tile"><div class="stat-ico is-blue"><i class="ti ti-repeat"></i></div><div><div class="stat-val">{{ center_stats.repeat|default(0) }}</div><div class="stat-label">Повторных</div></div></div>
|
||||
<div class="card stat-tile"><div class="stat-ico is-violet"><i class="ti ti-user-question"></i></div><div><div class="stat-val">{{ center_stats.duplicates|default(0) }}</div><div class="stat-label">Групп дублей</div></div></div>
|
||||
</div>
|
||||
|
||||
<nav class="customers-segments" aria-label="Сегменты покупателей">{% for code,label in center_segments %}<a class="{{ segment==code?'is-active':'' }}" href="{{ ADMINX_BASE }}/system/customers?tab=center&segment={{ code }}{% if q %}&q={{ q|url_encode }}{% endif %}">{{ label }}</a>{% endfor %}</nav>
|
||||
|
||||
{% if duplicate_groups %}<details class="alert alert-warning customers-duplicates"><summary><span><i class="ti ti-users-minus"></i><b>Найдены возможные дубли</b></span><span>{{ duplicate_groups|length }}</span></summary><div>{% for group in duplicate_groups %}<article><span><b>{{ group.kind=='email'?'Одинаковый email':'Одинаковый телефон' }}</b><small>{{ group.value }}</small></span><span class="mono">{% for id in group.ids %}#{{ id }}{% if not loop.last %}, {% endif %}{% endfor %}</span>{% if can_manage %}{% for id in group.ids %}{% if id!=group.target_id %}<button class="btn btn-secondary btn-sm" type="button" data-customer-merge data-target-id="{{ group.target_id }}" data-source-id="{{ id }}"><i class="ti ti-arrows-join"></i>Объединить #{{ id }} с #{{ group.target_id }}</button>{% endif %}{% endfor %}{% endif %}</article>{% endfor %}</div></details>{% endif %}
|
||||
|
||||
<section class="card ax-list-card customers-center-list">
|
||||
<div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--blue-100);--tile-fg:var(--blue-600)"><i class="ti ti-address-book"></i></span><div><h2>Покупатели</h2><p class="text-secondary">Откройте карточку, чтобы увидеть всю историю взаимодействия.</p></div></div><span class="badge badge-blue">{{ center_customers|length }}</span></div>
|
||||
<div class="table-scroll"><table class="table customers-center-table"><thead><tr><th>Покупатель</th><th>Заказы</th><th>Активность</th><th>Сегменты</th><th class="customers-actions-col">Действия</th></tr></thead><tbody>{% for customer in center_customers %}<tr data-customer-center-open data-url="{{ ADMINX_BASE }}/system/customers/center/{{ customer.id }}"><td><div class="customers-center-person"><span>{{ (customer.firstname|first ~ customer.lastname|first)|upper ?: '#' }}</span><div><b>{{ (customer.firstname ~ ' ' ~ customer.lastname)|trim ?: customer.user_name }}</b><small>{{ customer.email ?: customer.phone }} · #{{ customer.id }}</small></div></div></td><td><b>{{ customer.orders_count }} заказов</b><small>{{ customer.orders_total|number_format(0,'.',' ') }} ₽</small></td><td><b>{{ customer.last_order_at ? customer.last_order_at|date('d.m.Y') : 'Покупок нет' }}</b><small>Вход: {{ customer.last_visit ? customer.last_visit|date('d.m.Y') : 'не входил' }}</small></td><td><div class="customers-center-segment-list">{% for code in customer.segment_codes %}<span class="badge {{ code=='vip'?'badge-violet':(code=='repeat'?'badge-green':(code=='inactive'?'badge-gray':'badge-blue')) }}">{{ center_segments[code] }}</span>{% endfor %}</div></td><td><button class="btn btn-icon btn-ghost ax-act ax-act-view" type="button" data-tooltip="Открыть карточку" aria-label="Открыть карточку"><i class="ti ti-eye"></i></button></td></tr>{% else %}<tr><td colspan="5"><div class="empty-state"><i class="ti ti-user-search"></i><b>Покупатели не найдены</b><span>Измените поисковый запрос или сегмент.</span></div></td></tr>{% endfor %}</tbody></table></div>
|
||||
</section>
|
||||
|
||||
<aside class="drawer drawer-right customer-center-drawer" id="customerCenterDrawer" role="dialog" aria-modal="true" aria-labelledby="customerCenterDrawerTitle" hidden><div class="drawer-header"><div><h3 id="customerCenterDrawerTitle">Карточка покупателя</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><div class="drawer-body customers-center-detail" data-customer-center-detail><div class="skeleton" style="height:160px"></div></div><div class="drawer-footer"><button class="btn btn-ghost" type="button" data-close-drawer>Закрыть</button></div></aside>
|
||||
@@ -5,26 +5,29 @@
|
||||
|
||||
<div class="page-header"><div><h1>Пользователи сайта</h1><p class="text-secondary">Публичные аккаунты, профили и способы входа</p></div></div>
|
||||
|
||||
<div class="ax-summary customers-summary">
|
||||
{% if tab!='center' %}<div class="ax-summary customers-summary">
|
||||
<div class="card stat-tile"><div class="stat-ico"><i class="ti ti-users"></i></div><div><div class="stat-val">{{ stats.total }}</div><div class="stat-label">Всего</div></div></div>
|
||||
<div class="card stat-tile"><div class="stat-ico is-green"><i class="ti ti-user-check"></i></div><div><div class="stat-val">{{ stats.active }}</div><div class="stat-label">Активные</div></div></div>
|
||||
<div class="card stat-tile"><div class="stat-ico is-blue"><i class="ti ti-mail-check"></i></div><div><div class="stat-val">{{ stats.verified }}</div><div class="stat-label">Email подтверждён</div></div></div>
|
||||
<div class="card stat-tile"><div class="stat-ico is-violet"><i class="ti ti-forms"></i></div><div><div class="stat-val">{{ stats.fields }}</div><div class="stat-label">Доп. полей</div></div></div>
|
||||
</div>
|
||||
</div>{% endif %}
|
||||
|
||||
<nav class="tabs customers-tabs">
|
||||
<a class="tab{{ tab=='center'?' active':'' }}" href="{{ ADMINX_BASE }}/system/customers?tab=center"><i class="ti ti-users-group"></i>Центр покупателей</a>
|
||||
<a class="tab{{ tab=='customers'?' active':'' }}" href="{{ ADMINX_BASE }}/system/customers?tab=customers"><i class="ti ti-users"></i>Пользователи</a>
|
||||
<a class="tab{{ tab=='fields'?' active':'' }}" href="{{ ADMINX_BASE }}/system/customers?tab=fields"><i class="ti ti-forms"></i>Поля профиля</a>
|
||||
<a class="tab{{ tab=='auth'?' active':'' }}" href="{{ ADMINX_BASE }}/system/customers?tab=auth"><i class="ti ti-user-cog"></i>Регистрация</a>
|
||||
<a class="tab{{ tab=='pages'?' active':'' }}" href="{{ ADMINX_BASE }}/system/customers?tab=pages"><i class="ti ti-browser"></i>Страницы входа</a>
|
||||
</nav>
|
||||
|
||||
{% if tab=='customers' %}
|
||||
<div class="section-header ax-panel-header"><div class="section-icon"><i class="ti ti-user-search"></i></div><div><div class="section-eyebrow">Аккаунты сайта</div><h2>Пользователи</h2></div><div class="section-header-right"><form class="customers-filter"><input type="hidden" name="tab" value="customers"><div class="input-wrap"><i class="ti ti-search"></i><input class="input" type="search" name="q" value="{{ q|e }}" placeholder="Имя, email, телефон"></div><button class="btn btn-secondary"><i class="ti ti-filter"></i>Найти</button></form></div></div>
|
||||
{% if tab=='center' %}
|
||||
{% include '@customers/customer-center.twig' %}
|
||||
{% elseif tab=='customers' %}
|
||||
<div class="section-header ax-panel-header"><div class="section-icon"><i class="ti ti-user-search"></i></div><div><div class="section-eyebrow">Аккаунты сайта</div><h2>Пользователи</h2></div><div class="section-header-right"><form class="customers-filter"><input type="hidden" name="tab" value="customers"><div class="input-wrap"><i class="ti ti-search"></i><input class="input" type="search" name="q" value="{{ q|e }}" placeholder="Имя, email, телефон"></div><button class="btn btn-secondary"><i class="ti ti-filter"></i>Найти</button></form><a class="btn btn-secondary" href="{{ ADMINX_BASE }}/system/customers/export?q={{ q|url_encode }}"><i class="ti ti-file-spreadsheet"></i>CSV</a></div></div>
|
||||
<div class="card ax-list-card">
|
||||
<div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--green-100);--tile-fg:var(--green-600)"><i class="ti ti-users-group"></i></span><div><h2>Публичные аккаунты</h2><p class="text-secondary">Посетители, зарегистрированные на сайте, их контакты и доступ к личному кабинету.</p></div></div><span class="badge badge-blue">{{ customers|length }}</span></div>
|
||||
<div class="table-scroll"><table class="table customers-table"><thead><tr><th>ID</th><th>Пользователь</th><th>Контакты</th><th>Компания</th><th>Регистрация</th><th>Статус</th>{% if can_manage %}<th class="customers-actions-col">Действия</th>{% endif %}</tr></thead><tbody>
|
||||
{% for customer in customers %}<tr data-customer-row data-id="{{ customer.id }}"><td class="mono text-muted">{{ customer.id }}</td><td data-customer-name><b>{{ (customer.firstname ~ ' ' ~ customer.lastname)|trim ?: customer.user_name }}</b><small class="mono">{{ customer.user_name }}</small></td><td data-customer-contacts><span>{{ customer.email ?: customer.phone }}</span>{% if customer.email and customer.phone %}<small>{{ customer.phone }}</small>{% endif %}</td><td data-customer-company>{{ customer.company ?: '—' }}</td><td class="mono text-sm">{{ customer.reg_time ? customer.reg_time|date('d.m.Y') : '—' }}</td><td>{% if can_manage %}<label class="switch" data-tooltip="Изменить активность"><input type="checkbox" data-customer-toggle data-url="{{ ADMINX_BASE }}/system/customers/{{ customer.id }}/toggle"{{ customer.status=='1'?' checked':'' }}><span></span></label>{% else %}<span class="badge {{ customer.status=='1'?'badge-green':'badge-gray' }}">{{ customer.status=='1'?'Активен':'Отключён' }}</span>{% endif %}</td>{% if can_manage %}<td><button class="btn btn-icon btn-ghost ax-act ax-act-edit" type="button" data-customer-edit data-url="{{ ADMINX_BASE }}/system/customers/users/{{ customer.id }}" data-tooltip="Редактировать" aria-label="Редактировать"><i class="ti ti-pencil"></i></button></td>{% endif %}</tr>
|
||||
{% for customer in customers %}<tr data-customer-row data-id="{{ customer.id }}"><td class="mono text-muted">{{ customer.id }}</td><td data-customer-name><b>{{ (customer.firstname ~ ' ' ~ customer.lastname)|trim ?: customer.user_name }}</b><small class="mono">{{ customer.user_name }}</small></td><td data-customer-contacts><span>{{ customer.email ?: customer.phone }}</span>{% if customer.email and customer.phone %}<small>{{ customer.phone }}</small>{% endif %}</td><td data-customer-company>{{ customer.company ?: '—' }}</td><td class="mono text-sm">{{ customer.reg_time ? customer.reg_time|date('d.m.Y') : '—' }}</td><td>{% if can_manage %}<label class="switch" data-tooltip="{{ customer.id==current_public_user_id ? 'Собственную учётную запись нельзя отключить' : 'Изменить активность' }}"><input type="checkbox" data-customer-toggle data-url="{{ ADMINX_BASE }}/system/customers/{{ customer.id }}/toggle"{{ customer.status=='1'?' checked':'' }}{{ customer.id==current_public_user_id?' disabled':'' }}><span></span></label>{% else %}<span class="badge {{ customer.status=='1'?'badge-green':'badge-gray' }}">{{ customer.status=='1'?'Активен':'Отключён' }}</span>{% endif %}</td>{% if can_manage %}<td><button class="btn btn-icon btn-ghost ax-act ax-act-edit" type="button" data-customer-edit data-url="{{ ADMINX_BASE }}/system/customers/users/{{ customer.id }}" data-tooltip="Редактировать" aria-label="Редактировать"><i class="ti ti-pencil"></i></button>{% if customer.id==current_public_user_id %}<button class="btn btn-icon btn-ghost ax-act" type="button" disabled data-tooltip="Собственную учётную запись удалить нельзя" aria-label="Удаление недоступно"><i class="ti ti-lock"></i></button>{% else %}<button class="btn btn-icon btn-ghost ax-act ax-act-danger" type="button" data-customer-delete data-url="{{ ADMINX_BASE }}/system/customers/users/{{ customer.id }}/delete" data-tooltip="Удалить" aria-label="Удалить"><i class="ti ti-trash"></i></button>{% endif %}</td>{% endif %}</tr>
|
||||
{% else %}<tr><td colspan="{{ can_manage ? 7 : 6 }}"><div class="empty-state">Пользователи не найдены</div></td></tr>{% endfor %}
|
||||
</tbody></table></div>
|
||||
</div>
|
||||
@@ -70,17 +73,17 @@
|
||||
<section class="card customers-auth-section">
|
||||
<div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--green-100);--tile-fg:var(--green-600)"><i class="ti ti-user-plus"></i></span><div><h2>Создание аккаунта</h2><p class="text-secondary">Кто может зарегистрироваться и когда станет доступен вход.</p></div></div><label class="switch" data-tooltip="Разрешить регистрацию"><input type="checkbox" name="registration_enabled" value="1"{{ auth_settings.registration_enabled ? ' checked' : '' }}{{ can_manage ? '' : ' disabled' }}><span></span></label></div>
|
||||
<div class="customers-auth-settings-grid">
|
||||
<label class="field"><span class="field-label">Активация аккаунта</span><select class="select" name="registration_mode" data-registration-mode{{ can_manage ? '' : ' disabled' }}><option value="email"{{ auth_settings.registration_mode=='email' ? ' selected' : '' }}>После подтверждения email</option><option value="now"{{ auth_settings.registration_mode=='now' ? ' selected' : '' }}>Сразу после регистрации</option><option value="byadmin"{{ auth_settings.registration_mode=='byadmin' ? ' selected' : '' }}>После одобрения администратором</option></select><span class="field-hint">Для режима одобрения включите пользователя в первом табе.</span></label>
|
||||
<label class="field"><span class="field-label">Способ входа и регистрации</span><select class="select" name="registration_gate" data-registration-gate{{ can_manage ? '' : ' disabled' }}><option value="email"{{ auth_settings.registration_gate=='email' ? ' selected' : '' }}>По email и паролю</option><option value="phone"{{ auth_settings.registration_gate=='phone' ? ' selected' : '' }}>По телефону и SMS-коду</option><option value="email_phone"{{ auth_settings.registration_gate=='email_phone' ? ' selected' : '' }}>Оба способа</option></select><span class="field-hint">В телефонном режиме email остаётся необязательным контактом профиля и не используется для публичного входа.</span></label>
|
||||
<label class="field" data-auth-email-registration><span class="field-label">Активация регистрации по email</span><select class="select" name="registration_mode" data-registration-mode{{ can_manage ? '' : ' disabled' }}><option value="email"{{ auth_settings.registration_mode=='email' ? ' selected' : '' }}>После подтверждения email</option><option value="now"{{ auth_settings.registration_mode=='now' ? ' selected' : '' }}>Сразу после регистрации</option><option value="byadmin"{{ auth_settings.registration_mode=='byadmin' ? ' selected' : '' }}>После одобрения администратором</option></select><span class="field-hint">Телефон уже подтверждается одноразовым SMS-кодом.</span></label>
|
||||
<label class="field"><span class="field-label">Группа после регистрации</span><select class="select" name="default_group"{{ can_manage ? '' : ' disabled' }}>{% for group in customer_groups %}<option value="{{ group.id }}"{{ auth_settings.default_group==group.id ? ' selected' : '' }}>#{{ group.id }} · {{ group.name }} · {{ group.permissions_count }} разрешений</option>{% endfor %}</select><span class="field-hint">Вы сами выбираете группу, которая будет назначаться новым пользователям сайта.</span></label>
|
||||
<div class="field customers-auth-fixed"><span class="field-label">Канал регистрации</span><div class="customers-auth-fixed-value"><i class="ti ti-mail"></i><span><b>Email</b><small>Телефон и SMS подключаются отдельным гейтом.</small></span></div></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card customers-auth-section">
|
||||
<div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--cyan-100);--tile-fg:var(--cyan-600)"><i class="ti ti-forms"></i></span><div><h2>Поля формы регистрации</h2><p class="text-secondary">Базовые данные аккаунта. Дополнительные поля подключаются в соседнем табе.</p></div></div></div>
|
||||
<section class="card customers-auth-section" data-auth-email-form-fields>
|
||||
<div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--cyan-100);--tile-fg:var(--cyan-600)"><i class="ti ti-forms"></i></span><div><h2>Поля регистрации по email</h2><p class="text-secondary">Для регистрации по телефону достаточно номера и SMS-кода. Остальные данные пользователь заполнит в профиле.</p></div></div></div>
|
||||
<div class="customers-auth-fields" data-auth-fields>
|
||||
<div class="customers-auth-fields-head"><span>Поле</span><span>Показывать</span><span>Обязательное</span></div>
|
||||
<div class="customers-auth-field-row"><span><i class="ti ti-mail"></i><span><b>Email</b><small>Логин и канал подтверждения</small></span></span><span class="badge badge-blue">Всегда</span><span class="badge badge-blue">Всегда</span></div>
|
||||
<div class="customers-auth-field-row"><span><i class="ti ti-mail"></i><span><b>Email</b><small data-auth-email-field-description>{{ auth_settings.registration_gate == 'phone' ? 'Не используется для входа; можно добавить в профиле как контакт' : (auth_settings.registration_gate == 'email_phone' ? 'Запрашивается только при выборе регистрации по email' : 'Логин и канал подтверждения регистрации по email') }}</small></span></span><span class="badge {{ auth_settings.registration_gate == 'phone' ? 'badge-gray' : 'badge-blue' }}" data-auth-email-visibility>{{ auth_settings.registration_gate == 'phone' ? 'Только в профиле' : (auth_settings.registration_gate == 'email_phone' ? 'В email-форме' : 'Показывается') }}</span><span class="badge {{ auth_settings.registration_gate == 'email' ? 'badge-blue' : 'badge-gray' }}" data-auth-email-required>{{ auth_settings.registration_gate == 'phone' ? 'Необязательно' : (auth_settings.registration_gate == 'email_phone' ? 'По выбору способа' : 'Обязательно') }}</span></div>
|
||||
<div class="customers-auth-field-row"><span><i class="ti ti-user"></i><span><b>Имя</b><small>Основное имя пользователя</small></span></span><span class="badge badge-blue">Всегда</span><label class="switch"><input type="checkbox" name="require_firstname" value="1"{{ auth_settings.require_firstname ? ' checked' : '' }}{{ can_manage ? '' : ' disabled' }}><span></span></label></div>
|
||||
<div class="customers-auth-field-row" data-auth-field-row><span><i class="ti ti-id"></i><span><b>Фамилия</b><small>Дополняет отображаемое имя</small></span></span><label class="switch"><input type="checkbox" name="show_lastname" value="1" data-auth-show{{ auth_settings.show_lastname ? ' checked' : '' }}{{ can_manage ? '' : ' disabled' }}><span></span></label><label class="switch"><input type="checkbox" name="require_lastname" value="1" data-auth-required{{ auth_settings.require_lastname ? ' checked' : '' }}{{ can_manage ? '' : ' disabled' }}><span></span></label></div>
|
||||
<div class="customers-auth-field-row" data-auth-field-row><span><i class="ti ti-phone"></i><span><b>Телефон</b><small>Контакт для заказов и доставки</small></span></span><label class="switch"><input type="checkbox" name="show_phone" value="1" data-auth-show{{ auth_settings.show_phone ? ' checked' : '' }}{{ can_manage ? '' : ' disabled' }}><span></span></label><label class="switch"><input type="checkbox" name="require_phone" value="1" data-auth-required{{ auth_settings.require_phone ? ' checked' : '' }}{{ can_manage ? '' : ' disabled' }}><span></span></label></div>
|
||||
@@ -88,7 +91,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card customers-auth-section">
|
||||
<section class="card customers-auth-section" data-auth-email-settings>
|
||||
<div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--amber-100);--tile-fg:var(--amber-600)"><i class="ti ti-shield-lock"></i></span><div><h2>Пароль и подтверждение</h2><p class="text-secondary">Срок действия одноразовых ссылок и требования к паролю.</p></div></div></div>
|
||||
<div class="customers-auth-settings-grid">
|
||||
<label class="field"><span class="field-label">Минимальная длина пароля</span><input class="input" type="number" name="password_min_length" min="8" max="72" value="{{ auth_settings.password_min_length }}"{{ can_manage ? '' : ' disabled' }}></label>
|
||||
@@ -98,7 +101,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card customers-auth-section customers-checkout-registration">
|
||||
<section class="card customers-auth-section customers-checkout-registration" data-auth-email-settings>
|
||||
<div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--violet-100);--tile-fg:var(--violet-600)"><i class="ti ti-shopping-bag-check"></i></span><div><h2>Аккаунт после заказа</h2><p class="text-secondary">Покупатель может создать тот же личный кабинет прямо при оформлении.</p></div></div><label class="switch" data-tooltip="Предлагать регистрацию в корзине"><input type="checkbox" name="checkout_registration_enabled" value="1"{{ auth_settings.checkout_registration_enabled ? ' checked' : '' }}{{ can_manage ? '' : ' disabled' }}><span></span></label></div>
|
||||
<div class="customers-checkout-body">
|
||||
<div class="alert alert-info customers-checkout-note"><i class="ti ti-lock-check"></i><p>Пароль по почте не отправляется. После заказа пользователь сразу входит в аккаунт и получает одноразовую ссылку, чтобы задать пароль самостоятельно.</p></div>
|
||||
@@ -115,7 +118,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card customers-auth-section">
|
||||
<section class="card customers-auth-section" data-auth-email-settings>
|
||||
<div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--red-100);--tile-fg:var(--red-600)"><i class="ti ti-shield-x"></i></span><div><h2>Ограничения регистрации</h2><p class="text-secondary">Один email или домен на строку. Проверка не зависит от регистра букв.</p></div></div></div>
|
||||
<div class="customers-auth-restrictions"><label class="field"><span class="field-label">Запрещённые домены</span><textarea class="textarea mono" name="deny_domains" rows="5" placeholder="example.org mail.invalid"{{ can_manage ? '' : ' disabled' }}>{{ auth_settings.deny_domains|e }}</textarea></label><label class="field"><span class="field-label">Запрещённые адреса</span><textarea class="textarea mono" name="deny_emails" rows="5" placeholder="blocked@example.org"{{ can_manage ? '' : ' disabled' }}>{{ auth_settings.deny_emails|e }}</textarea></label></div>
|
||||
</section>
|
||||
@@ -123,14 +126,13 @@
|
||||
{% if can_manage %}<div class="customers-auth-actions"><button class="btn btn-primary" type="submit"><i class="ti ti-device-floppy"></i>Сохранить настройки</button></div>{% endif %}
|
||||
</form>
|
||||
|
||||
{% if oauth_modules %}
|
||||
<div class="section-header customers-social-head">
|
||||
<div class="section-icon"><i class="ti ti-login-2"></i></div>
|
||||
<div><div class="section-eyebrow">Авторизация</div><h2>Подключённые способы входа</h2><p class="section-desc">OAuth и вход по одноразовому коду используют одну учётную запись сайта.</p></div>
|
||||
<div class="section-header-right"><span class="badge badge-blue">{{ oauth_modules|length }} подключено</span></div>
|
||||
<div><div class="section-eyebrow">Авторизация</div><h2>Способы входа</h2><p class="section-desc">Яндекс, VK ID и SMS-код подключаются к одной учётной записи сайта.</p></div>
|
||||
<div class="section-header-right"><span class="badge badge-green">{{ auth_method_stats.active }} активно</span><span class="badge badge-gray">{{ auth_method_stats.installed }} установлено</span></div>
|
||||
</div>
|
||||
<div class="customers-social-grid">
|
||||
{% for provider in oauth_modules %}
|
||||
{% for provider in auth_methods %}
|
||||
<section class="card customers-social-card">
|
||||
<div class="ax-list-head">
|
||||
<div class="ax-list-title"><span class="customers-social-mark {{ provider.brand }}">{{ provider.mark }}</span><div><h3>{{ provider.label }}</h3><p class="text-secondary">{{ provider.description }}</p></div></div>
|
||||
@@ -138,19 +140,17 @@
|
||||
</div>
|
||||
<div class="customers-social-status">
|
||||
<div class="customers-social-checks">
|
||||
<span class="{{ provider.module_enabled ? 'is-ready' : '' }}"><i class="ti {{ provider.module_enabled ? 'ti-circle-check' : 'ti-circle-x' }}"></i>Модуль включён</span>
|
||||
<span class="{{ provider.configured ? 'is-ready' : '' }}"><i class="ti {{ provider.configured ? 'ti-key' : 'ti-key-off' }}"></i>Ключи настроены</span>
|
||||
<span class="{{ provider.installed ? 'is-ready' : '' }}"><i class="ti {{ provider.installed ? 'ti-package' : 'ti-package-off' }}"></i>Модуль {{ provider.installed ? 'установлен' : 'не установлен' }}</span>
|
||||
<span class="{{ provider.module_enabled ? 'is-ready' : '' }}"><i class="ti {{ provider.module_enabled ? 'ti-circle-check' : 'ti-circle-x' }}"></i>Модуль {{ provider.module_enabled ? 'включён' : 'выключен' }}</span>
|
||||
<span class="{{ provider.configured ? 'is-ready' : '' }}"><i class="ti {{ provider.configured ? 'ti-key' : 'ti-key-off' }}"></i>Подключение {{ provider.configured ? 'настроено' : 'не настроено' }}</span>
|
||||
<span class="{{ provider.allow_registration ? 'is-ready' : '' }}"><i class="ti ti-user-plus"></i>Регистрация {{ provider.allow_registration ? 'разрешена' : 'выключена' }}</span>
|
||||
</div>
|
||||
{% if provider.can_open %}<a class="btn btn-secondary btn-sm" href="{{ ADMINX_BASE }}{{ provider.url }}"><i class="ti ti-settings"></i>Настроить</a>{% endif %}
|
||||
{% if provider.can_open %}<a class="btn btn-secondary btn-sm" href="{{ ADMINX_BASE }}{{ provider.action_url }}"><i class="ti {{ provider.installed ? 'ti-settings' : 'ti-puzzle' }}"></i>{{ provider.action_label }}</a>{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-info customers-auth-note"><span class="icon-tile" style="--tile-bg:var(--blue-100);--tile-fg:var(--blue-600)"><i class="ti ti-plug-connected"></i></span><div><b>Дополнительные способы входа устанавливаются модулями</b><p>Яндекс, VK ID и SMSC настраиваются отдельно в разделе «Модули». Удаление пакета физически убирает его код и форму настроек.</p></div><a class="btn btn-secondary" href="{{ ADMINX_BASE }}/modules"><i class="ti ti-puzzle"></i>Открыть модули</a></div>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<div class="section-header ax-panel-header customers-pages-head"><div class="section-icon"><i class="ti ti-browser"></i></div><div><div class="section-eyebrow">Публичный сайт</div><h2>Страницы личного кабинета</h2><p class="section-desc">Каждая страница имеет редактируемый Twig-шаблон и выводится через `[tag:maincontent]` внутри выбранного шаблона сайта.</p></div>{% if can_manage %}<div class="section-header-right"><button class="btn btn-primary" type="submit" form="customerPagesForm"><i class="ti ti-device-floppy"></i>Сохранить</button></div>{% endif %}</div>
|
||||
|
||||
<div class="alert alert-info customers-auth-note"><span class="icon-tile" style="--tile-bg:var(--cyan-100);--tile-fg:var(--cyan-600)"><i class="ti ti-route"></i></span><div><b>Старые адреса продолжат работать</b><p>После смены URL системные `/login`, `/register`, `/remember`, `/password/reset` и `/personal` останутся совместимыми алиасами. Новые ссылки в интерфейсе и письмах сразу начнут использовать заданные адреса.</p></div></div>
|
||||
@@ -165,7 +165,7 @@
|
||||
</section>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<section class="card customers-auth-section customers-service-routes"><div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--gray-100);--tile-fg:var(--gray-700)"><i class="ti ti-code"></i></span><div><h2>Служебные маршруты</h2><p class="text-secondary">Подтверждение email, выход и общий шаблон системных результатов.</p></div></div>{% if can_manage %}<div class="customers-service-actions"><button class="btn btn-secondary btn-sm" type="button" data-auth-form-edit="message"><i class="ti ti-message-circle-check"></i>Сообщения</button></div>{% endif %}</div><div class="customers-auth-restrictions"><label class="field"><span class="field-label">Подтверждение email</span><span class="input-wrap"><i class="ti ti-link"></i><input class="input mono" name="pages[verify][path]" value="{{ auth_settings.pages.verify.path }}" required></span><input type="hidden" name="pages[verify][title]" value=""><input type="hidden" name="pages[verify][description]" value=""><input type="hidden" name="pages[verify][submit_label]" value=""><input type="hidden" name="pages[verify][template_id]" value="1"></label><label class="field"><span class="field-label">Выход</span><span class="input-wrap"><i class="ti ti-link"></i><input class="input mono" name="pages[logout][path]" value="{{ auth_settings.pages.logout.path }}" required></span><input type="hidden" name="pages[logout][title]" value=""><input type="hidden" name="pages[logout][description]" value=""><input type="hidden" name="pages[logout][submit_label]" value=""><input type="hidden" name="pages[logout][template_id]" value="1"></label></div></section>
|
||||
<section class="card customers-auth-section customers-service-routes"><div class="ax-list-head"><div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--gray-100);--tile-fg:var(--gray-700)"><i class="ti ti-code"></i></span><div><h2>Служебные маршруты и фрагменты</h2><p class="text-secondary">Подтверждение, выход, панель пользователя и подключаемые способы входа.</p></div></div>{% if can_manage %}<div class="customers-service-actions">{% for key in ['panel','message','phone','oauth','oauth_connections'] %}{% set form_meta = auth_forms[key] %}<button class="btn btn-secondary btn-sm" type="button" data-auth-form-edit="{{ key }}"><i class="ti {{ form_meta.icon }}"></i>{{ form_meta.label }}</button>{% endfor %}</div>{% endif %}</div><div class="customers-auth-restrictions"><label class="field"><span class="field-label">Подтверждение email</span><span class="input-wrap"><i class="ti ti-link"></i><input class="input mono" name="pages[verify][path]" value="{{ auth_settings.pages.verify.path }}" required></span><input type="hidden" name="pages[verify][title]" value=""><input type="hidden" name="pages[verify][description]" value=""><input type="hidden" name="pages[verify][submit_label]" value=""><input type="hidden" name="pages[verify][template_id]" value="1"></label><label class="field"><span class="field-label">Выход</span><span class="input-wrap"><i class="ti ti-link"></i><input class="input mono" name="pages[logout][path]" value="{{ auth_settings.pages.logout.path }}" required></span><input type="hidden" name="pages[logout][title]" value=""><input type="hidden" name="pages[logout][description]" value=""><input type="hidden" name="pages[logout][submit_label]" value=""><input type="hidden" name="pages[logout][template_id]" value="1"></label></div></section>
|
||||
{% if can_manage %}<div class="customers-auth-actions"><button class="btn btn-primary" type="submit"><i class="ti ti-device-floppy"></i>Сохранить страницы</button></div>{% endif %}
|
||||
</form>
|
||||
{% endif %}
|
||||
@@ -173,27 +173,27 @@
|
||||
{% if can_manage %}
|
||||
<aside class="drawer drawer-right customer-editor-drawer" id="customerEditorDrawer" role="dialog" aria-modal="true" aria-labelledby="customerEditorTitle" hidden>
|
||||
<div class="drawer-header"><div><h3 id="customerEditorTitle" data-customer-editor-title>Пользователь сайта</h3><p>Профиль, доступ и данные личного кабинета</p></div><button class="btn btn-icon btn-ghost" type="button" data-close-drawer aria-label="Закрыть"><i class="ti ti-x"></i></button></div>
|
||||
<form data-customer-editor data-base="{{ ADMINX_BASE }}">
|
||||
<form data-customer-editor data-base="{{ ADMINX_BASE }}" data-can-manage-admin-access="{{ can_manage_admin_access ? '1' : '0' }}">
|
||||
<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><input class="input" name="firstname" maxlength="50"></label><label class="field col-6"><span class="field-label">Фамилия</span><input class="input" name="lastname" maxlength="50"></label><label class="field col-6"><span class="field-label">Email</span><input class="input" type="email" name="email" maxlength="100" required></label><label class="field col-6"><span class="field-label">Логин</span><input class="input mono" name="user_name" maxlength="50" required><span class="field-hint">Можно использовать для входа наравне с email.</span></label><label class="field col-6"><span class="field-label">Телефон</span><input class="input" type="tel" name="phone" maxlength="50"></label><label class="field col-6"><span class="field-label">Компания</span><input class="input" name="company" maxlength="255"></label><label class="field col-4"><span class="field-label">Дата рождения</span><input class="input" type="date" name="birthday"></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><input class="input" name="city"></label><label class="field col-4"><span class="field-label">Улица</span><input class="input" name="street"></label><label class="field col-2"><span class="field-label">Дом</span><input class="input" name="street_nr"></label><label class="field col-2"><span class="field-label">Индекс</span><input class="input" name="zipcode"></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>
|
||||
<div class="form-grid">
|
||||
<label class="field col-6"><span class="field-label">Группа публичных пользователей</span><select class="select" name="user_group" required>{% for group in customer_groups %}<option value="{{ group.id }}">#{{ group.id }} · {{ group.name }} · {{ group.permissions_count }} разрешений</option>{% endfor %}</select></label>
|
||||
<label class="field col-6" data-customer-admin-role><span class="field-label">Роль в панели управления</span><select class="select" name="admin_role"{{ can_manage_admin_access ? '' : ' disabled' }}>{% for code, label in admin_roles %}<option value="{{ code }}">{{ label }}</option>{% endfor %}</select><span class="field-hint">Права роли настраиваются в разделе «Роли и права».</span></label>
|
||||
<label class="field col-6"><span class="field-label">Группа публичных пользователей</span><select class="select" name="user_group" required>{% for group in customer_groups %}<option value="{{ group.id }}">#{{ group.id }} · {{ group.name }} · {{ group.permissions_count }} разрешений</option>{% endfor %}</select><span class="field-hint" data-customer-group-hint>Определяет права пользователя на публичной части сайта.</span></label>
|
||||
<label class="field col-6" data-customer-admin-role><span class="field-label">Роль в панели управления</span><select class="select" name="admin_role"{{ can_manage_admin_access ? '' : ' disabled' }}>{% for code, label in admin_roles %}<option value="{{ code }}">{{ label }}</option>{% endfor %}</select><span class="field-hint" data-customer-admin-role-hint>Права роли настраиваются в разделе «Роли и права».</span></label>
|
||||
</div>
|
||||
<div class="customers-switch-grid customers-editor-access">
|
||||
<label class="customers-switch-card"><span><b>Аккаунт включён</b><small>Может входить на сайт и в личный кабинет.</small></span><span class="switch"><input type="checkbox" name="status" value="1"><span></span></span></label>
|
||||
<label class="customers-switch-card"><span><b>Доступ в панель управления</b><small>{{ 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" 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><input class="input" type="password" name="password" autocomplete="new-password" placeholder="Оставьте пустым, чтобы не менять"><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 %}
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
@@ -25,11 +28,67 @@
|
||||
*/
|
||||
class Backup
|
||||
{
|
||||
/** Ключ настройки «сколько копий хранить»; 0 — хранить все. */
|
||||
const KEEP_SETTING = 'database_backup_keep';
|
||||
const KEEP_DEFAULT = 10;
|
||||
const KEEP_MAX = 200;
|
||||
|
||||
public static function dir()
|
||||
{
|
||||
return BASEPATH . DS . 'tmp' . DS . 'backup';
|
||||
}
|
||||
|
||||
public static function keep()
|
||||
{
|
||||
$value = Settings::get(self::KEEP_SETTING);
|
||||
if ($value === null || $value === '') { return self::KEEP_DEFAULT; }
|
||||
return max(0, min(self::KEEP_MAX, (int) $value));
|
||||
}
|
||||
|
||||
public static function setKeep($value)
|
||||
{
|
||||
$value = max(0, min(self::KEEP_MAX, (int) $value));
|
||||
Settings::set(self::KEEP_SETTING, $value, 'integer');
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Оставляет только последние $keep копий, созданных системой.
|
||||
*
|
||||
* Загруженные вручную и чужие файлы не трогаются: их имя не проходит
|
||||
* isManagedName(), и админ мог положить их сюда намеренно. Страховочные
|
||||
* копии перед восстановлением тоже участвуют в ротации — иначе каждое
|
||||
* восстановление оставляло бы вечный файл.
|
||||
*/
|
||||
public static function prune($keep = null)
|
||||
{
|
||||
$keep = $keep === null ? self::keep() : $keep;
|
||||
$names = array();
|
||||
foreach (self::prunable(self::all(), $keep) as $name) {
|
||||
$path = self::path($name);
|
||||
if ($path !== null && @unlink($path)) { $names[] = $name; }
|
||||
}
|
||||
|
||||
return array('deleted' => count($names), 'names' => $names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Отбирает имена лишних копий: чистая функция, файлы не трогает.
|
||||
* Список приходит из all() и уже отсортирован «новые сверху».
|
||||
*/
|
||||
public static function prunable(array $items, $keep)
|
||||
{
|
||||
$keep = max(0, min(self::KEEP_MAX, (int) $keep));
|
||||
if ($keep < 1) { return array(); }
|
||||
|
||||
$managed = array();
|
||||
foreach ($items as $item) {
|
||||
if (!empty($item['own'])) { $managed[] = (string) $item['name']; }
|
||||
}
|
||||
|
||||
return count($managed) <= $keep ? array() : array_slice($managed, $keep);
|
||||
}
|
||||
|
||||
/** Список файлов резервных копий (name/size/mtime), новые сверху. */
|
||||
public static function all()
|
||||
{
|
||||
@@ -172,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(
|
||||
@@ -197,12 +258,27 @@
|
||||
flock($lock, LOCK_UN);
|
||||
fclose($lock);
|
||||
throw $e;
|
||||
} finally {
|
||||
if ($driver !== null) {
|
||||
$driver->getMysqli()->rollback();
|
||||
$driver->close();
|
||||
}
|
||||
}
|
||||
|
||||
flock($lock, LOCK_UN);
|
||||
fclose($lock);
|
||||
|
||||
return array('name' => $name, 'size' => filesize($path), 'tables' => count($tables), 'prefixes' => $prefixes);
|
||||
//-- Ротация только после успешного переименования: сначала новая
|
||||
//-- копия на диске, и лишь потом удаляются лишние старые.
|
||||
$pruned = self::prune();
|
||||
|
||||
return array(
|
||||
'name' => $name,
|
||||
'size' => filesize($path),
|
||||
'tables' => count($tables),
|
||||
'prefixes' => $prefixes,
|
||||
'pruned' => (int) $pruned['deleted'],
|
||||
);
|
||||
}
|
||||
|
||||
/** Новые имена AVE.cms и старые adminx-дампы поддерживаются одинаково. */
|
||||
@@ -217,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) {
|
||||
@@ -251,28 +325,50 @@
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
$ddl = preg_replace_callback('/\bCONSTRAINT\s+`([^`]+)`/i', function ($match) {
|
||||
return 'CONSTRAINT `{{prefix}}_fk_' . substr(hash('sha256', (string) $match[1]), 0, 16) . '`';
|
||||
}, (string) $ddl);
|
||||
|
||||
$ddl = preg_replace_callback('/`([^`]+)`/', function ($match) {
|
||||
return '`' . Model::portableTableName($match[1]) . '`';
|
||||
}, (string) $ddl);
|
||||
}, $ddl);
|
||||
|
||||
//-- MariaDB выводит DEFAULT NULL у TEXT/BLOB, тогда как MySQL 5.7
|
||||
//-- запрещает default для этих типов. NULL и без clause остаётся default.
|
||||
|
||||
@@ -42,6 +42,8 @@
|
||||
'tables' => Model::tables(),
|
||||
'stats' => Model::stats(),
|
||||
'backups' => Backup::all(),
|
||||
'backup_keep' => Backup::keep(),
|
||||
'backup_keep_max' => Backup::KEEP_MAX,
|
||||
'schema' => ModuleManager::coreSchemaStatus(),
|
||||
'can_manage' => Permission::check('manage_database'),
|
||||
]);
|
||||
@@ -94,11 +96,29 @@
|
||||
return $this->error('Не удалось создать бэкап: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
|
||||
return $this->success('Бэкап создан: ' . $info['name'] . ' (' . $info['tables'] . ' таблиц)', [
|
||||
$message = 'Бэкап создан: ' . $info['name'] . ' (' . $info['tables'] . ' таблиц)';
|
||||
if (!empty($info['pruned'])) {
|
||||
$message .= '. Удалено старых копий: ' . (int) $info['pruned'];
|
||||
}
|
||||
|
||||
return $this->success($message, [
|
||||
'redirect' => $this->base() . '/database?tab=backups',
|
||||
]);
|
||||
}
|
||||
|
||||
/** POST /database/backup/keep — сколько копий хранить. */
|
||||
public function backupKeep(array $params = array())
|
||||
{
|
||||
if (($resp = $this->guard()) !== null) { return $resp; }
|
||||
$keep = Backup::setKeep(Request::postInt('keep', Backup::KEEP_DEFAULT));
|
||||
$pruned = Backup::prune();
|
||||
$message = $keep > 0
|
||||
? 'Хранить последних копий: ' . $keep
|
||||
: 'Ротация выключена, копии не удаляются';
|
||||
if ($pruned['deleted'] > 0) { $message .= '. Удалено сейчас: ' . (int) $pruned['deleted']; }
|
||||
return $this->success($message, array('redirect' => $this->base() . '/database?tab=backups'));
|
||||
}
|
||||
|
||||
/** POST /database/backup/upload — загрузить и проверить внешний файл дампа. */
|
||||
public function backupUpload(array $params = array())
|
||||
{
|
||||
|
||||
@@ -96,7 +96,7 @@
|
||||
throw new \RuntimeException('SQL-дамп оборван или содержит незавершённую команду');
|
||||
}
|
||||
|
||||
if ($meta['format'] !== 'adminx full dump') {
|
||||
if ($meta['format'] !== 'ave.cms full dump') {
|
||||
throw new \RuntimeException('Файл не является полным дампом AVE.cms');
|
||||
}
|
||||
|
||||
@@ -309,8 +309,9 @@
|
||||
protected static function readMetadata($line, array &$meta)
|
||||
{
|
||||
$value = trim(substr(ltrim((string) $line), 2));
|
||||
if (strcasecmp($value, 'adminx full dump') === 0) {
|
||||
$meta['format'] = 'adminx full dump';
|
||||
if (strcasecmp($value, 'AVE.cms full dump') === 0
|
||||
|| strcasecmp($value, 'adminx full dump') === 0) {
|
||||
$meta['format'] = 'ave.cms full dump';
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -314,3 +314,31 @@
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
/* --- Ротация резервных копий ------------------------------------------ */
|
||||
.database-backup-keep {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
flex-wrap: wrap;
|
||||
padding: 14px 16px;
|
||||
}
|
||||
.database-backup-keep-text {
|
||||
flex: 1 1 260px;
|
||||
min-width: 0;
|
||||
}
|
||||
.database-backup-keep-text p {
|
||||
margin: 4px 0 0;
|
||||
}
|
||||
.database-backup-keep-field {
|
||||
flex: 0 0 auto;
|
||||
width: 150px;
|
||||
margin: 0;
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
.database-backup-keep {
|
||||
align-items: stretch;
|
||||
}
|
||||
.database-backup-keep-field {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +42,14 @@
|
||||
if (e.target.closest('[data-db-restore-close]')) { self.closeRestoreProgress(); return; }
|
||||
});
|
||||
|
||||
var keepForm = document.querySelector('[data-db-backup-keep-form]');
|
||||
if (keepForm) {
|
||||
keepForm.addEventListener('submit', function (e) {
|
||||
e.preventDefault();
|
||||
self.saveBackupKeep(keepForm);
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('input', function (e) {
|
||||
var filter = e.target.closest('[data-db-table-filter]');
|
||||
if (filter) { self.filterTables(filter.value); }
|
||||
@@ -340,6 +348,15 @@
|
||||
});
|
||||
},
|
||||
|
||||
saveBackupKeep: function (form) {
|
||||
if (!form.reportValidity()) { return; }
|
||||
this.post(this.base() + '/database/backup/keep', new FormData(form)).then(function (d) {
|
||||
if (d.success === false) { Adminx.Toast.show(d.message || 'Ошибка', 'error'); return; }
|
||||
Adminx.Toast.show(d.message || 'Сохранено', 'success');
|
||||
if (d.redirect) { window.location.href = d.redirect; } else { window.location.reload(); }
|
||||
});
|
||||
},
|
||||
|
||||
backup: function () {
|
||||
var self = this;
|
||||
Adminx.Confirm.open({
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
return [
|
||||
'code' => 'database',
|
||||
'name' => 'База данных',
|
||||
'version' => '0.1.5',
|
||||
'version' => '0.2.3',
|
||||
|
||||
'permissions' => [
|
||||
'key' => 'database',
|
||||
@@ -79,6 +79,7 @@
|
||||
array('GET', '/database', array(\App\Adminx\Database\Controller::class, 'index')),
|
||||
array('POST', '/database/maintenance', array(\App\Adminx\Database\Controller::class, 'maintenance')),
|
||||
array('POST', '/database/backup', array(\App\Adminx\Database\Controller::class, 'backupCreate')),
|
||||
array('POST', '/database/backup/keep', array(\App\Adminx\Database\Controller::class, 'backupKeep'), array('permission' => 'manage_database')),
|
||||
array('POST', '/database/backup/upload', array(\App\Adminx\Database\Controller::class, 'backupUpload'), array('permission' => 'manage_database')),
|
||||
array('GET', '/database/backup/download', array(\App\Adminx\Database\Controller::class, 'backupDownload')),
|
||||
array('POST', '/database/backup/delete', array(\App\Adminx\Database\Controller::class, 'backupDelete')),
|
||||
|
||||
@@ -123,6 +123,22 @@
|
||||
<div><b>Восстановление полностью заменяет данные текущей схемы</b><p>Перед запуском AVE.cms автоматически создаст страховочную копию. Не закрывайте страницу до завершения операции.</p></div>
|
||||
</div>
|
||||
|
||||
{% if can_manage %}
|
||||
<form class="card database-backup-keep" data-db-backup-keep-form>
|
||||
<input type="hidden" name="_csrf" value="{{ csrf_token }}">
|
||||
<span class="icon-tile" style="--tile-bg:var(--violet-100);--tile-fg:var(--violet-600)"><i class="ti ti-history-toggle"></i></span>
|
||||
<div class="database-backup-keep-text">
|
||||
<b>Сколько копий хранить</b>
|
||||
<p class="text-secondary text-sm">После создания новой копии лишние старые удаляются. Загруженные вручную файлы не трогаются. Ноль отключает ротацию.</p>
|
||||
</div>
|
||||
<label class="field database-backup-keep-field">
|
||||
<span class="field-label">Хранить последних</span>
|
||||
<input class="input" type="number" name="keep" min="0" max="{{ backup_keep_max }}" value="{{ backup_keep }}">
|
||||
</label>
|
||||
<button class="btn btn-secondary" type="submit"><i class="ti ti-device-floppy"></i>Применить</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
<div class="card ax-list-card database-backups-card">
|
||||
<div class="ax-list-head">
|
||||
<div class="ax-list-title"><span class="icon-tile" style="--tile-bg:var(--amber-100);--tile-fg:var(--amber-600)"><i class="ti ti-archive"></i></span><div><h2>Файлы резервных копий</h2><p class="text-secondary">Собственные и загруженные SQL-дампы базы данных.</p></div></div>
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="directories_delete_confirm">Delete directory?</phrase>
|
||||
<phrase data="directories_delete_value_confirm">Delete value?</phrase>
|
||||
<phrase data="directories_edit">Directory settings</phrase>
|
||||
<phrase data="directories_edit_value">Edit value</phrase>
|
||||
<phrase data="directories_in_use">Directory is in use</phrase>
|
||||
<phrase data="directories_new">New directory</phrase>
|
||||
<phrase data="directories_new_value">New value</phrase>
|
||||
<phrase data="directories_request_failed">Request failed</phrase>
|
||||
<phrase data="directories_save_failed">Failed to save data</phrase>
|
||||
</language>
|
||||
@@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="directories_title">Directories</phrase>
|
||||
<phrase data="directories_description">Shared value lists that can be connected to multiple fields.</phrase>
|
||||
<phrase data="directories_create">Create directory</phrase>
|
||||
<phrase data="directories_shared">Shared directories</phrase>
|
||||
<phrase data="directories_shared_description">Connect one list to multiple fields and maintain it centrally.</phrase>
|
||||
<phrase data="directories_list">Directory list</phrase>
|
||||
<phrase data="directories_storage_help">The key is stored in the document; the label can change without rewriting documents.</phrase>
|
||||
<phrase data="directories_empty">No directories yet</phrase>
|
||||
<phrase data="directories_empty_help">Create a shared value list for fields.</phrase>
|
||||
<phrase data="directories_values_empty">No values yet</phrase>
|
||||
<phrase data="directories_values_empty_help">Add the first key and label pair.</phrase>
|
||||
<phrase data="directories_new">New directory</phrase>
|
||||
<phrase data="directories_new_value">New value</phrase>
|
||||
<phrase data="directories_source_help">Shared value source for fields.</phrase>
|
||||
<phrase data="directories_stable_code_help">Stable technical code. It is generated from the name when left empty.</phrase>
|
||||
<phrase data="directories_stable_key">Stable key</phrase>
|
||||
<phrase data="directories_key_help">Stored in the document. Avoid changing the key after it is in use.</phrase>
|
||||
<phrase data="directories_label_help">Editors and site visitors will see this label.</phrase>
|
||||
<phrase data="directories_available">Available for field selection</phrase>
|
||||
<phrase data="directories_show">Show in fields</phrase>
|
||||
<phrase data="directories_open_values">Open values</phrase>
|
||||
<phrase data="directories_add_value">Add value</phrase>
|
||||
<phrase data="directories_edit">Directory settings</phrase>
|
||||
<phrase data="directories_in_use">Directory is in use</phrase>
|
||||
<phrase data="directories_delete_confirm">Delete directory?</phrase>
|
||||
<phrase data="directories_edit_value">Edit value</phrase>
|
||||
<phrase data="directories_delete_value_confirm">Delete value?</phrase>
|
||||
<phrase data="directories_save_failed">Failed to save data</phrase>
|
||||
<phrase data="directories_request_failed">Request failed</phrase>
|
||||
</language>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="directories_delete_confirm">Удалить справочник?</phrase>
|
||||
<phrase data="directories_delete_value_confirm">Удалить значение?</phrase>
|
||||
<phrase data="directories_edit">Настройки справочника</phrase>
|
||||
<phrase data="directories_edit_value">Изменить значение</phrase>
|
||||
<phrase data="directories_in_use">Справочник используется</phrase>
|
||||
<phrase data="directories_new">Новый справочник</phrase>
|
||||
<phrase data="directories_new_value">Новое значение</phrase>
|
||||
<phrase data="directories_request_failed">Ошибка запроса</phrase>
|
||||
<phrase data="directories_save_failed">Не удалось сохранить данные</phrase>
|
||||
</language>
|
||||
@@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<language>
|
||||
<phrase data="directories_title">Справочники</phrase>
|
||||
<phrase data="directories_description">Общие списки значений, которые можно подключать к нескольким полям.</phrase>
|
||||
<phrase data="directories_create">Создать справочник</phrase>
|
||||
<phrase data="directories_shared">Общие справочники</phrase>
|
||||
<phrase data="directories_shared_description">Один список можно подключить к нескольким полям и менять централизованно.</phrase>
|
||||
<phrase data="directories_list">Список справочников</phrase>
|
||||
<phrase data="directories_storage_help">Ключ хранится в документе, подпись можно менять без перезаписи документов.</phrase>
|
||||
<phrase data="directories_empty">Справочников пока нет</phrase>
|
||||
<phrase data="directories_empty_help">Создайте общий список значений для полей.</phrase>
|
||||
<phrase data="directories_values_empty">Значений пока нет</phrase>
|
||||
<phrase data="directories_values_empty_help">Добавьте первую пару «ключ → подпись».</phrase>
|
||||
<phrase data="directories_new">Новый справочник</phrase>
|
||||
<phrase data="directories_new_value">Новое значение</phrase>
|
||||
<phrase data="directories_source_help">Общий источник значений для полей.</phrase>
|
||||
<phrase data="directories_stable_code_help">Стабильный технический код. Если оставить пустым, сформируется из названия.</phrase>
|
||||
<phrase data="directories_stable_key">Стабильный ключ</phrase>
|
||||
<phrase data="directories_key_help">Хранится в документе. После начала использования ключ лучше не менять.</phrase>
|
||||
<phrase data="directories_label_help">Эту подпись увидят редактор и посетитель сайта.</phrase>
|
||||
<phrase data="directories_available">Доступен для выбора в полях</phrase>
|
||||
<phrase data="directories_show">Показывать в полях</phrase>
|
||||
<phrase data="directories_open_values">Открыть значения</phrase>
|
||||
<phrase data="directories_add_value">Добавить значение</phrase>
|
||||
<phrase data="directories_edit">Настройки справочника</phrase>
|
||||
<phrase data="directories_in_use">Справочник используется</phrase>
|
||||
<phrase data="directories_delete_confirm">Удалить справочник?</phrase>
|
||||
<phrase data="directories_edit_value">Изменить значение</phrase>
|
||||
<phrase data="directories_delete_value_confirm">Удалить значение?</phrase>
|
||||
<phrase data="directories_save_failed">Не удалось сохранить данные</phrase>
|
||||
<phrase data="directories_request_failed">Ошибка запроса</phrase>
|
||||
</language>
|
||||
@@ -17,7 +17,7 @@
|
||||
return array(
|
||||
'code' => 'directories',
|
||||
'name' => 'Справочники',
|
||||
'version' => '0.2.0',
|
||||
'version' => '0.2.1',
|
||||
'requires' => array('rubrics'),
|
||||
|
||||
'routes' => array(
|
||||
|
||||
@@ -0,0 +1,733 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------------
|
||||
| AVE.cms
|
||||
|--------------------------------------------------------------------------------------
|
||||
| @package AVE.cms
|
||||
| @file adminx/modules/Documents/BulkEditor.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\Documents;
|
||||
|
||||
defined('BASEPATH') || die('Direct access to this location is not allowed.');
|
||||
|
||||
use App\Common\AuditLog;
|
||||
use App\Common\DatabaseSchema;
|
||||
use App\Common\Lock;
|
||||
use App\Content\CatalogTables;
|
||||
use App\Content\ContentTables;
|
||||
use App\Content\Documents\DocumentMutationService;
|
||||
use App\Content\Documents\DocumentSearch;
|
||||
use App\Helpers\File;
|
||||
use DB;
|
||||
|
||||
/**
|
||||
* Server-side plans for safe, previewable document batch mutations.
|
||||
*
|
||||
* A plan freezes matching IDs before execution. The browser only sends the
|
||||
* opaque token back and cannot replace the document list after preview.
|
||||
*/
|
||||
class BulkEditor
|
||||
{
|
||||
const VERSION = 2;
|
||||
const MAX_DOCUMENTS = 5000;
|
||||
const CHUNK_SIZE = 20;
|
||||
const EXPIRES_AFTER = 7200;
|
||||
|
||||
protected static $documentFields = array(
|
||||
'document_title' => array(
|
||||
'label' => 'Заголовок документа',
|
||||
'payload' => 'title',
|
||||
'help' => 'Основной заголовок документа в AVE.cms. У товара название на сайте может браться из отдельного поля рубрики.',
|
||||
),
|
||||
'document_excerpt' => array('label' => 'Тизер (анонс)', 'payload' => 'excerpt'),
|
||||
'document_tags' => array('label' => 'Теги', 'payload' => 'tags'),
|
||||
'document_meta_keywords' => array('label' => 'Meta keywords', 'payload' => 'meta_keywords'),
|
||||
'document_meta_description' => array('label' => 'Meta description', 'payload' => 'meta_description'),
|
||||
'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(),
|
||||
);
|
||||
}
|
||||
|
||||
public static function preview(array $input, $actorId)
|
||||
{
|
||||
$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('По выбранным условиям документы не найдены');
|
||||
}
|
||||
|
||||
if ($matches['total'] > self::MAX_DOCUMENTS) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Найдено ' . $matches['total'] . ' документов. Уточните фильтр: за один запуск можно обработать до ' . self::MAX_DOCUMENTS
|
||||
);
|
||||
}
|
||||
|
||||
$matchedTotal = (int) $matches['total'];
|
||||
$changingRows = self::changingRows($matches['rows'], $operation);
|
||||
if (!$changingRows) {
|
||||
throw new \InvalidArgumentException('В найденных документах нет значений, которые изменит выбранное действие');
|
||||
}
|
||||
|
||||
$sample = array();
|
||||
foreach (array_slice($changingRows, 0, 20) as $row) {
|
||||
$change = self::previewChange($row, $operation);
|
||||
$sample[] = array(
|
||||
'id' => (int) $row['Id'],
|
||||
'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' => $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' => \App\Common\Language::translateSource($change['note']),
|
||||
);
|
||||
}
|
||||
|
||||
$token = bin2hex(random_bytes(20));
|
||||
$plan = array(
|
||||
'version' => self::VERSION,
|
||||
'token' => $token,
|
||||
'actor_id' => (int) $actorId,
|
||||
'status' => 'prepared',
|
||||
'created_at' => time(),
|
||||
'expires_at' => time() + self::EXPIRES_AFTER,
|
||||
'filters' => $filters,
|
||||
'operation' => $operation,
|
||||
'ids' => array_values(array_map(function ($row) { return (int) $row['Id']; }, $changingRows)),
|
||||
'total' => count($changingRows),
|
||||
'matched_total' => $matchedTotal,
|
||||
'unchanged_total' => max(0, $matchedTotal - count($changingRows)),
|
||||
'cursor' => 0,
|
||||
'done' => 0,
|
||||
'skipped' => 0,
|
||||
'errors' => array(),
|
||||
'sample' => $sample,
|
||||
);
|
||||
self::save($plan);
|
||||
return self::publicPlan($plan);
|
||||
}
|
||||
|
||||
public static function runChunk($token, $actorId)
|
||||
{
|
||||
return Lock::run('document-bulk:' . (string) $token, function () use ($token, $actorId) {
|
||||
$plan = self::load($token, $actorId);
|
||||
if (in_array($plan['status'], array('completed', 'cancelled'), true)) {
|
||||
return self::publicPlan($plan);
|
||||
}
|
||||
|
||||
$plan['status'] = 'running';
|
||||
$service = new DocumentMutationService();
|
||||
$end = min((int) $plan['total'], (int) $plan['cursor'] + self::CHUNK_SIZE);
|
||||
while ((int) $plan['cursor'] < $end) {
|
||||
$id = (int) $plan['ids'][$plan['cursor']];
|
||||
try {
|
||||
$result = self::apply($service, $id, $plan['operation'], (int) $actorId);
|
||||
if ($result) { $plan['done']++; }
|
||||
else { $plan['skipped']++; }
|
||||
} catch (\Throwable $e) {
|
||||
$plan['errors'][] = '#' . $id . ': ' . $e->getMessage();
|
||||
if (count($plan['errors']) > 100) {
|
||||
$plan['errors'] = array_slice($plan['errors'], -100);
|
||||
}
|
||||
}
|
||||
|
||||
$plan['cursor']++;
|
||||
}
|
||||
|
||||
if ((int) $plan['cursor'] >= (int) $plan['total']) {
|
||||
$plan['status'] = 'completed';
|
||||
$plan['completed_at'] = time();
|
||||
AuditLog::record('document.bulk_editor_completed', array(
|
||||
'actor_id' => (int) $actorId,
|
||||
'target_type' => 'document_batch',
|
||||
'meta' => array(
|
||||
'operation' => $plan['operation'],
|
||||
'filters' => $plan['filters'],
|
||||
'total' => $plan['total'],
|
||||
'done' => $plan['done'],
|
||||
'skipped' => $plan['skipped'],
|
||||
'errors' => count($plan['errors']),
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
self::save($plan);
|
||||
return self::publicPlan($plan);
|
||||
}, 5.0, true);
|
||||
}
|
||||
|
||||
public static function cancel($token, $actorId)
|
||||
{
|
||||
return Lock::run('document-bulk:' . (string) $token, function () use ($token, $actorId) {
|
||||
$plan = self::load($token, $actorId);
|
||||
if ($plan['status'] !== 'completed') {
|
||||
$plan['status'] = 'cancelled';
|
||||
$plan['cancelled_at'] = time();
|
||||
self::save($plan);
|
||||
}
|
||||
|
||||
return self::publicPlan($plan);
|
||||
}, 5.0, true);
|
||||
}
|
||||
|
||||
public static function status($token, $actorId)
|
||||
{
|
||||
return self::publicPlan(self::load($token, $actorId));
|
||||
}
|
||||
|
||||
protected static function apply(DocumentMutationService $service, $documentId, array $operation, $actorId)
|
||||
{
|
||||
$row = DB::query(
|
||||
"SELECT * FROM " . ContentTables::table('documents') . " WHERE Id=%i AND document_deleted='0' LIMIT 1",
|
||||
(int) $documentId
|
||||
)->getAssoc();
|
||||
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;
|
||||
if ((int) $row['document_status'] === $status) { return false; }
|
||||
$service->save($documentId, array('status' => $status), $actorId, 'bulk_editor');
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($type === 'recalculate') {
|
||||
$service->save($documentId, array('fields' => array()), $actorId, 'bulk_editor');
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($type === 'move') {
|
||||
if (Model::isProtectedDocument($documentId)) { return false; }
|
||||
$result = $service->move($documentId, $operation['target_rubric_id'], $actorId, 'bulk_editor');
|
||||
return !empty($result['moved']);
|
||||
}
|
||||
|
||||
$current = self::currentValue($row, $operation);
|
||||
$next = self::changedValue($current, $operation);
|
||||
if (!$next['changed']) { return false; }
|
||||
if ($operation['target_type'] === 'document') {
|
||||
$payloadKey = self::$documentFields[$operation['target']]['payload'];
|
||||
$service->save($documentId, array($payloadKey => $next['value']), $actorId, 'bulk_editor');
|
||||
} else {
|
||||
$service->save($documentId, array('fields' => array($operation['field_id'] => $next['value'])), $actorId, 'bulk_editor');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected static function filters(array $input)
|
||||
{
|
||||
$scope = isset($input['scope']) ? (string) $input['scope'] : 'all';
|
||||
if (!in_array($scope, array('all', 'documents', 'products'), true) || ($scope !== 'all' && !self::productsAvailable())) {
|
||||
$scope = 'all';
|
||||
}
|
||||
|
||||
$state = isset($input['state']) ? (string) $input['state'] : '';
|
||||
if (!in_array($state, array('', 'active', 'draft'), true)) { $state = ''; }
|
||||
return array(
|
||||
'q' => trim(isset($input['q']) ? (string) $input['q'] : ''),
|
||||
'rubric_id' => max(0, isset($input['rubric_id']) ? (int) $input['rubric_id'] : 0),
|
||||
'state' => $state,
|
||||
'scope' => $scope,
|
||||
);
|
||||
}
|
||||
|
||||
protected static function operation(array $input, array $filters)
|
||||
{
|
||||
$type = isset($input['operation']) ? (string) $input['operation'] : '';
|
||||
$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;
|
||||
if ($targetRubricId <= 0 || !Model::rubric($targetRubricId)) {
|
||||
throw new \InvalidArgumentException('Выберите целевую рубрику');
|
||||
}
|
||||
|
||||
if ($filters['rubric_id'] > 0 && $targetRubricId === $filters['rubric_id']) {
|
||||
throw new \InvalidArgumentException('Исходная и целевая рубрики совпадают');
|
||||
}
|
||||
|
||||
$operation['target_rubric_id'] = $targetRubricId;
|
||||
$operation['target_rubric_title'] = Model::rubric($targetRubricId)['rubric_title'];
|
||||
}
|
||||
|
||||
return $operation;
|
||||
}
|
||||
|
||||
$target = isset($input['target']) ? trim((string) $input['target']) : '';
|
||||
if (isset(self::$documentFields[$target])) {
|
||||
$operation['target_type'] = 'document';
|
||||
$operation['target'] = $target;
|
||||
$operation['target_label'] = self::$documentFields[$target]['label'];
|
||||
} elseif (strpos($target, 'field:') === 0) {
|
||||
$fieldId = (int) substr($target, 6);
|
||||
if ($filters['rubric_id'] <= 0) {
|
||||
throw new \InvalidArgumentException('Для изменения поля сначала выберите одну рубрику');
|
||||
}
|
||||
|
||||
$field = self::field($fieldId, $filters['rubric_id']);
|
||||
if (!$field) { throw new \InvalidArgumentException('Поле не принадлежит выбранной рубрике'); }
|
||||
$operation['target_type'] = 'field';
|
||||
$operation['target'] = $target;
|
||||
$operation['field_id'] = $fieldId;
|
||||
$operation['target_label'] = html_entity_decode((string) $field['rubric_field_title'], ENT_QUOTES, 'UTF-8');
|
||||
} else {
|
||||
throw new \InvalidArgumentException('Выберите поле для изменения');
|
||||
}
|
||||
|
||||
$operation['value'] = isset($input['value']) ? (string) $input['value'] : '';
|
||||
$operation['search'] = isset($input['search']) ? (string) $input['search'] : '';
|
||||
if ($type === 'replace' && $operation['search'] === '') {
|
||||
throw new \InvalidArgumentException('Укажите текст, который нужно заменить');
|
||||
}
|
||||
|
||||
return $operation;
|
||||
}
|
||||
|
||||
protected static function matches(array $filters)
|
||||
{
|
||||
$where = " WHERE d.document_deleted='0'";
|
||||
$args = array();
|
||||
if ($filters['rubric_id'] > 0) {
|
||||
$where .= ' AND d.rubric_id=%i';
|
||||
$args[] = $filters['rubric_id'];
|
||||
}
|
||||
|
||||
if ($filters['state'] === 'active') { $where .= " AND d.document_status='1'"; }
|
||||
elseif ($filters['state'] === 'draft') { $where .= " AND d.document_status='0'"; }
|
||||
|
||||
$productTable = CatalogTables::table('catalog_product_index');
|
||||
if (self::productsAvailable() && $filters['scope'] === 'products') {
|
||||
$where .= ' AND EXISTS (SELECT 1 FROM ' . $productTable . ' bp WHERE bp.product_id=d.Id)';
|
||||
} elseif (self::productsAvailable() && $filters['scope'] === 'documents') {
|
||||
$where .= ' AND NOT EXISTS (SELECT 1 FROM ' . $productTable . ' bp WHERE bp.product_id=d.Id)';
|
||||
}
|
||||
|
||||
$search = DocumentSearch::criteria($filters['q'], 'd');
|
||||
if ($search['where'] !== '') {
|
||||
$where .= ' AND ' . $search['where'];
|
||||
$args = array_merge($args, $search['where_args']);
|
||||
}
|
||||
|
||||
$sql = 'SELECT d.Id,d.document_title,d.document_status,d.rubric_id,r.rubric_title'
|
||||
. ' FROM ' . ContentTables::table('documents') . ' d'
|
||||
. ' LEFT JOIN ' . ContentTables::table('rubrics') . ' r ON r.Id=d.rubric_id'
|
||||
. $where . ' ORDER BY d.Id ASC LIMIT ' . (self::MAX_DOCUMENTS + 1);
|
||||
$rows = call_user_func_array(array('DB', 'query'), array_merge(array($sql), $args))->getAll() ?: array();
|
||||
$ids = array();
|
||||
foreach ($rows as $row) { $ids[] = (int) $row['Id']; }
|
||||
return array('ids' => $ids, 'rows' => $rows, 'total' => count($rows));
|
||||
}
|
||||
|
||||
protected static function changingRows(array $rows, array $operation)
|
||||
{
|
||||
if (!$rows || $operation['type'] === 'recalculate') { return $rows; }
|
||||
|
||||
$currentValues = array();
|
||||
$ids = array();
|
||||
foreach ($rows as $row) { $ids[] = (int) $row['Id']; }
|
||||
if (isset($operation['target_type']) && in_array($operation['target_type'], array('document', 'state'), true)) {
|
||||
$column = (string) $operation['target'];
|
||||
if ($operation['target_type'] === 'document' && !isset(self::$documentFields[$column])) {
|
||||
throw new \InvalidArgumentException('Поле документа недоступно для массового изменения');
|
||||
}
|
||||
|
||||
$valueRows = DB::query(
|
||||
'SELECT Id,`' . $column . '` current_value FROM ' . ContentTables::table('documents') . ' WHERE Id IN %li',
|
||||
$ids
|
||||
)->getAll();
|
||||
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'
|
||||
. ' FROM ' . ContentTables::table('document_fields') . ' df'
|
||||
. ' LEFT JOIN ' . ContentTables::table('document_fields_text') . ' dft'
|
||||
. ' ON dft.document_id=df.document_id AND dft.rubric_field_id=df.rubric_field_id'
|
||||
. ' WHERE df.document_id IN %li AND df.rubric_field_id=%i',
|
||||
$ids,
|
||||
(int) $operation['field_id']
|
||||
)->getAll();
|
||||
foreach ($valueRows ?: array() as $valueRow) {
|
||||
$currentValues[(int) $valueRow['document_id']] = (string) $valueRow['current_value'];
|
||||
}
|
||||
}
|
||||
|
||||
$changing = array();
|
||||
foreach ($rows as $row) {
|
||||
if (isset($operation['target_type'])) {
|
||||
$row['__bulk_current'] = isset($currentValues[(int) $row['Id']])
|
||||
? $currentValues[(int) $row['Id']]
|
||||
: '';
|
||||
}
|
||||
|
||||
if (self::previewChange($row, $operation)['changed']) { $changing[] = $row; }
|
||||
}
|
||||
|
||||
return $changing;
|
||||
}
|
||||
|
||||
protected static function previewChange(array $row, array $operation)
|
||||
{
|
||||
if ($operation['type'] === 'publish') {
|
||||
return array('before' => (int) $row['document_status'] ? 'Опубликован' : 'Черновик', 'after' => 'Опубликован', 'changed' => !(int) $row['document_status'], 'note' => '');
|
||||
}
|
||||
|
||||
if ($operation['type'] === 'unpublish') {
|
||||
return array('before' => (int) $row['document_status'] ? 'Опубликован' : 'Черновик', 'after' => 'Черновик', 'changed' => (bool) $row['document_status'], 'note' => '');
|
||||
}
|
||||
|
||||
if ($operation['type'] === 'recalculate') {
|
||||
return array('before' => 'Текущие значения', 'after' => 'Пересчитать поля и индексы', 'changed' => true, 'note' => '');
|
||||
}
|
||||
|
||||
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' => 'Переносятся только поля с одинаковыми системными именами и типами. Значения остальных полей не сохранятся в новой рубрике.');
|
||||
}
|
||||
|
||||
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' => isset($next['removed']) ? 'Удалится атрибутов style: ' . $next['removed'] : ($next['changed'] ? '' : 'Значение уже соответствует действию'));
|
||||
}
|
||||
|
||||
protected static function currentValue(array $row, array $operation)
|
||||
{
|
||||
if (array_key_exists('__bulk_current', $row)) {
|
||||
return (string) $row['__bulk_current'];
|
||||
}
|
||||
|
||||
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',
|
||||
(int) $row['Id']
|
||||
)->getValue();
|
||||
return html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
|
||||
return html_entity_decode((string) $row[$operation['target']], ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
|
||||
return (string) DB::query(
|
||||
'SELECT CONCAT(COALESCE(df.field_value,\'\'),COALESCE(dft.field_value,\'\'))'
|
||||
. ' FROM ' . ContentTables::table('document_fields') . ' df'
|
||||
. ' LEFT JOIN ' . ContentTables::table('document_fields_text') . ' dft'
|
||||
. ' ON dft.document_id=df.document_id AND dft.rubric_field_id=df.rubric_field_id'
|
||||
. ' WHERE df.document_id=%i AND df.rubric_field_id=%i LIMIT 1',
|
||||
(int) $row['Id'],
|
||||
(int) $operation['field_id']
|
||||
)->getValue();
|
||||
}
|
||||
|
||||
protected static function changedValue($current, array $operation)
|
||||
{
|
||||
$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') {
|
||||
$value = '';
|
||||
} elseif ($type === 'replace') {
|
||||
$value = str_replace((string) $operation['search'], (string) $operation['value'], $current);
|
||||
} else {
|
||||
$value = (string) $operation['value'];
|
||||
}
|
||||
|
||||
return array('value' => $value, 'changed' => $value !== $current);
|
||||
}
|
||||
|
||||
protected static function field($fieldId, $rubricId)
|
||||
{
|
||||
return DB::query(
|
||||
'SELECT Id,rubric_id,rubric_field_title,rubric_field_alias,rubric_field_type'
|
||||
. ' FROM ' . ContentTables::table('rubric_fields') . ' WHERE Id=%i AND rubric_id=%i LIMIT 1',
|
||||
(int) $fieldId,
|
||||
(int) $rubricId
|
||||
)->getAssoc() ?: null;
|
||||
}
|
||||
|
||||
public static function fields($rubricId)
|
||||
{
|
||||
$commerce = self::commerceFieldUsage((int) $rubricId);
|
||||
$rows = DB::query(
|
||||
'SELECT Id,rubric_field_title,rubric_field_alias,rubric_field_type'
|
||||
. ' FROM ' . ContentTables::table('rubric_fields')
|
||||
. ' WHERE rubric_id=%i ORDER BY rubric_field_position ASC,Id ASC',
|
||||
(int) $rubricId
|
||||
)->getAll();
|
||||
$out = array();
|
||||
foreach ($rows ?: array() as $row) {
|
||||
$fieldId = (int) $row['Id'];
|
||||
$usage = isset($commerce[$fieldId]) ? $commerce[$fieldId] : '';
|
||||
$out[] = array(
|
||||
'id' => $fieldId,
|
||||
'title' => html_entity_decode((string) $row['rubric_field_title'], ENT_QUOTES, 'UTF-8'),
|
||||
'alias' => (string) $row['rubric_field_alias'],
|
||||
'type' => (string) $row['rubric_field_type'],
|
||||
'usage' => $usage,
|
||||
'help' => $usage !== '' ? 'Это поле используется товарным представлением как ' . $usage . '. Изменение обновит витрину и товарный индекс.' : '',
|
||||
);
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
protected static function commerceFieldUsage($rubricId)
|
||||
{
|
||||
if ($rubricId <= 0 || !self::productsAvailable()) { return array(); }
|
||||
|
||||
$row = DB::query(
|
||||
'SELECT 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'
|
||||
. ' FROM ' . CatalogTables::table('module_catalog_settings')
|
||||
. " WHERE rubric_id=%i AND purpose='commerce' ORDER BY id ASC LIMIT 1",
|
||||
(int) $rubricId
|
||||
)->getAssoc();
|
||||
if (!$row) { return array(); }
|
||||
|
||||
$labels = 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' => 'изображения товара',
|
||||
);
|
||||
$usage = array();
|
||||
foreach ($labels as $column => $label) {
|
||||
$fieldId = isset($row[$column]) ? (int) $row[$column] : 0;
|
||||
if ($fieldId > 0) { $usage[$fieldId] = $label; }
|
||||
}
|
||||
|
||||
return $usage;
|
||||
}
|
||||
|
||||
protected static function productsAvailable()
|
||||
{
|
||||
try {
|
||||
return DatabaseSchema::tableExists(CatalogTables::table('catalog_product_index'));
|
||||
} catch (\Throwable $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
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' => 'Пересчитать поля и индексы',
|
||||
'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)));
|
||||
if ($value === '') { return 'Пусто'; }
|
||||
return mb_strlen($value, 'UTF-8') > 180 ? mb_substr($value, 0, 177, 'UTF-8') . '...' : $value;
|
||||
}
|
||||
|
||||
protected static function publicPlan(array $plan)
|
||||
{
|
||||
$total = max(1, (int) $plan['total']);
|
||||
return array(
|
||||
'token' => $plan['token'],
|
||||
'status' => $plan['status'],
|
||||
'total' => (int) $plan['total'],
|
||||
'matched_total' => isset($plan['matched_total']) ? (int) $plan['matched_total'] : (int) $plan['total'],
|
||||
'unchanged_total' => isset($plan['unchanged_total']) ? (int) $plan['unchanged_total'] : 0,
|
||||
'processed' => (int) $plan['cursor'],
|
||||
'done' => (int) $plan['done'],
|
||||
'skipped' => (int) $plan['skipped'],
|
||||
'errors' => $plan['errors'],
|
||||
'progress' => (int) floor(((int) $plan['cursor'] / $total) * 100),
|
||||
'operation' => $plan['operation'],
|
||||
'filters' => $plan['filters'],
|
||||
'sample' => $plan['sample'],
|
||||
);
|
||||
}
|
||||
|
||||
protected static function load($token, $actorId)
|
||||
{
|
||||
if (!preg_match('/^[a-f0-9]{40}$/', (string) $token)) {
|
||||
throw new \InvalidArgumentException('Некорректный идентификатор плана');
|
||||
}
|
||||
|
||||
$path = self::path($token);
|
||||
$data = is_file($path) ? json_decode((string) File::getContent($path), true) : null;
|
||||
if (!is_array($data) || (int) $data['version'] !== self::VERSION || !hash_equals((string) $data['token'], (string) $token)) {
|
||||
throw new \RuntimeException('План массового изменения не найден');
|
||||
}
|
||||
|
||||
if ((int) $data['actor_id'] !== (int) $actorId) {
|
||||
throw new \RuntimeException('План создан другим пользователем');
|
||||
}
|
||||
|
||||
if ((int) $data['expires_at'] < time() && !in_array($data['status'], array('completed', 'cancelled'), true)) {
|
||||
throw new \RuntimeException('Срок действия предпросмотра истёк. Выполните проверку ещё раз');
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
protected static function save(array $plan)
|
||||
{
|
||||
$directory = dirname(self::path($plan['token']));
|
||||
if (!is_dir($directory) && !@mkdir($directory, 0750, true) && !is_dir($directory)) {
|
||||
throw new \RuntimeException('Не удалось создать каталог заданий');
|
||||
}
|
||||
|
||||
$raw = json_encode($plan, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
|
||||
if (!File::putAtomic(self::path($plan['token']), $raw, 0640)) {
|
||||
throw new \RuntimeException('Не удалось сохранить план массового изменения');
|
||||
}
|
||||
}
|
||||
|
||||
protected static function path($token)
|
||||
{
|
||||
return rtrim(BASEPATH, '/\\') . '/storage/jobs/document-bulk/' . (string) $token . '.json';
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@
|
||||
use App\Common\ErrorReport;
|
||||
use App\Common\Permission;
|
||||
use App\Adminx\Support\CodeEditor;
|
||||
use App\Adminx\Support\SavedViews;
|
||||
use App\Adminx\Rubrics\AdminView;
|
||||
use App\Content\Documents\DocumentHookException;
|
||||
use App\Content\Documents\ContentCacheInvalidator;
|
||||
@@ -44,6 +45,9 @@
|
||||
|
||||
class Controller extends BaseController
|
||||
{
|
||||
protected function savedViewFields() { return array('q', 'field', 'rubric_id', 'state', 'per_page'); }
|
||||
protected function savedViewGuard() { if (($error = $this->csrfGuard()) !== null) { return $error; } return Permission::check('view_documents') ? null : $this->error('Недостаточно прав', array(), 403); }
|
||||
|
||||
public function index(array $params = array())
|
||||
{
|
||||
AdminAssets::addStyle($this->base() . '/modules/Documents/assets/documents.css', 50);
|
||||
@@ -84,9 +88,28 @@
|
||||
'table_name' => Model::documentsTable(),
|
||||
'can_manage' => Permission::check('manage_documents'),
|
||||
'open_create' => Request::getBool('create', false),
|
||||
'saved_views' => SavedViews::all('documents', Auth::id(), $this->savedViewFields()),
|
||||
));
|
||||
}
|
||||
|
||||
public function saveSavedView(array $params = array())
|
||||
{
|
||||
if (($error = $this->savedViewGuard()) !== null) { return $error; }
|
||||
$filters = json_decode(Request::postStr('filters', '{}'), true);
|
||||
if (!is_array($filters)) { return $this->error('Некорректный набор фильтров', array(), 422); }
|
||||
try { $views = SavedViews::save('documents', Auth::id(), Request::postStr('title', ''), $filters, $this->savedViewFields()); }
|
||||
catch (\InvalidArgumentException $e) { return $this->error($e->getMessage(), array(), 422); }
|
||||
return $this->success('Представление сохранено', array('data' => array('views' => $views)));
|
||||
}
|
||||
|
||||
public function deleteSavedView(array $params = array())
|
||||
{
|
||||
if (($error = $this->savedViewGuard()) !== null) { return $error; }
|
||||
try { $views = SavedViews::delete('documents', Auth::id(), isset($params['id']) ? $params['id'] : '', $this->savedViewFields()); }
|
||||
catch (\InvalidArgumentException $e) { return $this->error($e->getMessage(), array(), 404); }
|
||||
return $this->success('Представление удалено', array('data' => array('views' => $views)));
|
||||
}
|
||||
|
||||
public function create(array $params = array())
|
||||
{
|
||||
if (!Permission::check('manage_documents')) {
|
||||
@@ -190,7 +213,13 @@
|
||||
try {
|
||||
$scopes = Request::post('scopes', array());
|
||||
$scopes = is_array($scopes) ? $scopes : array();
|
||||
$result = ApiTokenRepository::issue(Auth::id(), Request::postStr('name', ''), $scopes, Request::postStr('expires_at', ''));
|
||||
$result = ApiTokenRepository::issueRestricted(
|
||||
Auth::id(),
|
||||
Request::postStr('name', ''),
|
||||
$scopes,
|
||||
array('documents:read', 'documents:write', 'documents:*'),
|
||||
Request::postStr('expires_at', '')
|
||||
);
|
||||
AuditLog::record('document.api_token_created', array('actor_id'=>Auth::id(),'target_type'=>'api_token','target_id'=>$result['id'],'meta'=>array('scopes'=>$result['scopes'])));
|
||||
return $this->success('API-токен создан', array('data' => $result));
|
||||
} catch (\Throwable $e) { return $this->error($e->getMessage(), array(), 422); }
|
||||
@@ -201,7 +230,10 @@
|
||||
if (($err = $this->csrfGuard()) !== null) { return $err; }
|
||||
if (!Permission::check('manage_document_api')) { return $this->error('Недостаточно прав', array(), 403); }
|
||||
$id = isset($params['id']) ? (int) $params['id'] : 0;
|
||||
if (!ApiTokenRepository::revoke($id)) { return $this->error('Токен не найден или уже отозван', array(), 404); }
|
||||
if (!ApiTokenRepository::revokeRestricted($id, array('documents:read', 'documents:write'))) {
|
||||
return $this->error('Токен документов не найден или уже отозван', array(), 404);
|
||||
}
|
||||
|
||||
AuditLog::record('document.api_token_revoked', array('actor_id'=>Auth::id(),'target_type'=>'api_token','target_id'=>$id));
|
||||
return $this->success('API-токен отозван');
|
||||
}
|
||||
@@ -329,13 +361,22 @@
|
||||
return $this->error('Недостаточно прав', array(), 403);
|
||||
}
|
||||
|
||||
$scope = Request::getStr('scope', 'document');
|
||||
$items = $scope === 'parent'
|
||||
? Model::parentDocumentPicker(
|
||||
Request::getStr('q', ''),
|
||||
Request::getInt('limit', 20),
|
||||
Request::getInt('exclude_id', 0)
|
||||
)
|
||||
: Model::documentPicker(
|
||||
Request::getStr('q', ''),
|
||||
Request::getStr('rubric_id', ''),
|
||||
Request::getInt('limit', 20)
|
||||
);
|
||||
|
||||
return $this->success('', array(
|
||||
'data' => array(
|
||||
'items' => Model::documentPicker(
|
||||
Request::getStr('q', ''),
|
||||
Request::getStr('rubric_id', ''),
|
||||
Request::getInt('limit', 20)
|
||||
),
|
||||
'items' => $items,
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -391,6 +432,71 @@
|
||||
return $this->success('Пакетное действие выполнено', array('data' => $result));
|
||||
}
|
||||
|
||||
public function bulkEditor(array $params = array())
|
||||
{
|
||||
if (!Permission::check('manage_documents')) {
|
||||
return $this->renderStatus('@adminx/404.twig', array('title' => 'Недостаточно прав'), 403);
|
||||
}
|
||||
|
||||
AdminAssets::addStyle($this->base() . '/modules/Documents/assets/documents.css', 50);
|
||||
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',
|
||||
));
|
||||
}
|
||||
|
||||
public function bulkEditorFields(array $params = array())
|
||||
{
|
||||
if (!Permission::check('manage_documents')) {
|
||||
return $this->error('Недостаточно прав', array(), 403);
|
||||
}
|
||||
|
||||
return $this->success('', array('data' => array(
|
||||
'items' => BulkEditor::fields(Request::getInt('rubric_id', 0)),
|
||||
)));
|
||||
}
|
||||
|
||||
public function bulkEditorPreview(array $params = array())
|
||||
{
|
||||
if (($err = $this->guard()) !== null) { return $err; }
|
||||
try {
|
||||
$plan = BulkEditor::preview(Request::postAll(), Auth::id());
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return $this->error($e->getMessage(), array(), 422);
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error(ErrorReport::publicMessage('Не удалось подготовить массовое изменение', $e, 'DOCBULKPREVIEW'), array(), 500);
|
||||
}
|
||||
|
||||
return $this->success('Предпросмотр подготовлен', array('data' => array('plan' => $plan)));
|
||||
}
|
||||
|
||||
public function bulkEditorRun(array $params = array())
|
||||
{
|
||||
if (($err = $this->guard()) !== null) { return $err; }
|
||||
try {
|
||||
$plan = BulkEditor::runChunk(Request::postStr('token', ''), Auth::id());
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return $this->error($e->getMessage(), array(), 422);
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error(ErrorReport::publicMessage('Не удалось выполнить пакет документов', $e, 'DOCBULKRUN'), array(), 500);
|
||||
}
|
||||
|
||||
return $this->success($plan['status'] === 'completed' ? 'Массовое изменение завершено' : 'Пакет обработан', array('data' => array('plan' => $plan)));
|
||||
}
|
||||
|
||||
public function bulkEditorCancel(array $params = array())
|
||||
{
|
||||
if (($err = $this->guard()) !== null) { return $err; }
|
||||
try {
|
||||
$plan = BulkEditor::cancel(Request::postStr('token', ''), Auth::id());
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage(), array(), 422);
|
||||
}
|
||||
|
||||
return $this->success('Выполнение остановлено', array('data' => array('plan' => $plan)));
|
||||
}
|
||||
|
||||
public function store(array $params = array())
|
||||
{
|
||||
if (($err = $this->guard()) !== null) {
|
||||
@@ -482,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'));
|
||||
@@ -559,6 +667,12 @@
|
||||
return $this->error('Проверьте поля документа', $errors, 422);
|
||||
}
|
||||
|
||||
$mediaReplacement = DocumentMediaReplacement::capture(
|
||||
$fieldGroups,
|
||||
$fieldValues,
|
||||
DocumentMediaReplacement::requestedFieldIds(Request::post('media_replace_fields', array()))
|
||||
);
|
||||
|
||||
$mediaFinalization = null;
|
||||
$previousDatabaseExceptionMode = DB::$throw_exception_on_error;
|
||||
DB::$throw_exception_on_error = true;
|
||||
@@ -622,10 +736,14 @@
|
||||
$snapshotError = ContentCacheInvalidator::consumeError($id);
|
||||
$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),
|
||||
), 'redirect' => $this->base() . '/documents/' . $id . '/edit'));
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user