Get historical stock level in Ubercart 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 |
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-&gt;sku, $stock-&gt;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);
}