44 lines
2.0 KiB
PHP
44 lines
2.0 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\Reward\Observer;
|
|
|
|
use Esun\Reward\Model\BalanceManager;
|
|
use Esun\Reward\Model\Config;
|
|
use Magento\Framework\App\ResourceConnection;
|
|
use Magento\Framework\Event\Observer;
|
|
use Magento\Framework\Event\ObserverInterface;
|
|
use Magento\Customer\Api\CustomerRepositoryInterface;
|
|
|
|
class AwardFirstAddressPoints implements ObserverInterface
|
|
{
|
|
public function __construct(
|
|
private readonly BalanceManager $balanceManager,
|
|
private readonly Config $config,
|
|
private readonly ResourceConnection $resource,
|
|
private readonly CustomerRepositoryInterface $customers
|
|
) {}
|
|
|
|
public function execute(Observer $observer): void
|
|
{
|
|
$address = $observer->getEvent()->getCustomerAddress();
|
|
$customerId = (int)($address?->getCustomerId() ?? 0);
|
|
if (!$this->config->isEnabled() || $customerId <= 0 || !$this->isComplete($address)) { return; }
|
|
$connection = $this->resource->getConnection();
|
|
$count = (int)$connection->fetchOne($connection->select()->from($this->resource->getTableName('customer_address_entity'), ['COUNT(*)'])->where('parent_id = ?', $customerId));
|
|
if ($count > 1) { return; }
|
|
$websiteId = (int)$this->customers->getById($customerId)->getWebsiteId();
|
|
$rule = $this->config->earningRule('first_shipping_address');
|
|
$this->balanceManager->change($customerId, $websiteId, (int)$rule['points'], 'first_shipping_address', 'first_shipping_address:' . $customerId, [
|
|
'reference_type' => 'customer_address', 'reference_id' => (int)$address->getId(), 'reason' => (string)__($rule['reason'])
|
|
]);
|
|
}
|
|
|
|
private function isComplete(mixed $address): bool
|
|
{
|
|
return $address && trim((string)$address->getCountryId()) !== '' && trim((string)$address->getCity()) !== ''
|
|
&& trim((string)$address->getPostcode()) !== '' && trim((string)$address->getTelephone()) !== ''
|
|
&& count(array_filter((array)$address->getStreet(), static fn ($value) => trim((string)$value) !== '')) > 0;
|
|
}
|
|
}
|