+function get_domestic_price($myrow, $stock_id)
+{
+ if ($myrow['type'] == ST_SUPPRECEIVE || $myrow['type'] == ST_SUPPCREDIT)
+ {
+ $price = $myrow['price'];
+ if ($myrow['person_id'] > 0)
+ {
+ // Do we have foreign currency?
+ $supp = get_supplier($myrow['person_id']);
+ $currency = $supp['curr_code'];
+ $ex_rate = $myrow['ex_rate'];
+ $price *= $ex_rate;
+ }
+ }
+ else
+ $price = $myrow['standard_cost']; //pick standard_cost for sales deliveries
+
+ return $price;
+}
+
+function getAverageCost($stock_id, $location, $to_date)
+{
+ if ($to_date == null)
+ $to_date = Today();
+
+ $to_date = date2sql($to_date);
+
+ $sql = "SELECT move.*, supplier.supplier_id person_id, IF(ISNULL(grn.rate), credit.rate, grn.rate) ex_rate
+ FROM ".TB_PREF."stock_moves move
+ LEFT JOIN ".TB_PREF."supp_trans credit ON credit.trans_no=move.trans_no AND credit.type=move.type
+ LEFT JOIN ".TB_PREF."grn_batch grn ON grn.id=move.trans_no AND 25=move.type
+ LEFT JOIN ".TB_PREF."suppliers supplier ON IFNULL(grn.supplier_id, credit.supplier_id)=supplier.supplier_id
+ LEFT JOIN ".TB_PREF."debtor_trans cust_trans ON cust_trans.trans_no=move.trans_no AND cust_trans.type=move.type
+ LEFT JOIN ".TB_PREF."debtors_master debtor ON cust_trans.debtor_no=debtor.debtor_no
+ WHERE stock_id=".db_escape($stock_id)."
+ AND move.tran_date <= '$to_date' AND standard_cost > 0.001 AND qty <> 0 AND move.type <> ".ST_LOCTRANSFER;
+
+ if ($location != 'all')
+ $sql .= " AND move.loc_code = ".db_escape($location);
+
+ $sql .= " ORDER BY tran_date";
+
+ $result = db_query($sql, "No standard cost transactions were returned");
+
+ if ($result == false)
+ return 0;
+ $qty = $tot_cost = 0;
+ while ($row=db_fetch($result))
+ {
+ $qty += $row['qty'];
+ $price = get_domestic_price($row, $stock_id);
+ $tran_cost = $row['qty'] * $price;
+ $tot_cost += $tran_cost;
+ }
+ if ($qty == 0)
+ return 0;
+ return $tot_cost / $qty;
+}
+