+function add_exchange_variation($trans_no, $date_, $acc_id, $account,
+ $currency, $person_type_id=null, $person_id = "")
+{
+ if (is_company_currency($currency))
+ return false;
+ if ($date_ == null)
+ $date_ = Today();
+ $for_amount = 0;
+
+ // We have to calculate all the currency accounts belonging to the GL account
+ // upto $date_ and calculate with the exchange rates. And then compare with the GL account balance.
+ // 2010-02-23 Joe Hunt with help of Ary Wibowo
+ $sql = "SELECT SUM(bt.amount) AS for_amount, ba.bank_curr_code
+ FROM ".TB_PREF."bank_trans bt, ".TB_PREF."bank_accounts ba
+ WHERE ba.id = bt.bank_act AND ba.account_code = ".db_escape($account)." AND bt.trans_date<='".date2sql($date_)."'
+ GROUP BY ba.bank_curr_code";
+ $result = db_query($sql, "Transactions for bank account $acc_id could not be calculated");
+ while ($row = db_fetch($result))
+ {
+ if ($row['for_amount'] == 0)
+ continue;
+ $rate = get_exchange_rate_from_home_currency($row['bank_curr_code'], $date_);
+ $for_amount += round2($row['for_amount'] * $rate, user_price_dec());
+ }
+ $amount = get_gl_trans_from_to("", $date_, $account);
+ $diff = $amount - $for_amount;
+ if ($diff != 0)
+ {
+ if ($trans_no == null)
+ $trans_no = get_next_trans_no(ST_JOURNAL);
+ if ($person_type_id == null)
+ $person_type_id = PT_MISC;
+ add_gl_trans(ST_JOURNAL, $trans_no, $date_, $account, 0, 0, _("Exchange Variance"),
+ -$diff, null, $person_type_id, $person_id);
+ add_gl_trans(ST_JOURNAL, $trans_no, $date_, get_company_pref('exchange_diff_act'), 0, 0,
+ _("Exchange Variance"), $diff, null, $person_type_id, $person_id);
+ }
+ return ($diff != 0);
+}
+
+function add_exchange_variation_all($date=null, $ref="", $memo)
+{
+ global $Refs;
+ begin_transaction();
+ $exchanged = false;
+ $trans_no = get_next_trans_no(ST_JOURNAL);
+ $sql = "SELECT * FROM ".TB_PREF."bank_accounts";
+ $result = db_query($sql, "could not retreive bank accounts");
+ while ($myrow = db_fetch($result))
+ {
+ if (add_exchange_variation($trans_no, $date, $myrow['id'], $myrow['account_code'],
+ $myrow['bank_curr_code']))
+ $exchanged = true;
+ }
+ if ($exchanged)
+ {
+ add_comments(ST_JOURNAL, $trans_no, $date, $memo);
+ if ($ref == "")
+ $ref = $Refs->get_next(ST_JOURNAL);
+ $Refs->save(ST_JOURNAL, $trans_no, $ref);
+ add_audit_trail(ST_JOURNAL, $trans_no, $date);
+ }
+ commit_transaction();
+ return ($exchanged ? $trans_no : 0);
+}