netresearch / module-shipping-core

The Netresearch shipping core package is the central component to offer generic functionality as required by all carriers.
Open Software License 3.0
0 stars 1 forks source link

Coding question: how to update shipping options? #9

Closed OvalMedia closed 2 weeks ago

OvalMedia commented 2 months ago

In a custom module I need to update the shipping options of this module:

/** @var $quoteSelection \Netresearch\ShippingCore\Model\ShippingSettings\ShippingOption\Selection\QuoteSelection */
$quoteSelection = $this->quoteSelectionFactory->create();
$quoteSelection->setData([
    SelectionInterface::SHIPPING_OPTION_CODE => Codes::SERVICE_OPTION_DROPOFF_DELIVERY,
    SelectionInterface::INPUT_CODE => 'details',
    SelectionInterface::INPUT_VALUE => $value
]);

/** @var \Netresearch\ShippingCore\Api\ShippingSettings\CheckoutManagementInterface */
$this->checkoutManagement->updateShippingOptionSelections($quoteId, [$quoteSelection]);

This works fine except this creates one option only. If there are other options already set (in table nrshipping_quote_address_shipping_option_selection) they will be removed.

What would be the proper way to update a single option without deleting the existing ones?

Thank you

Sebastian80 commented 1 month ago

Hi @OvalMedia,

i had a look into this and as it's currently implemented \Netresearch\ShippingCore\Model\ShippingSettings\ShippingOption\Selection\QuoteSelectionManager::save will allways delete existing entries. As a workaround you could make use of \Netresearch\ShippingCore\Model\ShippingSettings\ShippingOption\Selection\QuoteSelectionRepository::getList and build the selection as you need before persiting it.

What would be the proper way to update a single option without deleting the existing ones?

As i am not sure what you are trying to archive, thats hard to answer. What's your use case and what you are trying to archive ?

OvalMedia commented 1 month ago

I solved this now by loading all the existing options in advance, then remove the one from that result that I want to update/save, merge the results and save everything using updateShippingOptionSelections

protected function updateShippingOptionSelections(QuoteSelection $quoteSelection): mixed
{
    $quoteId = (int) $this->checkoutSession->getQuote()->getId();
    $quoteSelections = $this->getExistingQuoteSelections();

    foreach ($quoteSelections as $key => $selection) {
        if (
            $selection->getShippingOptionCode() == $quoteSelection->getShippingOptionCode() &&
            $selection->getInputCode() == $quoteSelection->getInputCode()
        ) {
            unset($quoteSelections[$key]);
            break;
        }
    }

    if (!empty($quoteSelection->getInputValue())) {
        $quoteSelections[] = $quoteSelection;
    }

    $this->checkoutManagement->updateShippingOptionSelections($quoteId, $quoteSelections);
    return $value;
}

Seems a little redundant but it does the job.