Jump to content
D. Tengler

[free script] Prestashop 1.7 change order reference and invoice number

Recommended Posts

Hi to all.
I'm tired of having a lot of customers buying expensive modules to change order numbers or change invoice numbering.
I put here a script that works like this:
1) Take the last two digits of the year + add the last highest number + add 1
2)  if the year changes, the numbering is automatically reset from 1

 

3) The file is named Order.php and is placed in the prestashop root/override/classes/order folder

I hope this helps a lot of people.

<?php
Class Order extends OrderCore
{
  public static function generateReference()
  {
    $curYear = substr(date('Y'),2,2); 
    $last_id = Db::getInstance()->getValue('
        SELECT MAX(id_order)
        FROM `'._DB_PREFIX_.'orders`');
      return $curYear.sprintf('%04d',(int)$last_id + 1);
   }
  
  public static function setLastInvoiceNumber($order_invoice_id, $id_shop)
  {
        if (!$order_invoice_id) {
            return false;
        }

        $curYear2 = substr(date('Y'),2,2); 
        $last_id2 = Db::getInstance()->getValue('
               SELECT MAX(number)
                FROM `'._DB_PREFIX_.'order_invoice`');

        $number1 = sprintf('%04d',(int)$last_id2 + 1);
        
        if (substr($number1,0,2) == $curYear2) 
        {
          $newInvoiceNumber = $number1;
        } else {
          $newInvoiceNumber = $curYear2.sprintf('%04d', (int)$last_id2 + 1);
        }
        
        $sql = 'UPDATE `'._DB_PREFIX_.'order_invoice` SET number = '.$newInvoiceNumber.' WHERE `id_order_invoice` = '.(int)$order_invoice_id;

        return Db::getInstance()->execute($sql);
        
  }

}

If I helped you, you can rate by clicking on the gray heart. You can rate one or more posts.

 

Download order.php

 

Order.php

Edited by D. Tengler
added download Order.php (see edit history)
  • Like 3
  • Thanks 1

Share this post


Link to post
Share on other sites
Posted (edited)
Quote

@Ezequielb

Invoice number is not working, is only repeating the same number in a loop, how can we solve it? 

Thank you.

Script updated.

 Fixed invoice number increase + 1.

(int)$last_id2 + 1

Edited by D. Tengler (see edit history)
  • Like 1

Share this post


Link to post
Share on other sites

Is it possible to do the same with product reference number? 

Share this post


Link to post
Share on other sites

Don't get a question?
Do you automatically generate an incremental reference number when you create a new product?

Share this post


Link to post
Share on other sites

Thanks for your great support,

When we create a new product, the reference number must be entered manually.  Is there a way to auto generate a code for this field base on a specific format? for example, I have a php code to create a random alphanumeric code that I want to use to populate this field automatically, but I don't know how to do it.

 

//Generates a random code in the format: B1234-C

<?php 


function random_code() 

   $start_letter = str_shuffle('ABCDE');
   $number = str_shuffle('0123456789');
   $letter = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ');    

    
          return substr(($start_letter), 0, 1).substr(($number), 0, 4).'-'.substr(($letter), 0, 1); 

echo random_code(); 

 

 

Best regards!

auto generate reference.png

Share this post


Link to post
Share on other sites

I understand.
To do this, override Product.php
I'm not at the computer now, just on my mobile.
We have AM 05:20 now.
Your code needs to be modified to check if the reference number already exists in the database.
Approx. in two hours I'll see what I can do.

Share this post


Link to post
Share on other sites
Posted (edited)

Hi,

modify ./src/PrestaShopBundle/Controller/Admin/ProductController.php

find public function newAction()......

Modify the code as instructed.
Add your function before the public function newAction () and into the function
public function newAction () add $product->reference = $this->random_code ();

 

public function random_code() 
    { 

        $start_letter = str_shuffle('ABCDE');
        $number = str_shuffle('0123456789');
        $letter = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
        $custom_reference = substr(($start_letter), 0, 1).substr(($number), 0, 4).'-'.substr(($letter), 0, 1);
        
        return $custom_reference;  
               
    }  

    /**
     * Create a new basic product
     * Then return to form action.
     *
     * @return RedirectResponse
     *
     * @throws \LogicException
     * @throws \PrestaShopException
     */
    public function newAction()
    {
        if (!$this->isGranted(PageVoter::CREATE, self::PRODUCT_OBJECT)) {
            $errorMessage = $this->trans('You do not have permission to add this.', 'Admin.Notifications.Error');
            $this->get('session')->getFlashBag()->add('permission_error', $errorMessage);

            return $this->redirectToRoute('admin_product_catalog');
        }

        $productProvider = $this->get('prestashop.core.admin.data_provider.product_interface');
        $languages = $this->get('prestashop.adapter.legacy.context')->getLanguages();

        /** @var $productProvider ProductInterfaceProvider */
        $productAdapter = $this->get('prestashop.adapter.data_provider.product');
        $productShopCategory = $this->getContext()->shop->id_category;

        /** @var Product $product */
        $product = $productAdapter->getProductInstance();
        $product->id_category_default = $productShopCategory;
        $product->reference = $this->random_code();
...
...
...
...

 

 

Edited by D. Tengler (see edit history)
  • Like 3
  • Thanks 1

Share this post


Link to post
Share on other sites

It would still care if the reference no longer exists in the database.
But you can handle it.

 

Share this post


Link to post
Share on other sites

A new function that checks the reference number in the database.

public function random_code() 
    { 
        $productArray = Product::getProducts($this->getContext()->language->id, 0, NULL, 'id_product', 'ASC', NULL);
        $referenceArray = array();
        
        $start_letter = str_shuffle('ABCDE');
        $number = str_shuffle('0123456789');
        $letter = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
        $custom_reference = substr(($start_letter), 0, 1).substr(($number), 0, 4).'-'.substr(($letter), 0, 1);
        
        foreach ($productArray as $products) {
           $referenceArray[] .= $products['reference'];     
        }
              
        if (in_array($custom_reference,$referenceArray)) {
            $this->random_code();
        } else  
        {
            return $custom_reference; 
        }
         
    } 

 

  • Like 2

Share this post


Link to post
Share on other sites

Amazing, you are very good for this. It would be great to work with you in other tasks... this code worked perfectly. Only thing missing is combinations, but I will  enter combinations manually to follow the reference sequence of the parent product.

Best regards!

Share this post


Link to post
Share on other sites

I will probably put my bank number into my profile 😉

  • Like 1

Share this post


Link to post
Share on other sites
5 minutes ago, D. Tengler said:

I will probably put my bank number into my profile 😉

Sure, we still have many small tasks to complete regarding our website. It would be a great if you wish to take care of them for a tiny commission .. 😎

Share this post


Link to post
Share on other sites
On 4/9/2020 at 5:30 PM, D. Tengler said:

I will probably put my bank number into my profile 😉

Dear friend, in prestashop 1.6 do you know where to add your function for the reference code?
Thanks in advance.

Share this post


Link to post
Share on other sites

Thank you very much for this override. It worked after I removed the extra bracket on this line:

$newInvoiceNumber = $curYear2.sprintf('%04d', (int)$last_id2 + 1));

The numbers are being generated correctly. However, when I try to create an invoice I get the following exception:

Unknown column '200001' in 'field list'

UPDATE `ps_order_invoice` SET number = 200001 WHERE `id_order_invoice` = 9

The invoice is generated correctly if I remove the override.

Share this post


Link to post
Share on other sites

Hello, 

I'm on prestashop 1.7.6.4.

I was so excited when I found this solution ! Unfortunately, it generates an error 500 ?

On debug mode, I get other errors but none to do with the order.php directly.

 

Any idea or insight would be much appreciated ! Thanks 

  • Sad 1

Share this post


Link to post
Share on other sites

Getting mistakes won't help us.
I need to know the mistakes exactly.
Make a screen with an error message or upload a log file from ./var/logs/dev.log or ./var/logs/xxx_exception.log here.

Share this post


Link to post
Share on other sites

Hahaha, indeed. 

Actually the back-office works fine, but in the front, it's an error 500 .. blank page. 

I attached the screen of the logs.

Thanks for being so reactive !

20200702_exception.log dev.log

  • Thanks 1

Share this post


Link to post
Share on other sites
Posted (edited)

It has nothing to do with adjustment.
This stains the thread.

Error 1:

Link to database cannot be established: SQLSTATE[HY000] [1203] User o321071 already has more than 'max_user_connections' active connections at line 127 in file classes/db/DbPDO.php

 

Error 2:

php.CRITICAL: Uncaught Exception: Unable to generate a URL for the named route "admin_mbo_catalog_module" as such route does not exist.

a) Rename folders dev and prod in ./var/cache/

b) Delete renamed folders

