Skip to content

Commit

Permalink
fix(checkout): show correct shipping prices (#61)
Browse files Browse the repository at this point in the history
INT-319
  • Loading branch information
joerivanveen committed Jan 23, 2024
1 parent 52f44c7 commit 310777d
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 48 deletions.
83 changes: 49 additions & 34 deletions src/Core/Checkout/Cart/Delivery/DeliveryCalculatorDecorator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use MyPa\Shopware\Defaults as MyParcelDefaults;
use MyPa\Shopware\Service\Config\ConfigGenerator;
use MyPa\Shopware\Service\Shopware\CartService;
use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment;
use Shopware\Core\Checkout\Cart\Cart;
use Shopware\Core\Checkout\Cart\Delivery\DeliveryCalculator;
use Shopware\Core\Checkout\Cart\Delivery\DeliveryProcessor;
Expand All @@ -21,6 +23,7 @@
use Shopware\Core\Checkout\Shipping\Aggregate\ShippingMethodPrice\ShippingMethodPriceEntity;
use Shopware\Core\Checkout\Shipping\Cart\Error\ShippingMethodBlockedError;
use Shopware\Core\Checkout\Shipping\Exception\ShippingMethodNotFoundException;
use Shopware\Core\Checkout\Shipping\ShippingException;
use Shopware\Core\Checkout\Shipping\ShippingMethodEntity;
use Shopware\Core\Defaults;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
Expand Down Expand Up @@ -97,6 +100,12 @@ public function calculate(
SalesChannelContext $context
): void
{
if (!isset($context->getShippingMethod()->getTranslated()['customFields']['myparcel'])) {
parent::calculate($data, $cart, $deliveries, $context);

return;
}

foreach ($deliveries as $delivery) {
$this->calculateDelivery($data, $cart, $delivery, $context);
}
Expand All @@ -117,9 +126,11 @@ private function calculateDelivery(
): void
{
$costs = null;
$shippingMethod = $delivery->getShippingMethod();

if ($delivery->getShippingCosts()->getUnitPrice() > 0) {
$costs = $this->calculateShippingCosts(
$shippingMethod,
new PriceCollection([
new Price(
Defaults::CURRENCY,
Expand All @@ -140,6 +151,7 @@ private function calculateDelivery(

if ($this->hasDeliveryWithOnlyShippingFreeItems($delivery)) {
$costs = $this->calculateShippingCosts(
$shippingMethod,
new PriceCollection([new Price(Defaults::CURRENCY, 0, 0, false)]),
$delivery->getPositions()->getLineItems(),
$context,
Expand All @@ -154,7 +166,11 @@ private function calculateDelivery(
$key = DeliveryProcessor::buildKey($delivery->getShippingMethod()->getId());

if (!$data->has($key)) {
throw new ShippingMethodNotFoundException($delivery->getShippingMethod()->getId());
if (class_exists(ShippingMethodNotFoundException::class)) {
throw new ShippingMethodNotFoundException($delivery->getShippingMethod()->getId());
}
/* Shopware 6.6: */
throw ShippingException::shippingMethodNotFound($delivery->getShippingMethod()->getId());
}

/** @var ShippingMethodEntity $shippingMethod */
Expand Down Expand Up @@ -189,49 +205,47 @@ private function calculateDelivery(
}

/**
* @param PriceCollection $priceCollection
* @param LineItemCollection $calculatedLineItems
* @param SalesChannelContext $context
* @param Cart $cart
* @param \Shopware\Core\Checkout\Shipping\ShippingMethodEntity $shippingMethod
* @param PriceCollection $priceCollection
* @param LineItemCollection $calculatedLineItems
* @param SalesChannelContext $context
* @param Cart $cart
*
* @return CalculatedPrice
*/
private function calculateShippingCosts(
PriceCollection $priceCollection,
LineItemCollection $calculatedLineItems,
SalesChannelContext $context,
Cart $cart
): CalculatedPrice
{
ShippingMethodEntity $shippingMethod,
PriceCollection $priceCollection,
LineItemCollection $calculatedLineItems,
SalesChannelContext $context,
Cart $cart
): CalculatedPrice {
$rules = $this->percentageTaxRuleBuilder->buildRules(
$calculatedLineItems->getPrices()->sum()
);

$price = $this->getCurrencyPrice($priceCollection, $context);

//Check if it is a my parcel shipping method
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('active', true));
$criteria->addFilter(new NotFilter(NotFilter::CONNECTION_OR, [
new EqualsFilter('customFields.myparcel', null),
]));

$shippingMethod = $this->shippingMethodRepository->search($criteria, $context->getContext())->first();
if ($shippingMethod instanceof ShippingMethodEntity) {
if ($context->getShippingMethod()->getId() === $shippingMethod->getId()) {
if ($cart->hasExtension(MyParcelDefaults::CART_EXTENSION_KEY)) {
$myParcelData = $cart->getExtension(MyParcelDefaults::CART_EXTENSION_KEY)->getVars();
if (!empty($myParcelData) && !empty($myParcelData['myparcel']['deliveryData'])) {
/** @var stdClass $deliveryData */
$deliveryData = $myParcelData['myparcel']['deliveryData'];
$deliveryData = json_decode(json_encode($deliveryData), true);
$price = $this->configGenerator->getCostForCarrierWithOptions(
$deliveryData,
$context->getSalesChannelId(),
$price
);
}
}
$cartExtension = $cart->getExtension(MyParcelDefaults::CART_EXTENSION_KEY);
$myParcelData = $cartExtension ? $cartExtension->getVars() : [];
if (! empty($myParcelData)
&& ! empty($myParcelData['myparcel']['deliveryData'])
&& $context->getShippingMethod()->getId() === $shippingMethod->getId()
) {
$cc = $context->getShippingLocation()
->getCountry()
->getIso();
if (isset($myParcelData[CartService::PACKAGE_TYPE_CART_DATA_KEY]) && $cc === AbstractConsignment::CC_NL) {
$myParcelData['myparcel']['deliveryData']->packageType = $myParcelData[CartService::PACKAGE_TYPE_CART_DATA_KEY];
}
/** @var stdClass $deliveryData */
$deliveryData = $myParcelData['myparcel']['deliveryData'];
$deliveryData = json_decode(json_encode($deliveryData), true);
$price = $this->configGenerator->getCostForCarrierWithOptions(
$deliveryData,
$context->getSalesChannelId(),
$price
);
}
$definition = new QuantityPriceDefinition($price, $rules, 1);

Expand Down Expand Up @@ -322,6 +336,7 @@ function (ShippingMethodPriceEntity $priceEntityA, ShippingMethodPriceEntity $pr
}

$costs = $this->calculateShippingCosts(
$delivery->getShippingMethod(),
$price,
$delivery->getPositions()->getLineItems(),
$context,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export default class DeliveryOptionsPlugin extends Plugin {

_addListeners() {
document.addEventListener('myparcel_updated_delivery_options', (event) => {
this._submitToCart();
this._submitToCart(event.detail);
this._setPackageTypeButtonText();
});
};
Expand All @@ -154,18 +154,16 @@ export default class DeliveryOptionsPlugin extends Plugin {
this.myparcelWarningAlert = DomAccess.querySelector(document, '#myparcel-alert');
};

_submitToCart() {
const data = {};
data['myparcel'] = JSON.stringify(event.detail);
_submitToCart(deliveryOptions) {
this._disableButton(true);
this._submitMyparcelData(data);
this._submitMyparcelData({ myparcel: JSON.stringify(deliveryOptions) });
}

_submitMyparcelData(data) {
this._client.post(this.options.urlAddToCart, JSON.stringify(data), (content, request) => {
// Retry on error?
if (request.status < 400) {
this._showWarningAlert("");
this._showWarningAlert('');
this._disableButton(false);
this._procesShippingCostsPage(JSON.parse(content));
} else {
Expand All @@ -177,15 +175,19 @@ export default class DeliveryOptionsPlugin extends Plugin {
_setPackageType(packageType) {
this._client.post(this.options.urlSetPackageType, JSON.stringify({packageType: packageType}), (content, request) => {
if (request.status < 400) {
window.MyParcelConfig.config.packageType = packageType;
document.dispatchEvent(new Event('myparcel_update_config'));
const form = document.getElementById('changeShippingForm');
form && form.submit();
} else {
this._showWarningAlert(this.options.translations.refreshMessage);
}
});
}

_procesShippingCostsPage(html) {
if (! html.content) {
console.warn(html);
return;
}
ElementReplaceHelper.replaceFromMarkup(html.content, '.checkout-aside-summary-container');
}

Expand Down
2 changes: 1 addition & 1 deletion src/Service/Config/ConfigGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public function getCostForCarrierWithOptions(array $options, string $salesChanne
//convert npm carrier to config carrier
$carrier = MyParcelCarriers::NPM_CARRIER_TO_CONFIG_CARRIER[$options['carrier']];

if (AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME === $options['packageType'] && $this->isSettingEnabled($salesChannelId, 'priceMailbox', $carrier)) {
if (isset($options['packageType']) && AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME === $options['packageType'] && $this->isSettingEnabled($salesChannelId, 'priceMailbox', $carrier)) {
return $this->getConfigFloat($salesChannelId, 'priceMailbox', $carrier);
}

Expand Down
12 changes: 7 additions & 5 deletions src/Storefront/Controller/CartController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Shopware\Core\Framework\Validation\DataBag\RequestDataBag;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse as SymfonyJsonResponse;
use Symfony\Component\Routing\Annotation\Route;

/**
Expand Down Expand Up @@ -47,10 +48,11 @@ public function addDataToCart(RequestDataBag $data, SalesChannelContext $context
'myparcel' => ['deliveryData' => json_decode($myParcelData)],
], $context);

$calculatedCard = $this->cartService->recalculate($context);
$html = $this->render('@Storefront/storefront/page/checkout/summary.html.twig', ['page' => ['cart' => $calculatedCard]]);
$calculatedCart = $this->cartService->recalculate($context);
$html = $this->render('@Storefront/storefront/page/checkout/summary.html.twig', ['page' => ['cart' => $calculatedCart]]);
$json = json_encode(['content' => $html->getContent()], ENT_QUOTES);

return $this->json($html, 200);
return new SymfonyJsonResponse($json, 200, [], true);
} else {
$this->logger->warning('No deliverData found', ['data' => $data]);

Expand All @@ -68,8 +70,8 @@ public function addDataToCart(RequestDataBag $data, SalesChannelContext $context
public function setPackageType(RequestDataBag $data, SalesChannelContext $context)
{
$packageType = $data->get(CartService::PACKAGE_TYPE_REQUEST_KEY);
$this->cartService->addData([CartService::PACKAGE_TYPE_CART_DATA_KEY=>$packageType], $context);
$this->cartService->addData([CartService::PACKAGE_TYPE_CART_DATA_KEY => $packageType], $context);

return $this->json([CartService::PACKAGE_TYPE_REQUEST_KEY=>$packageType], 200);
return $this->json([CartService::PACKAGE_TYPE_REQUEST_KEY => $packageType], 200);
}
}

0 comments on commit 310777d

Please sign in to comment.