+/**********************************************************************
+ Copyright (C) FrontAccounting, LLC.
+ Released under the terms of the GNU General Public License, GPL,
+ as published by the Free Software Foundation, either version 3
+ of the License, or (at your option) any later version.
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
+***********************************************************************/
+//------------------- update average material cost ----------------------------------------------
+function update_average_material_cost($supplier, $stock_id, $price, $qty, $date, $adj_only=false)
+{
+ // probably this function should be optimized
+ // passing transaction cart as argument. This would
+ // save a couple of db calls like get_supplier()
+
+ $supp = get_supplier($supplier);
+ if ($supplier != null)
+ $currency = $supp['curr_code'];
+ else
+ $currency = null;
+
+ if ($supp['tax_included'])
+ $price = get_tax_free_price_for_item($stock_id, $price, $supp['tax_group_id'],
+ $supp['tax_included']);
+
+ if ($currency != null)
+ {
+ $ex_rate = get_exchange_rate_to_home_currency($currency, $date);
+ $price_in_home_currency = $price / $ex_rate;
+ }
+ else
+ $price_in_home_currency = $price;
+
+ $price_in_home_currency_ = $price_in_home_currency;
+
+ // Handle if inventory will become negative
+ // Skip negative inventory adjustment for case of adjust_only
+ if (is_inventory_item($stock_id) && !$adj_only)
+ handle_negative_inventory($stock_id, $qty, $price_in_home_currency, $date);
+
+ $sql = "SELECT mb_flag, material_cost FROM ".TB_PREF."stock_master WHERE stock_id=".db_escape($stock_id);
+ $result = db_query($sql);
+ $myrow = db_fetch($result);
+ $material_cost = $myrow['material_cost'];
+
+ $cost_adjust = false;
+
+ $qoh = get_qoh_on_date($stock_id);
+
+ if ($adj_only)
+ {
+ if ($qoh > 0)
+ $material_cost = ($qoh * $material_cost + $qty * $price_in_home_currency) / $qoh;
+ }
+ else
+ {
+ if ($qoh < 0)
+ {
+ if ($qoh + $qty >= 0)
+ $cost_adjust = true;
+ $qoh = 0;
+ }
+ if ($qoh + $qty > 0)
+ $material_cost = ($qoh * $material_cost + $qty * $price_in_home_currency) / ($qoh + $qty);
+ }
+
+ if ($cost_adjust) // Material_cost replaced with price
+ adjust_deliveries($stock_id, $price_in_home_currency_, $date);
+ $sql = "UPDATE ".TB_PREF."stock_master SET material_cost=".db_escape($material_cost)."
+ WHERE stock_id=".db_escape($stock_id);
+
+ db_query($sql,"The cost details for the inventory item could not be updated");
+ return $material_cost;
+}