c) Go to admin and Clear chache and force recompile template

Edited by D. Tengler (see edit history)

Share this post


Link to post
Share on other sites

I saw these, I don't get what it means ...

But, I put the order.php in the file order >> Blank page, ERROR 500.

I remove it >> Site works again.

I tried it 5 times , same result, and I don't believe in coincidences ... 

 

But I get that it may be hard to help me through a screen,  nevertheless, I appreciate you trying !

 

Thanks D.Tengler !

Share this post


Link to post
Share on other sites

I received your last message later. I will do what you said. Crossing fingers here ! 

Thanks !

Share this post


Link to post
Share on other sites

Upload the Order.php file and the path where you saved the file here.

Share this post


Link to post
Share on other sites

1 - I don't know where to modify the max_user_connections (I'm on a dedicated server and cannot migrate).

2 - I renamed the files dev and prod, they are being deleted, as soon as it is done, i'll recompile the templates. 

 

The path is  ../override/classes/order 

And the file is attached (copy+paste of your code above)

order.php

Share this post


Link to post
Share on other sites
Posted (edited)

Ok

error is in line 22:

FROM `ps_order_invoice`'

change to:

FROM '._DB_PREFIX_.'`order_invoice`'

Table prefix ps_ 😁

Edited by D. Tengler (see edit history)

Share this post


Link to post
Share on other sites

Euh .. I made the change ...

Uploaded the file with correct line 22, error 500 on the front. 

Removed it, front working fine. 

 

🤯

Share this post


Link to post
Share on other sites

If it makes a mistake, there is something else wrong.
I would have to look at it.

Share this post


Link to post
Share on other sites

Maybe it's not compatible with some plugin or the theme .. I'm a newbie as stated on my profile, But I'll keep digging !!! 

Share this post


Link to post
Share on other sites

Maybe you already have a module installed that overwrites Order.php

Share this post


Link to post
Share on other sites

The Order.php file no longer existed in the ./override/classes/order/Order.php folder?

Share this post


Link to post
Share on other sites

Nope, in the folder, there was only one file : index.php.

Share this post


Link to post
Share on other sites

Same ERROR 500 on front. And ERROR 500 when I click on shop settings in BO.

Share this post


Link to post
Share on other sites
Posted (edited)

FIX bug:

* error in line 22

* error in line 30

Now fixed and updated in first post. 😉

Edited by D. Tengler (see edit history)
  • Like 1

Share this post


Link to post
Share on other sites

Amazing ! Thank you D.Tengler ... 

Really appreciated here .. No more orders PSDFOJS ... Thanks again !

Share this post


Link to post
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...

Important Information

Cookies ensure the smooth running of our services. Using these, you accept the use of cookies. Learn More