Skip to content

Commit

Permalink
Merge pull request #13 from synolia/bugfix/entity-refactor-and-email-…
Browse files Browse the repository at this point in the history
…sender

bugfixing Oro6 upgrading
  • Loading branch information
mi-lopez authored Jul 17, 2024
2 parents e0b9dd7 + bcc59b3 commit 1b5c5d4
Show file tree
Hide file tree
Showing 31 changed files with 291 additions and 299 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ This plugin allows the customer to subscribe to a product whose stock level is e

| | Version |
| :--- |:--------|
| PHP | 8.2 |
| OroCommerce | 5.1 |
| PHP | 8.3 |
| OroCommerce | 6.0 |

## Installation

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,50 +4,54 @@

namespace Synolia\Bundle\StockAlertBundle\Async;

use Doctrine\ORM\EntityManagerInterface;
use Oro\Bundle\CustomerBundle\Entity\CustomerUser;
use Oro\Bundle\SecurityBundle\Authentication\TokenAccessorInterface;
use Oro\Bundle\UserBundle\Mailer\UserTemplateEmailSender;
use Oro\Bundle\WebsiteBundle\Manager\WebsiteManager;
use Oro\Component\MessageQueue\Client\TopicSubscriberInterface;
use Oro\Component\MessageQueue\Consumption\MessageProcessorInterface;
use Oro\Component\MessageQueue\Transport\MessageInterface;
use Oro\Component\MessageQueue\Transport\SessionInterface;
use Oro\Component\MessageQueue\Util\JSON;
use Synolia\Bundle\StockAlertBundle\Async\Topic\StockAlertNotificationTopic;
use Synolia\Bundle\StockAlertBundle\Mailer\SimpleEmailMailer;

class StockAlertNotificationProcessor implements
MessageProcessorInterface,
TopicSubscriberInterface
{
public function __construct(
protected WebsiteManager $websiteManager,
protected SimpleEmailMailer $simpleEmailMailer,
protected UserTemplateEmailSender $userTemplateEmailSender,
protected EntityManagerInterface $entityManager,
) {
}

/**
* @throws \JsonException
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function process(MessageInterface $message, SessionInterface $session): string
{
$body = JSON::decode($message->getBody());
if (empty($body['customerEmail'])) {
return self::REJECT;
}

$website = $this->websiteManager->getCurrentWebsite();
if (!$website) {
return self::REJECT;
}
$id = $body['customerUserId'];

$this->simpleEmailMailer->send(
[$body['customerEmail']],
$customerUserRepository = $this->entityManager->getRepository(CustomerUser::class);
/** @var CustomerUser $customerUser */
$customerUser = $customerUserRepository->findOneBy(['id' => $id]);

$emailTemplateParams = [
'customerFullName' => $customerUser->getFullName(),
'productName' => $body['productName'],
'productSKU' => $body['productSKU'],
'websiteName' => $customerUser->getWebsite(),
];

$this->userTemplateEmailSender->sendUserTemplateEmail(
$customerUser,
'synolia_stock_alert_email',
$website,
[
'customerFullName' => $body['customerFullName'],
'productName' => $body['productName'],
'productSKU' => $body['productSKU'],
'websiteName' => $website->getName(),
]
$emailTemplateParams
);

return self::ACK;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Synolia\Bundle\StockAlertBundle\Async\Topic;

use Oro\Bundle\CustomerBundle\Entity\CustomerUser;
use Oro\Component\MessageQueue\Topic\AbstractTopic;
use Symfony\Component\OptionsResolver\OptionsResolver;

Expand All @@ -23,19 +24,16 @@ public function configureMessageBody(OptionsResolver $resolver): void
{
$resolver
->setDefined([
'customerEmail',
'customerFullName',
'customerUserId',
'productName',
'productSKU',
])
->setRequired([
'customerEmail',
'customerFullName',
'customerUserId',
'productName',
'productSKU',
])
->addAllowedTypes('customerEmail', 'string')
->addAllowedTypes('customerFullName', 'string')
->addAllowedTypes('customerUserId', 'int')
->addAllowedTypes('productName', 'string')
->addAllowedTypes('productSKU', 'string')
;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function form(Request $request, int $productId): Response
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
try {
$this->handler->create($product, $form->getData()->get('recipient_email'));
$this->handler->create($product);

$this->addFlash(
'success',
Expand Down Expand Up @@ -128,7 +128,7 @@ public function deleteAction(Product $product): JsonResponse
'status' => 'success',
'message' => $this->translator->trans('synolia.stockalert.alert.unregister.confirmation_message'),
]);
} catch (\Exception $exception) {
} catch (\Exception $e) {
}

return new JsonResponse([
Expand Down
3 changes: 1 addition & 2 deletions src/Synolia/Bundle/StockAlertBundle/Entity/StockAlert.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
use Oro\Bundle\ProductBundle\Entity\Product;
use Oro\Bundle\UserBundle\Entity\Ownership\UserAwareTrait;
use Synolia\Bundle\StockAlertBundle\Entity\Repository\StockAlertRepository;
use Synolia\Bundle\StockAlertBundle\Model\ExtendStockAlert;

#[ORM\Entity(repositoryClass: StockAlertRepository::class)]
#[ORM\Table(name: 'synolia_stock_alert')]
Expand All @@ -40,7 +39,7 @@
],
]
)]
class StockAlert extends ExtendStockAlert implements
class StockAlert implements
ExtendEntityInterface,
OrganizationAwareInterface,
CustomerOwnerAwareInterface,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,10 @@

