init
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model;
|
||||
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
|
||||
class BalanceManager
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ResourceConnection $resource,
|
||||
private readonly Json $json,
|
||||
private readonly TierResolver $tierResolver
|
||||
) {}
|
||||
|
||||
public function getAccount(int $customerId, int $websiteId): array
|
||||
{
|
||||
$connection = $this->resource->getConnection();
|
||||
$table = $this->resource->getTableName('esun_reward_account');
|
||||
$rows = $connection->fetchAll(
|
||||
$connection->select()->from($table)->where('customer_id = ?', $customerId)->order('account_id ASC')
|
||||
);
|
||||
if (!$rows) {
|
||||
return ['customer_id' => $customerId, 'website_id' => $websiteId, 'balance' => 0, 'pending_balance' => 0, 'lifetime_earned' => 0, 'lifetime_spend_base' => 0, 'tier_code' => 'bronze'];
|
||||
}
|
||||
|
||||
$account = $rows[0];
|
||||
$account['website_id'] = $websiteId;
|
||||
$account['balance'] = array_sum(array_column($rows, 'balance'));
|
||||
$account['pending_balance'] = array_sum(array_column($rows, 'pending_balance'));
|
||||
$account['lifetime_earned'] = array_sum(array_column($rows, 'lifetime_earned'));
|
||||
$account['lifetime_spend_base'] = array_sum(array_column($rows, 'lifetime_spend_base'));
|
||||
return $account;
|
||||
}
|
||||
|
||||
public function change(int $customerId, int $websiteId, int $points, string $type, string $uniqueKey, array $context = []): bool
|
||||
{
|
||||
if ($customerId <= 0 || $points === 0 || $uniqueKey === '') { return false; }
|
||||
$connection = $this->resource->getConnection();
|
||||
$accountTable = $this->resource->getTableName('esun_reward_account');
|
||||
$transactionTable = $this->resource->getTableName('esun_reward_transaction');
|
||||
$connection->beginTransaction();
|
||||
try {
|
||||
if ($connection->fetchOne($connection->select()->from($transactionTable, ['transaction_id'])->where('unique_key = ?', $uniqueKey))) {
|
||||
$connection->rollBack(); return false;
|
||||
}
|
||||
$connection->insertOnDuplicate($accountTable, ['customer_id' => $customerId, 'website_id' => $websiteId], []);
|
||||
$accounts = $connection->fetchAll(
|
||||
$connection->select()->from($accountTable)->where('customer_id = ?', $customerId)->order('account_id ASC')->forUpdate(true)
|
||||
);
|
||||
$account = $accounts[0];
|
||||
$balance = (int)array_sum(array_column($accounts, 'balance'));
|
||||
if ($balance + $points < 0 && empty($context['allow_negative'])) { throw new LocalizedException(__('The customer does not have enough reward points.')); }
|
||||
$newBalance = $balance + $points;
|
||||
$connection->update($accountTable, [
|
||||
'balance' => $newBalance,
|
||||
'pending_balance' => (int)array_sum(array_column($accounts, 'pending_balance')),
|
||||
'lifetime_earned' => (int)array_sum(array_column($accounts, 'lifetime_earned')) + max(0, $points),
|
||||
'lifetime_spend_base' => (float)array_sum(array_column($accounts, 'lifetime_spend_base')),
|
||||
], ['account_id = ?' => (int)$account['account_id']]);
|
||||
if (count($accounts) > 1) {
|
||||
$connection->update($accountTable, [
|
||||
'balance' => 0, 'pending_balance' => 0, 'lifetime_earned' => 0, 'lifetime_spend_base' => 0,
|
||||
], ['customer_id = ?' => $customerId, 'account_id <> ?' => (int)$account['account_id']]);
|
||||
}
|
||||
$connection->insert($transactionTable, [
|
||||
'customer_id' => $customerId, 'website_id' => $websiteId, 'points_delta' => $points,
|
||||
'balance_after' => $newBalance, 'type' => $type, 'status' => $context['status'] ?? 'available',
|
||||
'reference_type' => $context['reference_type'] ?? null, 'reference_id' => isset($context['reference_id']) ? (string)$context['reference_id'] : null,
|
||||
'unique_key' => $uniqueKey, 'reason' => $context['reason'] ?? null,
|
||||
'admin_user_id' => $context['admin_user_id'] ?? null,
|
||||
'metadata' => empty($context['metadata']) ? null : $this->json->serialize($context['metadata']),
|
||||
]);
|
||||
$connection->commit(); return true;
|
||||
} catch (\Throwable $e) {
|
||||
if ($connection->getTransactionLevel() > 0) { $connection->rollBack(); }
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
public function addLifetimeSpend(int $customerId, int $websiteId, float $amount, ?int $storeId = null): void
|
||||
{
|
||||
$connection = $this->resource->getConnection(); $table = $this->resource->getTableName('esun_reward_account');
|
||||
$connection->beginTransaction();
|
||||
try {
|
||||
$connection->insertOnDuplicate($table, ['customer_id' => $customerId, 'website_id' => $websiteId], []);
|
||||
$accounts = $connection->fetchAll(
|
||||
$connection->select()->from($table)->where('customer_id = ?', $customerId)->order('account_id ASC')->forUpdate(true)
|
||||
);
|
||||
$account = $accounts[0];
|
||||
$spend = max(0.0, (float)array_sum(array_column($accounts, 'lifetime_spend_base')) + $amount);
|
||||
$tier = $this->tierResolver->resolveEffective(
|
||||
(string)($account['tier_code'] ?? ''),
|
||||
$spend,
|
||||
$storeId
|
||||
);
|
||||
$connection->update($table, [
|
||||
'balance' => (int)array_sum(array_column($accounts, 'balance')),
|
||||
'pending_balance' => (int)array_sum(array_column($accounts, 'pending_balance')),
|
||||
'lifetime_earned' => (int)array_sum(array_column($accounts, 'lifetime_earned')),
|
||||
'lifetime_spend_base' => $spend,
|
||||
'tier_code' => $tier['code'],
|
||||
], ['account_id = ?' => (int)$account['account_id']]);
|
||||
if (count($accounts) > 1) {
|
||||
$connection->update($table, [
|
||||
'balance' => 0, 'pending_balance' => 0, 'lifetime_earned' => 0, 'lifetime_spend_base' => 0,
|
||||
], ['customer_id = ?' => $customerId, 'account_id <> ?' => (int)$account['account_id']]);
|
||||
}
|
||||
$connection->commit();
|
||||
} catch (\Throwable $e) { if ($connection->getTransactionLevel() > 0) { $connection->rollBack(); } throw $e; }
|
||||
}
|
||||
|
||||
public function importLegacySnapshot(
|
||||
int $customerId,
|
||||
int $websiteId,
|
||||
int $targetBalance,
|
||||
string $targetTierCode,
|
||||
string $batchId,
|
||||
array $metadata = []
|
||||
): bool {
|
||||
if ($customerId <= 0 || $websiteId <= 0 || $targetBalance < 0
|
||||
|| !in_array($targetTierCode, ['bronze', 'silver', 'gold'], true) || trim($batchId) === '') {
|
||||
throw new LocalizedException(__('Invalid reward migration snapshot.'));
|
||||
}
|
||||
$connection = $this->resource->getConnection();
|
||||
$accountTable = $this->resource->getTableName('esun_reward_account');
|
||||
$transactionTable = $this->resource->getTableName('esun_reward_transaction');
|
||||
$uniqueKey = sprintf('migration:%s:%d:%d', hash('sha256', trim($batchId)), $customerId, $websiteId);
|
||||
$connection->beginTransaction();
|
||||
try {
|
||||
if ($connection->fetchOne($connection->select()->from($transactionTable, ['transaction_id'])->where('unique_key = ?', $uniqueKey))) {
|
||||
$connection->rollBack();
|
||||
return false;
|
||||
}
|
||||
$connection->insertOnDuplicate($accountTable, ['customer_id' => $customerId, 'website_id' => $websiteId], []);
|
||||
$account = $connection->fetchRow($connection->select()->from($accountTable)
|
||||
->where('customer_id = ?', $customerId)->where('website_id = ?', $websiteId)->forUpdate(true));
|
||||
$currentBalance = (int)($account['balance'] ?? 0);
|
||||
$delta = $targetBalance - $currentBalance;
|
||||
$connection->update($accountTable, [
|
||||
'balance' => $targetBalance,
|
||||
'lifetime_earned' => max((int)($account['lifetime_earned'] ?? 0), $targetBalance),
|
||||
'tier_code' => $targetTierCode,
|
||||
], ['account_id = ?' => (int)$account['account_id']]);
|
||||
$connection->insert($transactionTable, [
|
||||
'customer_id' => $customerId, 'website_id' => $websiteId, 'points_delta' => $delta,
|
||||
'balance_after' => $targetBalance, 'type' => 'migration', 'status' => 'available',
|
||||
'reference_type' => 'migration', 'reference_id' => substr($batchId, 0, 64),
|
||||
'unique_key' => $uniqueKey, 'reason' => 'Legacy reward migration',
|
||||
'metadata' => $this->json->serialize($metadata + [
|
||||
'tier_code' => $targetTierCode,
|
||||
]),
|
||||
]);
|
||||
$connection->commit();
|
||||
return true;
|
||||
} catch (\Throwable $e) {
|
||||
if ($connection->getTransactionLevel() > 0) { $connection->rollBack(); }
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
public function getTransactions(int $customerId, int $limit = 50): array
|
||||
{
|
||||
$connection = $this->resource->getConnection();
|
||||
$rows = $connection->fetchAll(
|
||||
$connection->select()->from($this->resource->getTableName('esun_reward_transaction'))
|
||||
->where('customer_id = ?', $customerId)->order('transaction_id ASC')
|
||||
);
|
||||
$balance = 0;
|
||||
foreach ($rows as &$row) {
|
||||
$balance += (int)$row['points_delta'];
|
||||
$row['balance_after'] = $balance;
|
||||
}
|
||||
unset($row);
|
||||
return array_slice(array_reverse($rows), 0, max(1, min(200, $limit)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model;
|
||||
|
||||
use Magento\Checkout\Model\Cart as CheckoutCart;
|
||||
use Magento\Checkout\Model\ConfigProviderInterface;
|
||||
use Magento\Customer\Helper\Session\CurrentCustomer;
|
||||
|
||||
class CheckoutConfigProvider implements ConfigProviderInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CheckoutCart $checkoutCart,
|
||||
private readonly CurrentCustomer $currentCustomer,
|
||||
private readonly BalanceManager $balances,
|
||||
private readonly Config $config
|
||||
) {}
|
||||
|
||||
public function getConfig(): array
|
||||
{
|
||||
$quote = $this->checkoutCart->getQuote();
|
||||
$customerId = (int)$this->currentCustomer->getCustomerId()
|
||||
?: (int)$quote->getCustomerId();
|
||||
$balance = $customerId > 0
|
||||
? (int)$this->balances->getAccount(
|
||||
$customerId,
|
||||
(int)$quote->getStore()->getWebsiteId()
|
||||
)['balance']
|
||||
: 0;
|
||||
|
||||
return ['esunReward' => [
|
||||
'logged_in' => $customerId > 0,
|
||||
'balance' => $balance,
|
||||
'applied_points' => (int)$quote->getData('reward_points_used'),
|
||||
'maximum' => $this->config->maxCheckoutPoints((int)$quote->getStoreId()),
|
||||
'rate' => $this->config->redemptionRate((int)$quote->getStoreId()),
|
||||
]];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model;
|
||||
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Store\Model\ScopeInterface;
|
||||
|
||||
class Config
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ScopeConfigInterface $scopeConfig,
|
||||
private readonly Json $serializer
|
||||
) {}
|
||||
|
||||
public function isEnabled(?int $storeId = null): bool { return $this->flag('general/enabled', $storeId); }
|
||||
public function registrationPoints(?int $storeId = null): int { return (int)$this->earningRule('registration', $storeId)['points']; }
|
||||
public function firstAddressPoints(?int $storeId = null): int { return (int)$this->earningRule('first_shipping_address', $storeId)['points']; }
|
||||
public function orderRate(?int $storeId = null): float { return (float)$this->earningRule('order_earned', $storeId)['points']; }
|
||||
public function reviewTextPoints(?int $storeId = null): int { return (int)$this->earningRule('review_text', $storeId)['points']; }
|
||||
public function reviewMediaPoints(?int $storeId = null): int { return (int)$this->earningRule('review_media', $storeId)['points']; }
|
||||
public function socialPoints(?int $storeId = null): int { return (int)$this->earningRule('social_share', $storeId)['points']; }
|
||||
public function redemptionRate(?int $storeId = null): int { return max(1, $this->int('spending/points_per_dollar', $storeId)); }
|
||||
public function maxCheckoutPoints(?int $storeId = null): int { return $this->int('spending/max_checkout_points', $storeId); }
|
||||
public function reviewEligibility(?int $storeId = null): string { return (string)$this->value('review/eligibility', $storeId); }
|
||||
public function silverThreshold(?int $storeId = null): float { return $this->float('tiers/silver_threshold', $storeId); }
|
||||
public function silverMultiplier(?int $storeId = null): float { return $this->float('tiers/silver_multiplier', $storeId); }
|
||||
public function goldThreshold(?int $storeId = null): float { return $this->float('tiers/gold_threshold', $storeId); }
|
||||
public function goldMultiplier(?int $storeId = null): float { return $this->float('tiers/gold_multiplier', $storeId); }
|
||||
|
||||
/** @return array{code: string, points: float, name: string, reason: string} */
|
||||
public function earningRule(string $code, ?int $storeId = null): array
|
||||
{
|
||||
$rules = $this->earningRules($storeId);
|
||||
return $rules[$code] ?? ['code' => $code, 'points' => 0.0, 'name' => ucwords(str_replace('_', ' ', $code)), 'reason' => ''];
|
||||
}
|
||||
|
||||
/** @return array<string, array{code: string, points: float, name: string, reason: string}> */
|
||||
public function earningRules(?int $storeId = null): array
|
||||
{
|
||||
$defaults = [
|
||||
'registration' => ['points' => (float)$this->int('earning/registration_points', $storeId), 'name' => 'Account Registration', 'reason' => 'Account registration reward'],
|
||||
'first_shipping_address' => ['points' => (float)$this->int('earning/first_address_points', $storeId), 'name' => 'First Shipping Address', 'reason' => 'First saved shipping address reward'],
|
||||
'order_earned' => ['points' => $this->float('earning/points_per_dollar', $storeId), 'name' => 'Order Reward', 'reason' => 'Points earned from order %1'],
|
||||
'review_text' => ['points' => (float)$this->int('earning/review_text_points', $storeId), 'name' => 'Product Review', 'reason' => 'Approved product review reward'],
|
||||
'review_media' => ['points' => (float)$this->int('earning/review_media_points', $storeId), 'name' => 'Product Review with Media', 'reason' => 'Approved product review reward'],
|
||||
'social_share' => ['points' => (float)$this->int('earning/social_share_points', $storeId), 'name' => 'Social Share', 'reason' => 'Social share reward'],
|
||||
];
|
||||
foreach ($defaults as $code => &$rule) {
|
||||
$rule['code'] = $code;
|
||||
}
|
||||
unset($rule);
|
||||
|
||||
$value = $this->value('earning/items', $storeId);
|
||||
try {
|
||||
$items = is_array($value) ? $value : (empty($value) ? [] : $this->serializer->unserialize((string)$value));
|
||||
} catch (\InvalidArgumentException) {
|
||||
$items = [];
|
||||
}
|
||||
if (!is_array($items) || !$items) {
|
||||
return $defaults;
|
||||
}
|
||||
|
||||
$rules = [];
|
||||
foreach ($items as $item) {
|
||||
if (!is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
$code = strtolower(trim((string)($item['code'] ?? '')));
|
||||
$name = trim((string)($item['name'] ?? ''));
|
||||
if ($code === '' || $name === '') {
|
||||
continue;
|
||||
}
|
||||
$rules[$code] = [
|
||||
'code' => $code,
|
||||
'points' => max(0.0, (float)($item['points'] ?? 0)),
|
||||
'name' => $name,
|
||||
'reason' => trim((string)($item['reason'] ?? '')),
|
||||
];
|
||||
}
|
||||
return $rules ?: $defaults;
|
||||
}
|
||||
|
||||
/** @return array<int, array{code: string, label: string, threshold: float, multiplier: float}> */
|
||||
public function tiers(?int $storeId = null): array
|
||||
{
|
||||
$value = $this->value('tiers/items', $storeId);
|
||||
try {
|
||||
$items = is_array($value) ? $value : (empty($value) ? [] : $this->serializer->unserialize((string)$value));
|
||||
} catch (\InvalidArgumentException) {
|
||||
$items = [];
|
||||
}
|
||||
if (!is_array($items)) {
|
||||
$items = [];
|
||||
}
|
||||
|
||||
$tiers = [];
|
||||
foreach ($items as $item) {
|
||||
if (!is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
$label = trim((string)($item['label'] ?? ''));
|
||||
$threshold = max(0.0, (float)($item['threshold'] ?? 0));
|
||||
$multiplier = (float)($item['multiplier'] ?? 0);
|
||||
if ($label === '' || $multiplier <= 0) {
|
||||
continue;
|
||||
}
|
||||
$tiers[] = [
|
||||
'code' => strtolower((string)preg_replace('/[^a-z0-9]+/i', '_', $label)),
|
||||
'label' => $label,
|
||||
'threshold' => $threshold,
|
||||
'multiplier' => $multiplier,
|
||||
];
|
||||
}
|
||||
|
||||
if (!$tiers) {
|
||||
$tiers = [
|
||||
['code' => 'bronze', 'label' => 'Bronze Maker', 'threshold' => 0.0, 'multiplier' => 1.0],
|
||||
['code' => 'silver', 'label' => 'Silver Maker', 'threshold' => $this->silverThreshold($storeId), 'multiplier' => $this->silverMultiplier($storeId)],
|
||||
['code' => 'gold', 'label' => 'Gold Maker', 'threshold' => $this->goldThreshold($storeId), 'multiplier' => $this->goldMultiplier($storeId)],
|
||||
];
|
||||
}
|
||||
|
||||
usort($tiers, static fn(array $left, array $right): int => $left['threshold'] <=> $right['threshold']);
|
||||
return $tiers;
|
||||
}
|
||||
|
||||
private function value(string $path, ?int $storeId): mixed { return $this->scopeConfig->getValue('esun_reward/' . $path, ScopeInterface::SCOPE_STORE, $storeId); }
|
||||
private function int(string $path, ?int $storeId): int { return max(0, (int)$this->value($path, $storeId)); }
|
||||
private function float(string $path, ?int $storeId): float { return max(0.0, (float)$this->value($path, $storeId)); }
|
||||
private function flag(string $path, ?int $storeId): bool { return $this->scopeConfig->isSetFlag('esun_reward/' . $path, ScopeInterface::SCOPE_STORE, $storeId); }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model\Config\Backend;
|
||||
|
||||
use Magento\Config\Model\Config\Backend\Serialized\ArraySerialized;
|
||||
use Magento\Config\Model\ResourceModel\Config\Data as ConfigResource;
|
||||
use Magento\Config\Model\ResourceModel\Config\Data\Collection as ConfigCollection;
|
||||
|
||||
class EarningRuleItems extends ArraySerialized
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_setResourceModel(ConfigResource::class, ConfigCollection::class);
|
||||
}
|
||||
|
||||
public function beforeSave()
|
||||
{
|
||||
$items = [];
|
||||
$allowedCodes = [
|
||||
'registration', 'first_shipping_address', 'order_earned',
|
||||
'review_text', 'review_media', 'social_share',
|
||||
];
|
||||
$value = $this->getValue();
|
||||
if (is_array($value)) {
|
||||
unset($value['__empty']);
|
||||
foreach ($value as $row) {
|
||||
if (!is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
$code = strtolower(trim((string)($row['code'] ?? '')));
|
||||
$points = max(0.0, (float)($row['points'] ?? 0));
|
||||
$name = trim((string)($row['name'] ?? ''));
|
||||
$reason = trim((string)($row['reason'] ?? ''));
|
||||
if (!in_array($code, $allowedCodes, true) || $name === '') {
|
||||
continue;
|
||||
}
|
||||
$items[$code] = ['code' => $code, 'points' => $points, 'name' => $name, 'reason' => $reason];
|
||||
}
|
||||
}
|
||||
$this->setValue(array_values($items));
|
||||
return parent::beforeSave();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model\Config\Backend;
|
||||
|
||||
use Magento\Config\Model\Config\Backend\Serialized\ArraySerialized;
|
||||
use Magento\Config\Model\ResourceModel\Config\Data as ConfigResource;
|
||||
use Magento\Config\Model\ResourceModel\Config\Data\Collection as ConfigCollection;
|
||||
|
||||
class TierItems extends ArraySerialized
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_setResourceModel(ConfigResource::class, ConfigCollection::class);
|
||||
}
|
||||
|
||||
public function beforeSave()
|
||||
{
|
||||
$items = [];
|
||||
$value = $this->getValue();
|
||||
if (is_array($value)) {
|
||||
unset($value['__empty']);
|
||||
foreach ($value as $row) {
|
||||
if (!is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
$label = trim((string)($row['label'] ?? ''));
|
||||
$threshold = max(0.0, (float)($row['threshold'] ?? 0));
|
||||
$multiplier = (float)($row['multiplier'] ?? 0);
|
||||
if ($label === '' || $multiplier <= 0) {
|
||||
continue;
|
||||
}
|
||||
$items[] = ['label' => $label, 'threshold' => $threshold, 'multiplier' => $multiplier];
|
||||
}
|
||||
}
|
||||
|
||||
usort($items, static fn(array $left, array $right): int => $left['threshold'] <=> $right['threshold']);
|
||||
$this->setValue($items);
|
||||
|
||||
return parent::beforeSave();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model\Config\Source;
|
||||
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class ReviewEligibility implements OptionSourceInterface
|
||||
{
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
return [
|
||||
['value' => 'payment_success', 'label' => __('Payment Successful')],
|
||||
['value' => 'order_complete', 'label' => __('Order Complete')],
|
||||
['value' => 'confirmed_receipt', 'label' => __('Customer Confirmed Receipt')],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model\Import;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Framework\Stdlib\StringUtils;
|
||||
use Magento\ImportExport\Model\Import as ImportModel;
|
||||
use Magento\ImportExport\Model\Import\AbstractEntity;
|
||||
use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface;
|
||||
use Magento\ImportExport\Model\ImportFactory;
|
||||
use Magento\ImportExport\Model\ResourceModel\Helper;
|
||||
|
||||
class Reward extends AbstractEntity
|
||||
{
|
||||
public const ENTITY_CODE = 'esun_reward';
|
||||
public const COL_EMAIL = 'email';
|
||||
public const COL_TIER = 'member_tier';
|
||||
public const COL_POINTS = 'points';
|
||||
private const ERROR_EMAIL = 'rewardInvalidEmail';
|
||||
private const ERROR_TIER = 'rewardInvalidTier';
|
||||
private const ERROR_POINTS = 'rewardInvalidPoints';
|
||||
private const ERROR_NOT_FOUND = 'rewardCustomerNotFound';
|
||||
private const ERROR_MULTIPLE = 'rewardCustomerMultipleWebsites';
|
||||
private const ERROR_DUPLICATE = 'rewardDuplicateEmail';
|
||||
private const TIER_MAP = [
|
||||
'VIP I' => 'bronze', 'BRONZE MAKER' => 'bronze',
|
||||
'VIP II' => 'silver', 'SILVER MAKER' => 'silver',
|
||||
'VIP III' => 'gold', 'GOLD MAKER' => 'gold',
|
||||
];
|
||||
|
||||
protected $needColumnCheck = true;
|
||||
protected $validColumnNames = [self::COL_EMAIL, self::COL_TIER, self::COL_POINTS];
|
||||
protected $_availableBehaviors = [ImportModel::BEHAVIOR_APPEND];
|
||||
protected $masterAttributeCode = self::COL_EMAIL;
|
||||
private array $seenEmails = [];
|
||||
|
||||
public function __construct(
|
||||
StringUtils $string,
|
||||
ScopeConfigInterface $scopeConfig,
|
||||
ImportFactory $importFactory,
|
||||
Helper $resourceHelper,
|
||||
ResourceConnection $resource,
|
||||
ProcessingErrorAggregatorInterface $errorAggregator,
|
||||
private readonly ResourceConnection $rewardResource,
|
||||
private readonly BalanceManager $balances,
|
||||
array $data = [],
|
||||
?Json $serializer = null
|
||||
) {
|
||||
parent::__construct($string, $scopeConfig, $importFactory, $resourceHelper, $resource, $errorAggregator, $data, $serializer);
|
||||
$this->addMessageTemplate(self::ERROR_EMAIL, 'Email format is invalid');
|
||||
$this->addMessageTemplate(self::ERROR_TIER, 'Member tier is invalid; use VIP I/II/III or Bronze/Silver/Gold Maker');
|
||||
$this->addMessageTemplate(self::ERROR_POINTS, 'Points must be a non-negative integer');
|
||||
$this->addMessageTemplate(self::ERROR_NOT_FOUND, '未找到该邮箱对应的客户');
|
||||
$this->addMessageTemplate(self::ERROR_MULTIPLE, '该邮箱存在于多个 Website,请人工确认归属');
|
||||
$this->addMessageTemplate(self::ERROR_DUPLICATE, 'CSV 中邮箱重复');
|
||||
}
|
||||
|
||||
public function getEntityTypeCode(): string { return self::ENTITY_CODE; }
|
||||
|
||||
public function validateRow(array $rowData, $rowNumber): bool
|
||||
{
|
||||
if (isset($this->_validatedRows[$rowNumber])) {
|
||||
return !$this->getErrorAggregator()->isRowInvalid($rowNumber);
|
||||
}
|
||||
$this->_validatedRows[$rowNumber] = true;
|
||||
$email = strtolower(trim((string)($rowData[self::COL_EMAIL] ?? '')));
|
||||
$tier = $this->normalizeTier((string)($rowData[self::COL_TIER] ?? ''));
|
||||
$points = trim((string)($rowData[self::COL_POINTS] ?? ''));
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $this->addRowError(self::ERROR_EMAIL, $rowNumber, self::COL_EMAIL); }
|
||||
if ($tier === null) { $this->addRowError(self::ERROR_TIER, $rowNumber, self::COL_TIER); }
|
||||
if (!preg_match('/^\d+$/', $points)) { $this->addRowError(self::ERROR_POINTS, $rowNumber, self::COL_POINTS); }
|
||||
if ($email !== '') {
|
||||
if (isset($this->seenEmails[$email])) { $this->addRowError(self::ERROR_DUPLICATE, $rowNumber, self::COL_EMAIL); }
|
||||
$this->seenEmails[$email] = true;
|
||||
$count = count($this->findCustomers($email));
|
||||
if ($count === 0) { $this->addRowError(self::ERROR_NOT_FOUND, $rowNumber, self::COL_EMAIL); }
|
||||
if ($count > 1) { $this->addRowError(self::ERROR_MULTIPLE, $rowNumber, self::COL_EMAIL); }
|
||||
}
|
||||
return !$this->getErrorAggregator()->isRowInvalid($rowNumber);
|
||||
}
|
||||
|
||||
protected function _importData()
|
||||
{
|
||||
$batchId = 'admin-import-' . gmdate('YmdHis') . '-' . bin2hex(random_bytes(4));
|
||||
while ($bunch = $this->_dataSourceModel->getNextUniqueBunch($this->getIds())) {
|
||||
foreach ($bunch as $rowNumber => $rowData) {
|
||||
if (!$this->validateRow($rowData, $rowNumber)) { continue; }
|
||||
$email = strtolower(trim((string)$rowData[self::COL_EMAIL]));
|
||||
$customers = $this->findCustomers($email);
|
||||
$customer = reset($customers);
|
||||
$this->balances->importLegacySnapshot(
|
||||
(int)$customer['entity_id'], (int)$customer['website_id'], (int)$rowData[self::COL_POINTS],
|
||||
(string)$this->normalizeTier((string)$rowData[self::COL_TIER]), $batchId,
|
||||
['source' => 'admin_import', 'source_row' => $rowNumber, 'source_email' => $email]
|
||||
);
|
||||
$this->countItemsUpdated++;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private function normalizeTier(string $value): ?string
|
||||
{
|
||||
$label = strtoupper((string)preg_replace('/\s+/', ' ', trim($value)));
|
||||
return self::TIER_MAP[$label] ?? null;
|
||||
}
|
||||
|
||||
/** @return array<int,array{entity_id:string,website_id:string}> */
|
||||
private function findCustomers(string $email): array
|
||||
{
|
||||
$table = $this->rewardResource->getTableName('customer_entity');
|
||||
return $this->rewardResource->getConnection()->fetchAll(
|
||||
$this->rewardResource->getConnection()->select()
|
||||
->from($table, ['entity_id', 'website_id'])
|
||||
->where('LOWER(email) = ?', strtolower(trim($email)))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model;
|
||||
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
|
||||
class ReservationManager
|
||||
{
|
||||
public function __construct(private readonly ResourceConnection $resource, private readonly BalanceManager $balances) {}
|
||||
public function reserve(int $customerId, int $websiteId, int $quoteId, int $points): void
|
||||
{
|
||||
$connection = $this->resource->getConnection(); $table = $this->resource->getTableName('esun_reward_reservation');
|
||||
$connection->beginTransaction();
|
||||
try {
|
||||
$accountTable = $this->resource->getTableName('esun_reward_account');
|
||||
$connection->insertOnDuplicate($accountTable, ['customer_id' => $customerId, 'website_id' => $websiteId], []);
|
||||
$account = $connection->fetchRow($connection->select()->from($accountTable)->where('customer_id = ?', $customerId)->where('website_id = ?', $websiteId)->forUpdate(true));
|
||||
$otherReserved = (int)$connection->fetchOne($connection->select()->from($table, ['SUM(points)'])->where('customer_id = ?', $customerId)->where('status = ?', 'active')->where('quote_id != ?', $quoteId)->where('expires_at IS NULL OR expires_at > ?', date('Y-m-d H:i:s')));
|
||||
if ($points > max(0, (int)$account['balance'] - $otherReserved)) { throw new LocalizedException(__('You do not have enough available reward points.')); }
|
||||
if ($points <= 0) { $connection->delete($table, ['quote_id = ?' => $quoteId]); }
|
||||
else { $connection->insertOnDuplicate($table, ['customer_id' => $customerId, 'quote_id' => $quoteId, 'points' => $points, 'status' => 'active', 'expires_at' => date('Y-m-d H:i:s', time() + 86400)], ['customer_id', 'points', 'status', 'expires_at']); }
|
||||
$connection->commit();
|
||||
} catch (\Throwable $e) { if ($connection->getTransactionLevel() > 0) { $connection->rollBack(); } throw $e; }
|
||||
}
|
||||
public function markUsed(int $quoteId): void { $this->resource->getConnection()->update($this->resource->getTableName('esun_reward_reservation'), ['status' => 'used'], ['quote_id = ?' => $quoteId]); }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model;
|
||||
|
||||
class TierResolver
|
||||
{
|
||||
public function __construct(private readonly Config $config) {}
|
||||
|
||||
public function resolve(float $lifetimeSpend, ?int $storeId = null): array
|
||||
{
|
||||
$tiers = $this->config->tiers($storeId);
|
||||
$current = $tiers[0];
|
||||
$nextThreshold = null;
|
||||
|
||||
foreach ($tiers as $tier) {
|
||||
if ($lifetimeSpend >= $tier['threshold']) {
|
||||
$current = $tier;
|
||||
continue;
|
||||
}
|
||||
$nextThreshold = $tier['threshold'];
|
||||
break;
|
||||
}
|
||||
|
||||
return [
|
||||
'code' => $current['code'],
|
||||
'label' => $current['label'],
|
||||
'multiplier' => $current['multiplier'],
|
||||
'next_threshold' => $nextThreshold,
|
||||
];
|
||||
}
|
||||
|
||||
public function resolveEffective(string $savedTierCode, float $lifetimeSpend, ?int $storeId = null): array
|
||||
{
|
||||
$tiers = $this->config->tiers($storeId);
|
||||
$computed = $this->resolve($lifetimeSpend, $storeId);
|
||||
$byCode = [];
|
||||
foreach ($tiers as $position => $tier) {
|
||||
$byCode[$tier['code']] = ['position' => $position, 'tier' => $tier];
|
||||
}
|
||||
if (!isset($byCode[$savedTierCode])) {
|
||||
return $computed;
|
||||
}
|
||||
$saved = $byCode[$savedTierCode];
|
||||
$computedPosition = $byCode[$computed['code']]['position'] ?? 0;
|
||||
if ($saved['position'] <= $computedPosition) {
|
||||
return $computed;
|
||||
}
|
||||
$nextThreshold = $tiers[$saved['position'] + 1]['threshold'] ?? null;
|
||||
return [
|
||||
'code' => $saved['tier']['code'],
|
||||
'label' => $saved['tier']['label'],
|
||||
'multiplier' => $saved['tier']['multiplier'],
|
||||
'next_threshold' => $nextThreshold,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model\Total\Quote;
|
||||
|
||||
use Esun\Reward\Model\Config;
|
||||
use Magento\Quote\Api\Data\ShippingAssignmentInterface;
|
||||
use Magento\Quote\Model\Quote;
|
||||
use Magento\Quote\Model\Quote\Address\Total;
|
||||
use Magento\Quote\Model\Quote\Address\Total\AbstractTotal;
|
||||
|
||||
class RewardDiscount extends AbstractTotal
|
||||
{
|
||||
protected $_code = 'reward_discount';
|
||||
public function __construct(private readonly Config $config) {}
|
||||
public function collect(Quote $quote, ShippingAssignmentInterface $shippingAssignment, Total $total): self
|
||||
{
|
||||
parent::collect($quote, $shippingAssignment, $total);
|
||||
|
||||
// A physical quote is collected once for shipping and again for its
|
||||
// empty billing assignment. Do not let the empty pass erase the
|
||||
// reward amount calculated for the shipping address.
|
||||
if (!$shippingAssignment->getItems()) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$points = (int)$quote->getData('reward_points_used');
|
||||
if ($points <= 0 || !$quote->getCustomerId() || !$this->config->isEnabled((int)$quote->getStoreId())) {
|
||||
$quote->setData('reward_discount_amount', 0)->setData('base_reward_discount_amount', 0); return $this;
|
||||
}
|
||||
$baseRequested = $points / $this->config->redemptionRate((int)$quote->getStoreId());
|
||||
$baseMaximum = max(0.0, array_sum($total->getAllBaseTotalAmounts()));
|
||||
$baseDiscount = min($baseRequested, $baseMaximum);
|
||||
$discount = (float)$quote->getStore()->getBaseCurrency()->convert($baseDiscount, $quote->getStore()->getCurrentCurrency());
|
||||
$total->setBaseTotalAmount($this->getCode(), -$baseDiscount); $total->setTotalAmount($this->getCode(), -$discount);
|
||||
$quote->setData('base_reward_discount_amount', $baseDiscount)->setData('reward_discount_amount', $discount);
|
||||
return $this;
|
||||
}
|
||||
public function fetch(Quote $quote, Total $total): array
|
||||
{
|
||||
$amount = (float)$quote->getData('reward_discount_amount');
|
||||
$points = (int)$quote->getData('reward_points_used');
|
||||
return $amount > 0 ? [
|
||||
'code' => $this->getCode(),
|
||||
'title' => __('Points Discount (%1 points)', $points),
|
||||
'value' => -$amount
|
||||
] : [];
|
||||
}
|
||||
public function getLabel(): string { return (string)__('Points Discount'); }
|
||||
}
|
||||
Reference in New Issue
Block a user