Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions docs/components/msproductdiscounts/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,49 @@ switch($modx->event->name){

:::

#### mspdOnGetShowPrices - генерируется при подготовке цены показа товара в каталоге или на странице отдельного товара

Генерируется после применения скидок, но до расчёта строковых значений цены (**price_str**, **old_price_str**),
поэтому подписчик может подменить пару цен, и отформатированные значения будут посчитаны уже от подменённых.
Событие генерируется и для товара, у которого скидок нет вовсе — так сайт может показать пару «старая/новая цена»
там, где выгода не выражается ни одной записью скидки (например у товара-комплекта).

Доступные параметры:

* **$productData** - массив данных товара.
* **$discounts** - массив скидок, попавших в показ; может быть пустым.
* **$scope** - область показа: `catalog` или `product`.
* **$prices** - текущая пара цен: `['price' => ..., 'old_price' => ...]`.
* **$object** - экземпляр класса MsProductDiscounts\Discounts.

Подмена выполняется через свойство **$object->showPrices**; цену, которую подписчик не тронул, компонент считает
как раньше.

Пока показ скидок не включён системной настройкой **mspd_show_for_all** и ни у одной скидки не выставлено
«Показывать», компонент отвечает только по товарам из корзины со скидками — товар без скидок до расчёта цены
показа не доходит, и событие для него не генерируется. Сайту, который подаёт свои цены, нужно заявить об этом
свойством **$object->externalPrices** в событии **mspdOnFilterIdsByDiscount**: оно снимает ранний выход по корзине.
При этом в ответ попадают и товары, о которых сервер раньше молчал, а старая цена таких товаров берётся из карточки
товара — если поле старой цены там заполнено, а показывать её не нужно, обнулите её в подписчике.

::: details Пример плагина

```php:line-numbers
// показываем товару-комплекту 123 старую цену, посчитанную сайтом
switch($modx->event->name){
case 'mspdOnFilterIdsByDiscount':
$object->externalPrices = true;
break;
case 'mspdOnGetShowPrices':
if((int)$productData['id'] === 123){
$object->showPrices['old_price'] = 520.00;
}
break;
}
```

:::

#### mspdOnGetProductDiscounts - генерируется при получении скидок для товара

Доступные параметры:
Expand Down
44 changes: 44 additions & 0 deletions docs/en/components/msproductdiscounts/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,50 @@ switch($modx->event->name){

:::

#### mspdOnGetShowPrices - fired when preparing display price of a product in catalog or on product page

Fired after discounts are applied, but before formatted price values (**price_str**, **old_price_str**) are
calculated, so a subscriber can replace the price pair and formatted values will be calculated from the replaced
ones. The event is fired for a product without any discounts too — this way a site can show the «old / new price»
pair where the benefit is not expressed by any discount record (a bundle product, for example).

Available parameters:

* **$productData** - array of product data.
* **$discounts** - array of discounts included in display; may be empty.
* **$scope** - display area: `catalog` or `product`.
* **$prices** - current price pair: `['price' => ..., 'old_price' => ...]`.
* **$object** - MsProductDiscounts\Discounts instance.

Replacement is done through the **$object->showPrices** property; a price the subscriber did not touch is
calculated as before.

While discount display is not enabled by the **mspd_show_for_all** system setting and no discount has display set
to «Show», the component answers only for cart products with discounts — a product without discounts never reaches
display price calculation, and the event is not fired for it. A site that supplies its own prices must declare it
with the **$object->externalPrices** property in the **mspdOnFilterIdsByDiscount** event: it removes the early
return by cart. Note that products the server used to be silent about then get into the response, and their old
price is taken from the product itself — if the old price field is filled there and should not be shown, reset it
in your subscriber.

::: details Plugin example

```php:line-numbers
// show bundle product 123 the old price calculated by the site
switch($modx->event->name){
case 'mspdOnFilterIdsByDiscount':
$object->externalPrices = true;
break;
case 'mspdOnGetShowPrices':
if((int)$productData['id'] === 123){
$object->showPrices['old_price'] = 520.00;
}
break;
}
```

:::

#### mspdOnGetProductDiscounts - fired when getting discounts for product

Available parameters:
Expand Down