feat: add _formatted placeholders for currency and weight display#147
feat: add _formatted placeholders for currency and weight display#147
Conversation
System settings become the single source of truth for currency symbol,
currency position, and weight unit. Snippets now pre-format values via
Format::price($value, true) and Format::weightWithUnit() and pass them
to chunks as *_formatted fields, eliminating lexicon calls for display.
- Format.php: add weightWithUnit(), getWeightUnit(), getCurrencySymbol(),
extend getSettings() with weight_unit
- settings.php + lexicons (ru/en): add ms3_weight_unit system setting
- Snippets (ms3_cart, ms3_order_total, ms3_order, ms3_get_order): add
price_formatted, cost_formatted, weight_formatted, cart_cost_formatted,
delivery_cost_formatted, total_cost_formatted alongside raw numeric fields
- ms3_order.php: expose currency_symbol for JS-updated cost spans
- OrdersPageService: add _formatted fields to order list and detail data,
fix raw numeric values before formatting in getOrderProducts()
- Notification.php: add _formatted fields to products and total array
- Chunks: replace {'ms3_frontend_currency'|lexicon} and
{'ms3_frontend_weight_unit'|lexicon} with *_formatted placeholders
Lexicon keys ms3_frontend_currency and ms3_frontend_weight_unit are
retained for backward compatibility but no longer used by core chunks.
|
@biz87 проверь плиз туда ли я пошел или нужно было сделать иначе |
biz87
left a comment
There was a problem hiding this comment.
Code Review
Идея правильная — single source of truth для валюты и единиц. Реализация в целом хорошая, но есть баги и недочёты.
Баги
1. ms3_minicart.tpl — old_cost потерял валюту
Было:
{$product.old_cost} {'ms3_frontend_currency' | lexicon}
Стало:
{$product.old_cost}
Но old_cost_formatted нигде не генерируется (ни в ms3_cart.php, ни в других сниппетах). Результат: старая стоимость отображается как голое число без валюты. Нужно либо добавить old_cost_formatted в сниппет корзины и использовать его, либо сохранить лексикон для этого поля.
2. ms3_customer_order_details.tpl — old_price без валюты рядом с price_formatted
Строка 68 (в PR):
<div class="text-decoration-line-through text-muted small">{$product.old_price}</div>old_price — это format::price() (число без валюты: "150"), а рядом price_formatted — число с валютой: "100 ₽". Визуальная несогласованность. Аналогично в ms3_get_order.tpl (строка 72).
3. Docblock discount() в Format.php повреждён
После вставки weightWithUnit() и getWeightUnit() у метода discount() пропала строка описания. Было * Calculate discount percentage, стало пустая строка в docblock.
Проблемы дизайна
4. Нейминг: cost_with_currency vs *_formatted
В OrdersPageService для списка заказов используется cost_with_currency, а во всех остальных местах — *_formatted. В чанке ms3_customer_order_row.tpl — {$cost_with_currency}. Нужно привести к единому паттерну.
5. ms3_order_total.php — дублирование ternary
7 строк подряд с одинаковым паттерном $response['success'] ? $response['data']['...'] ?? 0 : 0. Стоит вынести в переменную:
$data = $response['success'] ? ($response['data'] ?? []) : [];
$total['cost_formatted'] = $ms3->format->price($data['cost'] ?? 0, true);
// ...Пропущенные места
6. Отсутствующие _formatted плейсхолдеры
Не сгенерированы, но могут понадобиться в кастомных чанках:
old_price_formatted— есть только вms3_cart.php, но отсутствует вms3_get_order.php,OrdersPageService,Notificationold_cost_formatted— отсутствует вездеdiscount_price_formatted,discount_cost_formatted— отсутствуют
Как минимум old_price_formatted стоит добавить во все точки, где генерируется price_formatted, для консистентности.
Мелкое
7. ms3_weight_unit — дефолт kg
Для русскоязычного проекта дефолт kg спорный. Может стоит кг? Или оставить kg как интернациональный вариант и указать в описании настройки.
Резюме
Основное перед мержем:
- Исправить
old_costв minicart (баг — пропала валюта) - Добавить
old_price_formattedвms3_get_order.php,OrdersPageService,Notificationили привести чанки к согласованному виду - Привести нейминг к единому
*_formatted(убратьcost_with_currency) - Восстановить docblock
discount()
Replaced raw price variables with formatted versions across multiple templates and snippets to ensure consistent currency display. Introduced new formatted fields for old prices and discount calculations, enhancing the presentation of pricing information in the customer order details, order rows, minicart, and notifications. This change improves user experience by providing clearer pricing information.
biz87
left a comment
There was a problem hiding this comment.
Code Review (повторный)
Все замечания из первого ревью исправлены во втором коммите. PR стал значительно лучше.
Что исправлено
ms3_minicart.tpl—old_cost_formattedтеперь генерируется и используетсяms3_customer_order_details.tplиms3_get_order.tpl—old_price_formattedс корректным условием- Нейминг унифицирован:
cost_with_currencyубран, везде*_formatted ms3_order_total.php—$dataвынесен, ternary не дублируется- Docblock
discount()— сохранён Notification.php— batch-загрузка productData для old_price, полный набор_formattedполей
Оставшееся замечание (некритичное, не блокирует мерж)
Семантика cost_formatted в OrdersPageService изменена:
Было: price($cost) → число без валюты ("1 500"), чанк добавлял {'ms3_frontend_currency' | lexicon}
Стало: price($cost, true) → число с валютой ("1 500 ₽")
Это breaking change для кастомных чанков ms3_customer_order_row, которые используют {$cost_formatted} и сами добавляют валюту — получат двойной символ. Стоит упомянуть в CHANGELOG / release notes.
Мелкое
Notification::getOrderProducts() вызывает $this->order->getMany('Products') дважды (сбор ID + основной цикл). Второй вызов вернёт кеш, но можно было итерировать один раз.
LGTM
Описание
Системные настройки становятся единственным источником истины для символа
валюты и единиц веса. Сниппеты теперь предварительно форматируют значения
через
Format::price($value, true)иFormat::weightWithUnit()и передаютрезультат в чанки через новые
*_formattedплейсхолдеры. Чанки используютготовые строки без лексиконных вызовов для валюты и веса.
Ранее символ валюты и единица веса отображались в чанках через лексиконы
(
{'ms3_frontend_currency'|lexicon},{'ms3_frontend_weight_unit'|lexicon}),хотя системные настройки (
ms3_currency_symbol,ms3_currency_position) ужеуправляли форматированием в PHP. Изменение символа валюты в системной
настройке не затрагивало вывод в чанках.
Тип изменений
Связанные Issues
Closes #144
Как это было протестировано?
Конфигурация тестирования:
Чеклист
Дополнительные заметки
Обратная совместимость:
price,cost,weight) не удалены — JS-логика не затронутаms3_frontend_currencyиms3_frontend_weight_unitсохранены,но не используются core-чанками
обновлённых чанков, заменив лексиконные вызовы на
*_formattedплейсхолдерыОсобые места кода:
ms3_order.tpl— JS динамически обновляет span'ы#ms3_order_costи др., поэтомулексикон заменён на
{$order.currency_symbol}(передаётся из сниппета), а не на_formattedплейсхолдерms3_get_order.php— сохраняются raw-числа до форматирования, чтобы_formattedполя получали корректный числовой вход