Skip to content

Commit

Permalink
feat(checkout): allow package type choice (#58)
Browse files Browse the repository at this point in the history
INT-33
  • Loading branch information
joerivanveen authored Jan 5, 2024
1 parent 02759b1 commit d1bea89
Show file tree
Hide file tree
Showing 10 changed files with 210 additions and 22 deletions.
7 changes: 5 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@
]
},
"config": {
"optimize-autoloader": true
"optimize-autoloader": true,
"allow-plugins": {
"symfony/runtime": true
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -224,11 +224,11 @@ private function calculateShippingCosts(
/** @var stdClass $deliveryData */
$deliveryData = $myParcelData['myparcel']['deliveryData'];
$deliveryData = json_decode(json_encode($deliveryData), true);
$raise = $this->configGenerator->getCostForCarrierWithOptions(
$price = $this->configGenerator->getCostForCarrierWithOptions(
$deliveryData,
$context->getSalesChannelId()
$context->getSalesChannelId(),
$price
);
$price += $raise;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,50 @@ export default class DeliveryOptionsPlugin extends Plugin {
this._configure();
this._addListeners();

this._enableSetPackageType();

//Set address
window.MyParcelConfig.address = this.options.address;

// Tell the plugin to re-render
document.dispatchEvent(new Event('myparcel_update_delivery_options'));
};

_enableSetPackageType() {
const btn = document.getElementById('myparcel-set-package-type-button');
if (! btn) return;

const defaultPackageType = this.options.config.defaultPackageType;

if ('package' === defaultPackageType) {
btn.remove();
} else {
btn.addEventListener('click', () => {
this.disable = true;
const currentPackageType = this.options.config.packageType;
this._setPackageType(currentPackageType === defaultPackageType ? 'package' : defaultPackageType);
});
}
}

_setPackageTypeButtonText() {
const btn = document.getElementById('myparcel-set-package-type-button');
if (! btn) return;

const defaultPackageType = this.options.config.defaultPackageType;
const currentPackageType = this.options.config.packageType;

const packageText = this.options.translations.setPackageTypePackage;
const defaultText = this.options.translations.setPackageTypeDefault;

if (defaultPackageType === currentPackageType) {
btn.value = packageText ? packageText : 'Kies pakket';
} else {
btn.value = defaultText ? defaultText : 'Kies standaard';
}
btn.disable = false;
}

_disableButton(disable) {
//Get the submit button
const submitButton = DomAccess.querySelector(document, '#confirmFormSubmit');
Expand Down Expand Up @@ -108,6 +145,7 @@ export default class DeliveryOptionsPlugin extends Plugin {
_addListeners() {
document.addEventListener('myparcel_updated_delivery_options', (event) => {
this._submitToCart();
this._setPackageTypeButtonText();
});
};

Expand All @@ -124,7 +162,7 @@ export default class DeliveryOptionsPlugin extends Plugin {
}

_submitMyparcelData(data) {
this._client.post(this.options.url, JSON.stringify(data), (content, request) => {
this._client.post(this.options.urlAddToCart, JSON.stringify(data), (content, request) => {
// Retry on error?
if (request.status < 400) {
this._showWarningAlert("");
Expand All @@ -136,6 +174,17 @@ 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'));
} else {
this._showWarningAlert(this.options.translations.refreshMessage);
}
});
}

_procesShippingCostsPage(html) {
ElementReplaceHelper.replaceFromMarkup(html.content, '.checkout-aside-summary-container');
}
Expand Down
54 changes: 54 additions & 0 deletions src/Resources/config/config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,25 @@
<name lang="nl-NL">Digitale postzegel</name>
</option>
</options>
<helpText>When you set this to other than package, you can use the fixed mailbox price setting, and activate the package selection button at checkout (below).
The button text can be changed in the 'Delivery Options text' (way below).
</helpText>
<helpText lang="de-DE">Wenn Sie dies auf etwas anderes als Paket setzen, können Sie die Einstellung für den
festen Briefkastenpreis verwenden, und den Paketauswahl-Button an der Kasse aktivieren (unten)..
Der Schaltflächentext kann in den 'Delivery Options text' geändert werden (weit unten).
</helpText>
<helpText lang="nl-NL">Wanneer u dit instelt op iets anders dan pakket, kunt u de instelling voor de
vaste prijs van de brievenbus gebruiken, en de pakket keuze knop in de checkout activeren (hieronder).
De tekst van de knop kan worden gewijzigd in de 'Delivery options teksten' (helemaal onderaan).
</helpText>
</input-field>

<input-field type="bool">
<name>allowSetPackageTypeButton</name>
<label>Allow set package type button</label>
<label lang="de-DE">Schaltfläche zum Festlegen des Pakettyps zulassen</label>
<label lang="nl-NL">Knop pakkettype instellen toestaan</label>
<defaultValue>true</defaultValue>
</input-field>

<!-- Overridable settings to copy to carriers-->
Expand Down Expand Up @@ -520,6 +539,27 @@
<helpText lang="de-DE">Diese Einstellung kann nicht deaktiviert werden</helpText>
</input-field>

<input-field type="bool">
<name>priceMailboxEnabledPostNL</name>
<label>Activate fixed mailbox price</label>
<label lang="de-DE">Festen Postfachpreis aktivieren</label>
<label lang="nl-NL">Activeer vaste prijs brievenbuspakje</label>
<defaultValue>false</defaultValue>
</input-field>

<input-field type="float">
<name>priceMailboxPostNL</name>
<label>Fixed mailbox Price</label>
<label lang="de-DE">Postfachpreis</label>
<label lang="nl-NL">Vaste prijs brievenbuspakje</label>
<helpText>In case of a mailbox package, the price will be fixed to this amount.
</helpText>
<helpText lang="de-DE">Bei einem Briefkastenpaket wird der Preis auf diesen Betrag festgelegt.
</helpText>
<helpText lang="nl-NL">Bij een brievenbuspakket wordt de prijs op dit bedrag vastgesteld.
</helpText>
</input-field>

<input-field type="bool">
<name>allowShowDeliveryDatePostNL</name>
<label>Show the delivery date</label>
Expand Down Expand Up @@ -2433,6 +2473,20 @@
<title lang="de-DE">Delivery Options Text</title>
<title lang="nl-NL">Delivery options teksten</title>

<input-field type="text">
<name>setPackageTypePackage</name>
<label>Set package type package (button)</label>
<label lang="de-DE">Legen Sie den Pakettyp Paket fest (button)</label>
<label lang="nl-NL">Pakkettype pakket instellen (button)</label>
</input-field>

<input-field type="text">
<name>setPackageTypeDefault</name>
<label>Set package type default (button)</label>
<label lang="de-DE">Legen Sie den Standard Pakkettyp fest (button)</label>
<label lang="nl-NL">Stel de standaardpakkettype in (button)</label>
</input-field>

<input-field type="text">
<name>addressNotFound</name>
<label>Address not found</label>
Expand Down
1 change: 1 addition & 0 deletions src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@

<service id="MyPa\Shopware\Service\Config\ConfigGenerator">
<argument type="service" id="Shopware\Core\System\SystemConfig\SystemConfigService"/>
<argument type="service" id="MyPa\Shopware\Service\Shopware\CartService"/>
</service>
<service id="MyPa\Shopware\Service\Config\ScriptService"/>
<service id="MyPa\Shopware\Service\Shopware\CartService">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@
<template data-delivery-options-plugin
data-delivery-options-plugin-options='{{ deliveryOptionsPluginOptions|json_encode }}'></template>
<div id="myparcel-delivery-options"></div>
{% if deliveryOptionsPluginOptions.config.allowSetPackageTypeButton %}
<input type="button" id="myparcel-set-package-type-button" value="Options" class="btn btn-outline-primary
mt-2"/>
{% endif %}
{% endif %}
{% endblock %}
3 changes: 2 additions & 1 deletion src/Resources/views/storefront/page/checkout/_page.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@

{% set deliveryOptionsPluginOptions =
{
url:path('frontend.checkout.myparcel.add-to-cart') ,
urlAddToCart:path('frontend.checkout.myparcel.add-to-cart'),
urlSetPackageType:path('frontend.checkout.myparcel.set-package-type'),
config:page.extensions.myparcel.config,
translations:page.extensions.myparcel.config.translationsFromSettings,
address: {
Expand Down
68 changes: 56 additions & 12 deletions src/Service/Config/ConfigGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace MyPa\Shopware\Service\Config;

use MyPa\Shopware\Service\Shopware\CartService;
use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment;
use MyParcelNL\Sdk\src\Support\Str;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
Expand All @@ -19,14 +20,24 @@ class ConfigGenerator
'allowSignature',
];

/**
* @var \MyPa\Shopware\Service\Shopware\CartService
*/
private CartService $cartService;

/**
* @var \Shopware\Core\System\SystemConfig\SystemConfigService
*/
private SystemConfigService $systemConfigService;

/**
* @param SystemConfigService $systemConfigService
* @param CartService $cartService
*/
public function __construct(SystemConfigService $systemConfigService)
public function __construct(SystemConfigService $systemConfigService, CartService $cartService)
{
$this->systemConfigService = $systemConfigService;
$this->cartService = $cartService;
}

/**
Expand All @@ -35,18 +46,21 @@ public function __construct(SystemConfigService $systemConfigService)
* @param string $salesChannelId
* @return float
*/
public function getCostForCarrierWithOptions(array $options, string $salesChannelId): float
public function getCostForCarrierWithOptions(array $options, string $salesChannelId, float $totalPrice): float
{
/**
* Settings with a cost:
* 'priceMorningDelivery', 'priceStandardDelivery', 'priceEveningDelivery',
* 'priceSameDayDelivery', 'priceSignature', 'priceOnlyRecipient', 'pricePickup';
*/

$totalPrice = 0.0;
//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)) {
return $this->getConfigFloat($salesChannelId, 'priceMailbox', $carrier);
}

//Is it pickup?
if ($options['isPickup']) {
return $this->addPriceForSetting($salesChannelId, 'pricePickup', $carrier, $totalPrice);
Expand Down Expand Up @@ -174,6 +188,8 @@ private function getDeliveryOptionsStrings(string $salesChannelId): array
'pickupTitle',
'postcode',
'retry',
'setPackageTypePackage',
'setPackageTypeDefault',
'signatureTitle',
'wrongHouseNumberCity',
];
Expand All @@ -193,18 +209,46 @@ private function getDeliveryOptionsStrings(string $salesChannelId): array
*/
private function getGeneralSettings(SalesChannelContext $salesChannelContext, string $locale): array
{
$cc = $salesChannelContext->getShippingLocation()->getCountry()->getIso();
$packageType = (AbstractConsignment::CC_NL === $cc)
? $this->systemConfigService->getString('MyPaShopware.config.packageType', $salesChannelContext->getSalesChannelId())
: AbstractConsignment::PACKAGE_TYPE_PACKAGE_NAME;
$settings = [
'platform' => $this->systemConfigService->getString('MyPaShopware.config.platform', $salesChannelContext->getSalesChannelId()),
'packageType' => $packageType,
'currency' => $salesChannelContext->getCurrency()->getIsoCode(),
'locale' => $locale,
'platform' => $this->systemConfigService->getString('MyPaShopware.config.platform', $salesChannelContext->getSalesChannelId()),
'currency' => $salesChannelContext->getCurrency()->getIsoCode(),
'locale' => $locale,
];

return array_merge($settings, $this->generateConfig($salesChannelContext->getSalesChannelId()));
return array_merge($settings, $this->getPackageTypes($salesChannelContext), $this->generateConfig($salesChannelContext->getSalesChannelId()));
}

/**
* @param \Shopware\Core\System\SalesChannel\SalesChannelContext $salesChannelContext
*
* @return array (packageType, defaultPackageType)
*/
private function getPackageTypes(SalesChannelContext $salesChannelContext): array
{
$cc = $salesChannelContext->getShippingLocation()
->getCountry()
->getIso();
$weight = $this->cartService->getWeightInGrams($salesChannelContext);

$chosenPackageType = $defaultPackageType = (AbstractConsignment::CC_NL === $cc && $weight <= 2000)
? $this->systemConfigService->getString(
'MyPaShopware.config.packageType',
$salesChannelContext->getSalesChannelId()
)
: AbstractConsignment::PACKAGE_TYPE_PACKAGE_NAME;

if (AbstractConsignment::PACKAGE_TYPE_PACKAGE_NAME !== $chosenPackageType) {
$chosenPackageType = $this->cartService->getByKey(CartService::PACKAGE_TYPE_CART_DATA_KEY, $salesChannelContext) ?? $defaultPackageType;
}

return [
'packageType' => $chosenPackageType,
'defaultPackageType' => $defaultPackageType,
'allowSetPackageTypeButton' => (bool) $this->systemConfigService->getString(
'MyPaShopware.config.allowSetPackageTypeButton',
$salesChannelContext->getSalesChannelId()
),
];
}

/**
Expand Down
16 changes: 16 additions & 0 deletions src/Service/Shopware/CartService.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ class CartService
const NAME = 'myparcel-data';
protected $cartService;

public const PACKAGE_TYPE_REQUEST_KEY = 'packageType';
public const PACKAGE_TYPE_CART_DATA_KEY = 'myparcelPackageType';

public function __construct(ShopwareCartService $cartService)
{
$this->cartService = $cartService;
Expand All @@ -23,6 +26,19 @@ public function recalculate(SalesChannelContext $context): Cart
return $this->cartService->recalculate($cart, $context);
}

public function getWeightInGrams(SalesChannelContext $context): float
{
$cart = $this->cartService->getCart($context->getToken(), $context);
$weight = 0.0;
foreach ($cart->getLineItems() as $lineItem) {
if (! $lineItem->getDeliveryInformation()) {
continue;
}
$weight += $lineItem->getQuantity() * $lineItem->getDeliveryInformation()->getWeight();
}
return $weight * 1000;
}

public function hasData(SalesChannelContext $context, ?string $key = null): bool
{
$cart = $this->cartService->getCart($context->getToken(), $context);
Expand Down
Loading

0 comments on commit d1bea89

Please sign in to comment.