2 /**********************************************************************
3 Copyright (C) FrontAccounting, LLC.
4 Released under the terms of the GNU General Public License, GPL,
5 as published by the Free Software Foundation, either version 3
6 of the License, or (at your option) any later version.
7 This program is distributed in the hope that it will be useful,
8 but WITHOUT ANY WARRANTY; without even the implied warranty of
9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 function add_exchange_variation($trans_no, $date_, $acc_id, $account,
13 $currency, $person_type_id=null, $person_id = "")
15 if (is_company_currency($currency))
21 // We have to calculate all the currency accounts belonging to the GL account
22 // upto $date_ and calculate with the exchange rates. And then compare with the GL account balance.
23 // 2010-02-23 Joe Hunt with help of Ary Wibowo
24 $sql = "SELECT SUM(bt.amount) AS for_amount, ba.bank_curr_code
25 FROM ".TB_PREF."bank_trans bt, ".TB_PREF."bank_accounts ba
26 WHERE ba.id = bt.bank_act AND ba.account_code = ".db_escape($account)." AND bt.trans_date<='".date2sql($date_)."'
27 GROUP BY ba.bank_curr_code";
28 $result = db_query($sql, "Transactions for bank account $acc_id could not be calculated");
29 while ($row = db_fetch($result))
31 if ($row['for_amount'] == 0)
33 $rate = get_exchange_rate_from_home_currency($row['bank_curr_code'], $date_);
34 $for_amount += round2($row['for_amount'] * $rate, user_price_dec());
36 $amount = get_gl_trans_from_to("", $date_, $account);
37 $diff = $amount - $for_amount;
38 if (floatcmp($diff,0))
40 // generate journal entry // FIXME: use cart?
44 $trans_no = get_next_trans_no(ST_JOURNAL);
45 $ref = $Refs->get_next(ST_JOURNAL);
47 add_journal(ST_JOURNAL, $trans_no, $diff, $date_ , $currency, $ref, '', $rate, $date_, $date_);
48 $Refs->save(ST_JOURNAL, $trans_no, $ref);
49 add_audit_trail(ST_JOURNAL, $trans_no, $date_);
50 add_comments(ST_JOURNAL, $trans_no, $date_, $memo);
52 if ($person_type_id == null)
53 $person_type_id = PT_MISC;
54 add_gl_trans(ST_JOURNAL, $trans_no, $date_, $account, 0, 0, _("Exchange Variance"),
55 $diff, null, $person_type_id, $person_id);
57 // positive change in value is positive variance for AR and bank accounts, and negative for AP
58 $variance_act = ($diff < 0 && $person_id==PT_SUPPLIER) || ($diff > 0 && $person_id != PT_SUPPLIER)
59 ? 'exchange_diff_act' : 'exchange_diff_neg_act';
60 add_gl_trans(ST_JOURNAL, $trans_no, $date_, get_company_pref('exchange_diff_act'), 0, 0,
61 _("Exchange Variance"), -$diff, null, $person_type_id, $person_id);
68 //------------- New helper functions for revaluation of customer/supplier currencies 2011-05-08 Joe Hunt.
69 function add_cust_supp_revaluation($ledger_act, $ex_act, $date, $amount, $person_type_id, $person_id, $memo)
76 $trans_no = get_next_trans_no(ST_JOURNAL);
77 $ref = $Refs->get_next(ST_JOURNAL);
79 add_journal(ST_JOURNAL, $trans_no, $amount, $date, $currency, $ref, '', $rate, $date, $date);
80 $Refs->save(ST_JOURNAL, $trans_no, $ref);
81 add_audit_trail(ST_JOURNAL, $trans_no, $date);
83 add_gl_trans(ST_JOURNAL, $trans_no, $date, $ledger_act, 0, 0, _("Exchange Variance"),
84 $amount, null, $person_type_id, $person_id);
85 add_gl_trans(ST_JOURNAL, $trans_no, $date, $ex_act, 0, 0,
86 _("Exchange Variance"), -$amount, null, $person_type_id, $person_id);
87 add_comments(ST_JOURNAL, $trans_no, $date, $memo);
91 function get_cust_account_curr_balances($date)
93 $to = date2sql($date);
95 $sql = "SELECT SUM(IF(t.type =".ST_CUSTCREDIT." OR t.type = ".ST_CUSTPAYMENT." OR t.type = ".ST_BANKDEPOSIT.",
96 -(t.ov_amount + t.ov_gst + t.ov_freight + t.ov_freight_tax + t.ov_discount),
97 (t.ov_amount + t.ov_gst + t.ov_freight + t.ov_freight_tax + t.ov_discount))) AS amount,
98 dt.debtor_no, dt.name, dt.curr_code, b.receivables_account
99 FROM ".TB_PREF."debtor_trans t
100 LEFT JOIN ".TB_PREF."debtors_master dt ON t.debtor_no = dt.debtor_no
101 LEFT JOIN ".TB_PREF."cust_branch b ON t.debtor_no = b.debtor_no
102 LEFT JOIN ".TB_PREF."voided as v ON v.type = t.type and v.id=t.trans_no
103 WHERE ISNULL(v.date_) AND t.type <> ".ST_CUSTDELIVERY." AND t.tran_date <= '$to'
104 AND t.branch_code=b.branch_code AND dt.curr_code<>'".get_company_pref('curr_default')."'
105 GROUP BY t.debtor_no, b.receivables_account";
107 $result = db_query($sql,"Open balances in foreign currency for cannot be retrieved");
111 function get_supp_account_curr_balances($date)
113 $to = date2sql($date);
115 $sql = "SELECT SUM(-(t.ov_amount + t.ov_gst + t.ov_discount)) AS amount,
116 supp.supplier_id, supp.supp_name, supp.curr_code, supp.payable_account
117 FROM ".TB_PREF."supp_trans t
118 LEFT JOIN ".TB_PREF."suppliers supp ON t.supplier_id = supp.supplier_id
119 LEFT JOIN ".TB_PREF."voided as v ON v.type = t.type and v.id=t.trans_no
120 WHERE ISNULL(v.date_) AND t.tran_date <= '$to'
121 AND supp.curr_code<>'".get_company_pref('curr_default')."'
122 GROUP BY t.supplier_id";
124 $result = db_query($sql,"Open balances in foreign currency for cannot be retrieved");
128 function get_account_home_balance($person_id, $person_type, $rec_account, $to_date)
130 $to = date2sql($to_date);
132 $sql = "SELECT SUM(amount) FROM ".TB_PREF."gl_trans
133 WHERE person_id=".db_escape($person_id)." AND account='$rec_account'
134 AND person_type_id=$person_type AND tran_date <= '$to'";
135 $result = db_query($sql, "The AR/AP balance for customer $person_id could not be calculated");
136 $row = db_fetch_row($result);
139 //------------- New helper functions for revaluation of customer/supplier currencies 2011-05-08 Joe Hunt.
141 function add_exchange_variation_all($date=null, $ref="", $memo)
146 $trans_no = get_next_trans_no(ST_JOURNAL);
147 $sql = "SELECT * FROM ".TB_PREF."bank_accounts";
148 $result = db_query($sql, "could not retreive bank accounts");
149 while ($myrow = db_fetch($result))
151 if (add_exchange_variation($trans_no, $date, $myrow['id'], $myrow['account_code'],
152 $myrow['bank_curr_code']))
157 add_comments(ST_JOURNAL, $trans_no, $date, $memo);
159 $ref = $Refs->get_next(ST_JOURNAL);
160 $Refs->save(ST_JOURNAL, $trans_no, $ref);
161 add_audit_trail(ST_JOURNAL, $trans_no, $date);
164 //------------- BEGIN inserted for revaluation of customer/supplier currencies 2011-05-08 Joe Hunt.
167 $exchange_act = get_company_pref('exchange_diff_act');
170 $res = get_cust_account_curr_balances($date);
172 while($row = db_fetch($res))
174 $exrate = get_exchange_rate_from_home_currency($row['curr_code'], $date);
175 $foreign = round2($row['amount']*$exrate, user_price_dec());
176 $home = round2(get_account_home_balance($row['debtor_no'], PT_CUSTOMER, $row['receivables_account'], $date), user_price_dec());
177 if ($foreign != $home)
179 $amount = $foreign - $home;
180 add_cust_supp_revaluation($row['receivables_account'], $exchange_act, $date, $amount, PT_CUSTOMER,
181 $row['debtor_no'], $memo);
186 $res = get_supp_account_curr_balances($date);
188 while($row = db_fetch($res))
190 $exrate = get_exchange_rate_from_home_currency($row['curr_code'], $date);
191 $foreign = round2($row['amount']*$exrate, user_price_dec());
192 $home = round2(get_account_home_balance($row['supplier_id'], PT_SUPPLIER, $row['payable_account'], $date), user_price_dec());
193 if ($foreign != $home)
195 $amount = $foreign - $home;
196 add_cust_supp_revaluation($row['payable_account'], $exchange_act, $date, $amount, PT_SUPPLIER,
197 $row['supplier_id'], $memo);
203 commit_transaction();
204 return array(($exchanged ? $trans_no : 0), $je);
206 //----------------------------------------------------------------------------------
207 // Add bank tranfer to database.
209 // $from_account - source bank account id
210 // $to_account - target bank account id
213 function add_bank_transfer($from_account, $to_account, $date_,
214 $amount, $ref, $memo_, $charge=0, $target_amount=0)
216 global $Refs, $SysPrefs;
219 $args = func_get_args(); if (count($args) < 8) $args[] = 0;
220 $args = (object)array_combine(array('from_account', 'to_account', 'date_', 'amount',
221 'ref', 'memo_', 'charge', 'target_amount'), $args);
223 hook_db_prewrite($args, ST_BANKTRANSFER);
225 $trans_type = ST_BANKTRANSFER;
227 $currency = get_bank_account_currency($from_account);
229 $trans_no = get_next_trans_no($trans_type);
231 $fromact = get_bank_account($from_account);
232 $toact = get_bank_account($to_account);
233 $person_id = _("From")." ".$fromact['bank_account_name']." "._("To")." ".$toact['bank_account_name'];
235 $from_gl_account = get_bank_gl_account($from_account);
236 $to_gl_account = get_bank_gl_account($to_account);
240 // do the source account postings
241 $total += add_gl_trans($trans_type, $trans_no, $date_, $from_gl_account, 0, 0, $person_id,
242 -($amount + $charge), $currency);
244 add_bank_trans($trans_type, $trans_no, $from_account, $ref,
245 $date_, -($amount + $charge),
246 PT_MISC, $person_id, $currency,
247 "Cannot insert a source bank transaction");
248 if ($SysPrefs->auto_currency_revaluation())
250 $trans_no1 = get_next_trans_no(ST_JOURNAL);
251 if (add_exchange_variation($trans_no1, $date_, $from_account, $from_gl_account,
252 $currency, PT_MISC, $person_id))
257 /* Now Debit bank charge account with charges */
258 $charge_act = get_bank_charge_account($from_account);
259 $total += add_gl_trans($trans_type, $trans_no, $date_,
260 $charge_act, 0, 0, $person_id, $charge, $currency);
263 // provide backward compatibility for extension modules (target amount can be not passed)
264 $to_currency = $target_amount ? $toact['bank_curr_code'] : $currency;
265 $to_amount = $target_amount ? $target_amount : $amount;
267 // do the destination account postings
268 $total += add_gl_trans($trans_type, $trans_no, $date_, $to_gl_account, 0, 0, $person_id,
269 $to_amount, $to_currency);
271 /*Post a balance post if $total != 0 */
272 if ($currency == $to_currency)
273 add_gl_balance($trans_type, $trans_no, $date_, -$total);
274 else // in this case those are exchange variances between bank and home rates
275 add_gl_trans($trans_type, $trans_no, $date_, get_company_pref('exchange_diff_act'),
276 0, 0, _("Exchange Variance"), -$total);
278 add_bank_trans($trans_type, $trans_no, $to_account, $ref,
279 $date_, $to_amount, PT_MISC, $person_id,
280 $to_currency, "Cannot insert a destination bank transaction");
282 if ($SysPrefs->auto_currency_revaluation())
284 $currency = get_bank_account_currency($to_account);
285 if (add_exchange_variation($trans_no1, $date_, $to_account, $to_gl_account,
286 $currency, PT_MISC, $person_id))
289 if ($exchanged == true)
291 $ref1 = $Refs->get_next(ST_JOURNAL);
292 $Refs->save(ST_JOURNAL, $trans_no1, $ref1);
293 add_audit_trail(ST_JOURNAL, $trans_no1, $date_);
295 add_comments($trans_type, $trans_no, $date_, $memo_);
297 $Refs->save($trans_type, $trans_no, $ref);
298 add_audit_trail($trans_type, $trans_no, $date_);
300 $args->trans_no = $trans_no;
301 hook_db_postwrite($args, ST_BANKTRANSFER);
302 commit_transaction();
307 function check_bank_transfer(
308 $trans_no, $from_account, $to_account, $date_,
309 $amount, $target_amount=0)
311 $dbResult = get_bank_trans(ST_BANKTRANSFER, $trans_no);
312 if (2 != db_num_rows($dbResult)) {
313 // How are errors handled? Throw an exception would be nice. CP 2014-10
316 $old_from = db_fetch($dbResult);
317 $old_to = db_fetch($dbResult);
318 if ($old_to['amount'] < 0.0) {
323 // There are four accounts to consider:
324 // 1) The original from account that is being voided. This results in funds being put back which is always fine.
325 // 2) The original to account that is being voided. This results in funds being removed which may result in a
326 // negative balance in the account at some time and therefore needs to be checked.
327 $problemTransaction = check_bank_account_history(-$old_to['amount'], $old_to['bank_act'], sql2date($old_to['trans_date']));
328 if ($problemTransaction) {
329 // If the destination account is the same as that being edited, it may be that this edit will resolve the
330 // problem of voiding.
331 if ($to_account == $old_to['bank_act'] && sql_date_comp($problemTransaction['trans_date'], date2sql($date_)) >= 0) {
332 $problemTransaction = check_bank_account_history($target_amount-$old_to['amount'], $to_account, $date_);
335 if (null != $problemTransaction) {
336 $problemTransaction['account'] = $old_to['bank_act'];
337 $problemTransaction['bank_account_name'] = $old_to['bank_account_name'];
338 return $problemTransaction;
341 // 3) The edited from account, that is having funds removed which may result in a
342 // negative balance in the account at some time and therefore needs to be checked.
343 $problemTransaction = check_bank_account_history(-$amount, $from_account, $date_);
344 if ($problemTransaction) {
345 // If the target account is the same as that being edited, it may be that voiding old transfer will
346 // solve balance problem.
348 if ($from_account == $old_from['bank_act'] && sql_date_comp($problemTransaction['trans_date'], $old_from['trans_date']) >=0 ) {
349 $problemTransaction = check_bank_account_history(-$amount-$old_from['amount'], $from_account, $date_);
353 if (null != $problemTransaction) {
354 $problemTransaction['account'] = $old_from['bank_act'];
355 $problemTransaction['bank_account_name'] = $old_from['bank_account_name'];
356 return $problemTransaction;
358 // 4) The edited to account, that is having funds added which is always ok.
360 return $problemTransaction;
364 function update_bank_transfer(
365 $trans_no, $from_account, $to_account, $date_,
366 $amount, $ref, $memo_, $charge=0, $target_amount=0)
369 delete_comments(ST_BANKTRANSFER, $trans_no);
370 void_bank_trans(ST_BANKTRANSFER, $trans_no, true);
371 void_gl_trans(ST_BANKTRANSFER, $trans_no, true);
372 $new_trans_no = add_bank_transfer(
373 $from_account, $to_account, $date_, $amount,
374 $ref, $memo_, $charge, $target_amount
376 commit_transaction();
377 return $new_trans_no;
380 //----------------------------------------------------------------------------------
381 // Add bank payment or deposit to database.
383 // $from_account - bank account id
384 // $items - transaction cart (line amounts in bank account's currency); negative for deposit
385 // $person_type_id - defines type of $person_id identifiers
386 // $person_id - supplier/customer/other id
387 // $person_detail_id - customer branch id or not used
388 // $settled_amount - settled amount in AR/AP (if applicable) in customer/supplier currency (always non-negative number)
390 // returns an array of (inserted trans type, trans no)
392 // FIXME -revise code for update case
394 function write_bank_transaction($trans_type, $trans_no, $from_account, $items, $date_,
395 $person_type_id, $person_id, $person_detail_id, $ref, $memo_, $use_transaction=true, $settled_amount=null)
397 global $Refs, $SysPrefs;
399 // we can only handle type 1 (payment)and type 2 (deposit)
400 if ($trans_type != ST_BANKPAYMENT && $trans_type != ST_BANKDEPOSIT)
401 display_db_error("Invalid type ($trans_type) sent to add_bank_transaction");
403 $do_exchange_variance = false;
405 if ($use_transaction)
408 $args = func_get_args(); if (count($args) < 11) $args[] = true;
409 $args = (object)array_combine(array('trans_type', 'trans_no', 'from_account', 'items', 'date_',
410 'person_type_id', 'person_id', 'person_detail_id', 'ref', 'memo_', 'use_transaction', 'settled_amount'),
412 hook_db_prewrite($args, $trans_type);
416 $old_trans = $trans_no;
417 $Refs->restore_last($trans_type, $trans_no);
418 $aid = has_attachment($trans_type, $trans_no);
421 $currency = get_bank_account_currency($from_account);
422 $bank_gl_account = get_bank_gl_account($from_account);
424 // the gl items are already inversed/negated for type 2 (deposit)
425 $total_amount = $items->gl_items_total();
427 if ($person_type_id == PT_CUSTOMER)
429 // we need to add a customer transaction record
430 // convert to customer currency
431 if (!isset($settled_amount)) // leaved for backward/ext compatibility
432 $cust_amount = exchange_from_to(abs($total_amount), $currency, get_customer_currency($person_id), $date_);
434 $cust_amount = $settled_amount;
436 if ($trans_type == ST_BANKPAYMENT)
437 $cust_amount = -$cust_amount;
439 $trans_no = write_customer_trans($trans_type, 0, $person_id, $person_detail_id, $date_,
441 move_trans_attachments($trans_type, $old_trans, $trans_no);
443 elseif ($person_type_id == PT_SUPPLIER)
445 // we need to add a supplier transaction record
446 // convert to supp currency
447 if (!isset($settled_amount)) // leaved for for backward/ext compatibility
448 $supp_amount = exchange_from_to(abs($total_amount), $currency, get_supplier_currency($person_id), $date_);
450 $supp_amount = $settled_amount;
452 if ($trans_type == ST_BANKPAYMENT)
453 $supp_amount = -$supp_amount;
455 $trans_no = write_supp_trans($trans_type, 0, $person_id, $date_, '',
456 $ref, "", $supp_amount, 0, 0);
457 move_trans_attachments($trans_type, $old_trans, $trans_no);
461 $trans_no = get_next_trans_no($trans_type);
462 $do_exchange_variance = $SysPrefs->auto_currency_revaluation();
463 if ($do_exchange_variance)
464 $trans_no1 = get_next_trans_no(ST_JOURNAL);
468 $row = get_attachment($aid);
469 update_attachment($aid, $row['type_no'], $trans_no, $row['description'],
470 $row['filename'], $row['unique_name'], $row['filesize'], $row['filetype']);
472 // do the source account postings
474 add_bank_trans($trans_type, $trans_no, $from_account, $ref,
475 $date_, -$total_amount,
476 $person_type_id, $person_id,
478 "Cannot insert a source bank transaction");
480 foreach ($items->gl_items as $gl_item)
482 $is_bank_to = is_bank_account($gl_item->code_id);
484 if ($trans_type == ST_BANKPAYMENT AND $is_bank_to)
486 // we don't allow payments to go to a bank account. use transfer for this !
487 display_db_error("invalid payment entered. Cannot pay to another bank account", "");
490 // do the destination account postings
491 $total += add_gl_trans($trans_type, $trans_no, $date_, $gl_item->code_id,
492 $gl_item->dimension_id, $gl_item->dimension2_id, $gl_item->reference,
493 $gl_item->amount, $currency, $person_type_id, $person_id);
497 add_bank_trans($trans_type, $trans_no, $is_bank_to, $ref,
498 $date_, $gl_item->amount,
499 $person_type_id, $person_id, $currency,
500 "Cannot insert a destination bank transaction");
501 if ($do_exchange_variance)
503 add_exchange_variation($trans_no1, $date_, $is_bank_to, $gl_item->code_id,
504 $currency, $person_type_id, $person_id);
507 // store tax details if the gl account is a tax account
509 $amount = $gl_item->amount;
510 $ex_rate = get_exchange_rate_from_home_currency($currency, $date_);
512 add_gl_tax_details($gl_item->code_id, $trans_type, $trans_no, -$amount,
513 $ex_rate, $date_, $memo_);
516 // do the source account postings
517 add_gl_trans($trans_type, $trans_no, $date_, $bank_gl_account, 0, 0, $memo_,
518 -$total, null, $person_type_id, $person_id);
520 if ($do_exchange_variance)
522 if ($exchanged || add_exchange_variation($trans_no1, $date_, $from_account, $bank_gl_account,
523 $currency, $person_type_id, $person_id))
525 $ref1 = $Refs->get_next(ST_JOURNAL);
526 $Refs->save(ST_JOURNAL, $trans_no1, $ref1);
527 add_audit_trail(ST_JOURNAL, $trans_no1, $date_);
531 add_comments($trans_type, $trans_no, $date_, $memo_);
533 $Refs->save($trans_type, $trans_no, $ref);
534 add_audit_trail($trans_type, $trans_no, $date_);
536 // old transaction can be voided only after new transaction is entered,
537 // otherwise the operation could fail for cash accounts due to temporary negative balance
539 void_transaction($trans_type, $old_trans, Today(), _("Document reentered."));
541 $args->trans_no = $trans_no;
542 hook_db_postwrite($args, $trans_type);
543 if ($use_transaction)
544 commit_transaction();
546 return array($trans_type, $trans_no);