Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions src/App/DeliveryOptions/Service/DeliveryOptionsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use MyParcelNL\Pdk\Base\Support\Collection;
use MyParcelNL\Pdk\Base\Support\SettingKey;
use MyParcelNL\Pdk\Base\Support\Utils;
use MyParcelNL\Pdk\Carrier\Collection\CarrierCollection;
use MyParcelNL\Pdk\Carrier\Contract\CarrierRepositoryInterface;
use MyParcelNL\Pdk\Carrier\Model\Carrier;
use MyParcelNL\Pdk\Carrier\Service\CapabilitiesValidationService;
Expand Down Expand Up @@ -150,10 +151,6 @@ private function createCarrierSettings(Carrier $carrier, PdkCart $cart, string $
->pluck('weekday')
->toArray();

// Always use Europe/Amsterdam timezone for cutoff checks, because cutoff times are meant as local shop time.
// This prevents bugs when the server runs in a different timezone (e.g. UTC).
$now = new DateTimeImmutable('now', new DateTimeZone('Europe/Amsterdam'));

$minimumDropOffDelay = -1 === $cart->shippingMethod->minimumDropOffDelay
? $carrierSettings['dropOffDelay']
: $cart->shippingMethod->minimumDropOffDelay;
Expand All @@ -173,9 +170,6 @@ private function createCarrierSettings(Carrier $carrier, PdkCart $cart, string $
[
'deliveryDaysWindow' => $carrierSettings->deliveryDaysWindow,
'dropOffDelay' => max($minimumDropOffDelay, $carrierSettings->dropOffDelay),
'allowSameDayDelivery' => ($settings['allowSameDayDelivery'] ?? false)
&& 0 === $minimumDropOffDelay
&& $now->format('H:i') <= ($carrierSettings['cutoffTimeSameDay'] ?? '00:00'),
'cutoffTime' => $dropOff->cutoffTime ?? null,
'cutoffTimeSameDay' => $carrierSettings['cutoffTimeSameDay'] ?? null,
'dropOffDays' => $dropOffDays,
Expand Down Expand Up @@ -229,8 +223,18 @@ private function getBaseSettings(CarrierSettings $carrierSettings, PdkCart $cart
*/
private function getValidCarrierOptions(PdkCart $cart): array
{
$carrierSettings = Settings::get(CarrierSettings::ID);

$carrierSettings = array_filter(
is_array($carrierSettings) ? $carrierSettings : [],
static fn($settings): bool => is_array($settings)
);

if (empty($carrierSettings)) {
return [DeliveryOptions::DEFAULT_PACKAGE_TYPE_NAME, new CarrierCollection()];
}

$allCarriers = $this->carrierRepository->all();
$carrierSettings = Settings::get(CarrierSettings::ID);
$shippingAddress = $cart->shippingMethod->shippingAddress;
$cc = $shippingAddress->cc ?? null;
$isBusiness = $shippingAddress->isBusiness;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@

final class CustomerInformationCalculator extends AbstractPdkOrderOptionCalculator
{
/*
* These carriers *require* customer information to be shared; ignore any global setting.
* There is no API exposing this type of requirement at this point in time (July 2026).
*/
Comment thread
Copilot marked this conversation as resolved.
private const CARRIERS_WITH_MANDATORY_CUSTOMER_INFO = [
RefTypesCarrierV2::DPD,
RefTypesCarrierV2::TRUNKRS,
];
Comment thread
Copilot marked this conversation as resolved.

public function calculate(): void
{
$orderCarrier = $this->order->deliveryOptions->carrier;
Expand Down Expand Up @@ -46,8 +55,7 @@ public function calculate(): void
protected function sharingCustomerInformation(Carrier $carrier): bool
{
// @TODO this is a specific carrier check as there is currently no endpoint exposing this information
if ($carrier->carrier === RefTypesCarrierV2::DPD) {
// DPD *requires* customer information to be shared, ignore any global setting
if (\in_array($carrier->carrier, self::CARRIERS_WITH_MANDATORY_CUSTOMER_INFO, true)) {
return true;
}

Expand Down
7 changes: 6 additions & 1 deletion src/Carrier/Service/CapabilitiesValidationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,16 @@ private function getEnabledCarrierNames(): array
{
$carrierSettings = Settings::get(CarrierSettings::ID) ?? [];

if (! is_array($carrierSettings)) {
return [];
}

return array_keys(
array_filter(
$carrierSettings,
static function ($settings): bool {
return ! empty($settings[CarrierSettings::DELIVERY_OPTIONS_ENABLED]);
return is_array($settings)
&& ! empty($settings[CarrierSettings::DELIVERY_OPTIONS_ENABLED]);
}
)
);
Expand Down
44 changes: 37 additions & 7 deletions src/Frontend/View/CarrierSettingsItemView.php
Original file line number Diff line number Diff line change
Expand Up @@ -482,15 +482,37 @@ function (FormOperationBuilder $builder) {
*/
private function getSameDayDeliverySettings(): array
{
if (!$this->carrierValidationService->supportsShipmentOption($this->carrier, SameDayDeliveryDefinition::class)) {
// Same-day is exposed either as a shipment option (e.g. DHL For You) or as a
// delivery type (e.g. Trunkrs), depending on the carrier's contract. This
// section is the single owner of the same-day fields for both representations;
// getDeliveryTypeSettings() and getShipmentOptionsSettings() skip same-day.
$definition = new SameDayDeliveryDefinition();

$hasSameDayDeliveryType = $this->carrier->deliveryTypes
Comment thread
FreekVR marked this conversation as resolved.
&& in_array(RefTypesDeliveryTypeV2::SAME_DAY, $this->carrier->deliveryTypes, true);

$hasSameDayShipmentOption = $this->carrierValidationService->supportsShipmentOption(
$this->carrier,
SameDayDeliveryDefinition::class
);

if (! $hasSameDayDeliveryType && ! $hasSameDayShipmentOption) {
return [];
}

$elements = $this->createSettingWithPriceFields(
$definition->getAllowSettingsKey(),
SettingKey::priceDeliveryType(RefTypesDeliveryTypeV2::SAME_DAY)
);

$capabilitiesKey = $definition->getCapabilitiesOptionsKey();

if ($capabilitiesKey) {
$this->makeReadOnlyWhenRequired($elements[0], $capabilitiesKey);
}

return array_merge(
$this->createSettingWithPriceFields(
(new SameDayDeliveryDefinition())->getAllowSettingsKey(),
SettingKey::priceDeliveryType(RefTypesDeliveryTypeV2::SAME_DAY)
),
$elements,
[new InteractiveElement(CarrierSettings::CUTOFF_TIME_SAME_DAY, Components::INPUT_TIME)]
);
}
Expand Down Expand Up @@ -547,8 +569,10 @@ private function getDeliveryTypeSettings(): array
}

foreach ($this->carrier->deliveryTypes as $deliveryType) {
// Pickup has its own section in getDeliveryOptionsFields(), so skip it here.
if ($deliveryType === RefTypesDeliveryTypeV2::PICKUP) {
// Pickup has its own section in getDeliveryOptionsFields() and same-day has its
// own section in getSameDayDeliverySettings() (with the cutoff time field), so
// skip both here.
if (in_array($deliveryType, [RefTypesDeliveryTypeV2::PICKUP, RefTypesDeliveryTypeV2::SAME_DAY], true)) {
continue;
}

Expand All @@ -575,6 +599,12 @@ private function getShipmentOptionsSettings(): array
$settings = [];

foreach ($definitions as $definition) {
// Same-day has its own section in getSameDayDeliverySettings() (with the
// cutoff time field), so skip it here to avoid a duplicate toggle.
if ($definition instanceof SameDayDeliveryDefinition) {
continue;
}

$allowKey = $definition->getAllowSettingsKey();
$priceKey = $definition->getPriceSettingsKey();

Expand Down
14 changes: 11 additions & 3 deletions src/Settings/Repository/AbstractPdkSettingsRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,18 @@ protected function updateSettingsFromCollection(
): Settings {
$category = $this->get($this->createSettingsKey($settingsId)) ?? [];

foreach ($category as $key => $item) {
$values = ['id' => $key] + $this->get($this->createSettingsKey("$settingsId.$key"));
if (! is_array($category)) {
$category = [];
}

foreach (array_keys($category) as $key) {
$values = $this->get($this->createSettingsKey("$settingsId.$key"));

if (! is_array($values)) {
continue;
}

$collection->offsetSet($key, $values);
$collection->offsetSet($key, ['id' => $key] + $values);
}

$settings->setAttribute($settingsId, $collection);
Expand Down
5 changes: 5 additions & 0 deletions tests/Unit/App/Context/Model/DeliveryOptionsConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use MyParcelNL\Pdk\Facade\Pdk;
use MyParcelNL\Pdk\Facade\Settings;
use MyParcelNL\Pdk\Proposition\Proposition;
use MyParcelNL\Pdk\Settings\Model\CarrierSettings;
use MyParcelNL\Pdk\Settings\Model\CheckoutSettings;
use MyParcelNL\Pdk\Tests\Bootstrap\MockPdkProductRepository;
use MyParcelNL\Pdk\Tests\Bootstrap\TestBootstrapper;
Expand Down Expand Up @@ -135,6 +136,10 @@
->withAllowPickupLocationsViewSelection(true)
->store();

factory(CarrierSettings::class, RefCapabilitiesSharedCarrierV2::POSTNL)
->withDeliveryOptionsEnabled(true)
->store();

/** @var \MyParcelNL\Pdk\Tests\Bootstrap\MockPdkProductRepository $productRepository */
$productRepository = Pdk::get(PdkProductRepositoryInterface::class);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use MyParcelNL\Pdk\Carrier\Model\Carrier;
use MyParcelNL\Pdk\Facade\FrontendData;
use MyParcelNL\Pdk\Facade\Pdk;
use MyParcelNL\Pdk\Settings\Contract\PdkSettingsRepositoryInterface;
use MyParcelNL\Pdk\Settings\Model\CarrierSettings;
use MyParcelNL\Pdk\Settings\Model\Settings;
use MyParcelNL\Pdk\Shipment\Model\DeliveryOptions;
Expand Down Expand Up @@ -307,6 +308,42 @@ function enqueueCapabilitiesPerType(array $responsesPerType): void
->and($result['carrierSettings'])->not->toHaveKey($disabledId);
});

it('keeps valid carriers when another carrier setting is malformed', function () {
$carrierName = RefCapabilitiesSharedCarrierV2::getAllowableEnumValues()[0];

storeCarrierSettings([$carrierName => true]);

/** @var \MyParcelNL\Pdk\Settings\Contract\PdkSettingsRepositoryInterface $settingsRepository */
$settingsRepository = Pdk::get(PdkSettingsRepositoryInterface::class);
$settingsKey = Pdk::get('createSettingsKey')(CarrierSettings::ID);
$carrierSettings = $settingsRepository->get($settingsKey);

$settingsRepository->store($settingsKey, array_merge($carrierSettings, ['invalid' => 'invalid']));

factory(Shop::class)
->withCarriers(
factory(CarrierCollection::class)
->push(factory(Carrier::class)
->withCarrier($carrierName)
->withCapabilityPackageTypes(['PACKAGE']))
)
->store();

resetStorageCache();

enqueueCapabilitiesPerType([
'PACKAGE' => [capabilityResult($carrierName, 100, ['PACKAGE'])],
]);

/** @var DeliveryOptionsServiceInterface $service */
$service = Pdk::get(DeliveryOptionsServiceInterface::class);
$result = $service->createAllCarrierSettings(makeCart('NL'));

$carrierId = FrontendData::getLegacyCarrierIdentifier($carrierName);

expect($result['carrierSettings'])->toHaveKey($carrierId);
});

it('passes contract ID from capabilities to carrier settings output', function () {
storeCarrierSettings([RefCapabilitiesSharedCarrierV2::POSTNL => true]);

Expand Down Expand Up @@ -476,4 +513,3 @@ function enqueueCapabilitiesPerType(array $responsesPerType): void

expect($result['packageType'])->toBe(DeliveryOptions::PACKAGE_TYPE_MAILBOX_NAME);
});

Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

/** @noinspection StaticClosureCanBeUsedInspection */

declare(strict_types=1);

namespace MyParcelNL\Pdk\App\DeliveryOptions\Service;

use Mockery;
use MyParcelNL\Pdk\App\Cart\Model\PdkCart;
use MyParcelNL\Pdk\App\DeliveryOptions\Contract\DeliveryOptionsServiceInterface;
use MyParcelNL\Pdk\Facade\Pdk;
use MyParcelNL\Pdk\Settings\Contract\SettingsManagerInterface;
use MyParcelNL\Pdk\Settings\Model\CarrierSettings;
use MyParcelNL\Pdk\Shipment\Model\DeliveryOptions;
use MyParcelNL\Pdk\Tests\Uses\UsesAccountMock;
use MyParcelNL\Pdk\Tests\Uses\UsesMockPdkInstance;

use function MyParcelNL\Pdk\Tests\usesShared;

uses()->group('checkout');

usesShared(new UsesMockPdkInstance(), new UsesAccountMock());

it('does not expose carriers when carrier settings are missing or invalid', function ($carrierSettings) {
$settingsManager = Mockery::mock(SettingsManagerInterface::class);
$settingsManager
->shouldReceive('get')
->andReturnUsing(static function (
string $key,
?string $namespace = null,
$default = null
) use ($carrierSettings) {
return CarrierSettings::ID === $key && null === $namespace
? $carrierSettings
: $default;
});
Pdk::set(SettingsManagerInterface::class, $settingsManager);

/** @var DeliveryOptionsServiceInterface $service */
$service = Pdk::get(DeliveryOptionsServiceInterface::class);

$result = $service->createAllCarrierSettings(new PdkCart([
'shippingMethod' => [
'shippingAddress' => ['cc' => 'NL'],
],
'lines' => [
[
'quantity' => 1,
'product' => [
'weight' => 1000,
'isDeliverable' => true,
],
],
],
]));

expect($result['packageType'])->toBe(DeliveryOptions::DEFAULT_PACKAGE_TYPE_NAME)
->and($result['carrierSettings'])->toBe([]);
})->with([
'missing' => [null],
'empty array' => [[]],
'malformed carrier entry' => [['carrier' => 'invalid']],
'boolean value' => [false],
'string value' => ['invalid'],
]);
Original file line number Diff line number Diff line change
Expand Up @@ -339,3 +339,52 @@ function (
$carrierId = FrontendData::getLegacyCarrierIdentifier($fakeCarrier->carrier);
expect($result['carrierSettings'][$carrierId]['pricePackageTypeMailbox'])->toBe(1.05);
});

it('passes allow* for deliveryTypes without looking at the cutoff times', function () {
$fakeCarrier = factory(Carrier::class)->withCarrier('POSTNL')->make();

// Same-day is switched on, and conditions are applied that in the past would block sameDayDelivery globally.
// Whether same-day is still achievable today is the widget's call, so the settings have to arrive as
// the merchant set them rather than pre-judged here.
factory(CarrierSettings::class, $fakeCarrier->carrier)
->withDeliveryOptions()
->withAllowSameDayDelivery(true)
->withAllowMorningDelivery(true)
->withAllowEveningDelivery(true)
->withCutoffTimeSameDay('02:00')
->withDropOffDelay(2)
->store();

factory(Shop::class)
->withCarriers(factory(CarrierCollection::class)->push(factory(Carrier::class)->withCarrier('POSTNL')))
->store();

/** @var \MyParcelNL\Pdk\App\DeliveryOptions\Contract\DeliveryOptionsServiceInterface $service */
$service = Pdk::get(DeliveryOptionsServiceInterface::class);

$result = $service->createAllCarrierSettings(new PdkCart([
'lines' => [
[
'quantity' => 1,
'product' => [
'weight' => 1,
'isDeliverable' => true,
'settings' => [
ProductSettings::DROP_OFF_DELAY => 5,
],
],
],
],
]));

$carrierId = FrontendData::getLegacyCarrierIdentifier($fakeCarrier->carrier);
$settings = $result['carrierSettings'][$carrierId];

// dropOffDelay proves the delay really reached the service, so the same-day assertion cannot pass
// just because nothing was delaying drop-off in the first place.
expect($settings['dropOffDelay'])->toBe(5)
->and($settings['allowSameDayDelivery'])->toBeTrue()
->and($settings['allowMorningDelivery'])->toBeTrue()
->and($settings['allowEveningDelivery'])->toBeTrue()
->and($settings['cutoffTimeSameDay'])->toBe('02:00');
});
Loading
Loading