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