class ProductListStockAlertListener
{
private EntityManagerInterface $entityManager;

private TokenAccessorInterface $tokenAccessor;

public function __construct(
EntityManagerInterface $entityManager,
TokenAccessorInterface $tokenAccessor
private EntityManagerInterface $entityManager,
private TokenAccessorInterface $tokenAccessor
) {
$this->entityManager = $entityManager;
$this->tokenAccessor = $tokenAccessor;
}

public function onBuildResult(BuildResultProductListEvent $event): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@

namespace Synolia\Bundle\StockAlertBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Exception\ORMException;
use Doctrine\ORM\OptimisticLockException;
use Oro\Bundle\CustomerBundle\Entity\CustomerUser;
use Oro\Bundle\EntityExtendBundle\PropertyAccess;
use Oro\Bundle\InventoryBundle\Entity\InventoryLevel;
use Oro\Bundle\ProductBundle\Entity\Product;
use Oro\Component\MessageQueue\Client\MessageProducerInterface;
use Oro\Component\MessageQueue\Transport\Exception\Exception;
use Symfony\Contracts\Translation\TranslatorInterface;
use Synolia\Bundle\StockAlertBundle\Async\Topic\StockAlertNotificationTopic;
use Synolia\Bundle\StockAlertBundle\Entity\Repository\StockAlertRepository;
use Synolia\Bundle\StockAlertBundle\Entity\StockAlert;
use Synolia\Bundle\StockAlertBundle\Handler\StockAlertHandler;

class InventoryLevelNotificationEventListener
Expand All @@ -34,22 +33,21 @@ public function __construct(
/**
* @throws Exception
*/
public function preUpdate(InventoryLevel $inventoryLevel, LifecycleEventArgs $args): void
public function preUpdate(InventoryLevel $inventoryLevel, PreUpdateEventArgs $args): void
{
if (!$args->getEntity() instanceof InventoryLevel) {
if (!$args->getObject() instanceof InventoryLevel) {
return;
}
if (!$this->inventoryHasNewStock($args)) {
return;
}
/** @var StockAlert[] $alerts */
$alerts = $this->stockAlertRepository->findUnexpiredByProduct($inventoryLevel->getProduct());
foreach ($alerts as $alert) {
$this->stockAlerts[] = $alert;
$accessor = PropertyAccess::createPropertyAccessor();
$this->sendStockAlertMessage(
$inventoryLevel->getProduct(),
$alert->getCustomerUser(),
$accessor->getValue($alert, 'recipient_email')
$alert->getCustomerUser()
);
}
}
Expand All @@ -63,11 +61,9 @@ public function postUpdate(): void
$this->stockAlertHandler->deleteStockAlerts($this->stockAlerts);
}

protected function inventoryHasNewStock(LifecycleEventArgs $args): bool
protected function inventoryHasNewStock(PreUpdateEventArgs $args): bool
{
/** @var PreUpdateEventArgs $args */
$oldQuantity = floatval($args->getOldValue('quantity'));
/** @var PreUpdateEventArgs $args */
$newQuantity = floatval($args->getNewValue('quantity'));

return $oldQuantity <= 0 && $newQuantity > 0;
Expand All @@ -78,26 +74,12 @@ protected function inventoryHasNewStock(LifecycleEventArgs $args): bool
*/
protected function sendStockAlertMessage(
Product $product,
?CustomerUser $customerUser = null,
?string $recipientEmail = null
CustomerUser $customerUser
): void {
$email = null;
$fullName = $this->translator->trans('synolia.stockalert.customer.fullname');

if ($customerUser instanceof CustomerUser) {
$email = $customerUser->getEmail();
$fullName = $customerUser->getFullName();
} elseif (!empty($recipientEmail)) {
$email = $recipientEmail;
}

if (!empty($email)) {
$this->messageProducer->send(StockAlertNotificationTopic::getName(), [
'customerEmail' => $email,
'customerFullName' => $fullName,
'productName' => $product->getName()->getString(),
'productSKU' => $product->getSku(),
]);
}
$this->messageProducer->send(StockAlertNotificationTopic::getName(), [
'customerUserId' => $customerUser->getId(),
'productName' => $product->getName()->getString(),
'productSKU' => $product->getSku(),
]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,13 @@

class StockAlertFrontendDatagridListener
{
private EntityManagerInterface $entityManager;

private TokenAccessorInterface $tokenAccessor;

public function __construct(
EntityManagerInterface $entityManager,
TokenAccessorInterface $tokenAccessor
private EntityManagerInterface $entityManager,
private TokenAccessorInterface $tokenAccessor
) {
$this->entityManager = $entityManager;
$this->tokenAccessor = $tokenAccessor;
}

public function onResultAfter(SearchResultAfter $event)
public function onResultAfter(SearchResultAfter $event): void
{
/** @var ResultRecord[] $records */
$records = $event->getRecords();
Expand Down Expand Up @@ -61,7 +55,7 @@ public function onResultAfter(SearchResultAfter $event)
}
}

public function onBuildBefore(BuildBefore $event)
public function onBuildBefore(BuildBefore $event): void
{
$config = $event->getConfig();
$config->offsetAddToArrayByPath(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@

class StockAlertType extends AbstractType
{
public const NAME = 'synolia_stock_alert_type';
public const string NAME = 'synolia_stock_alert_type';

/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
Expand Down
14 changes: 3 additions & 11 deletions src/Synolia/Bundle/StockAlertBundle/Handler/StockAlertHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ public function __construct(
* @throws NotSupported
* @throws ORMException
*/
public function create(Product $product, ?string $recipientEmail = null): StockAlert|bool
public function create(Product $product): StockAlert|bool
{
$user = $this->tokenAccessor->getUser();
$organization = $this->tokenAccessor->getOrganization();

$stockAlert = $this->getStockAlert($product, $user, $organization, $recipientEmail);
$stockAlert = $this->getStockAlert($product, $user, $organization);
if ($stockAlert instanceof StockAlert) {
return $stockAlert;
}
Expand All @@ -51,10 +51,6 @@ public function create(Product $product, ?string $recipientEmail = null): StockA
if ($organization instanceof Organization) {
$stockAlert->setOrganization($organization);
}
if (!empty($recipientEmail)) {
$accessor = PropertyAccess::createPropertyAccessor();
$accessor->setValue($stockAlert, 'recipient_email', $recipientEmail);
}
$stockAlert->setExpirationDate($this->getExpirationDate());
$this->entityManager->persist($stockAlert);
$this->entityManager->flush();
Expand Down Expand Up @@ -116,8 +112,7 @@ protected function getExpirationDate(): \DateTime
protected function getStockAlert(
Product $product,
?CustomerUser $user,
?Organization $organization,
?string $recipientEmail = null
?Organization $organization
): ?StockAlert {
$stockAlertRepository = $this->entityManager->getRepository(StockAlert::class);

Expand All @@ -128,9 +123,6 @@ protected function getStockAlert(
if ($organization instanceof Organization) {
$params['organization'] = $organization;
}
if (!empty($recipientEmail)) {
$params['recipient_email'] = $recipientEmail;
}

return $stockAlertRepository->findOneBy($params);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,10 @@

class InventoryQuantityDataProvider
{
/**
* @var InventoryQuantityProviderInterface
*/
protected $inventoryQuantityProvider;

public function __construct(
InventoryQuantityProviderInterface $inventoryQuantityProvider
protected InventoryQuantityProviderInterface $inventoryQuantityProvider
) {
$this->inventoryQuantityProvider = $inventoryQuantityProvider;
}

public function getAvailableQuantity(Product $product): int
Expand All @@ -29,6 +24,6 @@ public function getAvailableQuantity(Product $product): int
return 0;
}

return (int)$this->inventoryQuantityProvider->getAvailableQuantity($product, $unit);
return $this->inventoryQuantityProvider->getAvailableQuantity($product, $unit);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,11 @@

class StockAlertDataProvider
{
protected EntityManager $entityManager;

protected TokenAccessor $tokenAccessor;

public function __construct(
EntityManager $entityManager,
TokenAccessor $tokenAccessor
protected EntityManager $entityManager,
protected TokenAccessor $tokenAccessor
) {
$this->entityManager = $entityManager;
$this->tokenAccessor = $tokenAccessor;
}

/**
Expand Down
Loading

0 comments on commit 1b5c5d4

Please sign in to comment.