<?php
namespace App\EventListener\Client\Store;
use App\Entity\Client\Store\StoreGroup;
use App\Entity\Client\Store\StoreStock;
use App\EventListener\GenericEvent;
use App\Service\AppManager;
use App\Service\Aura\AuraManager;
use App\Utils\SQLUtils;
use Aura\SqlQuery\QueryFactory;
use Doctrine\DBAL\FetchMode;
class StoreGroupListener
{
private AppManager $appManager;
public function __construct(AppManager $appManager)
{
$this->appManager = $appManager;
}
public function copyAssortment(GenericEvent $genericEvent)
{
$storeGroup = $genericEvent->getSubject();
if (!$storeGroup instanceof StoreGroup) {
return;
}
if ($storeGroup->getCopyFromStores()->count() === 0) {
return;
}
$copyStoreIDs = [];
foreach ($storeGroup->getCopyFromStores() as $copyFromStore) {
$copyStoreIDs[] = $copyFromStore->getId();
}
$now = (new \DateTime())->format('Y-m-d H:i:s');
$connection = $this->appManager->getConnection();
$queryFactory = new QueryFactory('pgsql');
$storeStockQuery = $queryFactory->newSelect()
->cols(['ss.product_id'])
->from('client_' . $this->appManager->getClientId() . '.store_stock ss')
->where('ss.store_id IN (' . implode(',', $copyStoreIDs) . ')')
->where("ss.assortment = '".StoreStock::ASSORTMENT_IN."'")
->groupBy(['ss.product_id'])
->orderBy(['ss.product_id ASC']);
$storeStocks = AuraManager::fetchAll($connection, $storeStockQuery, FetchMode::COLUMN);
if (count($storeStocks) === 0) {
return;
}
foreach ($storeStocks as $productID) {
$updateQuery = $queryFactory->newInsert()
->into('client_' . $this->appManager->getClientId() . '.store_stock_group')
->set('product_id', $productID)
->set('created_at', SQLUtils::toSQLString($now))
->set('assortment', "'" .StoreStock::ASSORTMENT_IN . "'")
->set('store_group_id', $storeGroup->getId());
try {
$stmt = $connection->prepare($updateQuery->getStatement());
$stmt->execute($updateQuery->getBindValues());
echo '.';
} catch (\Exception $exception) {
echo '_';
}
}
return 0;
}
}