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