Magento – Magento 2 Random Order/Invoice/Shipping number

increment-idmagento-2.1orders

I am looking into ways to implement random sequence for Order/Invoice/Shipping number and make sure they are unique in there entity type. Is there a way to make it correct? Since i know that it is generates/calculates in Magento_SalesSequence module here https://mage2.pro/t/topic/511

Best Answer

You can do this via below code, Magento uses

Magento\SalesSequence\Model\Sequence::getNextValue()

For next increment ID

So what you can can do is

Create a plugin and rewrite this method in your plugin

Your di.xml file located in YourPackage/YourModule/etc folder

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\SalesSequence\Model\Sequence">
        <plugin name="order_increment_id" type="YourPackage\YourModule\Plugin\Model\Sequence" sortOrder="10"/>
    </type>
</config>

Your Sequence.php is,

<?php

namespace YourPackage\YourModule\Plugin\Model;

class Sequence
{
    private $connection;

    public function __construct(\Magento\Framework\App\ResourceConnection $connection) {
        $this->connection = $connection;
    }

    public function aroundGetNextValue(\Magento\SalesSequence\Model\Sequence $subject, callable $proceed)
    {
        return $this->getIncrementIds();
    }
    // this methid ensure and check for random number in order table

    public function getIncrementIds()
    {
        $connection =  $this->connection->getConnection();
        $sql = "SELECT temp.rnd FROM sales_order c,(SELECT FLOOR((RAND()*99999999)) AS rnd FROM sales_order LIMIT 0,50) AS temp
                 WHERE c.increment_id NOT IN (temp.rnd) LIMIT 1";
        $result = $connection->fetchAll($sql);

        return $result[0]['rnd'];
    }
}