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