When placing an order, the quantity of this article in stock is reduced correctly, but after deleting the order (or setting status to canceled), the quantity is not incremented again.

This will cause Drupal to show wrong quantities of an article in stock, e.g. when a customer skipped his order.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

Simon Georges’s picture

Version: 6.x-2.0-rc7 » 6.x-2.0
Issue tags: +uc_stock

The issue is still present in 6.x-2.0.

The trigger already exists when changing the status of the order, so I just had to add the following code (copying what already exists in the module), and it works.
But I can't figure out how to trigger something when the order is being deleted. Is-it possible ?

/**
 * Increment a product's stock.
 *
 * @param $product
 *   The product whose stock is decrementing.
 */
function uc_stock_increment_product_stock($product, $key, $order) {
  // Product has an active stock?
  if (!uc_stock_is_active($product->model)) {
    return;
  }

  // Decrement the product's stock.
  uc_stock_adjust($product->model, $product->qty);

  // Load the new stock record
  $stock = db_fetch_object(db_query("SELECT * FROM {uc_product_stock} WHERE sku = '%s'", $product->model));

  // Save a comment about the stock level.
  uc_order_comment_save($order->order_id, 0, t('The stock level for %model_name has been incremented to !qty.', array('%model_name' => $product->model, '!qty' => $stock->stock)));
}

/**
 * Implementation of hook_ca_predicate().
 */
function uc_stock_ca_predicate() {
  $predicates['uc_stock_action_increment_stock'] = array(
    '#title' => t('Increment stock on cancelling order'),
    '#trigger' => 'uc_order_status_update',
    '#conditions' => array(
      '#operator' => 'AND',
      '#conditions' => array(
        array(
          '#name' => 'uc_order_status_condition',
          '#title' => t('If the order status is Cancelled.'),
          '#argument_map' => array(
            'order' => 'updated_order',
          ),
          '#settings' => array(
            'order_status' => 'canceled',
          ),
        ),
      ),
    ),
    '#class' => 'uc_stock',
    '#status' => 1,
    '#actions' => array(
      array(
        '#name' => 'uc_stock_action_increment_stock',
        '#title' => t('Increment stock of products in order'),
        '#argument_map' => array(
          'order' => 'order',
        ),
      ),
    ),
  );

  return $predicates;
}

/**
 * Implementation of hook_action().
 */
function uc_stock_ca_action() {
  $actions['uc_stock_action_increment_stock'] = array(
    '#title' => t('Increment stock of products on the order with tracking activated.'),
    '#callback' => 'uc_stock_action_increment_stock',
    '#arguments' => array(
      'order' => array('#entity' => 'uc_order', '#title' => t('Order')),
    ),
    '#category' => t('Stock'),
  );

  return $actions;
}

/******************************************************************************
 * Conditional Action Callbacks and Forms                                     *
 ******************************************************************************/

/**
 * Increase the stock of ordered products.
 */
function uc_stock_action_increment_stock($order, $settings) {
  if (is_array($order->products)) {
    array_walk($order->products, 'uc_stock_increment_product_stock', $order);
  }
}
Danny_Joris’s picture

subscribing

Danny_Joris’s picture

Priority: Normal » Critical

I think it is safe to say that this is a critical bug, no? I don't think store administrators know it is not incremented again and they should not even have to think about it. If this happens a few times, the stock would become a complete chaos and would make it useless in the end.

Lightforge88’s picture

Where do you copy this code to implement this? I'd like to get it where I can set a conditional action that if a order is updated to a specific status that stock gets incremented. I'd really appreciate the help on this.

Simon Georges’s picture

Hi,

The code I used is in the 'uc_stock' module (I only replace decrement by increment).

I pasted the code in one of the costum modules I developped for the project I was working on, renaming every "uc_stock_function" into "project_name_function", and after refreshing the function (by visiting the module page), I could use the actions and conditions defined here to fix the bug.

I hope it helps, otherwise, I'll try to explain better.

Best Regards,
Simon

Clint Eagar’s picture

I agree, the only major flaw of Ubercart is stock handling. Having stock incremented is a must.

TR’s picture

How about posting a patch so we can try it out and see if it has any unintended consequences?

jasonabc’s picture

subscribing - agree this is critical.

Simon Georges’s picture

FileSize
3.24 KB

Hi, you'll find attached my first try to provide a patch taking #1 into account.

It's the first time I provide a patch, so my apologies if it's not perfect. Even if it works, I think the Ubercart would be able to provide a far better patch, because this one only suits my needs, and is not generic enough (I think).

Let me know if there is any problem with it anyway.

Best Regards,
Simon

TR’s picture

Status: Active » Needs review

Please change the status to "needs review" when you post a patch...

iori57’s picture

