This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerVat\Model;
use Magento\Directory\Model\ResourceModel\Country\CollectionFactory;
class EuCountries
{
public const CODES = [
'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE',
'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE',
];
public const RATES = [
'NL' => 21.0,
'AT' => 20.0,
'ES' => 21.0,
'CZ' => 21.0,
'PL' => 23.0,
'FR' => 20.0,
'IT' => 22.0,
'DE' => 19.0,
];
public function __construct(private readonly CollectionFactory $countryCollectionFactory)
{
}
public function isEu(string $countryId): bool
{
return in_array(strtoupper($countryId), self::CODES, true);
}
public function getRate(string $countryId): float
{
return self::RATES[strtoupper($countryId)] ?? 19.0;
}
public function getAppliedRate(string $countryId): float
{
return self::toAppliedRate($this->getRate($countryId));
}
public static function toAppliedRate(float $nominalRate): float
{
return $nominalRate > 0 ? ($nominalRate / (100 + $nominalRate)) * 100 : 0.0;
}
public function getOptions(): array
{
$options = [];
$collection = $this->countryCollectionFactory->create()
->addCountryIdFilter(self::CODES);
foreach ($collection as $country) {
$options[] = ['value' => $country->getCountryId(), 'label' => $country->getName()];
}
usort($options, static fn (array $a, array $b): int => strcasecmp((string)$a['label'], (string)$b['label']));
return $options;
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerVat\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class VatApplication extends AbstractDb
{
protected function _construct(): void
{
$this->_init('esun_customer_vat', 'entity_id');
}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerVat\Model\ResourceModel\VatApplication;
use Esun\CustomerVat\Model\VatApplication as VatApplicationModel;
use Esun\CustomerVat\Model\ResourceModel\VatApplication as VatApplicationResource;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct(): void
{
$this->_init(VatApplicationModel::class, VatApplicationResource::class);
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerVat\Model\Source;
use Esun\CustomerVat\Model\VatApplication;
use Magento\Framework\Data\OptionSourceInterface;
class Status implements OptionSourceInterface
{
public function toOptionArray(): array
{
$options = [];
foreach (VatApplication::getStatuses() as $value => $label) {
$options[] = ['value' => $value, 'label' => $label];
}
return $options;
}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerVat\Model;
class TaxContext
{
public function __construct(
public readonly string $mode,
public readonly float $nominalRate,
public readonly float $appliedRate,
public readonly bool $exempt,
public readonly ?VatApplication $vatApplication = null
) {
}
}
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerVat\Model;
use Magento\Store\Model\StoreManagerInterface;
class TaxContextResolver
{
public const MODE_NO_TAX = 'no_tax';
public const MODE_EU_STANDARD = 'eu_standard_vat';
public const MODE_EU_VAT_REGISTERED = 'eu_vat_registered';
public const MODE_UK_STANDARD = 'uk_standard';
public function __construct(
private readonly StoreManagerInterface $storeManager,
private readonly VatApplicationService $applications,
private readonly EuCountries $euCountries
) {
}
public function resolve(int $storeId, int $customerId, string $shippingCountryId): TaxContext
{
$websiteCode = (string)$this->storeManager->getStore($storeId)->getWebsite()->getCode();
if (in_array($websiteCode, ['uk', 'gb_site'], true)) {
return new TaxContext(
self::MODE_UK_STANDARD,
20.0,
EuCountries::toAppliedRate(20.0),
false
);
}
if (!in_array($websiteCode, ['eu', 'eu_site'], true)) {
return new TaxContext(self::MODE_NO_TAX, 0.0, 0.0, false);
}
$countryId = strtoupper($shippingCountryId);
if (!$this->euCountries->isEu($countryId)) {
return new TaxContext(self::MODE_NO_TAX, 0.0, 0.0, false);
}
$nominalRate = $this->euCountries->getRate($countryId);
$appliedRate = $this->euCountries->getAppliedRate($countryId);
$approvedVat = $this->applications->findApproved($customerId, $countryId);
if ($approvedVat !== null) {
return new TaxContext(
self::MODE_EU_VAT_REGISTERED,
$nominalRate,
$appliedRate,
false,
$approvedVat
);
}
return new TaxContext(self::MODE_EU_STANDARD, $nominalRate, $appliedRate, false);
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerVat\Model;
use Magento\Framework\Model\AbstractModel;
class VatApplication extends AbstractModel
{
public const STATUS_PENDING = 'pending';
public const STATUS_APPROVED = 'approved';
public const STATUS_REJECTED = 'rejected';
protected function _construct(): void
{
$this->_init(\Esun\CustomerVat\Model\ResourceModel\VatApplication::class);
}
public static function getStatuses(): array
{
return [
self::STATUS_PENDING => __('Pending Review'),
self::STATUS_APPROVED => __('Approved'),
self::STATUS_REJECTED => __('Rejected'),
];
}
}
@@ -0,0 +1,128 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerVat\Model;
use Esun\CustomerVat\Model\ResourceModel\VatApplication as VatResource;
use Esun\CustomerVat\Model\ResourceModel\VatApplication\CollectionFactory;
use Magento\Framework\Exception\LocalizedException;
class VatApplicationService
{
public function __construct(
private readonly VatApplicationFactory $applicationFactory,
private readonly VatResource $resource,
private readonly CollectionFactory $collectionFactory,
private readonly EuCountries $euCountries
) {
}
public function getByIdForCustomer(int $id, int $customerId): VatApplication
{
$application = $this->applicationFactory->create();
$this->resource->load($application, $id);
if (!$application->getId() || (int)$application->getData('customer_id') !== $customerId) {
throw new LocalizedException(__('The VAT application no longer exists.'));
}
return $application;
}
public function saveForCustomer(int $customerId, array $data, int $id = 0): VatApplication
{
$companyName = trim((string)($data['company_name'] ?? ''));
$countryId = strtoupper(trim((string)($data['country_id'] ?? '')));
$vatNumber = trim((string)($data['vat_number'] ?? ''));
$normalized = $this->normalize($vatNumber);
if ($companyName === '' || mb_strlen($companyName) > 255) {
throw new LocalizedException(__('Enter a valid company name.'));
}
if (!$this->euCountries->isEu($countryId)) {
throw new LocalizedException(__('Select a valid EU country.'));
}
if (strlen($normalized) < 4 || strlen($normalized) > 64) {
throw new LocalizedException(__('Enter a valid VAT number.'));
}
$duplicate = $this->collectionFactory->create()
->addFieldToFilter('customer_id', $customerId)
->addFieldToFilter('country_id', $countryId)
->addFieldToFilter('normalized_vat_number', $normalized);
if ($id > 0) {
$duplicate->addFieldToFilter('entity_id', ['neq' => $id]);
}
if ($duplicate->getSize()) {
throw new LocalizedException(__('This VAT number has already been submitted for the selected country.'));
}
$application = $id > 0
? $this->getByIdForCustomer($id, $customerId)
: $this->applicationFactory->create()->setData('customer_id', $customerId);
$changed = !$application->getId()
|| (string)$application->getData('company_name') !== $companyName
|| (string)$application->getData('country_id') !== $countryId
|| (string)$application->getData('normalized_vat_number') !== $normalized;
$application->addData([
'company_name' => $companyName,
'country_id' => $countryId,
'vat_number' => $vatNumber,
'normalized_vat_number' => $normalized,
]);
if ($changed) {
$application->addData([
'status' => VatApplication::STATUS_PENDING,
'review_note' => null,
'reviewed_by' => null,
'reviewed_at' => null,
]);
}
$this->resource->save($application);
return $application;
}
public function deleteForCustomer(int $id, int $customerId): void
{
$this->resource->delete($this->getByIdForCustomer($id, $customerId));
}
public function findApproved(int $customerId, string $countryId): ?VatApplication
{
if ($customerId <= 0 || !$this->euCountries->isEu($countryId)) {
return null;
}
$application = $this->collectionFactory->create()
->addFieldToFilter('customer_id', $customerId)
->addFieldToFilter('country_id', strtoupper($countryId))
->addFieldToFilter('status', VatApplication::STATUS_APPROVED)
->setOrder('reviewed_at', 'DESC')
->setPageSize(1)
->getFirstItem();
return $application->getId() ? $application : null;
}
public function getCustomerStatus(int $customerId): string
{
if ($customerId <= 0) {
return 'guest';
}
$statuses = $this->collectionFactory->create()
->addFieldToFilter('customer_id', $customerId)
->getColumnValues('status');
if (in_array(VatApplication::STATUS_APPROVED, $statuses, true)) {
return VatApplication::STATUS_APPROVED;
}
if (in_array(VatApplication::STATUS_PENDING, $statuses, true)) {
return VatApplication::STATUS_PENDING;
}
if (in_array(VatApplication::STATUS_REJECTED, $statuses, true)) {
return VatApplication::STATUS_REJECTED;
}
return 'none';
}
public function normalize(string $vatNumber): string
{
return strtoupper((string)preg_replace('/[^A-Z0-9]/i', '', $vatNumber));
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerVat\Model;
use Magento\Customer\Model\Session;
use Magento\Framework\Url\EncoderInterface;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
class VatPromptProvider
{
public function __construct(
private readonly Session $customerSession,
private readonly StoreManagerInterface $storeManager,
private readonly VatApplicationService $applications,
private readonly UrlInterface $urlBuilder,
private readonly EncoderInterface $urlEncoder
) {
}
public function getData(): array
{
if ((string)$this->storeManager->getWebsite()->getCode() !== 'eu_site') {
return ['show' => false];
}
$loggedIn = $this->customerSession->isLoggedIn();
$status = $this->applications->getCustomerStatus((int)$this->customerSession->getCustomerId());
$show = !$loggedIn || in_array($status, ['none', VatApplication::STATUS_REJECTED], true);
$vatUrl = $this->urlBuilder->getUrl('esun_customer_vat/vat/new');
$applyUrl = $loggedIn ? $vatUrl : $this->urlBuilder->getUrl('customer/account/login', [
'referer' => $this->urlEncoder->encode($vatUrl),
]);
return [
'show' => $show,
'is_logged_in' => $loggedIn,
'status' => $status,
'apply_url' => $applyUrl,
];
}
}