Skip to content
Merged
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
8 changes: 4 additions & 4 deletions Backend/Controllers/CampaignEditAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -397,14 +397,14 @@ static function ($tier): array {
// -------------------------------------------------------------------------

/**
* Завантажує всі доступні фіди з OkayCMS/Feeds та OkayCMS/GoogleMerchant.
* Перевіряє class_exists(), щоб контролер працював навіть без одного з модулів.
* Доступні цілі акції: фіди OkayCMS/Feeds і OkayCMS/GoogleMerchant та Sviat/MerchantApi.
* Перевіряє class_exists(), щоб контролер працював без будь-якого з цих модулів.
*
* @return array{feeds: object[], gm: object[]}
* @return array{feeds: object[], gm: object[], merchant_api: bool}
*/
private function loadAvailableFeeds(EntityFactory $entityFactory): array
{
$result = ['feeds' => [], 'gm' => []];
$result = ['feeds' => [], 'gm' => [], 'merchant_api' => class_exists(\Okay\Modules\Sviat\MerchantApi\Services\CatalogItemBuilder::class)];

$feedsEntityClass = \Okay\Modules\OkayCMS\Feeds\Entities\FeedsEntity::class;
if (class_exists($feedsEntityClass)) {
Expand Down
22 changes: 21 additions & 1 deletion Backend/design/html/campaign_edit.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -862,7 +862,7 @@
</div>

<div class="toggle_body_wrap fn_card fn_promo_feeds_body{if !empty($promo->feed_enabled)} on{/if}"{if empty($promo->feed_enabled)} style="display:none"{/if}>
{if empty($available_feeds.feeds) && empty($available_feeds.gm)}
{if empty($available_feeds.feeds) && empty($available_feeds.gm) && empty($available_feeds.merchant_api)}
<p class="text_grey text_13 mb-0">{$btr->sviat_promo__feeds_no_feeds|escape}</p>
{else}
<div class="permission_block">
Expand Down Expand Up @@ -912,6 +912,26 @@
{/foreach}
{/if}

{* ── Sviat / Google Merchant API (без фідів — одна ціль) ─────── *}
{if !empty($available_feeds.merchant_api)}
<div class="col-lg-12 mb-1{if !empty($available_feeds.feeds) || !empty($available_feeds.gm)} mt-1{/if}">
<div class="heading_label">{$btr->sviat_promo__feeds_merchant_api_title|escape}</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-12">
<div class="permission_box permission_box--long">
<span>{$btr->sviat_promo__feeds_merchant_api_label|escape}</span>
<label class="switch switch-default">
<input class="switch-input" type="checkbox"
name="feed_ids[merchant_api][]"
value="1"
{if in_array(1, $linked_feed_ids.merchant_api|default:[])}checked=""{/if} />
<span class="switch-label"></span>
<span class="switch-handle"></span>
</label>
</div>
</div>
{/if}

</div>
</div>
{/if}
Expand Down
4 changes: 3 additions & 1 deletion Backend/lang/en.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@
$lang['sviat_promo__section_feeds'] = 'Feed transmission';
$lang['sviat_promo__feeds_module_title'] = 'OkayCMS / Feeds';
$lang['sviat_promo__feeds_gm_title'] = 'Google Merchant';
$lang['sviat_promo__feeds_no_feeds'] = 'No feeds available. Make sure OkayCMS/Feeds or OkayCMS/GoogleMerchant modules are installed.';
$lang['sviat_promo__feeds_merchant_api_title'] = 'Google Merchant API';
$lang['sviat_promo__feeds_merchant_api_label'] = 'Promo price in Google via the Google Merchant API module';
$lang['sviat_promo__feeds_no_feeds'] = 'No feeds available. Make sure OkayCMS/Feeds, OkayCMS/GoogleMerchant or Sviat/MerchantApi is installed.';
$lang['sviat_promo__settings_meta_section'] = 'Meta tags for /promo page';
$lang['sviat_promo__open_promo_list'] = 'Open promo list page';
$lang['sviat_promo__meta_title_label'] = 'Meta-title';
Expand Down
4 changes: 3 additions & 1 deletion Backend/lang/ru.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@
$lang['sviat_promo__section_feeds'] = 'Передача в фиды';
$lang['sviat_promo__feeds_module_title'] = 'OkayCMS / Feeds';
$lang['sviat_promo__feeds_gm_title'] = 'Google Merchant';
$lang['sviat_promo__feeds_no_feeds'] = 'Нет доступных фидов. Убедитесь, что модули OkayCMS/Feeds или OkayCMS/GoogleMerchant установлены.';
$lang['sviat_promo__feeds_merchant_api_title'] = 'Google Merchant API';
$lang['sviat_promo__feeds_merchant_api_label'] = 'Цена акции в Google через модуль Google Merchant API';
$lang['sviat_promo__feeds_no_feeds'] = 'Нет доступных фидов. Убедитесь, что установлен OkayCMS/Feeds, OkayCMS/GoogleMerchant или Sviat/MerchantApi.';
$lang['sviat_promo__settings_meta_section'] = 'Meta-теги для страницы /promo';
$lang['sviat_promo__open_promo_list'] = 'Перейти к промоакциям';
$lang['sviat_promo__meta_title_label'] = 'Meta-title';
Expand Down
4 changes: 3 additions & 1 deletion Backend/lang/ua.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@
$lang['sviat_promo__section_feeds'] = 'Передача до фідів';
$lang['sviat_promo__feeds_module_title'] = 'OkayCMS / Feeds';
$lang['sviat_promo__feeds_gm_title'] = 'Google Merchant';
$lang['sviat_promo__feeds_no_feeds'] = 'Немає доступних фідів. Переконайтесь, що модулі OkayCMS/Feeds або OkayCMS/GoogleMerchant встановлені.';
$lang['sviat_promo__feeds_merchant_api_title'] = 'Google Merchant API';
$lang['sviat_promo__feeds_merchant_api_label'] = 'Ціна акції в Google через модуль Google Merchant API';
$lang['sviat_promo__feeds_no_feeds'] = 'Немає доступних фідів. Переконайтесь, що встановлено OkayCMS/Feeds, OkayCMS/GoogleMerchant або Sviat/MerchantApi.';
$lang['sviat_promo__settings_meta_section'] = 'Meta-теги для сторінки /promo';
$lang['sviat_promo__open_promo_list'] = 'Перейти до промоакцій';
$lang['sviat_promo__meta_title_label'] = 'Meta-title';
Expand Down
27 changes: 27 additions & 0 deletions Entities/PromoFeedLinkEntity.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ class PromoFeedLinkEntity extends Entity
{
public const TYPE_FEEDS = 'feeds';
public const TYPE_GM = 'gm';
/** Sviat/MerchantApi надсилає товари без фідів — ціль одна, з умовним id: зв'язки з id 0 не зберігаються. */
public const TYPE_MERCHANT_API = 'merchant_api';
public const MERCHANT_API_FEED_ID = 1;
/** Значення ENUM-колонки feed_type: install() і оновлення беруть саме цей список. */
public const TYPES = [self::TYPE_FEEDS, self::TYPE_GM, self::TYPE_MERCHANT_API];

protected static $fields = [
'promo_id',
Expand Down Expand Up @@ -57,4 +62,26 @@ public function getLinkedFeedsGrouped(array $promoIds): array
}
return $result;
}

/**
* Акції, які діяли у фідах GoogleMerchant, але ще не прив'язані до MerchantApi: при переході на нього вони
* мають і далі потрапляти в Google.
*
* @param iterable<array{promo_id: int|string, feed_type: string, feed_id: int|string}> $rows
* @return list<int>
*/
public static function promoIdsMissingMerchantApi(iterable $rows): array
{
$gm = [];
$merchantApi = [];
foreach ($rows as $row) {
if ($row['feed_type'] === self::TYPE_GM) {
$gm[(int) $row['promo_id']] = true;
} elseif ($row['feed_type'] === self::TYPE_MERCHANT_API) {
$merchantApi[(int) $row['promo_id']] = true;
}
}

return array_keys(array_diff_key($gm, $merchantApi));
}
}
21 changes: 19 additions & 2 deletions Extenders/PromoGoogleMerchantExtender.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
use Okay\Modules\Sviat\Promo\Services\PromotionEligibility;

/**
* Акційні ціни кампаній для OkayCMS/GoogleMerchant (legacy).
* Акційні ціни кампаній для OkayCMS/GoogleMerchant і Sviat/MerchantApi.
*
* GoogleMerchantHelper::getQuery — контекст фіда, preload кампаній і валют; getItem — акційна ціна та sale_price_effective_date.
* getQuery — контекст фіда, preload кампаній і валют; getItem — акційна ціна та sale_price_effective_date.
*/
class PromoGoogleMerchantExtender implements ExtensionInterface
{
Expand Down Expand Up @@ -73,6 +73,23 @@ public function preloadForFeed(Select $sql, $feedId): Select
return $sql;
}

/**
* Хук Sviat/MerchantApi CatalogItemBuilder::getQuery (chain): той самий запис, що й у фіді GoogleMerchant,
* тільки ціль — «Google Merchant API», а не конкретний фід.
*/
public function preloadForMerchantApi(Select $sql): Select
{
$this->resolver->setCurrentFeed(PromoFeedLinkEntity::TYPE_MERCHANT_API, PromoFeedLinkEntity::MERCHANT_API_FEED_ID);
$this->resolver->preload();

/** @var CurrenciesEntity $currenciesEntity */
$currenciesEntity = $this->entityFactory->get(CurrenciesEntity::class);
$this->mainCurrency = $currenciesEntity->getMainCurrency();
$this->allCurrencies = $currenciesEntity->mappedBy('id')->find();

return $sql;
}

/**
* Хук GoogleMerchantHelper::getItem (chain).
*
Expand Down
2 changes: 1 addition & 1 deletion Helpers/CampaignRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public function saveFeedLinks(int $promoId, int $feedEnabled, array $feedIds): v
return;
}

foreach ([PromoFeedLinkEntity::TYPE_FEEDS, PromoFeedLinkEntity::TYPE_GM] as $type) {
foreach ([PromoFeedLinkEntity::TYPE_FEEDS, PromoFeedLinkEntity::TYPE_GM, PromoFeedLinkEntity::TYPE_MERCHANT_API] as $type) {
foreach ((array) ($feedIds[$type] ?? []) as $feedId) {
$feedId = (int) $feedId;
if ($feedId > 0) {
Expand Down
49 changes: 45 additions & 4 deletions Init/Init.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

namespace Okay\Modules\Sviat\Promo\Init;

use Okay\Modules\Sviat\MerchantApi\Services\CatalogItemBuilder;
use Okay\Core\Cart;
use Okay\Core\Database;
use Okay\Core\EntityFactory;
use Okay\Core\QueryFactory;
use Okay\Core\ServiceLocator;
use Okay\Core\Classes\Purchase;
Expand Down Expand Up @@ -120,10 +122,7 @@ public function install(): void

$this->migrateEntityTable(PromoFeedLinkEntity::class, [
new EntityField('promo_id')->setTypeInt(11)->setIndex(),
new EntityField('feed_type')->setTypeEnum([
PromoFeedLinkEntity::TYPE_FEEDS,
PromoFeedLinkEntity::TYPE_GM,
])->setDefault(PromoFeedLinkEntity::TYPE_FEEDS)->setIndex(),
new EntityField('feed_type')->setTypeEnum(PromoFeedLinkEntity::TYPES)->setDefault(PromoFeedLinkEntity::TYPE_FEEDS)->setIndex(),
new EntityField('feed_id')->setTypeInt(11)->setIndex(),
]);

Expand Down Expand Up @@ -370,6 +369,24 @@ public function init(): void
);
}
}

$this->registerMerchantApiExtensions();
}

/** Sviat/MerchantApi від 2.0 збирає записи сам — без нього підключення просто немає (сток). */
private function registerMerchantApiExtensions(): void
{
if (!class_exists(CatalogItemBuilder::class)) {
return;
}
$this->registerChainExtension(
['class' => CatalogItemBuilder::class, 'method' => 'getQuery'],
['class' => PromoGoogleMerchantExtender::class, 'method' => 'preloadForMerchantApi']
);
$this->registerChainExtension(
['class' => CatalogItemBuilder::class, 'method' => 'getItem'],
['class' => PromoGoogleMerchantExtender::class, 'method' => 'applyPromoToItem']
);
}

/**
Expand Down Expand Up @@ -503,4 +520,28 @@ public function update_1_0_5(): void
new EntityField('exclude_no_image')->setTypeTinyInt(1, true)->setDefault(0)
);
}

/**
* 2.0: акції, що діяли у фідах GoogleMerchant, діють і в Google через Sviat/MerchantApi. Ідемпотентно:
* update_* виконуються й на чистій інсталяції.
*/
public function update_2_0_0(): void
{
// Без індексу: колонка лише міняє список значень, індекс у неї вже є.
$this->migrateEntityField(
PromoFeedLinkEntity::class,
new EntityField('feed_type')->setTypeEnum(PromoFeedLinkEntity::TYPES)->setDefault(PromoFeedLinkEntity::TYPE_FEEDS)
);

$locator = ServiceLocator::getInstance();
$links = $locator->getService(EntityFactory::class)->get(PromoFeedLinkEntity::class);
$rows = array_map(static fn(object $row) => (array) $row, $links->noLimit()->find());
foreach (PromoFeedLinkEntity::promoIdsMissingMerchantApi($rows) as $promoId) {
$links->add([
'promo_id' => $promoId,
'feed_type' => PromoFeedLinkEntity::TYPE_MERCHANT_API,
'feed_id' => PromoFeedLinkEntity::MERCHANT_API_FEED_ID,
]);
}
}
}
2 changes: 1 addition & 1 deletion Init/module.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"Okay": "4.5.3",
"version": "1.0.21",
"version": "2.0.0",
"moduleName": "Promo: акції та знижки",
"vendor": {
"email": "devsviat@proton.me",
Expand Down
23 changes: 18 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,24 @@
- Для акцій типу «Подарунок» можна вказати список подарункових товарів.
- Подарунки відображаються в кошику та замовленні як безкоштовні позиції.

### Робота з фідами (опційно)
### Google та інші фіди (опційно)

- Передача промо-даних у фіди, якщо встановлені модулі:
- `OkayCMS/Feeds`
- `OkayCMS/GoogleMerchant`
Акційна ціна й дати акції потрапляють у Google та інші фіди, якщо в магазині
стоїть хоч один із модулів:

- `Sviat/MerchantApi` 2.0 і новіше: товари йдуть у Merchant Center через API;
- `OkayCMS/GoogleMerchant`: XML-фід для Google;
- `OkayCMS/Feeds`: фіди, зокрема Google і Facebook.

Модулі можуть стояти одночасно. У картці акції в кожного свій перемикач, тож
акцію можна, наприклад, лишити в старому XML-фіді й не надсилати через API.

## Вимоги

- PHP 8.5+
- OkayCMS 4.5.3 (чиста або [форк](https://github.com/devSviat/OkayCMS-Fork))
- Перевірено на PHP 8.5 — на чистій OkayCMS 4.5.3 і на форку
- (Опційно) `OkayCMS/Feeds` та/або `OkayCMS/GoogleMerchant` — якщо хочете передавати акції у фіди
- (Опційно) `Sviat/MerchantApi` 2.0+, `OkayCMS/GoogleMerchant` або `OkayCMS/Feeds`, якщо акції мають іти в Google чи інші фіди

## Встановлення

Expand All @@ -72,6 +78,13 @@

Після встановлення перейдіть в адмін-панель → Модулі → Знайдіть «Promo: акції та знижки» → Натисніть «Встановити».

### Оновлення з 1.x

Замініть файли модуля й натисніть «Оновити» в списку модулів. Версія 2.0 додає
ціль «Google Merchant API» для модуля `Sviat/MerchantApi`. Акції, які вже йшли у
фіди `OkayCMS/GoogleMerchant`, отримують цю ціль автоматично, тож після переходу
на API вони не загубляться. Старі фіди працюють як раніше.

## Налаштування та запуск акції

1. Перейдіть в адмін-панель → Каталог → Акції.
Expand Down
3 changes: 2 additions & 1 deletion Requests/CampaignPayloadRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Okay\Modules\Sviat\Promo\Requests;

use Okay\Modules\Sviat\Promo\Entities\PromoFeedLinkEntity;
use Okay\Core\Request;
use Okay\Modules\Sviat\Promo\Entities\PromoCampaignEntity;

Expand Down Expand Up @@ -193,7 +194,7 @@ public function postFeedIds(): array
return [];
}
$result = [];
foreach (['feeds', 'gm'] as $type) {
foreach ([PromoFeedLinkEntity::TYPE_FEEDS, PromoFeedLinkEntity::TYPE_GM, PromoFeedLinkEntity::TYPE_MERCHANT_API] as $type) {
if (!empty($raw[$type]) && is_array($raw[$type])) {
$result[$type] = array_values(array_map(intval(...), $raw[$type]));
}
Expand Down
2 changes: 1 addition & 1 deletion Services/PromoFeedPriceResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public function __construct(EntityFactory $entityFactory, QueryFactory $queryFac
* Встановлює контекст поточного фіда перед preload() і findBestCampaign().
* Викликати один раз для кожної генерації фіда.
*
* @param string $type PromoFeedLinkEntity::TYPE_FEEDS | TYPE_GM
* @param string $type PromoFeedLinkEntity::TYPE_FEEDS | TYPE_GM | TYPE_MERCHANT_API
* @param int $feedId
*/
public function setCurrentFeed(string $type, int $feedId): void
Expand Down
Loading
Loading