Fixed Logical Bug in Customer Balances Report.
[fa-stable.git] / reporting / rep101.php
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 $page_security = 'SA_CUSTPAYMREP';
13
14 // ----------------------------------------------------------------
15 // $ Revision:  2.0 $
16 // Creator:     Joe Hunt
17 // date_:       2005-05-19
18 // Title:       Customer 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 = ".ST_JOURNAL." 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 = ".ST_JOURNAL." 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 = ".ST_JOURNAL." AND t.ov_amount>0), t.alloc * -1, t.alloc)) AS Allocated,";
42
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)
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.*,
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 $allocated_from ON alloc_from.trans_type = trans.type AND alloc_from.trans_no = trans.trans_no
81                         LEFT JOIN $allocated_to ON alloc_to.trans_type = trans.type AND alloc_to.trans_no = trans.trans_no
82
83         WHERE trans.tran_date >= '$from'
84                         AND trans.tran_date <= '$to'
85                         AND trans.debtor_no = ".db_escape($debtorno)."
86                         AND trans.type <> ".ST_CUSTDELIVERY."
87                         AND ISNULL(voided.id)
88         ORDER BY trans.tran_date";
89     return db_query($sql,"No transactions were returned");
90 }
91
92 //----------------------------------------------------------------------------------------------------
93
94 function print_customer_balances()
95 {
96         global $path_to_root, $systypes_array;
97
98         $from = $_POST['PARAM_0'];
99         $to = $_POST['PARAM_1'];
100         $fromcust = $_POST['PARAM_2'];
101         $show_balance = $_POST['PARAM_3'];
102         $currency = $_POST['PARAM_4'];
103         $no_zeros = $_POST['PARAM_5'];
104         $comments = $_POST['PARAM_6'];
105         $orientation = $_POST['PARAM_7'];
106         $destination = $_POST['PARAM_8'];
107         if ($destination)
108                 include_once($path_to_root . "/reporting/includes/excel_report.inc");
109         else
110                 include_once($path_to_root . "/reporting/includes/pdf_report.inc");
111
112         $orientation = ($orientation ? 'L' : 'P');
113         if ($fromcust == ALL_TEXT)
114                 $cust = _('All');
115         else
116                 $cust = get_customer_name($fromcust);
117         $dec = user_price_dec();
118
119         if ($currency == ALL_TEXT)
120         {
121                 $convert = true;
122                 $currency = _('Balances in Home Currency');
123         }
124         else
125                 $convert = false;
126
127         if ($no_zeros) $nozeros = _('Yes');
128         else $nozeros = _('No');
129
130         $cols = array(0, 95, 140, 200,  250, 320, 385, 450,     515);
131
132         $headers = array(_('Trans Type'), _('#'), _('Date'), _('Due Date'), _('Charges'), _('Credits'),
133                 _('Allocated'),         _('Outstanding'));
134
135         if ($show_balance)
136                 $headers[7] = _('Balance');
137         $aligns = array('left', 'left', 'left', 'left', 'right', 'right', 'right', 'right');
138
139     $params =   array(  0 => $comments,
140                                     1 => array('text' => _('Period'), 'from' => $from,          'to' => $to),
141                                     2 => array('text' => _('Customer'), 'from' => $cust,        'to' => ''),
142                                     3 => array('text' => _('Currency'), 'from' => $currency, 'to' => ''),
143                                                 4 => array('text' => _('Suppress Zeros'), 'from' => $nozeros, 'to' => ''));
144
145     $rep = new FrontReport(_('Customer Balances'), "CustomerBalances", user_pagesize(), 9, $orientation);
146     if ($orientation == 'L')
147         recalculate_cols($cols);
148     $rep->Font();
149     $rep->Info($params, $cols, $headers, $aligns);
150     $rep->NewPage();
151
152         $grandtotal = array(0,0,0,0);
153
154         $sql = "SELECT debtor_no, name, curr_code FROM ".TB_PREF."debtors_master ";
155         if ($fromcust != ALL_TEXT)
156                 $sql .= "WHERE debtor_no=".db_escape($fromcust);
157         $sql .= " ORDER BY name";
158         $result = db_query($sql, "The customers could not be retrieved");
159
160         while ($myrow = db_fetch($result))
161         {
162                 if (!$convert && $currency != $myrow['curr_code']) continue;
163                 
164                 $accumulate = 0;
165                 $rate = $convert ? get_exchange_rate_from_home_currency($myrow['curr_code'], Today()) : 1;
166                 $bal = get_open_balance($myrow['debtor_no'], $from, $convert);
167                 $init[0] = $init[1] = 0.0;
168                 $init[0] = round2(abs($bal['charges']*$rate), $dec);
169                 $init[1] = round2(Abs($bal['credits']*$rate), $dec);
170                 $init[2] = round2($bal['Allocated']*$rate, $dec);
171                 if ($show_balance)
172                 {
173                         $init[3] = $init[0] - $init[1];
174                         $accumulate += $init[3];
175                 }       
176                 else    
177                         $init[3] = round2($bal['OutStanding']*$rate, $dec);
178
179                 $res = get_transactions($myrow['debtor_no'], $from, $to);
180                 if ($no_zeros && db_num_rows($res) == 0) continue;
181
182                 $rep->fontSize += 2;
183                 $rep->TextCol(0, 2, $myrow['name']);
184                 if ($convert)
185                         $rep->TextCol(2, 3,     $myrow['curr_code']);
186                 $rep->fontSize -= 2;
187                 $rep->TextCol(3, 4,     _("Open Balance"));
188                 $rep->AmountCol(4, 5, $init[0], $dec);
189                 $rep->AmountCol(5, 6, $init[1], $dec);
190                 $rep->AmountCol(6, 7, $init[2], $dec);
191                 $rep->AmountCol(7, 8, $init[3], $dec);
192                 $total = array(0,0,0,0);
193                 for ($i = 0; $i < 4; $i++)
194                 {
195                         $total[$i] += $init[$i];
196                         $grandtotal[$i] += $init[$i];
197                 }
198                 $rep->NewLine(1, 2);
199                 $rep->Line($rep->row + 4);
200                 if (db_num_rows($res)==0) {
201                         $rep->NewLine(1, 2);
202                         continue;
203                 }
204                 while ($trans = db_fetch($res))
205                 {
206             if ($no_zeros) {
207                 if ($show_balance) {
208                     if ($trans['TotalAmount'] == 0) continue;
209                 } else {
210                     if (floatcmp($trans['TotalAmount'], $trans['Allocated']) == 0) continue;
211                 }
212             }
213                         $rep->NewLine(1, 2);
214                         $rep->TextCol(0, 1, $systypes_array[$trans['type']]);
215                         $rep->TextCol(1, 2,     $trans['reference']);
216                         $rep->DateCol(2, 3,     $trans['tran_date'], true);
217                         if ($trans['type'] == ST_SALESINVOICE)
218                                 $rep->DateCol(3, 4,     $trans['due_date'], true);
219                         $item[0] = $item[1] = 0.0;
220                         if ($trans['type'] == ST_CUSTCREDIT || $trans['type'] == ST_CUSTPAYMENT || $trans['type'] == ST_BANKDEPOSIT)
221                                 $trans['TotalAmount'] *= -1;
222                         if ($trans['TotalAmount'] > 0.0)
223                         {
224                                 $item[0] = round2(abs($trans['TotalAmount']) * $rate, $dec);
225                                 $rep->AmountCol(4, 5, $item[0], $dec);
226                                 $accumulate += $item[0];
227                                 $item[2] = round2($trans['Allocated'] * $rate, $dec);
228                         }
229                         else
230                         {
231                                 $item[1] = round2(Abs($trans['TotalAmount']) * $rate, $dec);
232                                 $rep->AmountCol(5, 6, $item[1], $dec);
233                                 $accumulate -= $item[1];
234                                 $item[2] = round2($trans['Allocated'] * $rate, $dec) * -1;
235                         }
236                         $rep->AmountCol(6, 7, $item[2], $dec);
237                         if ($trans['type'] == ST_SALESINVOICE || $trans['type'] == ST_BANKPAYMENT)
238                                 $item[3] = $item[0] - $item[2];
239                         else    
240                                 $item[3] = -$item[1] - $item[2];
241                         if ($show_balance)      
242                                 $rep->AmountCol(7, 8, $accumulate, $dec);
243                         else    
244                                 $rep->AmountCol(7, 8, $item[3], $dec);
245                         for ($i = 0; $i < 4; $i++)
246                         {
247                                 $total[$i] += $item[$i];
248                                 $grandtotal[$i] += $item[$i];
249                         }
250                         if ($show_balance)
251                                 $total[3] = $total[0] - $total[1];
252                 }
253                 $rep->Line($rep->row - 8);
254                 $rep->NewLine(2);
255                 $rep->TextCol(0, 3, _('Total'));
256                 for ($i = 0; $i < 4; $i++)
257                         $rep->AmountCol($i + 4, $i + 5, $total[$i], $dec);
258                 $rep->Line($rep->row  - 4);
259                 $rep->NewLine(2);
260         }
261         $rep->fontSize += 2;
262         $rep->TextCol(0, 3, _('Grand Total'));
263         $rep->fontSize -= 2;
264         if ($show_balance)
265                 $grandtotal[3] = $grandtotal[0] - $grandtotal[1];
266         for ($i = 0; $i < 4; $i++)
267                 $rep->AmountCol($i + 4, $i + 5, $grandtotal[$i], $dec);
268         $rep->Line($rep->row  - 4);
269         $rep->NewLine();
270         $rep->End();
271 }
272