Security update merged from 2.1.
[fa-stable.git] / gl / includes / db / gl_db_trans.inc
1 <?php
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 //--------------------------------------------------------------------------------
13
14 // Base function for adding a GL transaction
15 // $date_ is display date (non-sql)
16 // $amount is in $currency currency
17 // if $currency is not set, then defaults to no conversion
18
19 function add_gl_trans($type, $trans_id, $date_, $account, $dimension, $dimension2, $memo_,
20         $amount, $currency=null, $person_type_id=null, $person_id=null, $err_msg="", $rate=0)
21 {
22         global $use_audit_trail;
23
24         $date = date2sql($date_);
25         if ($currency != null)
26         {
27                 if ($rate == 0)
28                         $amount_in_home_currency = to_home_currency($amount, $currency, $date_);
29                 else
30                         $amount_in_home_currency = round2($amount * $rate,  user_price_dec());
31         }               
32         else
33                 $amount_in_home_currency = round2($amount, user_price_dec());
34         if ($dimension == null || $dimension < 0)
35                 $dimension = 0;
36         if ($dimension2 == null || $dimension2 < 0)
37                 $dimension2 = 0;
38         if (isset($use_audit_trail) && $use_audit_trail)
39         {
40                 if ($memo_ == "" || $memo_ == null)
41                         $memo_ = $_SESSION["wa_current_user"]->username;
42                 else
43                         $memo_ = $_SESSION["wa_current_user"]->username . " - " . $memo_;
44         }
45         $sql = "INSERT INTO ".TB_PREF."gl_trans ( type, type_no, tran_date,
46                 account, dimension_id, dimension2_id, memo_, amount";
47
48         if ($person_type_id != null)
49                 $sql .= ", person_type_id, person_id";
50
51         $sql .= ") ";
52
53         $sql .= "VALUES (".db_escape($type).", ".db_escape($trans_id).", '$date',
54                 ".db_escape($account).", ".db_escape($dimension).", "
55                 .db_escape($dimension2).", ".db_escape($memo_).", "
56                 .db_escape($amount_in_home_currency);
57
58         if ($person_type_id != null)
59                 $sql .= ", ".db_escape($person_type_id).", ". db_escape($person_id);
60
61         $sql .= ") ";
62
63         if ($err_msg == "")
64                 $err_msg = "The GL transaction could not be inserted";
65
66         db_query($sql, $err_msg);
67         return $amount_in_home_currency;
68 }
69
70 //--------------------------------------------------------------------------------
71
72 // GL Trans for standard costing, always home currency regardless of person
73 // $date_ is display date (non-sql)
74 // $amount is in HOME currency
75
76 function add_gl_trans_std_cost($type, $trans_id, $date_, $account, $dimension, $dimension2,
77         $memo_, $amount, $person_type_id=null, $person_id=null, $err_msg="")
78 {
79         if ($amount != 0)
80                 return add_gl_trans($type, $trans_id, $date_, $account, $dimension, $dimension2, $memo_,
81                         $amount, null, $person_type_id, $person_id, $err_msg);
82         else
83                 return 0;
84 }
85
86 // Function for even out rounding problems
87 function add_gl_balance($type, $trans_id, $date_, $amount, $person_type_id=null, $person_id=null)
88 {
89         $amount = round2($amount, user_price_dec());
90         if ($amount != 0)
91                 return add_gl_trans($type, $trans_id, $date_, get_company_pref('exchange_diff_act'), 0, 0, "",
92                         $amount, null, $person_type_id, $person_id, "The balanced GL transaction could not be inserted");
93         else
94                 return 0;
95 }       
96
97 //--------------------------------------------------------------------------------
98
99 function get_gl_transactions($from_date, $to_date, $trans_no=0,
100         $account=null, $dimension=0, $dimension2=0, $filter_type=null)
101 {
102         $from = date2sql($from_date);
103         $to = date2sql($to_date);
104
105         $sql = "SELECT ".TB_PREF."gl_trans.*, "
106                 .TB_PREF."chart_master.account_name FROM ".TB_PREF."gl_trans, "
107                 .TB_PREF."chart_master
108                 WHERE ".TB_PREF."chart_master.account_code=".TB_PREF."gl_trans.account
109                 AND tran_date >= '$from'
110                 AND tran_date <= '$to'";
111         if ($trans_no > 0)
112                 $sql .= " AND ".TB_PREF."gl_trans.type_no LIKE ".db_escape('%'.$trans_no);
113
114         if ($account != null)
115                 $sql .= " AND ".TB_PREF."gl_trans.account = ".db_escape($account);
116
117         if ($dimension > 0)
118                 $sql .= " AND ".TB_PREF."gl_trans.dimension_id = ".db_escape($dimension);
119
120         if ($dimension2 > 0)
121                 $sql .= " AND ".TB_PREF."gl_trans.dimension2_id = ".db_escape($dimension2);
122
123         if ($filter_type != null AND is_numeric($filter_type))
124                 $sql .= " AND ".TB_PREF."gl_trans.type= ".db_escape($filter_type);
125
126         $sql .= " ORDER BY tran_date";
127
128         return db_query($sql, "The transactions for could not be retrieved");
129 }
130
131
132 //--------------------------------------------------------------------------------
133
134 function get_gl_trans($type, $trans_id)
135 {
136         $sql = "SELECT ".TB_PREF."gl_trans.*, "
137                 .TB_PREF."chart_master.account_name FROM "
138                         .TB_PREF."gl_trans, ".TB_PREF."chart_master
139                 WHERE ".TB_PREF."chart_master.account_code=".TB_PREF."gl_trans.account
140                 AND ".TB_PREF."gl_trans.type=".db_escape($type)
141                 ." AND ".TB_PREF."gl_trans.type_no=".db_escape($trans_id);
142
143         return db_query($sql, "The gl transactions could not be retrieved");
144 }
145
146 //--------------------------------------------------------------------------------
147
148 function get_gl_wo_cost_trans($trans_id, $person_id=-1)
149 {
150         $sql = "SELECT ".TB_PREF."gl_trans.*, ".TB_PREF."chart_master.account_name FROM "
151                 .TB_PREF."gl_trans, ".TB_PREF."chart_master
152                 WHERE ".TB_PREF."chart_master.account_code=".TB_PREF."gl_trans.account
153                 AND ".TB_PREF."gl_trans.type=".ST_WORKORDER
154                 ." AND ".TB_PREF."gl_trans.type_no=".db_escape($trans_id)."
155                 AND ".TB_PREF."gl_trans.person_type_id=".PT_WORKORDER;
156         if ($person_id != -1)
157                 $sql .= " AND ".TB_PREF."gl_trans.person_id=".db_escape($person_id);
158         $sql .= " AND amount < 0";      
159
160         return db_query($sql, "The gl transactions could not be retrieved");
161 }
162
163 function get_gl_balance_from_to($from_date, $to_date, $account, $dimension=0, $dimension2=0)
164 {
165         $from = date2sql($from_date);
166         $to = date2sql($to_date);
167
168     $sql = "SELECT SUM(amount) FROM ".TB_PREF."gl_trans
169                 WHERE account='$account'";
170         if ($from_date != "")
171                 $sql .= "  AND tran_date > '$from'";
172         if ($to_date != "")
173                 $sql .= "  AND tran_date < '$to'";
174         if ($dimension > 0)
175                 $sql .= " AND dimension_id = ".db_escape($dimension);
176         if ($dimension2 > 0)
177                 $sql .= " AND dimension2_id = ".db_escape($dimension2);
178
179         $result = db_query($sql, "The starting balance for account $account could not be calculated");
180
181         $row = db_fetch_row($result);
182         return $row[0];
183 }
184
185 //--------------------------------------------------------------------------------
186
187 function get_gl_trans_from_to($from_date, $to_date, $account, $dimension=0, $dimension2=0)
188 {
189         $from = date2sql($from_date);
190         $to = date2sql($to_date);
191
192     $sql = "SELECT SUM(amount) FROM ".TB_PREF."gl_trans
193                 WHERE account='$account'";
194         if ($from_date != "")
195                 $sql .= " AND tran_date >= '$from'";
196         if ($to_date != "")
197                 $sql .= " AND tran_date <= '$to'";
198         if ($dimension > 0)
199                 $sql .= " AND dimension_id = ".db_escape($dimension);
200         if ($dimension2 > 0)
201                 $sql .= " AND dimension2_id = ".db_escape($dimension2);
202
203         $result = db_query($sql, "Transactions for account $account could not be calculated");
204
205         $row = db_fetch_row($result);
206         return $row[0];
207 }
208
209 //----------------------------------------------------------------------------------------------------
210 function get_balance($account, $dimension, $dimension2, $from, $to, $from_incl=true, $to_incl=true) 
211 {
212         $sql = "SELECT SUM(IF(amount >= 0, amount, 0)) as debit, 
213                 SUM(IF(amount < 0, -amount, 0)) as credit, SUM(amount) as balance 
214                 FROM ".TB_PREF."gl_trans,".TB_PREF."chart_master,"
215                         .TB_PREF."chart_types, ".TB_PREF."chart_class 
216                 WHERE ".TB_PREF."gl_trans.account=".TB_PREF."chart_master.account_code AND "
217                 .TB_PREF."chart_master.account_type=".TB_PREF."chart_types.id 
218                 AND ".TB_PREF."chart_types.class_id=".TB_PREF."chart_class.cid AND";
219                 
220         if ($account != null)
221                 $sql .= " account=".db_escape($account)." AND";
222         if ($dimension > 0)
223                 $sql .= " dimension_id=".db_escape($dimension)." AND";
224         if ($dimension2 > 0)
225                 $sql .= " dimension2_id=".db_escape($dimension2)." AND";
226         $from_date = date2sql($from);
227         if ($from_incl)
228                 $sql .= " tran_date >= '$from_date'  AND";
229         else
230                 $sql .= " tran_date > IF(ctype>0 AND ctype<".CL_INCOME.", '0000-00-00', '$from_date') AND";
231         $to_date = date2sql($to);
232         if ($to_incl)
233                 $sql .= " tran_date <= '$to_date' ";
234         else
235                 $sql .= " tran_date < '$to_date' ";
236
237         $result = db_query($sql,"No general ledger accounts were returned");
238
239         return db_fetch($result);
240 }
241
242 //--------------------------------------------------------------------------------
243
244 function get_budget_trans_from_to($from_date, $to_date, $account, $dimension=0, $dimension2=0)
245 {
246
247         $from = date2sql($from_date);
248         $to = date2sql($to_date);
249
250         $sql = "SELECT SUM(amount) FROM ".TB_PREF."budget_trans
251                 WHERE account=".db_escape($account);
252         if ($from_date != "")
253                 $sql .= " AND tran_date >= '$from' ";
254         if ($to_date != "")
255                 $sql .= " AND tran_date <= '$to' ";
256         if ($dimension > 0)
257                 $sql .= " AND dimension_id = ".db_escape($dimension);
258         if ($dimension2 > 0)
259                 $sql .= " AND dimension2_id = ".db_escape($dimension2);
260         $result = db_query($sql,"No budget accounts were returned");
261
262         $row = db_fetch_row($result);
263         return $row[0];
264 }
265
266 //--------------------------------------------------------------------------------
267 //      Stores journal/bank transaction tax details if applicable
268 //
269 function add_gl_tax_details($gl_code, $trans_type, $trans_no, $amount, $ex_rate, $date, $memo)
270 {
271         $tax_type = is_tax_account($gl_code);
272         if(!$tax_type) return;  // $gl_code is not tax account
273         
274         $tax = get_tax_type($tax_type);
275         //if ($gl_code == $tax['sales_gl_code']) 
276         //      $amount = -$amount;
277         // we have to restore net amount as we cannot know the base amount
278         if ($tax['rate'] == 0) {
279 //              display_warning(_("You should not post gl transactions  
280 //                      to tax account with     zero tax rate."));
281                 $net_amount = 0;
282         } else { 
283                 // calculate net amount
284                 $net_amount = $amount/$tax['rate']*100; 
285         }
286                 
287         add_trans_tax_details($trans_type, $trans_no, $tax['id'], $tax['rate'], 0, 
288                 $amount, $net_amount, $ex_rate, $date, $memo);
289                         
290 }
291
292 //--------------------------------------------------------------------------------
293 //
294 //      Store transaction tax details for fiscal purposes with 'freezed' 
295 //      actual tax type rate.
296 //
297 function add_trans_tax_details($trans_type, $trans_no, $tax_id, $rate, $included,
298         $amount, $net_amount, $ex_rate, $tran_date, $memo)
299 {
300
301         $sql = "INSERT INTO ".TB_PREF."trans_tax_details 
302                 (trans_type, trans_no, tran_date, tax_type_id, rate, ex_rate,
303                         included_in_price, net_amount, amount, memo)
304                 VALUES (".db_escape($trans_type)."," . db_escape($trans_no).",'"
305                                 .date2sql($tran_date)."',".db_escape($tax_id).","
306                                 .db_escape($rate).",".db_escape($ex_rate).",".($included ? 1:0).","
307                                 .db_escape($net_amount).","
308                                 .db_escape($amount).",".db_escape($memo).")";
309
310         db_query($sql, "Cannot save trans tax details");
311
312 }
313 //----------------------------------------------------------------------------------------
314
315 function get_trans_tax_details($trans_type, $trans_no)
316 {
317         $sql = "SELECT ".TB_PREF."trans_tax_details.*, "
318                 .TB_PREF."tax_types.name AS tax_type_name
319                 FROM ".TB_PREF."trans_tax_details,".TB_PREF."tax_types
320                 WHERE trans_type = ".db_escape($trans_type)."
321                 AND trans_no = ".db_escape($trans_no)."
322                 AND (net_amount != 0 OR amount != 0)
323                 AND ".TB_PREF."tax_types.id = ".TB_PREF."trans_tax_details.tax_type_id";
324
325         return db_query($sql, "The transaction tax details could not be retrieved");
326 }
327
328 //----------------------------------------------------------------------------------------
329
330 function void_trans_tax_details($type, $type_no)
331 {
332         $sql = "UPDATE ".TB_PREF."trans_tax_details SET amount=0, net_amount=0
333                 WHERE trans_no=".db_escape($type_no)
334                 ." AND trans_type=".db_escape($type);
335
336         db_query($sql, "The transaction tax details could not be voided");
337 }
338
339 function get_tax_summary($from, $to)
340 {
341         $fromdate = date2sql($from);
342         $todate = date2sql($to);
343
344         $sql = "SELECT 
345                                 SUM(IF(trans_type=".ST_CUSTCREDIT." || trans_type=".ST_SUPPINVOICE.",-1,1)*
346                                 IF(trans_type=".ST_BANKDEPOSIT." || trans_type=".ST_SALESINVOICE." || trans_type=".ST_CUSTCREDIT.", net_amount*ex_rate,0)) net_output,
347                                 SUM(IF(trans_type=".ST_CUSTCREDIT." || trans_type=".ST_SUPPINVOICE.",-1,1)*
348                                 IF(trans_type=".ST_BANKDEPOSIT." || trans_type=".ST_SALESINVOICE." || trans_type=".ST_CUSTCREDIT.", amount*ex_rate,0)) payable,
349                                 SUM(IF(trans_type=".ST_CUSTCREDIT." || trans_type=".ST_SUPPINVOICE.",-1,1)*
350                                 IF(trans_type=".ST_BANKDEPOSIT." || trans_type=".ST_SALESINVOICE." || trans_type=".ST_CUSTCREDIT.", 0, net_amount*ex_rate)) net_input,
351                                 SUM(IF(trans_type=".ST_CUSTCREDIT." || trans_type=".ST_SUPPINVOICE.",-1,1)*
352                                 IF(trans_type=".ST_BANKDEPOSIT." || trans_type=".ST_SALESINVOICE." || trans_type=".ST_CUSTCREDIT.", 0, amount*ex_rate)) collectible,
353                                 taxrec.rate,
354                                 ttype.id,
355                                 ttype.name
356                 FROM ".TB_PREF."tax_types ttype,
357                          ".TB_PREF."trans_tax_details taxrec
358                 WHERE taxrec.tax_type_id=ttype.id
359                         AND taxrec.trans_type != ".ST_CUSTDELIVERY."
360                         AND taxrec.tran_date >= '$fromdate'
361                         AND taxrec.tran_date <= '$todate'
362                 GROUP BY ttype.id";
363 //display_error($sql);
364     return db_query($sql,"Cannot retrieve tax summary");
365 }
366
367 //--------------------------------------------------------------------------------
368 // Write/update journal entries.
369 //
370 function write_journal_entries(&$cart, $reverse, $use_transaction=true)
371 {
372         global $Refs;
373
374         $date_ = $cart->tran_date;
375         $ref   = $cart->reference;
376         $memo_ = $cart->memo_;
377         $new = $cart->order_id == 0;
378         $trans_type = $cart->trans_type;
379         $trans_id = $new ? get_next_trans_no($trans_type) : $cart->order_id;
380
381         if ($use_transaction)
382                 begin_transaction();
383         
384         if($new) {
385                 $cart->order_id = $trans_id;
386         } else {
387                 void_journal_trans($trans_type, $trans_id, true);
388                 delete_comments($trans_type, $trans_id);
389         }
390
391         foreach ($cart->gl_items as $journal_item)
392         {
393                 // post to first found bank account using given gl acount code.
394                 $is_bank_to = is_bank_account($journal_item->code_id);
395
396                 add_gl_trans($trans_type, $trans_id, $date_, $journal_item->code_id,
397                         $journal_item->dimension_id, $journal_item->dimension2_id,
398                         $journal_item->reference, $journal_item->amount);
399         if ($is_bank_to)
400         {
401                 add_bank_trans($trans_type, $trans_id, $is_bank_to, $ref,
402                         $date_, $journal_item->amount,  0, "", get_company_currency(),
403                         "Cannot insert a destination bank transaction");
404         }
405                 // store tax details if the gl account is a tax account
406                 add_gl_tax_details($journal_item->code_id, 
407                         ($journal_item->amount < 0.0 ? ST_BANKDEPOSIT : ST_BANKPAYMENT), $trans_id, -$journal_item->amount, 1, $date_, $memo_);
408         }
409         
410         if ($new) {
411                 add_comments($trans_type, $trans_id, $date_, $memo_);
412                 $Refs->save($trans_type, $trans_id, $ref);
413         } else
414                 update_comments($trans_type, $trans_id, null, $memo_);
415
416         add_audit_trail($trans_type, $trans_id, $date_);
417
418         if ($reverse)
419         {
420         //$reversingDate = date(user_date_display(),
421         //      Mktime(0,0,0,get_month($date_)+1,1,get_year($date_)));
422         $reversingDate = begin_month(add_months($date_, 1));
423
424         $trans_id_reverse = get_next_trans_no($trans_type);
425
426         foreach ($cart->gl_items as $journal_item)
427         {
428                         $is_bank_to = is_bank_account($journal_item->code_id);
429
430                 add_gl_trans($trans_type, $trans_id_reverse, $reversingDate,
431                         $journal_item->code_id, $journal_item->dimension_id, $journal_item->dimension2_id,
432                         $journal_item->reference, -$journal_item->amount);
433                 if ($is_bank_to)
434                 {
435                         add_bank_trans($trans_type, $trans_id_reverse, $is_bank_to, $ref,
436                                 $reversingDate, -$journal_item->amount,
437                                 0, "", get_company_currency(),
438                                 "Cannot insert a destination bank transaction");
439                 }
440                         // store tax details if the gl account is a tax account
441                         add_gl_tax_details($journal_item->code_id, 
442                                 ($journal_item->amount < 0.0 ? ST_BANKDEPOSIT : ST_BANKPAYMENT), $trans_id, $journal_item->amount, 1, $date, $memo_);
443         }
444
445         add_comments($trans_type, $trans_id_reverse, $reversingDate, $memo_);
446
447         $Refs->save($trans_type, $trans_id_reverse, $ref);
448                 add_audit_trail($trans_type, $trans_id_reverse, $reversingDate);
449         }
450
451         if ($use_transaction)
452                 commit_transaction();
453
454         return $trans_id;
455 }
456
457 //--------------------------------------------------------------------------------------------------
458
459 function exists_gl_trans($type, $trans_id)
460 {
461         $sql = "SELECT type_no FROM ".TB_PREF."gl_trans WHERE type=".db_escape($type)
462                 ." AND type_no=".db_escape($trans_id);
463         $result = db_query($sql, "Cannot retreive a gl transaction");
464
465     return (db_num_rows($result) > 0);
466 }
467
468 //--------------------------------------------------------------------------------------------------
469
470 function void_gl_trans($type, $trans_id, $nested=false)
471 {
472         if (!$nested)
473                 begin_transaction();
474
475         $sql = "UPDATE ".TB_PREF."gl_trans SET amount=0 WHERE type=".db_escape($type)
476         ." AND type_no=".db_escape($trans_id);
477
478         db_query($sql, "could not void gl transactions for type=$type and trans_no=$trans_id");
479
480         if (!$nested)
481                 commit_transaction();
482 }
483
484 //----------------------------------------------------------------------------------------
485
486 function void_journal_trans($type, $type_no)
487 {
488         begin_transaction();
489
490         void_bank_trans($type, $type_no, true);
491 //      void_gl_trans($type, $type_no, true);    // this is done above
492 //      void_trans_tax_details($type, $type_no); // ditto
493
494         commit_transaction();
495 }
496
497 ?>