How to Disable Source in Multi-source Inventory (MSI) Magento 2.

Multi-Source Inventory module has the functionality to contains the number of sources to manage items at different warehouse/location and you can disable any custom source using MSI except the Default source.

Keep In Mind,
Default Source Can’t be disabled.

The Default Source must be enabled. A default source is required for single-source merchants and product migration.

If you try to Disable default source programmatically, the System throws an error for Default Source.

To disable Other Source in MSI module, You need to use interface Magento\InventoryApi\Api\SourceRepositoryInterface.

SourceRepositoryInterface first fetch the source object by source code, verify its enable or not, if enable You can disable the source using save() method.

Let’s for example, Website has multiple sources available,
We use Canada store source, source_code is ca_source and we want to disable it.

We can disable ca_source programmatically using the given code snippet,

<?
namespace Jesadiya\SourceDisable\Model;

use Exception;
use Magento\InventoryApi\Api\Data\SourceInterface;
use Magento\InventoryApi\Api\SourceRepositoryInterface;
use Psr\Log\LoggerInterface;

class DisableSource
{
    /**
     * @var SourceRepositoryInterface
     */
    private $sourceRepository;

    /**
     * @var LoggerInterface
     */
    private $logger;

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

    /**
     * @return void
     */
    public function disableSourceByCode($sourceCode)
    {
        try {
            $source = $this->sourceRepository->get($sourceCode);
            $this->sourceDisable($source);
        } catch (Exception $exception) {
            $this->logger->error($exception->getMessage());
        }
    }

    /**
     * @param SourceInterface $source
     *
     * @return void
     */
    public function sourceDisable(SourceInterface $source): void
    {
        if ($source->isEnabled()) {
            try {
                $source->setEnabled(false);
                $this->sourceRepository->save($source);
            } catch (Exception $exception) {
                $this->logger->error($exception->getMessage());
            }
        }
    }
}

Call function to disable source except for default source,
$sourceCode = ‘ca_source’;
$stockData = $this->disableSourceByCode($sourceCode);

After successfully call function, the Source will be disabled from the Site. You can check the Source from the Admin panel.