+/*
+ Returns quantity and total cost of $stock_id purchases, entered after record with $move_id
+*/
+function get_purchases_from_trans($stock_id, $move_id)
+{
+ // Calculate All inward stock moves i.e. qty > 0
+ $sql = "SELECT SUM(qty), SUM(qty*standard_cost)
+ FROM ".TB_PREF."stock_moves
+ WHERE stock_id=".db_escape($stock_id)." AND qty > 0 AND
+ trans_id>'$move_id' GROUP BY stock_id";
+ $result = db_query($sql, "Could not get get_purchases_from_trans");
+ $row = db_fetch_row($result);
+
+ return $row;
+}
+
+//-------------------------------------------------------------------
+/*
+ This routine fixes stock and COGS balances for all $stock_id sales made during negative inventory status.
+ This is called when delivery is received causing inventory status to be positive again.
+*/
+function adjust_deliveries($stock_id, $material_cost, $to)
+{
+ global $Refs;
+
+ if (!is_inventory_item($stock_id))
+ return;
+
+ $move_id = last_negative_stock_trans_id($stock_id, $to);
+ if ($move_id == false || $move_id == -1)
+ return;
+
+ $row = get_deliveries_from_trans($stock_id, $move_id);
+
+ if ($row == false)
+ return;
+ $old_sales_cost = $row[1];
+ $new_sales_cost = $row[0] * $material_cost;
+ $sales_diff = $new_sales_cost - $old_sales_cost;
+
+ $row = get_purchases_from_trans($stock_id, $move_id);
+ $purchase_diff = 0;
+ $old_purchase_cost = $new_purchase_cost = 0;
+ if ($row != false)
+ {
+ $old_purchase_cost = $row[1];
+ $new_purchase_cost = $row[0] * $material_cost;
+ $purchase_diff = $new_purchase_cost - $old_purchase_cost;
+ }
+
+ $diff = $sales_diff - $purchase_diff;
+
+ if ($diff != 0)
+ {
+ $stock_gl_code = get_stock_gl_code($stock_id);
+
+ $dec = user_price_dec();
+ $old_cost = -round2($old_sales_cost-$old_purchase_cost,$dec);
+ $new_cost = -round2($new_sales_cost-$new_purchase_cost,$dec);
+
+ $cart = new items_cart(ST_COSTUPDATE);
+ $cart->tran_date = $cart->doc_date = $cart->event_date = $to;
+ if (!is_date_in_fiscalyear($cart->tran_date))
+ $cart->tran_date = end_fiscalyear();
+ $cart->reference = $Refs->get_next(ST_COSTUPDATE, null, $cart->tran_date, $to);
+
+ $cart->memo_ = _("Cost was ") . $old_cost. _(" changed to ") . $new_cost . _(" for item ")."'$stock_id'";
+
+ $cart->add_gl_item($stock_gl_code["cogs_account"], $stock_gl_code["dimension_id"], $stock_gl_code["dimension2_id"], $diff);
+ $cart->add_gl_item($stock_gl_code["inventory_account"], 0, 0, -$diff);
+
+ write_journal_entries($cart);
+ }
+}
+
+function get_stock_gl_code($stock_id)
+{
+ /*Gets the GL Codes relevant to the item account */
+ $sql = "SELECT mb_flag, inventory_account, cogs_account,
+ adjustment_account, sales_account, wip_account, dimension_id, dimension2_id FROM
+ ".TB_PREF."stock_master WHERE stock_id = ".db_escape($stock_id);