a05959b81878cfca93b77e0f636a671a45424085
[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 $SysPrefs;
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($SysPrefs->use_audit_trail) && $SysPrefs->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         if (!is_subledger_account($account) || $account==get_company_pref('grn_clearing_act'))
46                 $person_id = $person_type_id = null;
47         
48         $sql = "INSERT INTO ".TB_PREF."gl_trans ( type, type_no, tran_date,
49                 account, dimension_id, dimension2_id, memo_, amount";
50
51         if ($person_type_id != null)
52                 $sql .= ", person_type_id, person_id";
53
54         $sql .= ") ";
55
56         $sql .= "VALUES (".db_escape($type).", ".db_escape($trans_id).", '$date',
57                 ".db_escape($account).", ".db_escape($dimension).", "
58                 .db_escape($dimension2).", ".db_escape($memo_).", "
59                 .db_escape($amount_in_home_currency);
60
61         if ($person_type_id != null)
62                 $sql .= ", ".db_escape($person_type_id).", ". db_escape($person_id);
63
64         $sql .= ") ";
65
66         if ($err_msg == "")
67                 $err_msg = "The GL transaction could not be inserted";
68
69         db_query($sql, $err_msg);
70         return $amount_in_home_currency;
71 }
72
73 //--------------------------------------------------------------------------------
74
75 // GL Trans for standard costing, always home currency regardless of person
76 // $date_ is display date (non-sql)
77 // $amount is in HOME currency
78
79 function add_gl_trans_std_cost($type, $trans_id, $date_, $account, $dimension, $dimension2,
80         $memo_, $amount, $person_type_id=null, $person_id=null, $err_msg="")
81 {
82
83         if ($amount != 0)
84                 return add_gl_trans($type, $trans_id, $date_, $account, $dimension, $dimension2, $memo_,
85                         $amount, null, $person_type_id, $person_id, $err_msg);
86         else
87                 return 0;
88 }
89
90 // Function for even out rounding problems
91 function add_gl_balance($type, $trans_id, $date_, $amount, $person_type_id=null, $person_id=null)
92 {
93         $amount = round2($amount, user_price_dec());
94
95         if (floatcmp($amount, 0))
96         {
97                 error_log(sprintf( _("Rounding error %s encountered for trans_type:%s,trans_no:%s"), $amount, $type, $trans_id));
98                 return add_gl_trans($type, $trans_id, $date_, get_company_pref('exchange_diff_act'), 0, 0, "",
99                         $amount, null, $person_type_id, $person_id, "The balanced GL transaction could not be inserted");
100         } else
101                 return 0;
102 }
103
104 //--------------------------------------------------------------------------------
105
106 function get_gl_transactions($from_date, $to_date, $trans_no=0,
107         $account=null, $dimension=0, $dimension2=0, $filter_type=null,
108         $amount_min=null, $amount_max=null, $person_id=null, $memo='')
109 {
110         global $SysPrefs;
111
112         $from = date2sql($from_date);
113         $to = date2sql($to_date);
114
115         $sql = "SELECT gl.*, j.event_date, j.doc_date, a.gl_seq, u.user_id, st.supp_reference, gl.person_id subcode,
116                         IFNULL(IFNULL(sup.supp_name, debt.name), bt.person_id) as person_name, 
117                         IFNULL(gl.person_id, IFNULL(sup.supplier_id, IFNULL(debt.debtor_no, bt.person_id))) as person_id,
118             IF(gl.person_id, gl.person_type_id, IF(sup.supplier_id,".  PT_SUPPLIER . "," .  "IF(debt.debtor_no," . PT_CUSTOMER . "," . 
119             "IF(bt.person_id != '' AND !ISNULL(bt.person_id), bt.person_type_id, -1)))) as person_type_id,
120                         IFNULL(st.tran_date, IFNULL(dt.tran_date, IFNULL(bt.trans_date, IFNULL(grn.delivery_date, gl.tran_date)))) as doc_date,
121                         coa.account_name, ref.reference
122                          FROM "
123                         .TB_PREF."gl_trans gl
124                         LEFT JOIN ".TB_PREF."voided v ON gl.type_no=v.id AND v.type=gl.type
125
126                         LEFT JOIN ".TB_PREF."supp_trans st ON gl.type_no=st.trans_no AND st.type=gl.type AND (gl.type!=".ST_JOURNAL." OR gl.person_id=st.supplier_id)
127                         LEFT JOIN ".TB_PREF."grn_batch grn ON grn.id=gl.type_no AND gl.type=".ST_SUPPRECEIVE."
128                         LEFT JOIN ".TB_PREF."debtor_trans dt ON gl.type_no=dt.trans_no AND dt.type=gl.type AND (gl.type!=".ST_JOURNAL." OR gl.person_id=dt.debtor_no)
129
130                         LEFT JOIN ".TB_PREF."suppliers sup ON st.supplier_id=sup.supplier_id OR grn.supplier_id=sup.supplier_id
131                         LEFT JOIN ".TB_PREF."cust_branch branch ON dt.branch_code=branch.branch_code
132                         LEFT JOIN ".TB_PREF."debtors_master debt ON dt.debtor_no=debt.debtor_no
133
134                         LEFT JOIN ".TB_PREF."bank_trans bt ON bt.type=gl.type AND bt.trans_no=gl.type_no AND bt.amount!=0
135                                  AND (bt.person_id != '' AND !ISNULL(bt.person_id))
136
137                         LEFT JOIN ".TB_PREF."journal j ON j.type=gl.type AND j.trans_no=gl.type_no
138                         LEFT JOIN ".TB_PREF."audit_trail a ON a.type=gl.type AND a.trans_no=gl.type_no AND NOT ISNULL(gl_seq)
139                         LEFT JOIN ".TB_PREF."users u ON a.user=u.id
140
141                         LEFT JOIN ".TB_PREF."refs ref ON ref.type=gl.type AND ref.id=gl.type_no,"
142                 .TB_PREF."chart_master coa
143                 WHERE coa.account_code=gl.account
144                 AND ISNULL(v.date_)
145                 AND gl.tran_date >= '$from'
146                 AND gl.tran_date <= '$to'
147                 AND gl.amount <> 0"; 
148
149         if ($person_id)
150                 $sql .= " AND gl.person_id=".db_escape($person_id); 
151
152         if ($trans_no > 0)
153                 $sql .= " AND gl.type_no LIKE ".db_escape('%'.$trans_no);;
154
155         if ($account != null)
156                 $sql .= " AND gl.account = ".db_escape($account);
157
158         if ($dimension != 0)
159                 $sql .= " AND gl.dimension_id = ".($dimension<0 ? 0 : db_escape($dimension));
160
161         if ($dimension2 != 0)
162                 $sql .= " AND gl.dimension2_id = ".($dimension2<0 ? 0 : db_escape($dimension2));
163
164         if ($filter_type != null AND is_numeric($filter_type))
165                 $sql .= " AND gl.type= ".db_escape($filter_type);
166
167         if ($amount_min != null)
168                 $sql .= " AND ABS(gl.amount) >= ABS(".db_escape($amount_min).")";
169         
170         if ($amount_max != null)
171                 $sql .= " AND ABS(gl.amount) <= ABS(".db_escape($amount_max).")";
172
173         if ($memo) {
174                 $sql .= " AND gl.memo_ LIKE ". db_escape("%$memo%");
175         }
176         $sql .= " GROUP BY counter";
177         $sql .= " ORDER BY tran_date, counter";
178
179         return db_query($sql, "The transactions for could not be retrieved");
180 }
181
182
183 //--------------------------------------------------------------------------------
184
185 function get_gl_trans($type, $trans_id)
186 {
187         $sql = "SELECT gl.*, cm.account_name, IFNULL(refs.reference, '') AS reference, user.real_name, 
188                         COALESCE(st.tran_date, dt.tran_date, bt.trans_date, grn.delivery_date, gl.tran_date) as doc_date,
189                         IF(ISNULL(st.supp_reference), '', st.supp_reference) AS supp_reference
190         FROM ".TB_PREF."gl_trans as gl
191                 LEFT JOIN ".TB_PREF."chart_master as cm ON gl.account = cm.account_code
192                 LEFT JOIN ".TB_PREF."refs as refs ON (gl.type=refs.type AND gl.type_no=refs.id)
193                 LEFT JOIN ".TB_PREF."audit_trail as audit ON (gl.type=audit.type AND gl.type_no=audit.trans_no AND NOT ISNULL(gl_seq))
194                 LEFT JOIN ".TB_PREF."users as user ON (audit.user=user.id)
195         # all this below just to retrieve doc_date :>
196                 LEFT JOIN ".TB_PREF."supp_trans st ON gl.type_no=st.trans_no AND st.type=gl.type AND (gl.type!=".ST_JOURNAL." OR gl.person_id=st.supplier_id)
197                 LEFT JOIN ".TB_PREF."grn_batch grn ON grn.id=gl.type_no AND gl.type=".ST_SUPPRECEIVE." AND gl.person_id=grn.supplier_id
198                 LEFT JOIN ".TB_PREF."debtor_trans dt ON gl.type_no=dt.trans_no AND dt.type=gl.type AND (gl.type!=".ST_JOURNAL." OR gl.person_id=dt.debtor_no)
199                 LEFT JOIN ".TB_PREF."bank_trans bt ON bt.type=gl.type AND bt.trans_no=gl.type_no AND bt.amount!=0
200                          AND bt.person_type_id=gl.person_type_id AND bt.person_id=gl.person_id
201                 LEFT JOIN ".TB_PREF."journal j ON j.type=gl.type AND j.trans_no=gl.type_no"
202
203                 ." WHERE gl.type= ".db_escape($type) 
204                 ." AND gl.type_no = ".db_escape($trans_id)
205                 ." AND gl.amount <> 0"
206                 ." ORDER BY tran_date, counter";
207
208         return db_query($sql, "The gl transactions could not be retrieved");
209 }
210
211 //--------------------------------------------------------------------------------
212
213 function get_gl_wo_cost_trans($trans_id, $cost_type=-1, $all_gl=false)
214 {
215         $sql = "SELECT costing.*, gl.*, chart.account_name, com.memo_
216                 FROM "
217                 .TB_PREF."wo_costing costing, "
218                 .TB_PREF."gl_trans gl LEFT JOIN ".TB_PREF."comments com ON gl.type=com.type     AND gl.type_no=com.id,"
219                 .TB_PREF."chart_master chart
220                 WHERE 
221                         costing.workorder_id=".db_escape($trans_id)
222                 ."      AND chart.account_code=gl.account
223                         AND gl.type=costing.trans_type
224                         AND gl.type_no=costing.trans_no";
225         if ($cost_type != -1)
226                 $sql .= " AND costing.cost_type=".db_escape($cost_type);
227         $sql .= $all_gl ? " AND amount != 0" : " AND amount < 0";
228
229         return db_query($sql, "The gl transactions could not be retrieved");
230 }
231
232 function get_gl_wo_issue_trans($trans_id, $person_id=-1, $all_gl=false)
233 {
234         $sql = "SELECT issue.*, gl.*, chart.account_name, com.memo_
235                 FROM "
236                         .TB_PREF."wo_issues issue,"
237                         .TB_PREF."gl_trans gl LEFT JOIN ".TB_PREF."comments com ON gl.type=com.type     AND gl.type_no=com.id,"
238                         .TB_PREF."chart_master chart
239                 WHERE issue.workorder_id=".db_escape($trans_id)
240                  ." AND chart.account_code=gl.account
241                         AND gl.type=".ST_MANUISSUE." AND gl.type_no=issue.issue_no";
242 //                      ." AND gl.person_type_id=".PT_WORKORDER;
243         if ($person_id != -1)
244                 $sql .= " AND gl.person_id=".db_escape($person_id);
245         $sql .= $all_gl ? " AND amount != 0" : " AND amount < 0";
246         $sql .= " ORDER BY type, type_no";
247         return db_query($sql, "The gl transactions could not be retrieved");
248 }
249
250 function get_gl_wo_productions($trans_id, $all_gl=false)
251 {
252         $sql = "SELECT rcv.*, gl.*, chart.account_name, com.memo_
253                 FROM "
254                 .TB_PREF."wo_manufacture rcv, "
255                 .TB_PREF."gl_trans gl LEFT JOIN ".TB_PREF."comments com ON gl.type=com.type     AND gl.type_no=com.id,"
256                 .TB_PREF."chart_master chart
257                 WHERE 
258                         rcv.workorder_id=".db_escape($trans_id)
259                 ."      AND chart.account_code=gl.account
260                         AND gl.type=".ST_MANURECEIVE."
261                         AND gl.type_no=rcv.id
262                         AND amount != 0 "
263                 .($all_gl ? " AND amount != 0" : " AND amount < 0")
264                 ." ORDER BY type, type_no";
265
266         return db_query($sql, "The gl transactions could not be retrieved");
267 }
268
269 function get_gl_balance_from_to($from_date, $to_date, $account, $dimension=0, $dimension2=0)
270 {
271         $from = date2sql($from_date);
272         $to = date2sql($to_date);
273
274     $sql = "SELECT SUM(amount) FROM ".TB_PREF."gl_trans
275                 WHERE account='$account'";
276         if ($from_date != "")
277                 $sql .= "  AND tran_date > '$from'";
278         if ($to_date != "")
279                 $sql .= "  AND tran_date < '$to'";
280         if ($dimension != 0)
281                 $sql .= " AND dimension_id = ".($dimension<0 ? 0 : db_escape($dimension));
282         if ($dimension2 != 0)
283                 $sql .= " AND dimension2_id = ".($dimension2<0 ? 0 : db_escape($dimension2));
284
285         $result = db_query($sql, "The starting balance for account $account could not be calculated");
286
287         $row = db_fetch_row($result);
288         return $row[0];
289 }
290
291 //--------------------------------------------------------------------------------
292
293 function get_gl_trans_from_to($from_date, $to_date, $account, $dimension=0, $dimension2=0)
294 {
295         $from = date2sql($from_date);
296         $to = date2sql($to_date);
297
298     $sql = "SELECT SUM(amount) FROM ".TB_PREF."gl_trans
299                 WHERE account='$account'";
300         if ($from_date != "")
301                 $sql .= " AND tran_date >= '$from'";
302         if ($to_date != "")
303                 $sql .= " AND tran_date <= '$to'";
304         if ($dimension != 0)
305                 $sql .= " AND dimension_id = ".($dimension<0 ? 0 : db_escape($dimension));
306         if ($dimension2 != 0)
307                 $sql .= " AND dimension2_id = ".($dimension2<0 ? 0 : db_escape($dimension2));
308
309         $result = db_query($sql, "Transactions for account $account could not be calculated");
310
311         $row = db_fetch_row($result);
312         return (float)$row[0];
313 }
314
315 //----------------------------------------------------------------------------------------------------
316 function get_balance($account, $dimension, $dimension2, $from, $to, $from_incl=true, $to_incl=true) 
317 {
318         $from_date = date2sql($from);
319         $to_date = date2sql($to);
320
321         $sql = "SELECT  SUM(IF(amount >= 0, amount, 0)) as debit, 
322                                         SUM(IF(amount < 0, -amount, 0)) as credit,
323                                         SUM(amount) as balance 
324                 FROM ".TB_PREF."gl_trans trans,"
325                         .TB_PREF."chart_master coa,"
326                         .TB_PREF."chart_types act_type, "
327                         .TB_PREF."chart_class act_class
328                 WHERE trans.account=coa.account_code
329                         AND coa.account_type=act_type.id 
330                 AND act_type.class_id=act_class.cid"
331                 ." AND ".($from_incl ? "tran_date >= '$from_date'" : "tran_date > IF(ctype>0 AND ctype<".CL_INCOME.", '0000-00-00', '$from_date')")
332                 ." AND ".($to_incl ? "tran_date <= '$to_date'" : "tran_date < '$to_date'")
333                 .($account == null ? '' : " AND account=".db_escape($account))
334                 .($dimension == 0 ? ''  : " AND dimension_id = ".($dimension<0 ? 0 : db_escape($dimension)))
335                 .($dimension2 == 0 ? '' : " AND dimension2_id = ".($dimension2<0 ? 0 : db_escape($dimension2)));
336
337         $result = db_query($sql,"No general ledger accounts were returned");
338
339         return db_fetch($result);
340 }
341
342 //--------------------------------------------------------------------------------
343
344 function get_budget_trans_from_to($from_date, $to_date, $account, $dimension=0, $dimension2=0)
345 {
346
347         $from = date2sql($from_date);
348         $to = date2sql($to_date);
349
350         $sql = "SELECT SUM(amount)
351                 FROM ".TB_PREF."budget_trans
352                 WHERE account=".db_escape($account);
353         if ($from_date != "")
354                 $sql .= " AND tran_date >= '$from' ";
355         if ($to_date != "")
356                 $sql .= " AND tran_date <= '$to' ";
357         if ($dimension != 0)
358                 $sql .= " AND dimension_id = ".($dimension<0?0:db_escape($dimension));
359         if ($dimension2 != 0)
360                 $sql .= " AND dimension2_id = ".($dimension2<0?0:db_escape($dimension2));
361         $result = db_query($sql,"No budget accounts were returned");
362
363         $row = db_fetch_row($result);
364         return $row[0];
365 }
366 //-------------------------------------------------------------------------------------
367
368 function exists_gl_budget($date_, $account, $dimension, $dimension2)
369 {
370         $sql = "SELECT account FROM ".TB_PREF."budget_trans WHERE account=".db_escape($account)
371         ." AND tran_date='$date_' AND
372                 dimension_id=".db_escape($dimension)." AND dimension2_id=".db_escape($dimension2);
373         $result = db_query($sql, "Cannot retreive a gl transaction");
374
375     return (db_num_rows($result) > 0);
376 }
377
378 function add_update_gl_budget_trans($date_, $account, $dimension, $dimension2, $amount)
379 {
380         $date = date2sql($date_);
381
382         if (exists_gl_budget($date, $account, $dimension, $dimension2))
383                 $sql = "UPDATE ".TB_PREF."budget_trans SET amount=".db_escape($amount)
384                 ." WHERE account=".db_escape($account)
385                 ." AND dimension_id=".db_escape($dimension)
386                 ." AND dimension2_id=".db_escape($dimension2)
387                 ." AND tran_date='$date'";
388         else
389                 $sql = "INSERT INTO ".TB_PREF."budget_trans (tran_date,
390                         account, dimension_id, dimension2_id, amount, memo_) VALUES ('$date',
391                         ".db_escape($account).", ".db_escape($dimension).", "
392                         .db_escape($dimension2).", ".db_escape($amount).", '')";
393
394         db_query($sql, "The GL budget transaction could not be saved");
395 }
396
397 function delete_gl_budget_trans($date_, $account, $dimension, $dimension2)
398 {
399         $date = date2sql($date_);
400
401         $sql = "DELETE FROM ".TB_PREF."budget_trans WHERE account=".db_escape($account)
402         ." AND dimension_id=".db_escape($dimension)
403         ." AND dimension2_id=".db_escape($dimension2)
404         ." AND tran_date='$date'";
405         db_query($sql, "The GL budget transaction could not be deleted");
406 }
407
408 function get_only_budget_trans_from_to($from_date, $to_date, $account, $dimension=0, $dimension2=0)
409 {
410
411         $from = date2sql($from_date);
412         $to = date2sql($to_date);
413
414         $sql = "SELECT SUM(amount) FROM ".TB_PREF."budget_trans
415                 WHERE account=".db_escape($account)
416                 ." AND tran_date >= '$from' AND tran_date <= '$to'
417                  AND dimension_id = ".db_escape($dimension)
418                  ." AND dimension2_id = ".db_escape($dimension2);
419         $result = db_query($sql,"No budget accounts were returned");
420
421         $row = db_fetch_row($result);
422         return $row[0];
423 }
424
425 //--------------------------------------------------------------------------------
426 //      Stores journal/bank transaction tax details if applicable
427 //
428 function add_gl_tax_details($gl_code, $trans_type, $trans_no, $amount, $ex_rate, $date, $memo, $included=0, $net_amount = null)
429 {
430         $tax_type = is_tax_account($gl_code);
431         if(!$tax_type) return;  // $gl_code is not tax account
432         
433         $tax = get_tax_type($tax_type);
434         if ($trans_type == ST_SALESINVOICE || $trans_type == ST_CUSTDELIVERY || $trans_type == ST_CUSTCREDIT)
435                 $amount = -$amount;
436         // we have to restore net amount as we cannot know the base amount
437         if ($net_amount===null) {
438                 if ($tax['rate'] == 0) {
439                         $net_amount = 0;
440                 } else { 
441                         // calculate net amount
442                         $net_amount = $amount/$tax['rate']*100; 
443                 }
444         }
445         add_trans_tax_details($trans_type, $trans_no, $tax['id'], $tax['rate'], $included, 
446                 $amount, $net_amount, $ex_rate, $date, $memo, null);
447
448 }
449
450 //--------------------------------------------------------------------------------
451 //
452 //      Store transaction tax details for fiscal purposes with 'freezed' 
453 //      actual tax type rate.
454 //
455 function add_trans_tax_details($trans_type, $trans_no, $tax_id, $rate, $included,
456         $amount, $net_amount, $ex_rate, $tran_date, $memo, $reg_type=null)
457 {
458         // guess tax register if not set
459         if (!isset($reg_type))
460                 $reg_type = in_array($trans_type, array(ST_SUPPINVOICE, ST_SUPPCREDIT)) ? TR_OUTPUT
461                                 : in_array($trans_type, array(ST_SALESINVOICE, ST_CUSTCREDIT)) ? TR_INPUT : null;
462
463         $sql = "INSERT INTO ".TB_PREF."trans_tax_details 
464                 (trans_type, trans_no, tran_date, tax_type_id, rate, ex_rate,
465                         included_in_price, net_amount, amount, memo, reg_type)
466                 VALUES (".db_escape($trans_type)."," . db_escape($trans_no).",'"
467                                 .date2sql($tran_date)."',".db_escape($tax_id).","
468                                 .db_escape($rate).",".db_escape($ex_rate).",".($included ? 1:0).","
469                                 .db_escape($net_amount).","
470                                 .db_escape($amount).",".db_escape($memo).",".db_escape($reg_type, true).")";
471
472         db_query($sql, "Cannot save trans tax details");
473
474 }
475 //----------------------------------------------------------------------------------------
476
477 function get_trans_tax_details($trans_type, $trans_no)
478 {
479     $sql = "SELECT tax_details.*, tax_type.name AS tax_type_name, tax_type.rate AS rate
480         FROM ".TB_PREF."trans_tax_details tax_details INNER JOIN 
481         ".TB_PREF."tax_types tax_type ON tax_type.id = tax_details.tax_type_id
482         WHERE 
483                 trans_type = ".db_escape($trans_type)."
484             AND trans_no = ".db_escape($trans_no)."
485             AND (net_amount != 0 OR amount != 0)";
486
487     return db_query($sql, "The transaction tax details could not be retrieved");
488 }
489
490 //----------------------------------------------------------------------------------------
491
492 function void_trans_tax_details($type, $type_no)
493 {
494         $sql = "UPDATE ".TB_PREF."trans_tax_details SET amount=0, net_amount=0
495                 WHERE trans_no=".db_escape($type_no)
496                 ." AND trans_type=".db_escape($type);
497
498         db_query($sql, "The transaction tax details could not be voided");
499 }
500
501 //----------------------------------------------------------------------------------------
502
503 function clear_trans_tax_details($type, $type_no)
504 {
505         $sql = "DELETE FROM ".TB_PREF."trans_tax_details 
506                 WHERE trans_no=".db_escape($type_no)
507                 ." AND trans_type=".db_escape($type);
508
509         db_query($sql, "The transaction tax details could not be cleared");
510 }
511
512 function get_tax_summary($from, $to, $also_zero_purchases=false)
513 {
514         $fromdate = date2sql($from);
515         $todate = date2sql($to);
516
517         $sql = "SELECT 
518                                 SUM(IF(trans_type=".ST_CUSTCREDIT.",-1,1)*
519                                 IF((reg_type=".TR_OUTPUT.")"
520                                         ." || ((trans_type IN(".ST_SALESINVOICE.",".ST_CUSTCREDIT.") OR (trans_type=".ST_JOURNAL." AND reg_type=".TR_INPUT."))
521                                         ), net_amount*ex_rate,0)
522                                 ) net_output,
523
524                                 SUM(IF(trans_type=".ST_CUSTCREDIT.",-1,1)*
525                                 IF((reg_type=".TR_OUTPUT.")"
526                                         ." || ((trans_type IN(".ST_SALESINVOICE.",".ST_CUSTCREDIT.") OR (trans_type=".ST_JOURNAL." AND reg_type=".TR_INPUT."))
527                                         ), amount*ex_rate,0)) payable,
528
529                                 SUM(IF(trans_type IN(".ST_SUPPCREDIT."),-1,1)*
530                                 IF(reg_type=".TR_INPUT
531                                         . ($also_zero_purchases ? '': " AND tax_type_id AND taxrec.rate")
532                                         .", net_amount*ex_rate, 0)) net_input,
533
534                                 SUM(IF(trans_type IN(".ST_SUPPCREDIT."),-1,1)*
535                                 IF(reg_type=".TR_INPUT
536                                         . ($also_zero_purchases ? '': " AND tax_type_id AND taxrec.rate ") 
537                                         .", amount*ex_rate, 0)) collectible,
538                                 taxrec.rate,
539                                 ttype.id,
540                                 ttype.name
541                 FROM ".TB_PREF."trans_tax_details taxrec LEFT JOIN ".TB_PREF."tax_types ttype ON taxrec.tax_type_id=ttype.id
542                 WHERE taxrec.trans_type IN (".implode(',',
543                         array(ST_SALESINVOICE, ST_CUSTCREDIT, ST_SUPPINVOICE, ST_SUPPCREDIT, ST_JOURNAL)).")
544                         AND taxrec.tran_date >= '$fromdate'
545                         AND taxrec.tran_date <= '$todate'
546                 GROUP BY ttype.id";
547
548                 // display_error($sql);
549     return db_query($sql,"Cannot retrieve tax summary");
550 }
551
552 //--------------------------------------------------------------------------------------------------
553
554 function exists_gl_trans($type, $trans_id)
555 {
556         $sql = "SELECT type_no FROM ".TB_PREF."gl_trans WHERE type=".db_escape($type)
557                 ." AND type_no=".db_escape($trans_id);
558         $result = db_query($sql, "Cannot retreive a gl transaction");
559
560     return (db_num_rows($result) > 0);
561 }
562
563 //--------------------------------------------------------------------------------------------------
564
565 function void_gl_trans($type, $trans_id, $nested=false)
566 {
567         if (!$nested)
568                 begin_transaction();
569
570         $sql = "UPDATE ".TB_PREF."gl_trans SET amount=0 WHERE type=".db_escape($type)
571         ." AND type_no=".db_escape($trans_id);
572
573         db_query($sql, "could not void gl transactions for type=$type and trans_no=$trans_id");
574
575         if (!$nested)
576                 commit_transaction();
577 }
578
579 //----------------------------------------------------------------------------------------
580
581 function clear_gl_trans($type, $trans_id, $nested=false)
582 {
583         if (!$nested)
584                 begin_transaction();
585
586         $sql = "DELETE FROM ".TB_PREF."gl_trans WHERE type=".db_escape($type)
587         ." AND type_no=".db_escape($trans_id);
588
589         db_query($sql, "could not clear gl transactions for type=$type and trans_no=$trans_id");
590
591         if (!$nested)
592                 commit_transaction();
593 }
594
595 function get_sql_for_journal_inquiry($filter, $from, $to, $ref='', $memo='', $alsoclosed=false,
596                  $user_id=null, $contractor_id=null, $dimension=null)
597 {
598
599         $sql = "SELECT  IFNULL(a.gl_seq,0) as gl_seq,
600                 gl.tran_date,
601                 gl.type as trans_type,
602                 gl.type_no as trans_no,
603                 IFNULL(MAX(supp.supp_name), MAX(cust.name)) as name,
604                 IF(ISNULL(st.supp_reference), '', st.supp_reference) AS supp_reference,
605                 refs.reference,"
606                 .($dimension ? " -SUM(IF(dim.dimension in(gl.dimension_id,gl.dimension2_id), gl.amount, 0)) as amount,":" SUM(IF(gl.amount>0, gl.amount,0)) as amount,")
607                 ."com.memo_,
608                 IF(ISNULL(u.user_id),'',u.user_id) as user_id";
609
610         if ($contractor_id > 0) {
611                 $sql.= ", st.supplier_id, dt.debtor_no ";
612         }
613
614         $sql.= " FROM ".TB_PREF."gl_trans as gl
615                  LEFT JOIN ".TB_PREF."audit_trail as a ON
616                         (gl.type=a.type AND gl.type_no=a.trans_no)
617                  LEFT JOIN ".TB_PREF."comments as com ON
618                         (gl.type=com.type AND gl.type_no=com.id)
619                  LEFT JOIN ".TB_PREF."refs as refs ON
620                         (gl.type=refs.type AND gl.type_no=refs.id)
621                  LEFT JOIN ".TB_PREF."users as u ON
622                         a.user=u.id
623                  LEFT JOIN ".TB_PREF."debtor_trans dt ON dt.type=gl.type AND gl.type_no=dt.trans_no
624                  LEFT JOIN ".TB_PREF."debtors_master cust ON gl.person_type_id=2 AND gl.person_id=cust.debtor_no
625                  LEFT JOIN ".TB_PREF."supp_trans st ON st.type=gl.type AND gl.type_no=st.trans_no
626                  LEFT JOIN ".TB_PREF."suppliers supp ON gl.person_type_id=3 AND gl.person_id=supp.supplier_id"
627                  .($dimension ? 
628                  " LEFT JOIN (SELECT type, type_no, MAX(IFNULL(dimension_id, dimension2_id)) dimension FROM ".TB_PREF."gl_trans GROUP BY type, type_no) dim 
629                                 ON gl.type=dim.type AND gl.type_no=dim.type_no" : '')
630                 ." WHERE gl.tran_date >= '" . date2sql($from) . "'
631                 AND gl.tran_date <= '" . date2sql($to) . "'
632                 AND gl.amount!=0";
633         if ($ref) {
634                 $sql .= " AND refs.reference LIKE ". db_escape("%$ref%");
635         }
636         if ($memo) {
637                 $sql .= " AND com.memo_ LIKE ". db_escape("%$memo%");
638         }
639         if ($filter != -1) {
640                 $sql .= " AND gl.type=".db_escape($filter);
641         }
642         if (!$alsoclosed) {
643                 $sql .= " AND gl_seq=0";
644         }
645         else
646                 $sql .= " AND NOT ISNULL(a.gl_seq)";
647
648         if ($user_id != null)
649                 $sql .= " AND user_id = ".db_escape($user_id);
650
651         if ($contractor_id > 0) {
652                 $sql.= " AND (dt.debtor_no =".$contractor_id;
653                 $sql.= " OR st.supplier_id =".$contractor_id.") ";
654         }       
655
656         if ($dimension != null)
657                 $sql .= " AND dim.dimension = ".db_escape($dimension);
658
659         $sql .= " GROUP BY gl.tran_date, a.gl_seq, gl.type, gl.type_no";
660
661         return $sql;
662 }