This is my first time trying to patch a module but it failed, I'm using ubercart 6.x-2.2 btw.. does it matter?

In need to increment stock on order cancellation/deletion! >.<

Simon Georges’s picture

If I remember correctly, I tested the patch on ubercart 6.x-2.2 as well. What command line did you use to patch your module ?

Please not that the patch only cover order cancellation (see #1). I don't know how to trigger the stock increment on order deletion, I'd have to go deeper in my ubercart understanding ;)

iori57’s picture

I'm using http://gnuwin32.sourceforge.net/ to apply the patch :)

Hmm what I really need is to increment the stock on order deletion.. I don't understand why ubercart was around for so long but there's still no fix on this.. I thought this is the most basic function in any e-commerce system :(

Really need this function.. Help!

dzah’s picture

I am subscribing, too

Stock incrementing after order cancellation and after order deletion are highly needed basic functions.

nicjasno’s picture

I'm also in dire need of this!!!!

nicjasno’s picture

Any reports on the progress of this? When will this be implemented into ubercart?

acura’s picture

Thx dude this patch worked just fine 4 me !!

chrisschaub’s picture

But what if a single product is removed from an order. It would be cool to handle that as well.

barteque’s picture

Category: bug » task
FileSize
1.83 KB

I've made a simple module based on code #1 and I've expanded it to return products during the order remove. My module gives You a new trigger [on order delete] and predicate which returns products.
It's pre-beta and I don't know if it's good-enough to be put on drupal repository but it's working.
Tell me if it's working fine on your applications. Maybe someone would make a uc_stock patch out of it ?

Sorry if my English is poor

checker’s picture

@barteque

There is no file?

DDJ’s picture

subscribing, not happy to read the above

barteque’s picture

FileSize
1.8 KB

Ok I'm giving it once again.
It's on my ftp http://gogol.etrius.net/Public/uc_stock_return.zip and on drupal.org...
Have fun!

Kaory’s picture

Thank you barteque!

It's working just fine.

checker’s picture

I tested it with product attributes - no problems!

calbasi’s picture

Subscribing

mo6’s picture

subscribe

vallab444’s picture

Thank you, Barteque.

I used it. Puts the stock back when an order is deleted.

Thank you for solving a major issue in UC ordering!

checker’s picture

Status: Needs review » Reviewed & tested by the community

There are three reviewer (#23). Marking this as RTBTC

TR’s picture

Status: Reviewed & tested by the community » Active

Can't be RBTC because there is nothing to commit yet! Still need a patch here people ... and the patch should address the concerns raised in #12 (works only for order cancellation, not for order deletion) and #18 (only works for entire orders, doesn't work when single products are removed from an order).

Maico de Jong’s picture

@barteque
Thanks!
Installed the module, worked great.

There's still a problem:

- When an order is canceled the stock is incremented correctly
- But when a canceled order is updated to some other status, the quantity is not reduced again.

safetypin’s picture

So, what's the status of this thread? Do we need someone to roll this into a patch for uc_stock?

longwave’s picture

"But when a canceled order is updated to some other status, the quantity is not reduced again."

This can be achieved by adding another CA predicate to check the existing status is cancelled and the new status is something other than cancelled, with an action to decrement the stock again. Perhaps this should in fact replace the current default predicate that decrements stock on checkout completion, to instead decrement stock if the current order status is either in checkout or cancelled and the new order status is neither of these.

goose2000’s picture

I think that sounds right.

Also feels like this should all be part of the shipped uc_stock module.

davidw’s picture

Subscribing.

I've got to follow this one.
Thanks everybody!

mandreato’s picture

Subscribing.

Todd Zebert’s picture

subscribe

hanoii’s picture

Version: 6.x-2.0 » 6.x-2.x-dev

I had to look at this, I was about to submit a patch but it has proven to be a bit more complex that I first thought.

One important note is that the stock is properly restored when an item is removed from an order, that's currently working, the only thing is that is not properly logged. I am submitting a patch to fix this and also stock decrement for product kits when added on admin created orders, please help review that one as well if you can #1014994: Product kit stock decrement not working and stock increment on product removal doesn't create order comment.

For this specific issue which I tried to address, I first added which was going to be a patch:

   // Update stock on order deletion
    if (module_exists('uc_stock')) {
      foreach ($order->products as $product) {
        // setting it negative so the stock goes back up
        $product->qty = -$product->qty;
        uc_stock_adjust_product_stock($product, 0, $order);
      }
      // uc_stock_adjust_product_stockThe stock of the order's products has been restored.
      drupal_set_message(t('The stock level of each product in this order has been restored.'));
    }

to uc_order_delete() but then I realized that you might delete orders which stock were never decreased, like 'in checkout' orders never completed, so I think that the idea proposed by the module on #23 to create a trigger for order deletion and then an action to restore stock is the proper way to go. It might be good to have that included in ubercart rather than in an external module. If that patch will be consider I might step in and work it out. Don't have the time right now but if @TR or any other ubercart dev might be willing to consider/include it for the next release, just give me a shout and I'll try to chip this in.

What I said above about restoring stock on order deletion which might have not been decreased applies as well for removing individual products. If you remove a product from an in_checkout order, it will increase stock.

The main problem here is that stock decrement is both mixed as conditional actions and hardcoded in the code, depending on what workflow or action you take on an order.

Ideally stock decrement/increment should be either controlled entirely by conditional actions and different triggers, or properly handled within the code when it's really necessary, which is probably more tricky. CA seems the best way but I don't think that will happen on 2.x.

epgibson’s picture

This causes problems for me too. Please keep us posted on a resolution to this bug. Thanks.

epgibson’s picture

Subscribing.

mserinjane’s picture

This module (found in post #23) works great. Simply download and enable it as normal. Go to /admin/store/ca and add a new predicate. Give it a title of 'Increment stock on canceling an order', and choose 'An order is being canceled'. Then give it the increment stock action.

You should now find that your stock is incremented when you cancel an order.

If you would rather have this work on canceling an order, open the uc_stock_return.module file in your text editor and string replace all instances of 'delete', 'deleted', and 'deleting' (case insensitive) with 'Cancel', 'Canceled', and 'Canceling'. Save and/or reupload.

chrisschaub’s picture

Can we get this up as a project on drupal.org? Esp #23 or the latest working?

Anonymous’s picture

Thank you very much Bartosz.

gutzz’s picture

Subscribing

millenniumtree’s picture

I've been using my own, custom stock implementation for YEARS because of things like this.
sub.

bwynants’s picture

same in 7.x I think a rule action should be made 'increment stock on order canceling'

amariotti’s picture

Amazing that this is still a lingering issue. Any progress here? Wish I could help...have a site needing this and maybe able to throw some money at it.

PieterDC’s picture

@millenniumtree Could you share your implementation?

Does it contain a stock log, so it knows why the stock is currently at its level?

PieterDC’s picture

Component: Code » Stock
Category: task » bug
Status: Active » Needs work
FileSize
1.72 KB

I improved the module posted by barteque. See attached.

It now also works when switching back from 'canceled' to another order status.
And it always excludes the 'in_checkout' status.
But that can be adjusted through the conditional actions interface, if you'd like.

In reply to #30:
+ it already acted on order deletion
+ the Ubercart core Order module module already handles individual product removal from an order, updating stock level

Ideally this module would be merged with the Ubercart core Stock module.

Have fun

zeezhao’s picture

subscribing

TR’s picture

@PieterDC: Can you please post a patch? A .zip file is not very useful.

PieterDC’s picture

Status: Needs work » Needs review
FileSize
7.26 KB

A .zip file containing a standalone module is super useful for people wanting this fix, without having to patch the original Ubercart module.

Nevertheless; you'll find a patch attached.
Didn't test it yet, just moved the code into the Ubercart Stock module and did some renaming ('uc_stock_return' to 'uc_stock').

longwave’s picture

Category: bug » feature
Priority: Critical » Normal
FileSize
7.03 KB

Improved version of #52 attached, moving the order delete trigger to uc_order and rearranging other code. This also disables the new predicates by default; you can easily enable them, and existing stores may already have similar CAs in place. In 7.x we can probably enable them by default if this lands before 7.x-3.0.

Quarantine’s picture

Just a quick question, these patches are only for D6 and not D7 right? If that's the case, should I open a new issue for D7 or use this thread?

longwave’s picture

We may as well use the same thread, if you can port this patch to D7 and Rules then please do so.

z-buffer’s picture

will this problem be solved in the near future?

longwave’s picture

Please test the patches and post your results here, that will help get this feature included in Ubercart.

mandreato’s picture

Status: Needs review » Reviewed & tested by the community

Patch #53 provides three new conditional actions:
- Increment stock on deleting an order
- Increment stock on cancelling order (setting its status to cancel)
- Decrement stock when order cancellation is being undone

I've tried them one by one and they work like a charm !

longwave’s picture

Version: 6.x-2.x-dev » 7.x-3.x-dev
Status: Reviewed & tested by the community » Patch (to be ported)

Committed #53 to 6.x, needs porting to 7.x.

mandreato’s picture

I don't see the changes on latest 6.x-2.x-dev.

longwave’s picture

If you're using the snapshot you may need to wait another 12-24 hours for it to update. It is in the git repo, committed in two parts:

http://drupalcode.org/project/ubercart.git/commitdiff/271cd86
http://drupalcode.org/project/ubercart.git/commitdiff/d613c06

longwave’s picture

Ported and committed the order deletion trigger to Rules in 7.x-3.x. The actual stock handling rules still need porting.

mandreato’s picture

OK, I'll wait... sorry to bother.

ndmaque’s picture

#49 PieterDC
I initally thought this was working fine, setting an order to 'cancelled' decrements stock but when i put it back to 'in_checkout' it didn't increment.

I think i am right in saying that if you change the cancelled order to any status except in_checkout the stock gets incremented again Ok.

My simple workaround was to simply remove the 'in_checkout' option when the order is set to 'cancelled' using hook_form alter, but i guess it can be done by setting/removing the conditions at admin/store/ca/uc_stock_decrement_on_uncancel/edit/conditions.

You just saved me a whole bunch of work.
Thanks

tungpham42’s picture

Version: 7.x-3.x-dev » 7.x-3.0
Status: Patch (to be ported) » Needs review
FileSize
792 bytes

Here I have a small fix on the uc_order.module file. It adjusts the stock level on order deleted. Tested but still needs review.

TR’s picture

Version: 7.x-3.0 » 7.x-3.x-dev

Testbot needs the patch against the latest dev.

longwave’s picture

Status: Needs review » Needs work

#65 should be implemented with Rules so it can be optionally enabled or have conditions added; not every site may want this feature.

tungpham42’s picture

Status: Needs work » Needs review
FileSize
2.77 KB

This patch will add the action 'Restore stock of products on the order with tracking activated.' into the Rules options. You should run cron after making change to the code. I only tested with Order being deleted event, the Order status updated can mess up the stock level.

Status: Needs review » Needs work
Issue tags: -uc_stock

The last submitted patch, restore_stock_rules_action-588746-68.patch, failed testing.

tungpham42’s picture

Status: Needs work » Needs review
Issue tags: +uc_stock
tungpham42’s picture

I updated the patch so that it logs correctly into admin comment of the orders.

longwave’s picture

This patch ports the following rules from 6.x:
- Increment stock on cancelling order
- Increment stock on deleting an order
- Decrement stock when order cancellation is being undone

These are disabled by default as this changes the behaviour of 7.x, but can easily be enabled from the Rules admin pages.

tungpham42’s picture

#72 worked like a charm, thank you

longwave’s picture

Status: Needs review » Fixed

Committed #72

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

ratinakage’s picture

Hi all..

Can this be back-ported to D6?

Thank you!!

Hannu’s picture

Status: Closed (fixed) » Active

Hi.

It seems to me that this issue is not fixed after all.

When deleting an order either by clicking the delete icon at admin/store/orders/view, or by clicking the delete button at the bottom of admin/store/orders/<number>/edit the stock level is not incremented.

The stock level increases, however, when the line item is deleted by clicking the red X icon at admin/store/orders/<number>/edit, so that is a work around at the moment.

TR’s picture

Status: Active » Postponed (maintainer needs more info)

According to #72 "These are disabled by default as this changes the behaviour of 7.x, but can easily be enabled from the Rules admin pages".

So, did you enable them on the Rules admin page?

Hannu’s picture

Good catch! No, I did not, but it was enabled anyway.
Now that I looked at the rules admin page, it says (with a red error message):

Increment stock upon order deletion
Machine name: rules_increment_stock_upon_order_deletion, Weight: 0
Error: Data selector order for parameter order is invalid.
After deleting a order product	Custom	edit	translate	disable	clone	delete	export

When I click open the edit page, it says:

Actions
ELEMENTS	OPERATIONS
 
Decrement stock of products on the order with tracking activated.
Parameter: Order: [order]
Error: Data selector order for parameter order is invalid.

And, when clicking the edit link on that:

DATA SELECTORS
SELECTOR	               LABEL	DESCRIPTION
site:current-user:roles:	User roles	The roles of the user.
uc-order-product:node:author:	Author	The author of the node.
uc-order-product:node:source:	Translation source node	The original-language version of this node, if one exists.
uc-order-product:node:body:	The main body text

I do not know what to change, so thanks for any help!

Hannu’s picture

I think I got it now!

For some reason there are TWO rules for order deletion:

Increment stock upon order deletion and Increment stock on deleting an order

The former was enabled, and shows the errors mentioned in #79, while apparently the latter is the correct one. When I enabled that (and disabled the other), the stock increment happened after I deleted an order.

Thanks for pointing me to the right direction.

longwave’s picture

Status: Postponed (maintainer needs more info) » Fixed

"Increment stock on deleting an order" is the rule currently provided by Ubercart. "Increment stock upon order deletion" is either from a contrib module, an old Ubercart patch, or was manually created, and as it doesn't work it sounds like you can safely delete it.

Status: Fixed » Closed (fixed)
Issue tags: -uc_stock

Automatically closed -- issue fixed for 2 weeks with no activity.