This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,213 @@
<?php
namespace Stemcell\Customer\Model;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Api\Data\ValidationResultsInterfaceFactory;
use Magento\Customer\Api\SessionCleanerInterface;
use Magento\Customer\Helper\View as CustomerViewHelper;
use Magento\Customer\Model\AccountConfirmation;
use Magento\Customer\Model\AddressRegistry;
use Magento\Customer\Model\AuthenticationInterface;
use Magento\Customer\Model\Config\Share as ConfigShare;
use Magento\Customer\Model\Customer;
use Magento\Customer\Model\Customer as CustomerModel;
use Magento\Customer\Model\Customer\CredentialsValidator;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Model\EmailNotificationInterface;
use Magento\Customer\Model\ForgotPasswordToken\GetCustomerByToken;
use Magento\Customer\Model\Metadata\Validator;
use Magento\Customer\Model\ResourceModel\Visitor\CollectionFactory;
use Magento\Directory\Model\AllowedCountries;
use Magento\Framework\Api\ExtensibleDataObjectConverter;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\AuthorizationInterface;
use Magento\Framework\DataObjectFactory as ObjectFactory;
use Magento\Framework\Encryption\EncryptorInterface as Encryptor;
use Magento\Framework\Encryption\Helper\Security;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\State\ExpiredException;
use Magento\Framework\Exception\State\InputMismatchException;
use Magento\Framework\Intl\DateTimeFactory;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Math\Random;
use Magento\Framework\Reflection\DataObjectProcessor;
use Magento\Framework\Registry;
use Magento\Framework\Session\SaveHandlerInterface;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\Framework\Stdlib\DateTime;
use Magento\Framework\Stdlib\StringUtils as StringHelper;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface as PsrLogger;
class AccountManagement extends \Magento\Customer\Model\AccountManagement
{
protected AddressRegistry $addressRegistry;
protected GetCustomerByToken $getByToken;
protected CustomerRegistry $customerRegistry;
protected CredentialsValidator $credentialsValidator;
protected CustomerRepositoryInterface $customerRepository;
protected SessionCleanerInterface $sessionCleaner;
public function __construct(
CustomerFactory $customerFactory,
ManagerInterface $eventManager,
StoreManagerInterface $storeManager,
Random $mathRandom,
Validator $validator,
ValidationResultsInterfaceFactory $validationResultsDataFactory,
AddressRepositoryInterface $addressRepository,
CustomerMetadataInterface $customerMetadataService,
CustomerRegistry $customerRegistry,
PsrLogger $logger,
Encryptor $encryptor,
ConfigShare $configShare,
StringHelper $stringHelper,
CustomerRepositoryInterface $customerRepository,
ScopeConfigInterface $scopeConfig,
TransportBuilder $transportBuilder,
DataObjectProcessor $dataProcessor,
Registry $registry,
CustomerViewHelper $customerViewHelper,
DateTime $dateTime,
Customer $customerModel,
ObjectFactory $objectFactory,
ExtensibleDataObjectConverter $extensibleDataObjectConverter,
CredentialsValidator $credentialsValidator,
DateTimeFactory $dateTimeFactory = null,
AccountConfirmation $accountConfirmation = null,
SessionManagerInterface $sessionManager = null,
SaveHandlerInterface $saveHandler = null,
CollectionFactory $visitorCollectionFactory = null,
SearchCriteriaBuilder $searchCriteriaBuilder = null,
AddressRegistry $addressRegistry,
GetCustomerByToken $getByToken,
AllowedCountries $allowedCountriesReader = null,
SessionCleanerInterface $sessionCleaner,
AuthorizationInterface $authorization = null
) {
parent::__construct($customerFactory, $eventManager, $storeManager, $mathRandom, $validator, $validationResultsDataFactory, $addressRepository, $customerMetadataService, $customerRegistry, $logger, $encryptor, $configShare, $stringHelper, $customerRepository, $scopeConfig, $transportBuilder, $dataProcessor, $registry, $customerViewHelper, $dateTime, $customerModel, $objectFactory, $extensibleDataObjectConverter, $credentialsValidator, $dateTimeFactory, $accountConfirmation, $sessionManager, $saveHandler, $visitorCollectionFactory, $searchCriteriaBuilder, $addressRegistry, $getByToken, $allowedCountriesReader, $sessionCleaner, $authorization);
$this->addressRegistry = $addressRegistry;
$this->getByToken = $getByToken;
$this->customerRegistry = $customerRegistry;
$this->credentialsValidator = $credentialsValidator;
$this->customerRepository = $customerRepository;
$this->sessionCleaner = $sessionCleaner;
}
/**
* Disable Customer Address Validation
*
* @param CustomerInterface $customer
* @throws NoSuchEntityException
*/
protected function disableAddressValidation($customer)
{
foreach ($customer->getAddresses() as $address) {
$addressModel = $this->addressRegistry->retrieve($address->getId());
$addressModel->setShouldIgnoreValidation(true);
}
}
/**
* Set ignore_validation_flag for reset password flow to skip unnecessary address and customer validation
*
* @param Customer $customer
* @return void
*/
protected function setIgnoreValidationFlag($customer)
{
$customer->setData('ignore_validation_flag', true);
}
/**
* Validate the Reset Password Token for a customer.
*
* @param int $customerId
* @param string $resetPasswordLinkToken
*
* @return bool
* @throws ExpiredException If token is expired
* @throws InputException If token or customer id is invalid
* @throws InputMismatchException If token is mismatched
* @throws LocalizedException
* @throws NoSuchEntityException If customer doesn't exist
* @SuppressWarnings(PHPMD.LongVariable)
*/
protected function validateResetPasswordToken($customerId, $resetPasswordLinkToken)
{
if ($customerId !== null && $customerId <= 0) {
throw new InputException(
__(
'Invalid value of "%value" provided for the %fieldName field.',
['value' => $customerId, 'fieldName' => 'customerId']
)
);
}
if ($customerId === null) {
//Looking for the customer.
$customerId = $this->getByToken
->execute($resetPasswordLinkToken)
->getId();
}
if (!is_string($resetPasswordLinkToken) || empty($resetPasswordLinkToken)) {
$params = ['fieldName' => 'resetPasswordLinkToken'];
throw new InputException(__('"%fieldName" is required. Enter and try again.', $params));
}
$customerSecureData = $this->customerRegistry->retrieveSecureData($customerId);
$rpToken = $customerSecureData->getRpToken();
$rpTokenCreatedAt = $customerSecureData->getRpTokenCreatedAt();
if (!Security::compareStrings($rpToken, $resetPasswordLinkToken)) {
throw new InputMismatchException(__('The password token is mismatched. Reset and try again.'));
} elseif ($this->isResetPasswordLinkTokenExpired($rpToken, $rpTokenCreatedAt)) {
throw new ExpiredException(__('The password token is expired. Reset and try again.'));
}
return true;
}
public function resetPassword($email, $resetToken, $newPassword)
{
if (!$email && $resetToken) {
$customer = $this->getByToken->execute($resetToken);
$email = $customer->getEmail();
} else {
$customer = $this->customerRepository->get($email);
}
// No need to validate customer and customer address while saving customer reset password token
$this->disableAddressValidation($customer);
$this->setIgnoreValidationFlag($customer);
//Validate Token and new password strength
if ($resetToken) {
$this->validateResetPasswordToken($customer->getId(), $resetToken);
}
$this->credentialsValidator->checkPasswordDifferentFromEmail(
$email,
$newPassword
);
$this->checkPasswordStrength($newPassword);
//Update secure data
$customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId());
$customerSecure->setRpToken(null);
$customerSecure->setRpTokenCreatedAt(null);
$customerSecure->setPasswordHash($this->createPasswordHash($newPassword));
$this->sessionCleaner->clearFor((int)$customer->getId());
$this->customerRepository->save($customer);
return true;
}
}
@@ -0,0 +1,150 @@
<?php
namespace Stemcell\Customer\Model;
use Stemcell\ChineseDirectory\Model\CollectionFactory;
use Magento\Customer\Api\AddressMetadataInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\AddressInterfaceFactory;
use Magento\Customer\Api\Data\RegionInterfaceFactory;
use Magento\Customer\Model\Address\CustomAttributeListInterface;
use Magento\Customer\Model\CustomerFactory;
use Magento\Directory\Helper\Data;
use Magento\Directory\Model\CountryFactory;
use Magento\Directory\Model\RegionFactory;
use Magento\Eav\Model\Config;
use Magento\Framework\Api\AttributeValueFactory;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\ExtensionAttributesFactory;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Indexer\IndexerRegistry;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Reflection\DataObjectProcessor;
use Magento\Framework\Registry;
class Address extends \Magento\Customer\Model\Address
{
protected CustomAttributeListInterface $attributeList;
protected CollectionFactory $collectionFactory;
public function __construct(
Context $context,
Registry $registry,
ExtensionAttributesFactory $extensionFactory,
AttributeValueFactory $customAttributeFactory,
Data $directoryData,
Config $eavConfig,
\Magento\Customer\Model\Address\Config $addressConfig,
RegionFactory $regionFactory,
CountryFactory $countryFactory,
AddressMetadataInterface $metadataService,
AddressInterfaceFactory $addressDataFactory,
RegionInterfaceFactory $regionDataFactory,
DataObjectHelper $dataObjectHelper,
CustomerFactory $customerFactory,
DataObjectProcessor $dataProcessor,
IndexerRegistry $indexerRegistry,
CollectionFactory $collectionFactory,
AbstractResource $resource = null,
AbstractDb $resourceCollection = null,
array $data = []
) {
$this->collectionFactory = $collectionFactory;
parent::__construct(
$context, $registry,
$extensionFactory,
$customAttributeFactory,
$directoryData,
$eavConfig,
$addressConfig,
$regionFactory,
$countryFactory,
$metadataService,
$addressDataFactory,
$regionDataFactory,
$dataObjectHelper,
$customerFactory,
$dataProcessor,
$indexerRegistry,
$resource,
$resourceCollection,
$data
);
}
/**
* @param String $type
* @param int $administrativeId
* @return \Magento\Framework\DataObject
*/
public function getAdministrativeName(String $type, $administrativeId) {
if ($administrativeId===null){
$this->_logger->error('Argument ($administrativeId) is null, Argument ($type):'.$type);
return new \Magento\Framework\DataObject();
}
if (!in_array(strtolower($type), ['city', 'district', 'town', 'region'])) {
throw new \InvalidArgumentException(__('Invalid parameter type'));
}
$collection = $this->collectionFactory->create(strtolower($type))
->addFieldToFilter('code', $administrativeId)
->addFieldToSelect('*');
if ($type == 'region') {
$collection->addFieldToFilter('country_id', 'CN');
}
return $collection->getFirstItem();
}
public function updateData(AddressInterface $address)
{
// Set all attributes
$attributes = $this->dataProcessor
->buildOutputDataArray($address, AddressInterface::class);
foreach ($attributes as $attributeCode => $attributeData) {
if (AddressInterface::REGION === $attributeCode) {
$this->setRegion($address->getRegion()->getRegion());
$this->setRegionCode($address->getRegion()->getRegionCode());
$this->setRegionId($address->getRegion()->getRegionId());
} else {
$this->setDataUsingMethod($attributeCode, $attributeData);
}
}
if (!$this->getCity()) {
$cityCode = $address->getCustomAttribute('city_code')? $address->getCustomAttribute('city_code')->getValue():null;
$city = $this->getAdministrativeName('city', $cityCode);
$this->setData('city', $city->getData('name'));
}
$this->setData('postcode', '0000000');
$districtCode = $address->getCustomAttribute('district_code')? $address->getCustomAttribute('district_code')->getValue():null;
$district = $this->getAdministrativeName('district', $districtCode);
$this->setCustomAttribute('district', $district->getData('name'));
$districtCode = $address->getCustomAttribute('town_code')? $address->getCustomAttribute('town_code')->getValue():null;
$district = $this->getAdministrativeName('town', $districtCode);
$this->setCustomAttribute('town', $district->getData('name'));
$districtCode = $address->getCustomAttribute('city_code')? $address->getCustomAttribute('city_code')->getValue():null;
$this->setCustomAttribute('city_code', $districtCode);
$districtCode = $address->getCustomAttribute('district_code')? $address->getCustomAttribute('district_code')->getValue():null;
$this->setCustomAttribute('district_code', $districtCode);
$districtCode = $address->getCustomAttribute('town_code')? $address->getCustomAttribute('town_code')->getValue():null;
$this->setCustomAttribute('town_code', $districtCode);
// Need to explicitly set this due to discrepancy in the keys between model and data object
$this->setIsDefaultBilling($address->isDefaultBilling());
$this->setIsDefaultShipping($address->isDefaultShipping());
$customAttributes = $address->getCustomAttributes();
if ($customAttributes !== null) {
foreach ($customAttributes as $attribute) {
$this->setData($attribute->getAttributeCode(), $attribute->getValue());
}
}
return $this;
}
}
@@ -0,0 +1,130 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Stemcell\Customer\Model\Address\Validator;
use Magento\Customer\Model\Address\AbstractAddress;
use Magento\Framework\Validator\NotEmpty;
use Magento\Framework\Validator\ValidatorChain;
use Magento\Directory\Helper\Data;
use Magento\Directory\Model\AllowedCountries;
use Magento\Framework\Escaper;
use Magento\Framework\App\ObjectManager;
use Magento\Store\Model\ScopeInterface;
/**
* Address country and region validator.
*/
class Country extends \Magento\Customer\Model\Address\Validator\Country
{
/**
* @var Escaper
*/
protected $escaper;
/**
* @var Data
*/
protected $directoryData;
/**
* @var AllowedCountries
*/
protected $allowedCountriesReader;
/**
* @param Data $directoryData
* @param AllowedCountries $allowedCountriesReader
* @param Escaper|null $escaper
*/
public function __construct(
Data $directoryData,
AllowedCountries $allowedCountriesReader,
Escaper $escaper = null
) {
$this->directoryData = $directoryData;
$this->allowedCountriesReader = $allowedCountriesReader;
$this->escaper = $escaper ?? ObjectManager::getInstance()->get(
Escaper::class
);
parent::__construct($directoryData, $allowedCountriesReader, $escaper);
}
/**
* @inheritdoc
*/
public function validate(AbstractAddress $address)
{
$errors = $this->validateCountry($address);
if (empty($errors)) {
$errors = $this->validateRegion($address);
}
return $errors;
}
/**
* Validate country existence.
*
* @param AbstractAddress $address
* @return array
*/
private function validateCountry(AbstractAddress $address)
{
$countryId = $address->getCountryId();
$errors = [];
if (!ValidatorChain::is($countryId, NotEmpty::class)) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'countryId']);
} elseif (!in_array($countryId, $this->getWebsiteAllowedCountries($address), true)) {
//Checking if such country exists.
$errors[] = __(
'Invalid value of "%value" provided for the %fieldName field.',
['fieldName' => 'countryId', 'value' => $this->escaper->escapeHtml($countryId)]
);
}
return $errors;
}
/**
* @param AbstractAddress $address
* @return array
* @throws \Magento\Framework\Validator\ValidateException
*/
private function validateRegion(AbstractAddress $address)
{
$errors = [];
$countryId = $address->getCountryId();
$countryModel = $address->getCountryModel();
$regionCollection = $countryModel->getRegionCollection();
$region = $address->getRegion();
$regionId = (string)$address->getRegionId();
$allowedRegions = $regionCollection->getAllIds();
$isRegionRequired = $this->directoryData->isRegionRequired($countryId);
if ($isRegionRequired && empty($allowedRegions) && !ValidatorChain::is($region, NotEmpty::class)) {
//If region is required for country and country doesn't provide regions list
//region must be provided.
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'region']);
} elseif ($allowedRegions && !ValidatorChain::is($regionId, NotEmpty::class) && $isRegionRequired) {
//If country actually has regions and requires you to
//select one then it must be selected.
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'regionId']);
}
return $errors;
}
/**
* Return allowed counties per website.
*
* @param AbstractAddress $address
* @return array
*/
private function getWebsiteAllowedCountries(AbstractAddress $address): array
{
$storeId = $address->getData('store_id');
return $this->allowedCountriesReader->getAllowedCountries(ScopeInterface::SCOPE_STORE, $storeId);
}
}
@@ -0,0 +1,149 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Stemcell\Customer\Model\Address\Validator;
use Magento\Customer\Api\AddressMetadataInterface;
use Magento\Customer\Model\Address\AbstractAddress;
use Magento\Framework\Validator\NotEmpty;
use Magento\Framework\Validator\ValidatorChain;
/**
* Address general fields validator.
*/
class General extends \Magento\Customer\Model\Address\Validator\General
{
/**
* @var \Magento\Eav\Model\Config
*/
protected $eavConfig;
/**
* @var \Magento\Directory\Helper\Data
*/
protected $directoryData;
/**
* @param \Magento\Eav\Model\Config $eavConfig
* @param \Magento\Directory\Helper\Data $directoryData
*/
public function __construct(
\Magento\Eav\Model\Config $eavConfig,
\Magento\Directory\Helper\Data $directoryData
) {
$this->eavConfig = $eavConfig;
$this->directoryData = $directoryData;
parent::__construct($eavConfig, $directoryData);
}
/**
* @inheritdoc
*/
public function validate(AbstractAddress $address)
{
$errors = array_merge(
$this->checkRequiredFields($address),
$this->checkOptionalFields($address)
);
return $errors;
}
/**
* @param AbstractAddress $address
* @return array
* @throws \Magento\Framework\Validator\ValidateException
*/
private function checkRequiredFields(AbstractAddress $address)
{
$errors = [];
if (!ValidatorChain::is($address->getFirstname(), NotEmpty::class)) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'firstname']);
}
if (!ValidatorChain::is($address->getStreetLine(1), NotEmpty::class)) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'street']);
}
return $errors;
}
/**
* @param AbstractAddress $address
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Validator\ValidateException
*/
private function checkOptionalFields(AbstractAddress $address)
{
$this->reloadAddressAttributes($address);
$errors = [];
if ($this->isTelephoneRequired()
&& !ValidatorChain::is($address->getTelephone(), NotEmpty::class)
) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'telephone']);
}
if ($this->isFaxRequired()
&& !ValidatorChain::is($address->getFax(), NotEmpty::class)
) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'fax']);
}
if ($this->isCompanyRequired()
&& !ValidatorChain::is($address->getCompany(), NotEmpty::class)
) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'company']);
}
return $errors;
}
/**
* Check if company field required in configuration.
*
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function isCompanyRequired()
{
return $this->eavConfig->getAttribute('customer_address', 'company')->getIsRequired();
}
/**
* Check if telephone field required in configuration.
*
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function isTelephoneRequired()
{
return $this->eavConfig->getAttribute('customer_address', 'telephone')->getIsRequired();
}
/**
* Check if fax field required in configuration.
*
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function isFaxRequired()
{
return $this->eavConfig->getAttribute('customer_address', 'fax')->getIsRequired();
}
/**
* Reload address attributes for the certain store
*
* @param AbstractAddress $address
* @return void
*/
private function reloadAddressAttributes(AbstractAddress $address): void
{
$attributeSetId = $address->getAttributeSetId() ?: AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS;
$address->setData('attribute_set_id', $attributeSetId);
$this->eavConfig->getEntityAttributes(AddressMetadataInterface::ENTITY_TYPE_ADDRESS, $address);
}
}
@@ -0,0 +1,16 @@
<?php
namespace Stemcell\Customer\Model\Attribute\Source;
use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;
class CustomerType extends AbstractSource
{
public function getAllOptions(): array
{
return $this->_options = [
['label' => __('Distributor'), 'value' => 1],
['label' => __('Personal'), 'value' => 2],
];
}
}
@@ -0,0 +1,24 @@
<?php
namespace Stemcell\Customer\Model\Attribute\Source;
use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;
class ResearchFields extends AbstractSource
{
public function getAllOptions()
{
return $this->_options = [
['label' => __('细胞治疗'), 'value' => __('细胞治疗')],
['label' => __('免疫研究'), 'value' => __('免疫研究')],
['label' => __('抗体筛选'), 'value' => __('抗体筛选')],
['label' => __('多能干细胞'), 'value' => __('多能干细胞')],
['label' => __('间充质干细胞'), 'value' => __('间充质干细胞')],
['label' => __('神经科学'), 'value' => __('神经科学')],
['label' => __('造血干细胞'), 'value' => __('造血干细胞')],
['label' => __('类器官'), 'value' => __('类器官')],
['label' => __('其他'), 'value' => __('其他')],
];
}
}
+139
View File
@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
namespace Stemcell\Customer\Model;
use Magento\Framework\Model\AbstractModel;
use Stemcell\Customer\Api\Data\AvatrInterface;
class Avatr extends AbstractModel implements AvatrInterface
{
/**
* @inheritDoc
*/
public function _construct()
{
$this->_init(\Stemcell\Customer\Model\ResourceModel\Avatr::class);
}
/**
* @inheritDoc
*/
public function getName()
{
return $this->getData(self::NAME);
}
/**
* @inheritDoc
*/
public function setName($name)
{
return $this->setData(self::NAME, $name);
}
/**
* @inheritDoc
*/
public function getTelephone()
{
return $this->getData(self::TELEPHONE);
}
/**
* @inheritDoc
*/
public function setTelephone($telephone)
{
return $this->setData(self::TELEPHONE, $telephone);
}
/**
* @inheritDoc
*/
public function getFavoriteVehicle()
{
return $this->getData(self::FAVORITE_VEHICLE);
}
/**
* @inheritDoc
*/
public function setFavoriteVehicle($favoriteVehicle)
{
return $this->setData(self::FAVORITE_VEHICLE, $favoriteVehicle);
}
/**
* @inheritDoc
*/
public function getProvinceId()
{
return $this->getData(self::PROVINCE_ID);
}
/**
* @inheritDoc
*/
public function setProvinceId($provinceId)
{
return $this->setData(self::PROVINCE_ID, $provinceId);
}
/**
* @inheritDoc
*/
public function getCityId()
{
return $this->getData(self::CITY_ID);
}
/**
* @inheritDoc
*/
public function setCityId($cityId)
{
return $this->setData(self::CITY_ID, $cityId);
}
/**
* @inheritDoc
*/
public function getIsSent()
{
return $this->getData(self::IS_SENT);
}
/**
* @inheritDoc
*/
public function setIsSent($isSent)
{
return $this->setData(self::IS_SENT, $isSent);
}
/**
* @inheritDoc
*/
public function getCreatedAt()
{
return $this->getData(self::CREATED_AT);
}
/**
* @inheritDoc
*/
public function getResponse()
{
return $this->getData(self::RESPONSE);
}
/**
* @inheritDoc
*/
public function setResponse(string $response)
{
return $this->setData(self::RESPONSE, $response);
}
}
@@ -0,0 +1,159 @@
<?php
declare(strict_types=1);
namespace Stemcell\Customer\Model;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;
use Stemcell\Customer\Api\AvatrRepositoryInterface;
use Stemcell\Customer\Api\Data\AvatrInterface;
use Stemcell\Customer\Api\Data\AvatrInterfaceFactory;
use Stemcell\Customer\Api\Data\AvatrSearchResultsInterfaceFactory;
use Stemcell\Customer\Model\ResourceModel\Avatr as ResourceAvatr;
use Stemcell\Customer\Model\ResourceModel\Avatr\CollectionFactory as AvatrCollectionFactory;
class AvatrRepository implements AvatrRepositoryInterface
{
/**
* @var CollectionProcessorInterface
*/
protected $collectionProcessor;
/**
* @var AvatrInterfaceFactory
*/
protected $avatrFactory;
/**
* @var ResourceAvatr
*/
protected $resource;
/**
* @var AvatrCollectionFactory
*/
protected $avatrCollectionFactory;
/**
* @var Avatr
*/
protected $searchResultsFactory;
/**
* @param ResourceAvatr $resource
* @param AvatrInterfaceFactory $avatrFactory
* @param AvatrCollectionFactory $avatrCollectionFactory
* @param AvatrSearchResultsInterfaceFactory $searchResultsFactory
* @param CollectionProcessorInterface $collectionProcessor
*/
public function __construct(
ResourceAvatr $resource,
AvatrInterfaceFactory $avatrFactory,
AvatrCollectionFactory $avatrCollectionFactory,
AvatrSearchResultsInterfaceFactory $searchResultsFactory,
CollectionProcessorInterface $collectionProcessor
) {
$this->resource = $resource;
$this->avatrFactory = $avatrFactory;
$this->avatrCollectionFactory = $avatrCollectionFactory;
$this->searchResultsFactory = $searchResultsFactory;
$this->collectionProcessor = $collectionProcessor;
}
/**
* @inheritDoc
*/
public function save(AvatrInterface $avatr)
{
try {
$this->resource->save($avatr);
} catch (\Exception $exception) {
throw new CouldNotSaveException(__(
'Could not save the avatr: %1',
$exception->getMessage()
));
}
return $avatr;
}
/**
* @inheritDoc
*/
public function get($avatrId)
{
$avatr = $this->avatrFactory->create();
$this->resource->load($avatr, $avatrId);
if (!$avatr->getId()) {
throw new NoSuchEntityException(__('Avatr with id "%1" does not exist.', $avatrId));
}
return $avatr;
}
/**
* @inheritDoc
*/
public function getList(
\Magento\Framework\Api\SearchCriteriaInterface $criteria
) {
$collection = $this->avatrCollectionFactory->create();
$this->collectionProcessor->process($criteria, $collection);
$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($criteria);
$items = [];
foreach ($collection as $model) {
$items[] = $model;
}
$searchResults->setItems($items);
$searchResults->setTotalCount($collection->getSize());
return $searchResults;
}
/**
* @inheritDoc
*/
public function delete(AvatrInterface $avatr)
{
try {
$avatrModel = $this->avatrFactory->create();
$this->resource->load($avatrModel, $avatr->getAvatrId());
$this->resource->delete($avatrModel);
} catch (\Exception $exception) {
throw new CouldNotDeleteException(__(
'Could not delete the Avatr: %1',
$exception->getMessage()
));
}
return true;
}
/**
* @inheritDoc
*/
public function deleteById($avatrId)
{
return $this->delete($this->get($avatrId));
}
/**
* @param string $telephone
* @param string $model
* @return AvatrInterface
*/
public function getByTelephone(string $telephone, string $model): AvatrInterface
{
$collection = $this->avatrCollectionFactory->create();
$collection->addFieldToFilter('telephone', $telephone)
->addFieldToFilter('favorite_vehicle', $model)
->setItemObjectClass(Avatr::class);
return $collection->getFirstItem();
}
}
@@ -0,0 +1,8 @@
<?php
namespace Stemcell\Customer\Model;
class Customer
{
const EMAIL_DOMAIN = '@placeholder.com';
const MOBILE_PATTERN = '/^(?:\+?86)?1(?:3\d{3}|5[^4\D]\d{2}|8\d{3}|7(?:[0-35-9]\d{2}|4(?:0\d|1[0-2]|9\d))|9[0-35-9]\d{2}|6[2567]\d{2}|4(?:(?:10|4[01])\d{3}|[68]\d{4}|[579]\d{2}))\d{6}$/';
}
@@ -0,0 +1,67 @@
<?php
namespace Stemcell\Customer\Model\Data;
use Stemcell\Customer\Api\Data\Http;
use Magento\Framework\DataObject;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Setup\Module\I18n\Dictionary\Phrase;
class JsonResponse extends DataObject implements Http\JsonResponse
{
protected bool $errors = false;
protected array $message = [];
protected Json $jsonSerializer;
public function __construct(
Json $jsonSerializer,
array $data = []
) {
$this->jsonSerializer = $jsonSerializer;
parent::__construct($data);
}
public function setErrors(bool $status = false): self
{
$this->errors = $status;
return $this;
}
public function setMessages(array $message): self
{
$this->message = array_merge($this->message, $message);
return $this;
}
public function setData($key, $value = null): self
{
if (is_array($key)) {
$this->_data = array_merge($this->_data, $key);
} else {
parent::setData($key, $value);
}
return $this;
}
public function toArray(array $keys = []): array
{
return [
'error' => $this->errors,
'message' =>array_values($this->message),
'data' => $this->_data
];
}
public function getErrors(): bool
{
return $this->errors;
}
public function getMessages(): array
{
return $this->message;
}
}
+130
View File
@@ -0,0 +1,130 @@
<?php
declare(strict_types=1);
namespace Stemcell\Customer\Model;
use Magento\Framework\Model\AbstractModel;
use Stemcell\Customer\Api\Data\LabInterface;
class Lab extends AbstractModel implements LabInterface
{
/**
* @inheritDoc
*/
public function _construct()
{
$this->_init(\Stemcell\Customer\Model\ResourceModel\Lab::class);
}
/**
* @inheritDoc
*/
public function getLabCode()
{
return $this->getData(self::LAB_CODE);
}
/**
* @inheritDoc
*/
public function setLabCode($labCode)
{
return $this->setData(self::LAB_CODE, $labCode);
}
/**
* @inheritDoc
*/
public function getBookingAccount()
{
return $this->getData(self::BOOKING_ACCOUNT);
}
/**
* @inheritDoc
*/
public function setBookingAccount($bookingAccount)
{
return $this->setData(self::BOOKING_ACCOUNT, $bookingAccount);
}
/**
* @inheritDoc
*/
public function getPiSapId()
{
return $this->getData(self::PI_SAP_ID);
}
/**
* @inheritDoc
*/
public function setPiSapId($piSapId)
{
return $this->setData(self::PI_SAP_ID, $piSapId);
}
/**
* @inheritDoc
*/
public function getVendorName()
{
return $this->getData(self::VENDOR_NAME);
}
/**
* @inheritDoc
*/
public function setVendorName($vendorName)
{
return $this->setData(self::VENDOR_NAME, $vendorName);
}
/**
* @inheritDoc
*/
public function getIsActive()
{
return $this->getData(self::IS_ACTIVE);
}
/**
* @inheritDoc
*/
public function setIsActive($isActive)
{
return $this->setData(self::IS_ACTIVE, $isActive);
}
public function getLabId()
{
return $this->getData(self::LAB_ID);
}
/**
* @inheritDoc
*/
public function setLabId(int $labId)
{
return $this->setData(self::LAB_ID, $labId);
}
/**
* @param int $salespersonId
* @return LabInterface
*/
public function setSalespersonId(int $salespersonId): LabInterface
{
return $this->setData(self::SALESPERSON_ID, $salespersonId);
}
/**
* @return int
*/
public function getSalespersonId()
{
return $this->getData(self::SALESPERSON_ID);
}
}
@@ -0,0 +1,178 @@
<?php
namespace Stemcell\Customer\Model\Lab;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Ui\Component\MassAction\Filter;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Stemcell\Customer\Model\ResourceModel\Lab\CollectionFactory as LabCollectionFactory;
use Magento\Framework\Filesystem;
use Stemcell\Customer\Model\ResourceModel\Salesperson\CollectionFactory as SalespersonCollectionFactory;
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory as CustomerCollectionFactory;
use Stemcell\Customer\Model\Salesperson;
use Magento\Customer\Model\ResourceModel\Group\CollectionFactory as GroupCollectionFactory;
class Export
{
protected Filesystem\Directory\WriteInterface $directory;
protected array $salesperson = [];
protected array $dealers = [];
const VENDOR_CUSTOMER_GROUP_CODE = [
'STEMCELL CN 经销商组',
'库存查询组',
];
public function __construct(
protected Filter $filter,
protected LabCollectionFactory $labCollectionFactory,
protected Filesystem $filesystem,
protected Filesystem\DirectoryList $directoryList,
protected SalespersonCollectionFactory $salespersonCollectionFactory,
protected CustomerCollectionFactory $customerCollectionFactory,
protected GroupCollectionFactory $groupCollectionFactory,
) {
$this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
}
protected function getSalesperson()
{
if (!empty($this->salesperson)) {
return $this->salesperson;
}
$collection = $this->salespersonCollectionFactory->create()->addFieldToSelect('*');
foreach ($collection as $salesperson) {
/* @var $salesperson Salesperson */
$this->salesperson[$salesperson->getId()] = $salesperson->getName();
}
return $this->salesperson;
}
protected function getDealers()
{
if (!empty($this->dealers)) {
return $this->dealers;
}
$groups = $this->groupCollectionFactory->create()
->addFieldToFilter('customer_group_code', ['in' => self::VENDOR_CUSTOMER_GROUP_CODE]);
$collection = $this->customerCollectionFactory->create()->addAttributeToSelect('firstname')
->addAttributeToFilter('group_id', ['in' => $groups->getColumnValues('customer_group_id')]);
foreach ($collection as $customer) {
$this->dealers[$customer->getEntityId()] = $customer->getFirstname();
}
return $this->dealers;
}
public function getExcelFile()
{
$this->directory->create('export');
$file = 'export/Labs-'.date("YmdH:i:s") . '.xlsx';
$filePath = $this->directoryList->getPath('var').'/'.$file;
$this->getSalesperson();
$this->getDealers();
$spreadSheet = new Spreadsheet();
$writer = IOFactory::createWriter($spreadSheet, 'Xlsx');
$worksheet = $spreadSheet->getActiveSheet();
$styles = [
'alignment' => [
'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
],
];
$columnIndex = 'A';
$headers = $this->getHeaders();
foreach ($headers as $row) {
$cell = $worksheet->getCell($columnIndex.'1');
$cell->getAppliedStyle()->applyFromArray($styles);
$cell->setValue($row);
$columnIndex++;
}
$rowIndex = 2;
$result = $this->getFilterResult();
foreach ($result as $row) {
/* @var $row \Stemcell\Customer\Model\Lab */
$columnIndex = 'A';
$worksheet->getColumnDimension($columnIndex)->setWidth(15);
$worksheet->getRowDimension($rowIndex)->setRowHeight(20);
foreach (array_keys($headers) as $field) {
$value = '';
if (in_array($field, ['customer_id', 'salesperson_id'])) {
if ($row->getData($field)) {
if ($field == 'customer_id') {
$value = isset($this->dealers[$row->getData($field)])? $this->dealers[$row->getData($field)] : '';
} else {
$value = isset($this->salesperson[$row->getData($field)])? $this->salesperson[$row->getData($field)] : '';
}
}
} elseif ($field == 'is_active') {
$value = $row->getData($field) == 1? '是':'否';
} else {
$value = $row->getData($field);
}
$cell = $worksheet->getCell($columnIndex.$rowIndex);
$cell->setValue($value);
$columnIndex++;
}
$rowIndex++;
}
$writer->save($filePath);
return [
'type' => 'filename',
'value' => $file,
'rm' => true // can delete file after use
];
}
/**
* @return \Stemcell\Customer\Model\Lab[]
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function getFilterResult()
{
/* @var $component \Magento\Ui\Component\Listing */
$component = $this->filter->getComponent();
// md5() here is not for cryptographic use.
// phpcs:ignore Magento2.Security.InsecureFunction
$name = md5(microtime());
$file = 'export/'. $component->getName() . '-'.date("YmdH:i:s") . '.xlsx';
$this->filter->prepareComponent($component);
$this->filter->applySelectionOnTargetProvider();
/* @var $dataProvider \Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider */
$dataProvider = $component->getContext()->getDataProvider();
// $this->directory->create('export');
// $filePath = $this->directoryList->getPath('var').'/'.$file;
$dataProvider->setLimit(0, 100000);
$items = $dataProvider->getSearchResult()->getItems();
return $items;
}
protected function getHeaders()
{
return [
'lab_code' => 'Lab ID',
'booking_account' => 'Booking Account',
'pi_sap_id' => 'PI SAP ID',
'customer_id' => 'Dealer Name',
'salesperson_id' => 'Sales Person',
'is_active' => 'Is Active',
];
}
}
@@ -0,0 +1,180 @@
<?php
declare(strict_types=1);
namespace Stemcell\Customer\Model;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Psr\Log\LoggerInterface;
use Stemcell\Customer\Api\Data\LabInterface;
use Stemcell\Customer\Api\Data\LabInterfaceFactory;
use Stemcell\Customer\Api\Data\LabSearchResultsInterfaceFactory;
use Stemcell\Customer\Api\LabRepositoryInterface;
use Stemcell\Customer\Model\ResourceModel\Lab as ResourceLab;
use Stemcell\Customer\Model\ResourceModel\Lab\CollectionFactory as LabCollectionFactory;
class LabRepository implements LabRepositoryInterface
{
/**
* @var ResourceLab
*/
protected $resource;
/**
* @var LabInterfaceFactory
*/
protected $labFactory;
/**
* @var LabCollectionFactory
*/
protected $labCollectionFactory;
/**
* @var Lab
*/
protected $searchResultsFactory;
/**
* @var CollectionProcessorInterface
*/
protected $collectionProcessor;
protected \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder;
/**
* @param ResourceLab $resource
* @param LabInterfaceFactory $labFactory
* @param LabCollectionFactory $labCollectionFactory
* @param LabSearchResultsInterfaceFactory $searchResultsFactory
* @param CollectionProcessorInterface $collectionProcessor
*/
public function __construct(
ResourceLab $resource,
LabInterfaceFactory $labFactory,
LabCollectionFactory $labCollectionFactory,
LabSearchResultsInterfaceFactory $searchResultsFactory,
CollectionProcessorInterface $collectionProcessor,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
) {
$this->resource = $resource;
$this->labFactory = $labFactory;
$this->labCollectionFactory = $labCollectionFactory;
$this->searchResultsFactory = $searchResultsFactory;
$this->collectionProcessor = $collectionProcessor;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
}
/**
* @inheritDoc
*/
public function save(LabInterface $lab)
{
try {
$this->resource->save($lab);
} catch (\Exception $exception) {
throw new CouldNotSaveException(__(
'Could not save the lab: %1',
$exception->getMessage()
));
}
return $lab;
}
/**
* @inheritDoc
*/
public function get($labId)
{
$lab = $this->labFactory->create();
$this->resource->load($lab, $labId);
if (!$lab->getId()) {
throw new NoSuchEntityException(__('Lab with id "%1" does not exist.', $labId));
}
return $lab;
}
/**
* @inheritDoc
*/
public function getList(
\Magento\Framework\Api\SearchCriteriaInterface $criteria
) {
$collection = $this->labCollectionFactory->create();
$this->collectionProcessor->process($criteria, $collection);
$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($criteria);
$items = [];
foreach ($collection as $model) {
$items[] = $model;
}
$searchResults->setItems($items);
$searchResults->setTotalCount($collection->getSize());
return $searchResults;
}
/**
* @inheritDoc
*/
public function delete(LabInterface $lab)
{
try {
$labModel = $this->labFactory->create();
$this->resource->load($labModel, $lab->getId());
$this->resource->delete($labModel);
} catch (\Exception $exception) {
throw new CouldNotDeleteException(__(
'Could not delete the Lab: %1',
$exception->getMessage()
));
}
return true;
}
/**
* @inheritDoc
*/
public function deleteById($labId)
{
return $this->delete($this->get($labId));
}
/**
* @inheirtDoc
*/
public function getByDealerId(int $customerId): ResourceLab\Collection
{
$collection = $this->labCollectionFactory->create();
$collection->addFieldToFilter('main_table.customer_id', $customerId)
->getSelect()
->joinLeft('customer_entity', 'customer_entity.entity_id=main_table.customer_id', ['customer_name'=>'firstname'])
->joinLeft('salesperson', 'salesperson.salesperson_id=main_table.salesperson_id', ['salesperson_name'=>'salesperson.name'])
->query();
return $collection;
}
/**
* @inheritDoc
*/
public function getByLabCode($labCode)
{
$lab = $this->labFactory->create();
$this->resource->load($lab, $labCode, 'lab_code');
if (!$lab->getId()) {
throw new NoSuchEntityException(__('Lab with id "%1" does not exist.', $labCode));
}
return $lab;
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Stemcell\Customer\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Avatr extends AbstractDb
{
/**
* @inheritDoc
*/
protected function _construct()
{
$this->_init('avatr', 'entity_id');
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Stemcell\Customer\Model\ResourceModel\Avatr;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
/**
* @inheritDoc
*/
protected $_idFieldName = 'entity_id';
/**
* @inheritDoc
*/
protected function _construct()
{
$this->_init(
\Stemcell\Customer\Model\Avatr::class,
\Stemcell\Customer\Model\ResourceModel\Avatr::class
);
}
}
@@ -0,0 +1,104 @@
<?php
namespace Stemcell\Customer\Model\ResourceModel;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Api\Data\CustomerSearchResultsInterfaceFactory;
use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Customer\Model\Customer\NotificationStorage;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Model\Data\CustomerSecureFactory;
use Magento\Customer\Model\Delegation\Storage as DelegatedStorage;
use Magento\Customer\Model\ResourceModel;
use Magento\Customer\Model\ResourceModel\AddressRepository;
use Magento\Customer\Model\ResourceModel\Customer;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\ExtensibleDataObjectConverter;
use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface;
use Magento\Framework\Api\ImageProcessorInterface;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;
use Psr\Log\LoggerInterface;
class CustomerRepository extends ResourceModel\CustomerRepository
{
const MOBILE_PATTERN = '/^(1(([3456789][0-9])|(47)|[8][01236789]))\d{8}$/';
protected CollectionFactory $customerCollectionFactory;
public function __construct(
CustomerFactory $customerFactory,
CustomerSecureFactory $customerSecureFactory,
CustomerRegistry $customerRegistry,
AddressRepository $addressRepository,
Customer $customerResourceModel,
CustomerMetadataInterface $customerMetadata,
CustomerSearchResultsInterfaceFactory $searchResultsFactory,
ManagerInterface $eventManager,
StoreManagerInterface $storeManager,
ExtensibleDataObjectConverter $extensibleDataObjectConverter,
DataObjectHelper $dataObjectHelper,
ImageProcessorInterface $imageProcessor,
JoinProcessorInterface $extensionAttributesJoinProcessor,
CollectionProcessorInterface $collectionProcessor,
NotificationStorage $notificationStorage,
CollectionFactory $customerCollectionFactory,
DelegatedStorage $delegatedStorage = null,
?GroupRepositoryInterface $groupRepository = null
) {
$this->customerCollectionFactory = $customerCollectionFactory;
parent::__construct($customerFactory, $customerSecureFactory, $customerRegistry, $addressRepository, $customerResourceModel, $customerMetadata, $searchResultsFactory, $eventManager, $storeManager, $extensibleDataObjectConverter, $dataObjectHelper, $imageProcessor, $extensionAttributesJoinProcessor, $collectionProcessor, $notificationStorage, $delegatedStorage, $groupRepository);
}
/**
* @param String $mobile
* @param null $websiteId
* @return \Magento\Customer\Model\Customer
* @throws NoSuchEntityException
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function getCustomerByMobile(String $mobile, $websiteId = null) {
$websiteId = $websiteId?: $this->storeManager->getDefaultStoreView()->getWebsiteId();
/* @var $customer \Magento\Customer\Model\Customer */
$customer = $this->customerCollectionFactory->create()
->addAttributeToSelect('*')
->addAttributeToFilter('mobile', $mobile)
->addAttributeToFilter(CustomerInterface::WEBSITE_ID, $websiteId)
->getFirstItem();
if (!$customer->getId()) {
throw new NoSuchEntityException(
__(
'No such entity with %fieldName = %fieldValue, %field2Name = %field2Value',
[
'fieldName' => 'mobile',
'fieldValue' => $mobile,
'field2Name' => 'websiteId',
'field2Value' => $websiteId
]
)
);
}
return $customer;
}
/**
* @param string $email
* @param null $websiteId
* @return \Magento\Customer\Api\Data\CustomerInterface
* @throws NoSuchEntityException
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function get($email, $websiteId = null)
{
if (preg_match(self::MOBILE_PATTERN, $email)) {
return $this->getCustomerByMobile($email, $websiteId)->getDataModel();
}
return parent::get($email, $websiteId);
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Stemcell\Customer\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Lab extends AbstractDb
{
/**
* @inheritDoc
*/
protected function _construct()
{
$this->_init('lab', 'lab_id');
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Stemcell\Customer\Model\ResourceModel\Lab;
use Magento\Framework\DataObject;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
/**
* @inheritDoc
*/
protected $_idFieldName = 'lab_id';
/**
* @inheritDoc
*/
protected function _construct()
{
$this->_init(
\Stemcell\Customer\Model\Lab::class,
\Stemcell\Customer\Model\ResourceModel\Lab::class
);
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Stemcell\Customer\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Salesperson extends AbstractDb
{
/**
* @inheritDoc
*/
protected function _construct()
{
$this->_init('salesperson', 'salesperson_id');
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Stemcell\Customer\Model\ResourceModel\Salesperson;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
/**
* @inheritDoc
*/
protected $_idFieldName = 'salesperson_id';
/**
* @inheritDoc
*/
protected function _construct()
{
$this->_init(
\Stemcell\Customer\Model\Salesperson::class,
\Stemcell\Customer\Model\ResourceModel\Salesperson::class
);
}
/**
* @param $valueField
* @param $labelField
* @param $additional
* @return array
*/
protected function _toOptionArray($valueField = 'salesperson_id', $labelField = 'name', $additional = [])
{
return parent::_toOptionArray($valueField, $labelField, $additional);
}
}
@@ -0,0 +1,148 @@
<?php
declare(strict_types=1);
namespace Stemcell\Customer\Model;
use Magento\Framework\Model\AbstractModel;
use Stemcell\Customer\Api\Data\SalespersonInterface;
class Salesperson extends AbstractModel implements SalespersonInterface
{
/**
* @inheritDoc
*/
public function _construct()
{
$this->_init(\Stemcell\Customer\Model\ResourceModel\Salesperson::class);
}
/**
* @inheritDoc
*/
public function getName()
{
return $this->getData(self::NAME);
}
/**
* @inheritDoc
*/
public function setName($name)
{
return $this->setData(self::NAME, $name);
}
/**
* @inheritDoc
*/
public function getEmail()
{
return $this->getData(self::EMAIL);
}
/**
* @inheritDoc
*/
public function setEmail($email)
{
return $this->setData(self::EMAIL, $email);
}
/**
* @inheritDoc
*/
public function getTelephone()
{
return $this->getData(self::TELEPHONE);
}
/**
* @inheritDoc
*/
public function setTelephone($telephone)
{
return $this->setData(self::TELEPHONE, $telephone);
}
/**
* @inheritDoc
*/
public function getRsmEmail()
{
return $this->getData(self::RSM_EMAIL);
}
/**
* @inheritDoc
*/
public function setRsmEmail($rsmEmail)
{
return $this->setData(self::RSM_EMAIL, $rsmEmail);
}
/**
* @inheritDoc
*/
public function getSisrEmail()
{
return $this->getData(self::SISR_EMAIL);
}
/**
* @inheritDoc
*/
public function setSisrEmail($sisrEmail)
{
return $this->setData(self::SISR_EMAIL, $sisrEmail);
}
/**
* @inheritDoc
*/
public function getCsrEmail()
{
return $this->getData(self::CSR_EMAIL);
}
/**
* @inheritDoc
*/
public function setCsrEmail($csrEmail)
{
return $this->setData(self::CSR_EMAIL, $csrEmail);
}
/**
* @inheritDoc
*/
public function getIsActive()
{
return $this->getData(self::IS_ACTIVE);
}
/**
* @inheritDoc
*/
public function setIsActive($isActive)
{
return $this->setData(self::IS_ACTIVE, $isActive);
}
/**
* @inheritDoc
*/
public function getSalespersonId()
{
return $this->getData(self::SALESPERSON_ID);
}
/**
* @inheritDoc
*/
public function setSalespersonId($salespersonId)
{
return $this->setData(self::SALESPERSON_ID, $salespersonId);
}
}
@@ -0,0 +1,145 @@
<?php
declare(strict_types=1);
namespace Stemcell\Customer\Model;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;
use Stemcell\Customer\Api\Data\SalespersonInterface;
use Stemcell\Customer\Api\Data\SalespersonInterfaceFactory;
use Stemcell\Customer\Api\Data\SalespersonSearchResultsInterfaceFactory;
use Stemcell\Customer\Api\SalespersonRepositoryInterface;
use Stemcell\Customer\Model\ResourceModel\Salesperson as ResourceSalesperson;
use Stemcell\Customer\Model\ResourceModel\Salesperson\CollectionFactory as SalespersonCollectionFactory;
class SalespersonRepository implements SalespersonRepositoryInterface
{
/**
* @var ResourceSalesperson
*/
protected $resource;
/**
* @var SalespersonInterfaceFactory
*/
protected $salespersonFactory;
/**
* @var SalespersonCollectionFactory
*/
protected $salespersonCollectionFactory;
/**
* @var Salesperson
*/
protected $searchResultsFactory;
/**
* @var CollectionProcessorInterface
*/
protected $collectionProcessor;
/**
* @param ResourceSalesperson $resource
* @param SalespersonInterfaceFactory $salespersonFactory
* @param SalespersonCollectionFactory $salespersonCollectionFactory
* @param SalespersonSearchResultsInterfaceFactory $searchResultsFactory
* @param CollectionProcessorInterface $collectionProcessor
*/
public function __construct(
ResourceSalesperson $resource,
SalespersonInterfaceFactory $salespersonFactory,
SalespersonCollectionFactory $salespersonCollectionFactory,
SalespersonSearchResultsInterfaceFactory $searchResultsFactory,
CollectionProcessorInterface $collectionProcessor
) {
$this->resource = $resource;
$this->salespersonFactory = $salespersonFactory;
$this->salespersonCollectionFactory = $salespersonCollectionFactory;
$this->searchResultsFactory = $searchResultsFactory;
$this->collectionProcessor = $collectionProcessor;
}
/**
* @inheritDoc
*/
public function save(SalespersonInterface $salesperson)
{
try {
$this->resource->save($salesperson);
} catch (\Exception $exception) {
throw new CouldNotSaveException(__(
'Could not save the salesperson: %1',
$exception->getMessage()
));
}
return $salesperson;
}
/**
* @inheritDoc
*/
public function get($salespersonId)
{
$salesperson = $this->salespersonFactory->create();
$this->resource->load($salesperson, $salespersonId);
if (!$salesperson->getId()) {
//throw new NoSuchEntityException(__('Salesperson with id "%1" does not exist.', $salespersonId));
}
return $salesperson;
}
/**
* @inheritDoc
*/
public function getList(
\Magento\Framework\Api\SearchCriteriaInterface $criteria
) {
$collection = $this->salespersonCollectionFactory->create();
$this->collectionProcessor->process($criteria, $collection);
$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($criteria);
$items = [];
foreach ($collection as $model) {
$items[] = $model;
}
$searchResults->setItems($items);
$searchResults->setTotalCount($collection->getSize());
return $searchResults;
}
/**
* @inheritDoc
*/
public function delete(SalespersonInterface $salesperson)
{
try {
$salespersonModel = $this->salespersonFactory->create();
$this->resource->load($salespersonModel, $salesperson->getId());
$this->resource->delete($salespersonModel);
} catch (\Exception $exception) {
throw new CouldNotDeleteException(__(
'Could not delete the Salesperson: %1',
$exception->getMessage()
));
}
return true;
}
/**
* @inheritDoc
*/
public function deleteById($salespersonId)
{
return $this->delete($this->get($salespersonId));
}
}
@@ -0,0 +1,52 @@
<?php
namespace Stemcell\Customer\Model\Validator;
use Magento\Customer\Model\Customer;
use Magento\Framework\App\ObjectManager;
use Psr\Log\LoggerInterface;
class Name extends \Magento\Customer\Model\Validator\Name
{
protected const PATTERN_NAME = '/^(?:[\p{L}\p{M}\p{P}\s\d]){1,255}+$/u';
/**
* Validate name fields.
*
* @param Customer $customer
* @return bool
*/
public function isValid($customer)
{
if (!$this->isValidName($customer->getFirstname())) {
parent::_addMessages([['firstname' => 'First Name is not valid!']]);
}
if (!$this->isValidName($customer->getLastname())) {
parent::_addMessages([['lastname' => 'Last Name is not valid!']]);
}
if (!$this->isValidName($customer->getMiddlename())) {
parent::_addMessages([['middlename' => 'Middle Name is not valid!']]);
}
return count($this->_messages) == 0;
}
/**
* Check if name field is valid.
*
* @param string|null $nameValue
* @return bool
*/
protected function isValidName($nameValue)
{
if ($nameValue != null) {
if (preg_match(self::PATTERN_NAME, $nameValue, $matches)) {
return $matches[0] == $nameValue;
}
}
return true;
}
}