Incorrect Journal Balance (sales invoice) when many decimals in tax and price.
[fa-stable.git] / reporting / rep115.php
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting Team.
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 $page_security = 'SA_CUSTPAYMREP';
13
14 // ----------------------------------------------------------------
15 // $ Revision:    2.0 $
16 // Creator:    @boxygen
17 // date_:    2018-12-20
18 // Title:    Customer Trial Balances
19 // ----------------------------------------------------------------
20 $path_to_root="..";
21
22 include_once($path_to_root . "/includes/session.inc");
23 include_once($path_to_root . "/includes/date_functions.inc");
24 include_once($path_to_root . "/includes/data_checks.inc");
25 include_once($path_to_root . "/gl/includes/gl_db.inc");
26 include_once($path_to_root . "/sales/includes/db/customers_db.inc");
27
28 //----------------------------------------------------------------------------------------------------
29
30 print_customer_balances();
31
32 function get_open_balance($debtorno, $to)
33 {
34         if($to)
35                 $to = date2sql($to);
36         $sql = "SELECT SUM(IF(t.type = ".ST_SALESINVOICE." OR (t.type IN (".ST_JOURNAL." , ".ST_BANKPAYMENT.") AND t.ov_amount>0),
37              -abs(IF(t.prep_amount, t.prep_amount, t.ov_amount + t.ov_gst + t.ov_freight + t.ov_freight_tax + t.ov_discount)), 0)) AS charges,";
38
39         $sql .= "SUM(IF(t.type != ".ST_SALESINVOICE." AND NOT(t.type IN (".ST_JOURNAL." , ".ST_BANKPAYMENT.") AND t.ov_amount>0),
40              abs(t.ov_amount + t.ov_gst + t.ov_freight + t.ov_freight_tax + t.ov_discount) * -1, 0)) AS credits,";              
41
42     $sql .= "SUM(IF(t.type != ".ST_SALESINVOICE." AND NOT(t.type IN (".ST_JOURNAL." , ".ST_BANKPAYMENT.")), t.alloc * -1, t.alloc)) AS Allocated,";
43
44         $sql .= "SUM(IF(t.type = ".ST_SALESINVOICE." OR (t.type IN (".ST_JOURNAL." , ".ST_BANKPAYMENT.") AND t.ov_amount>0), 1, -1) *
45                         (IF(t.prep_amount, t.prep_amount, abs(t.ov_amount + t.ov_gst + t.ov_freight + t.ov_freight_tax + t.ov_discount)) - abs(t.alloc))) AS OutStanding
46                 FROM ".TB_PREF."debtor_trans t
47         WHERE t.debtor_no = ".db_escape($debtorno)
48                 ." AND t.type <> ".ST_CUSTDELIVERY;
49     if ($to)
50         $sql .= " AND t.tran_date < '$to'";
51         $sql .= " GROUP BY debtor_no";
52
53     $result = db_query($sql,"No transactions were returned");
54     return db_fetch($result);
55 }
56
57 function get_transactions($debtorno, $from, $to)
58 {
59     $from = date2sql($from);
60     $to = date2sql($to);
61
62     $sign = "IF(trans.type IN(".implode(',',  array(ST_CUSTCREDIT,ST_CUSTPAYMENT,ST_BANKDEPOSIT))."), -1, 1)";
63
64     $allocated_from =
65         "(SELECT trans_type_from as trans_type, trans_no_from as trans_no, date_alloc, sum(amt) amount
66         FROM ".TB_PREF."cust_allocations alloc
67         WHERE person_id=".db_escape($debtorno)."
68         AND date_alloc <= '$to'
69         GROUP BY trans_type_from, trans_no_from) alloc_from";
70     $allocated_to =
71         "(SELECT trans_type_to as trans_type, trans_no_to as trans_no, date_alloc, sum(amt) amount
72         FROM ".TB_PREF."cust_allocations alloc
73         WHERE person_id=".db_escape($debtorno)."
74         AND date_alloc <= '$to'
75         GROUP BY trans_type_to, trans_no_to) alloc_to";
76
77     $sql = "SELECT trans.*, comments.memo_,
78         $sign*IF(trans.prep_amount, trans.prep_amount, trans.ov_amount + trans.ov_gst + trans.ov_freight + trans.ov_freight_tax + trans.ov_discount)
79             AS TotalAmount,
80         $sign*IFNULL(alloc_from.amount, alloc_to.amount) AS Allocated,
81         ((trans.type = ".ST_SALESINVOICE.")    AND trans.due_date < '$to') AS OverDue
82         FROM ".TB_PREF."debtor_trans trans
83         LEFT JOIN ".TB_PREF."voided voided ON trans.type=voided.type AND trans.trans_no=voided.id
84         LEFT JOIN ".TB_PREF."comments comments ON trans.type=comments.type AND trans.trans_no=comments.id
85         LEFT JOIN $allocated_from ON alloc_from.trans_type = trans.type AND alloc_from.trans_no = trans.trans_no
86         LEFT JOIN $allocated_to ON alloc_to.trans_type = trans.type AND alloc_to.trans_no = trans.trans_no
87         WHERE trans.tran_date >= '$from'
88         AND trans.tran_date <= '$to'
89         AND trans.debtor_no = ".db_escape($debtorno);
90     $sql .= " AND trans.type <> ".ST_CUSTDELIVERY;
91     $sql .= " AND ISNULL(voided.id)
92         ORDER BY trans.tran_date ";
93     
94     return db_query($sql,"No transactions were returned");
95 }
96
97 function get_customer_reference ($order_number)
98 {
99
100     $sql = "SELECT customer_ref FROM ".TB_PREF."sales_orders WHERE order_no ='$order_number' AND trans_type=".ST_SALESORDER."";
101
102     $result = db_query($sql,"No Transcation were returned");
103
104     $val = db_fetch($result);
105
106     return $val['customer_ref'];
107 }
108 //----------------------------------------------------------------------------------------------------
109
110 function print_customer_balances()
111 {
112     global $path_to_root, $systypes_array;
113
114     $from = $_POST['PARAM_0'];
115     $to = $_POST['PARAM_1'];
116     $fromcust = $_POST['PARAM_2'];
117     $area = $_POST['PARAM_3']; //added by Faisal to filter by area
118     $folk = $_POST['PARAM_4'];  // added by Faisal to filter by sales person
119     $currency = $_POST['PARAM_5'];
120     $no_zeros = $_POST['PARAM_6'];
121     $comments = $_POST['PARAM_7'];
122     $orientation = $_POST['PARAM_8'];
123     $destination = $_POST['PARAM_9'];
124     if ($destination)
125         include_once($path_to_root . "/reporting/includes/excel_report.inc");
126     else
127         include_once($path_to_root . "/reporting/includes/pdf_report.inc");
128
129     $orientation = ($orientation ? 'L' : 'P');
130     if ($fromcust == ALL_TEXT)
131         $cust = _('All');
132     else
133         $cust = get_customer_name($fromcust);
134     $dec = user_price_dec();
135
136     if ($area == ALL_NUMERIC)
137         $area = 0;
138
139     if ($area == 0)
140         $sarea = _('All Areas');
141     else
142         $sarea = get_area_name($area);
143
144     if ($folk == ALL_NUMERIC)
145         $folk = 0;
146     if ($folk == 0)
147         $salesfolk = _('All Sales Man');
148      else
149         $salesfolk = get_salesman_name($folk);
150
151     if ($currency == ALL_TEXT)
152     {
153         $convert = true;
154         $currency = _('Balances in Home Currency');
155     }
156     else
157         $convert = false;
158
159     if ($no_zeros) $nozeros = _('Yes');
160     else $nozeros = _('No');
161
162     $cols = array(0, 100, 130, 190, 250, 320, 385, 450, 515);
163
164     $headers = array(_('Name'), '', '', _('Open Balance'), _('Debit'), _('Credit'), '', _('Balance'));
165
166     $aligns = array('left', 'left', 'left', 'right', 'right', 'right', 'right', 'right');
167
168     $params =   array(  0 => $comments,
169                         1 => array('text' => _('Period'), 'from' => $from,   'to' => $to),
170                         2 => array('text' => _('Customer'), 'from' => $cust, 'to' => ''),
171                                     3 => array('text' => _('Sales Areas'), 'from' => $sarea,            'to' => ''),
172                                     4 => array('text' => _('Sales Folk'), 'from' => $salesfolk,         'to' => ''),
173                         5 => array('text' => _('Currency'), 'from' => $currency, 'to' => ''),
174                         6 => array('text' => _('Suppress Zeros'), 'from' => $nozeros, 'to' => ''));
175
176     $rep = new FrontReport(_('Customer Trial Balance'), "CustomerTB", user_pagesize(), 9, $orientation);
177     if ($orientation == 'L')
178         recalculate_cols($cols);
179     $rep->Font();
180     $rep->Info($params, $cols, $headers, $aligns);
181     $rep->NewPage();
182
183     $grandtotal = array(0,0,0,0);
184
185     $sql = "SELECT ".TB_PREF."debtors_master.debtor_no, name, curr_code FROM ".TB_PREF."debtors_master
186         INNER JOIN ".TB_PREF."cust_branch
187         ON ".TB_PREF."debtors_master.debtor_no=".TB_PREF."cust_branch.debtor_no
188         INNER JOIN ".TB_PREF."areas
189         ON ".TB_PREF."cust_branch.area = ".TB_PREF."areas.area_code
190         INNER JOIN ".TB_PREF."salesman
191         ON ".TB_PREF."cust_branch.salesman=".TB_PREF."salesman.salesman_code";
192     if ($fromcust != ALL_TEXT )
193     {
194         // if ($area != 0 || $folk != 0) continue;
195         $sql .= " WHERE ".TB_PREF."debtors_master.debtor_no=".db_escape($fromcust);
196     }
197     elseif ($area != 0)
198     {
199         if ($folk != 0)
200             $sql .= " WHERE ".TB_PREF."salesman.salesman_code=".db_escape($folk)."
201                 AND ".TB_PREF."areas.area_code=".db_escape($area);
202         else
203             $sql .= " WHERE ".TB_PREF."areas.area_code=".db_escape($area);
204     }
205     elseif ($folk != 0 )
206     {
207         $sql .= " WHERE ".TB_PREF."salesman.salesman_code=".db_escape($folk);
208     }
209
210         $sql .= " GROUP BY ".TB_PREF."debtors_master.debtor_no ORDER BY name";
211
212     $result = db_query($sql, "The customers could not be retrieved");
213
214         $tot_cur_cr = $tot_cur_db = $tot_open = $tot_bal = 0;
215     while ($myrow = db_fetch($result))
216     {
217         if (!$convert && $currency != $myrow['curr_code']) continue;
218
219         $rate = $convert ? get_exchange_rate_from_home_currency($myrow['curr_code'], Today()) : 1;
220         $bal = get_open_balance($myrow['debtor_no'], $from);
221         $init = array();
222         $curr_db = $bal ? round2(abs($bal['charges'] * $rate), $dec) : 0; // db
223         $curr_cr = $bal ? round2(abs($bal['credits'] * $rate), $dec) : 0; // cr
224 //        $curr_alloc = $bal ? round2($bal['Allocated'] * $rate, $dec) : 0;    // allocated
225         $curr_open = $curr_db-$curr_cr;                        // balance
226         $tot_open += $curr_open;
227
228         $res = get_transactions($myrow['debtor_no'], $from, $to);
229
230         if (db_num_rows($res) == 0 && !$no_zeros) 
231         {
232             $rep->TextCol(0, 2, $myrow['name']);
233             $rep->AmountCol(3, 4, $curr_open, $dec);
234             $rep->AmountCol(7, 8, $curr_open, $dec);
235             $rep->NewLine(1);
236             continue;
237         }
238         $curr_db = $curr_cr = 0;
239         while ($trans = db_fetch($res)) //Detail starts here
240         {
241
242             if ($trans['TotalAmount'] > 0.0)
243                 $curr_db += round2(($trans['TotalAmount']) * $rate, $dec);
244             else
245                 $curr_cr += -round2(($trans['TotalAmount']) * $rate, $dec);
246         }
247
248         $tot_cur_db += $curr_db;
249         $tot_cur_cr += $curr_cr;
250
251         if ($no_zeros && $curr_open == 0.0 && $curr_db == 0.0 && $curr_cr == 0.0) continue;
252         $rep->TextCol(0, 2, $myrow['name']);
253         $rep->AmountCol(3, 4, $curr_open, $dec);
254         $rep->AmountCol(4, 5, $curr_db, $dec);
255         $rep->AmountCol(5, 6, $curr_cr, $dec);
256         $rep->AmountCol(7, 8, $curr_open+$curr_db-$curr_cr, $dec);
257         $rep->NewLine(1);
258
259     }
260
261     $rep->Line($rep->row + 4);
262     $rep->NewLine();
263     $rep->fontSize += 2;
264     $rep->TextCol(0, 3, _('Grand Total'));
265     $rep->fontSize -= 2;
266
267     $tot_bal = $tot_open+$tot_cur_db-$tot_cur_cr;
268
269     $rep->AmountCol(3, 4, $tot_open, $dec);
270     $rep->AmountCol(4, 5, $tot_cur_db, $dec);
271     $rep->AmountCol(5, 6, $tot_cur_cr, $dec);
272     $rep->AmountCol(7, 8, $tot_bal, $dec);
273     $rep->Line($rep->row - 6, 1);
274     $rep->NewLine();
275     $rep->End();
276 }