Jump to content

Custom reference code for orders


Recommended Posts

Hi,

I'm trying to generate a custom reference, but I found a problem, and I don't know if I'm doing something wrong. 

When I generate a reference, I want to check in the DB the last number generated for a year, to create a reference in the format "YEAR/0/ORDER_COUNT/W" (200001W),  I want to reset the order count each year so it starts at 1. So i edited the generateReference in Order class.

I used the DB::getInstance()->getValue($sql) method, but I get an old value, even after deleting the registry in the database. So I thought that was something related with the DB cache. I tried to set the parameter use_cache to false, but still got the old value.

We are talking about a unique reference, and I don't want repeated references or problems caused by the cache.

I leave the code I created below.

 public static function generateReference(){
		$year = Date("Y"); 
        $yearCode = Date("y"); 
                
        //Checks if the current year is created in the DB
        $countSql = 'SELECT COUNT(*) FROM '._DB_PREFIX_.'order_count WHERE year = '.$year;
        $exists = Db::getInstance()->getValue($countSql, false);

        if ($exists>0){
            //Get the current countNumber
            $sql = 'SELECT countNumber FROM '._DB_PREFIX_.'order_count WHERE year = '.$year;
            $count = Db::getInstance()->getValue($sql, false);
            //Update the order count
            $count+=1;

            //Update the order count value in the DB
            Db::getInstance()->update("order_count", array('countNumber' =>(int)$count), 'year  ='.(int)$year, 0, false, false);

        }else{
            //In case the year is not created, create a new registry with the order count starting at 1. 
            Db::getInstance()->insert('order_count', array(
                'year' => (int)$year,
                'countNumber' =>(int)1,
            ),false, false);
            $count = 1;
        }

        //Adds the needed "0" to create the correct format for the reference.
        $countStr = str_pad($count, 3, '0', STR_PAD_LEFT);

        //Generate the reference concatenating all strings.
        $code = $yearCode ."0".$countStr."W";
        return $code;
}

As you can see, I created a new table (ps_order_count) in the database with 2 columns (year and countNumber)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...