Skip to content

Commit

Permalink
refactoring shipment api call (#87)
Browse files Browse the repository at this point in the history
  • Loading branch information
schmitzcarsten authored Mar 11, 2021
1 parent 8327839 commit acdb9ab
Show file tree
Hide file tree
Showing 14 changed files with 84 additions and 141 deletions.
2 changes: 1 addition & 1 deletion src/Exception/MissingPriceLineItemException.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public function __construct(string $id)

public function getErrorCode(): string
{
return 'ORDER__LINE_ITEM_MISSING_PRICE_COLLECTION';
return 'MOLLIE_PAYMENTS__LINE_ITEM_MISSING_PRICE_COLLECTION';
}

public function getStatusCode(): int
Expand Down
7 changes: 3 additions & 4 deletions src/Facade/MollieShipment.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,9 @@ public function setShipment(string $orderDeliveryId, Context $context): bool
}

$customFields = $order->getCustomFields();
$mollieOrderId = $customFields[CustomFieldsInterface::MOLLIE_KEY][CustomFieldsInterface::ORDER_KEY] ?? null;

if (!isset($customFields[CustomFieldsInterface::MOLLIE_KEY][CustomFieldsInterface::ORDER_KEY])) {
if (!$mollieOrderId) {
$this->logger->warning(
sprintf('Mollie orderId does not exist in shopware order (%s)', (string)$order->getOrderNumber())
);
Expand All @@ -93,12 +94,10 @@ public function setShipment(string $orderDeliveryId, Context $context): bool
return false;
}

$mollieOrderId = $customFields[CustomFieldsInterface::MOLLIE_KEY][CustomFieldsInterface::ORDER_KEY];

$addedMollieShipment = $this->mollieApiOrderService->setShipment($mollieOrderId, $order->getSalesChannelId());

if ($addedMollieShipment) {
$values[CustomFieldsInterface::DELIVERY_SHIPPED] = true;
$values = [CustomFieldsInterface::DELIVERY_SHIPPED => true];
$this->orderDeliveryService->updateCustomFields($delivery, $values, $context);
}

Expand Down
4 changes: 3 additions & 1 deletion src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,9 @@


<!-- Validators -->
<service id="Kiener\MolliePayments\Validator\OrderLineItemValidator"/>
<service id="Kiener\MolliePayments\Validator\OrderLineItemValidator">
<argument type="service" id="monolog.logger"/>
</service>

</services>

Expand Down
1 change: 0 additions & 1 deletion src/Resources/config/services/subscriber.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

<services>
<service id="Kiener\MolliePayments\Subscriber\OrderDeliverySubscriber" class="Kiener\MolliePayments\Subscriber\OrderDeliverySubscriber">
<argument type="service" id="Mollie\Api\MollieApiClient"/>
<argument type="service" id="Kiener\MolliePayments\Facade\MollieShipment"/>
<tag name="kernel.event_subscriber"/>
</service>
Expand Down
1 change: 0 additions & 1 deletion src/Service/CustomFieldsInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
*/
interface CustomFieldsInterface
{

public const MOLLIE_KEY = 'mollie_payments';

public const ORDER_KEY = 'order_id';
Expand Down
23 changes: 8 additions & 15 deletions src/Service/MollieApi/Order.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Kiener\MolliePayments\Factory\MollieApiFactory;
use Mollie\Api\Exceptions\ApiException;
use Mollie\Api\Resources\OrderLine;
use Psr\Log\LoggerInterface;

class Order
Expand All @@ -21,7 +22,6 @@ class Order

public function __construct(MollieApiFactory $clientFactory, LoggerInterface $logger)
{

$this->clientFactory = $clientFactory;
$this->logger = $logger;
}
Expand All @@ -38,28 +38,21 @@ public function setShipment(string $mollieOrderId, string $salesChannelId): bool
'API error occured when fetching mollie order %s with message %s',
$mollieOrderId,
$e->getMessage()
),
$e->getTrace()
)
);

return false;
throw $e;
}

