70 lines
3.2 KiB
PHP
70 lines
3.2 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\Reward\Setup\Patch\Data;
|
|
|
|
use Magento\Framework\App\ResourceConnection;
|
|
use Magento\Framework\Setup\ModuleDataSetupInterface;
|
|
use Magento\Framework\Setup\Patch\DataPatchInterface;
|
|
|
|
class ConsolidateGlobalRewardBalances implements DataPatchInterface
|
|
{
|
|
public function __construct(
|
|
private readonly ModuleDataSetupInterface $moduleDataSetup,
|
|
private readonly ResourceConnection $resource
|
|
) {}
|
|
|
|
public function apply(): self
|
|
{
|
|
$connection = $this->moduleDataSetup->getConnection();
|
|
$accountTable = $this->resource->getTableName('esun_reward_account');
|
|
$transactionTable = $this->resource->getTableName('esun_reward_transaction');
|
|
$this->moduleDataSetup->startSetup();
|
|
try {
|
|
$customerIds = $connection->fetchCol(
|
|
$connection->select()->from($accountTable, ['customer_id'])->group('customer_id')->having('COUNT(*) > 1')
|
|
);
|
|
foreach ($customerIds as $customerId) {
|
|
$rows = $connection->fetchAll(
|
|
$connection->select()->from($accountTable)->where('customer_id = ?', (int)$customerId)->order('account_id ASC')
|
|
);
|
|
$primaryId = (int)$rows[0]['account_id'];
|
|
$connection->update($accountTable, [
|
|
'balance' => (int)array_sum(array_column($rows, 'balance')),
|
|
'pending_balance' => (int)array_sum(array_column($rows, 'pending_balance')),
|
|
'lifetime_earned' => (int)array_sum(array_column($rows, 'lifetime_earned')),
|
|
'lifetime_spend_base' => (float)array_sum(array_column($rows, 'lifetime_spend_base')),
|
|
], ['account_id = ?' => $primaryId]);
|
|
$connection->update($accountTable, [
|
|
'balance' => 0, 'pending_balance' => 0, 'lifetime_earned' => 0, 'lifetime_spend_base' => 0,
|
|
], ['customer_id = ?' => (int)$customerId, 'account_id <> ?' => $primaryId]);
|
|
}
|
|
|
|
$connection->update(
|
|
$transactionTable,
|
|
['reason' => 'Approved product review reward'],
|
|
['type IN (?)' => ['review_media', 'review_text']]
|
|
);
|
|
foreach ($connection->fetchCol($connection->select()->from($transactionTable, ['customer_id'])->distinct()) as $customerId) {
|
|
$balance = 0;
|
|
$transactions = $connection->fetchAll(
|
|
$connection->select()->from($transactionTable, ['transaction_id', 'points_delta'])
|
|
->where('customer_id = ?', (int)$customerId)->order('transaction_id ASC')
|
|
);
|
|
foreach ($transactions as $transaction) {
|
|
$balance += (int)$transaction['points_delta'];
|
|
$connection->update($transactionTable, ['balance_after' => $balance], [
|
|
'transaction_id = ?' => (int)$transaction['transaction_id'],
|
|
]);
|
|
}
|
|
}
|
|
} finally {
|
|
$this->moduleDataSetup->endSetup();
|
|
}
|
|
return $this;
|
|
}
|
|
|
|
public static function getDependencies(): array { return []; }
|
|
public function getAliases(): array { return []; }
|
|
}
|