2

Is there a way to find out the stock level of an Ubercart product on a given date?

I can a) get the total number of items sold between a given date and today, and then b) subtract that number from the current stock level. That's not very useful, though, since the client will likely update the stock level in the interim.

If Ubercart logged changes in stock, something like this, then I think I'd be good to go:

| nid | stock_level | datestamp  | 
----------------------------------
| 23  | 15          | 1303707600 |
| 23  | 25          | 1327471200 |
3

Ubercart doesn't store that information by default, and there's no way to do it without patching the uc_stock.module file.

The reason is that the uc_stock_set() function updates the uc_product_stock database table, but doesn't invoke any hooks to allow other modules to act on that information.

If you create a patch that changes the uc_stock_set() function to this:

function uc_stock_set($sku, $qty) {
  db_query("UPDATE {uc_product_stock} SET stock = %d WHERE sku = '%s'", $qty, $sku);
  $stock = db_fetch_object(db_query("SELECT * FROM {uc_product_stock} WHERE sku = '%s'", $sku));
  module_invoke_all('uc_stock_set', $stock);
}

then you'll be able to write a custom module that implements the new hook_uc_stock_set() hook to save timestamp data to a custom table. That would look something like this:

function MYMODULE_uc_stock_set($stock) {
  db_query("INSERT INTO {MYMODULE_table} (sku, stock_level, datestamp) VALUES ('%s', %d, UNIX_TIMESTAMP())", $stock->sku, $stock->qty);
}

The uc_stock module works with the sku rather than the node id so it would be best to store that in your custom table.

The other hook you'll need to implement is one already provided by the uc_stock module, hook_uc_stock_adjusted(). Your module's implementation would look like this:

function MYMODULE_uc_stock_adjusted($sku, $prior_stock_level, $qty) {
  $stock_level = $prior_stock_level + $qty;
  db_query("INSERT INTO {MYMODULE_table} (sku, stock_level, datestamp) VALUES ('%s', %d, UNIX_TIMESTAMP())", $sku, $stock_level);
}
  • HI, thank you this works. However, after implementing, new records are written to db only if stock level is changed due to buy action. If I change stock level manually, no record is written to custom database table. Any solution for this? Thank you for help. – loparr Jul 27 '14 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.