$shouldCreateShipment = false;
/** @var OrderLine $orderLine */
foreach ($mollieOrder->lines() as $orderLine) {
if ($orderLine->shippableQuantity > 0) {
$mollieOrder->shipAll();

foreach ($mollieOrder->lines as $line) {
if ($line->shippableQuantity > 0) {
$shouldCreateShipment = true;
break;
return true;
}
}

if ($shouldCreateShipment) {
$mollieOrder->shipAll();

return true;
}

return false;
}
}
29 changes: 12 additions & 17 deletions src/Service/MolliePaymentExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@

class MolliePaymentExtractor
{
public const MOLLIE_PAYMENT_HANDLER_NAMESPACE = 'Kiener\MolliePayments\Handler\Method';

/**
* method extracts last created transaction if it is a mollie payment transaction.
*
* @param OrderTransactionCollection $collection
* @param OrderTransactionCollection|null $collection
* @return OrderTransactionEntity|null
*/
public function extractLast(?OrderTransactionCollection $collection): ?OrderTransactionEntity
Expand All @@ -25,38 +27,31 @@ public function extractLast(?OrderTransactionCollection $collection): ?OrderTran
}

// only transactions with a payment method
$collection->filter(function (OrderTransactionEntity $transaction) {
$collection->filter(static function (OrderTransactionEntity $transaction) {
return ($transaction->getPaymentMethod() instanceof PaymentMethodEntity);
});

// sort all transactions chronological
$collection->sort(function (OrderTransactionEntity $a, OrderTransactionEntity $b) {
$collection->sort(static function (OrderTransactionEntity $a, OrderTransactionEntity $b) {
return $a->getCreatedAt() > $b->getCreatedAt();
});

$lastTransaction = $collection->last();

if ($this->isMolliePayment($lastTransaction)) {
if ($lastTransaction instanceof OrderTransactionEntity && $this->isMolliePayment($lastTransaction)) {
return $lastTransaction;
}

return null;
}

private function isMolliePayment(?OrderTransactionEntity $transaction): bool
private function isMolliePayment(OrderTransactionEntity $transaction): bool
{
if (!$transaction instanceof OrderTransactionEntity) {
return false;
}

$molliePaymentsNamespace = 'Kiener\MolliePayments\Handler\Method';

$handlerName = substr($transaction->getPaymentMethod()->getHandlerIdentifier(), 0, strlen($molliePaymentsNamespace));

if ($handlerName === $molliePaymentsNamespace) {
return true;
}
$pattern = sprintf(
'/^%s/',
preg_quote(self::MOLLIE_PAYMENT_HANDLER_NAMESPACE)
);

return false;
return preg_match($pattern, $transaction->getPaymentMethod()->getHandlerIdentifier()) === 1;
}
}
10 changes: 1 addition & 9 deletions src/Service/OrderDeliveryService.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ class OrderDeliveryService

public function __construct(EntityRepositoryInterface $orderDeliveryRepository)
{

$this->orderDeliveryRepository = $orderDeliveryRepository;
}

Expand All @@ -27,14 +26,7 @@ public function getDelivery(string $orderDeliveryId, Context $context): ?OrderDe
$criteria->addAssociations(['order', 'order.transactions', 'order.transactions.paymentMethod']);
$result = $this->orderDeliveryRepository->search($criteria, $context);

if ($result->count() === 0) {
return null;
}

/** @var OrderDeliveryEntity $delivery */
$delivery = $result->first();

return $delivery;
return $result->first();
}

public function updateCustomFields(OrderDeliveryEntity $delivery, array $values, Context $context): void
Expand Down
26 changes: 6 additions & 20 deletions src/Service/OrderService.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,13 @@
use Mollie\Api\Types\OrderLineType;
use Psr\Log\LoggerInterface;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Checkout\Cart\Price\Struct\CalculatedPrice;
use Shopware\Core\Checkout\Cart\Price\Struct\CartPrice;
use Shopware\Core\Checkout\Cart\Tax\Struct\CalculatedTax;
use Shopware\Core\Checkout\Cart\Tax\Struct\CalculatedTaxCollection;
use Shopware\Core\Checkout\Cart\Tax\TaxCalculator;
use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemEntity;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Checkout\Promotion\Cart\PromotionProcessor;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
Expand Down Expand Up @@ -146,19 +143,7 @@ public function getOrderLinesArray(OrderEntity $order): array
$sku = $item->getProduct()->getProductNumber();
}

try {
$molliePreparedApiPrices = $this->calculateLineItemPriceData($item, $order->getTaxStatus(), $currencyCode);
} catch (MissingPriceLineItemException $e) {
$this->logger->critical(
sprintf(
'The order could not be prepared for mollie api. The LineItem with id (%s), sku (%s) has no prices',
$item->getId(),
(string)$sku
)
);

throw $e;
}
$molliePreparedApiPrices = $this->calculateLineItemPriceData($item, $order->getTaxStatus(), $currencyCode);

// Get the image
$imageUrl = null;
Expand Down Expand Up @@ -298,6 +283,11 @@ public function calculateLineItemPriceData(OrderLineItemEntity $item, string $or
$vatRate = $itemTax->getTaxRate();
}

// Remove VAT if the order is tax free
if ($orderTaxType === CartPrice::TAX_STATE_FREE) {
$vatRate = 0.0;
}

$unitPrice = $price->getUnitPrice();
$lineItemTotalPrice = $item->getTotalPrice();

Expand All @@ -312,10 +302,6 @@ public function calculateLineItemPriceData(OrderLineItemEntity $item, string $or

$unitPrice = round($unitPrice, self::MOLLIE_PRICE_PRECISION);

// Remove VAT if the order is tax free
if ($orderTaxType === CartPrice::TAX_STATE_FREE) {
$vatRate = 0.0;
}

$roundedLineItemTotalPrice = round($lineItemTotalPrice, self::MOLLIE_PRICE_PRECISION);
$roundedVatRate = round($vatRate, self::MOLLIE_PRICE_PRECISION);
Expand Down
46 changes: 8 additions & 38 deletions src/Subscriber/OrderDeliverySubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,33 +11,18 @@

class OrderDeliverySubscriber implements EventSubscriberInterface
{

/** @var MollieApiClient */
private $apiClient;

/** @var SettingsService */
protected $settingsService;

/** @var MollieShipment */
private $mollieShipment;

public function __construct(
MollieShipment $mollieShipment
)
{
$this->mollieShipment = $mollieShipment;
}

/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * array('eventName' => 'methodName')
* * array('eventName' => array('methodName', $priority))
* * array('eventName' => array(array('methodName1', $priority), array('methodName2'))
*
* @return array The event names to listen to
* @return array
*/
public static function getSubscribedEvents(): array
{
Expand All @@ -46,21 +31,6 @@ public static function getSubscribedEvents(): array
];
}

/**
* Creates a new instance of PaymentMethodSubscriber.
*
* @param MollieApiClient $apiClient
* @param MollieShipment $mollieShipment
*/
public function __construct(
MollieApiClient $apiClient,
MollieShipment $mollieShipment
)
{
$this->apiClient = $apiClient;
$this->mollieShipment = $mollieShipment;
}

public function onOrderDeliveryChanged(StateMachineStateChangeEvent $event): void
{
if ($event->getTransitionSide() !== StateMachineStateChangeEvent::STATE_MACHINE_TRANSITION_SIDE_ENTER) {
Expand Down
18 changes: 18 additions & 0 deletions src/Validator/OrderLineItemValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,22 @@


use Kiener\MolliePayments\Exception\MissingPriceLineItemException;
use Psr\Log\LoggerInterface;
use Shopware\Core\Checkout\Cart\Price\Struct\CalculatedPrice;
use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemEntity;

class OrderLineItemValidator
{
/**
* @var LoggerInterface
*/
private $logger;

public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}

/**
* @param OrderLineItemEntity $lineItemEntity
* @throws MissingPriceLineItemException
Expand All @@ -19,6 +30,13 @@ public function validate(OrderLineItemEntity $lineItemEntity): void
$price = $lineItemEntity->getPrice();

if (!$price instanceof CalculatedPrice) {
$this->logger->critical(
sprintf(
'The order could not be prepared for mollie api. The LineItem with id (%s) has no prices',
$lineItemEntity->getId()
)
);

throw new MissingPriceLineItemException($lineItemEntity->getId());
}
}
Expand Down
Loading

0 comments on commit acdb9ab

Please sign in to comment.