Incorrect Journal Balance (sales invoice) when many decimals in tax and price.
[fa-stable.git] / reporting / rep102.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 // $ Revision:  2.0 $
15 // Creator:     Joe Hunt
16 // date_:       2005-05-19
17 // Title:       Aged Customer Balances
18 // ----------------------------------------------------------------
19 $path_to_root="..";
20
21 include_once($path_to_root . "/includes/session.inc");
22 include_once($path_to_root . "/includes/date_functions.inc");
23 include_once($path_to_root . "/includes/data_checks.inc");
24 include_once($path_to_root . "/gl/includes/gl_db.inc");
25
26 //----------------------------------------------------------------------------------------------------
27
28 print_aged_customer_analysis();
29
30 function get_invoices($customer_id, $to, $all=true)
31 {
32         $todate = date2sql($to);
33         $PastDueDays1 = get_company_pref('past_due_days');
34         $PastDueDays2 = 2 * $PastDueDays1;
35
36         $sign = "IF(`type` IN(".implode(',',  array(ST_CUSTCREDIT,ST_CUSTPAYMENT,ST_BANKDEPOSIT))."), -1, 1)";
37
38         $value = "$sign*(IF(trans.prep_amount, trans.prep_amount,
39                 ABS(trans.ov_amount + trans.ov_gst + trans.ov_freight + trans.ov_freight_tax + trans.ov_discount)) ".($all ? '' : "- trans.alloc").")";
40
41         $due = "IF (type=".ST_SALESINVOICE.", due_date, tran_date)";
42
43         $sql = "SELECT type, reference, tran_date,
44                 $value as Balance,
45                 IF ((TO_DAYS('$todate') - TO_DAYS($due)) >= 0,$value,0) AS Due,
46                 IF ((TO_DAYS('$todate') - TO_DAYS($due)) >= $PastDueDays1,$value,0) AS Overdue1,
47                 IF ((TO_DAYS('$todate') - TO_DAYS($due)) >= $PastDueDays2,$value,0) AS Overdue2
48
49                 FROM ".TB_PREF."debtor_trans trans
50
51                 WHERE type <> ".ST_CUSTDELIVERY."
52                         AND debtor_no = $customer_id 
53                         AND tran_date <= '$todate'
54                         AND ABS($value) > " . FLOAT_COMP_DELTA;
55
56         $sql .= "ORDER BY tran_date";
57
58         return db_query($sql, "The customer transactions could not be retrieved");
59 }
60
61 //----------------------------------------------------------------------------------------------------
62
63 function print_aged_customer_analysis()
64 {
65     global $path_to_root, $systypes_array, $SysPrefs;
66
67     $to = $_POST['PARAM_0'];
68     $fromcust = $_POST['PARAM_1'];
69     $currency = $_POST['PARAM_2'];
70     $show_all = $_POST['PARAM_3'];
71         $summaryOnly = $_POST['PARAM_4'];
72     $no_zeros = $_POST['PARAM_5'];
73     $graphics = $_POST['PARAM_6'];
74     $comments = $_POST['PARAM_7'];
75         $orientation = $_POST['PARAM_8'];
76         $destination = $_POST['PARAM_9'];
77         if ($destination)
78                 include_once($path_to_root . "/reporting/includes/excel_report.inc");
79         else
80                 include_once($path_to_root . "/reporting/includes/pdf_report.inc");
81         $orientation = ($orientation ? 'L' : 'P');
82         if ($graphics)
83         {
84                 include_once($path_to_root . "/reporting/includes/class.graphic.inc");
85                 $pg = new chart($graphics);
86         }
87
88         if ($fromcust == ALL_TEXT)
89                 $from = _('All');
90         else
91                 $from = get_customer_name($fromcust);
92         $dec = user_price_dec();
93
94         if ($summaryOnly == 1)
95                 $summary = _('Summary Only');
96         else
97                 $summary = _('Detailed Report');
98         if ($currency == ALL_TEXT)
99         {
100                 $convert = true;
101                 $currency = _('Balances in Home Currency');
102         }
103         else
104                 $convert = false;
105
106         if ($no_zeros) $nozeros = _('Yes');
107         else $nozeros = _('No');
108         if ($show_all) $show = _('Yes');
109         else $show = _('No');
110
111         $PastDueDays1 = get_company_pref('past_due_days');
112         $PastDueDays2 = 2 * $PastDueDays1;
113         $nowdue = "1-" . $PastDueDays1 . " " . _('Days');
114         $pastdue1 = $PastDueDays1 + 1 . "-" . $PastDueDays2 . " " . _('Days');
115         $pastdue2 = _('Over') . " " . $PastDueDays2 . " " . _('Days');
116
117         $cols = array(0, 100, 130, 190, 250, 320, 385, 450,     515);
118         $headers = array(_('Customer'), '',     '',     _('Current'), $nowdue, $pastdue1, $pastdue2,
119                 _('Total Balance'));
120
121         $aligns = array('left', 'left', 'left', 'right', 'right', 'right', 'right',     'right');
122
123         $params =   array(      0 => $comments,
124                                 1 => array('text' => _('End Date'), 'from' => $to, 'to' => ''),
125                                 2 => array('text' => _('Customer'),     'from' => $from, 'to' => ''),
126                                 3 => array('text' => _('Currency'), 'from' => $currency, 'to' => ''),
127                                 4 => array('text' => _('Type'),         'from' => $summary,'to' => ''),
128                     5 => array('text' => _('Show Also Allocated'), 'from' => $show, 'to' => ''),                
129                                 6 => array('text' => _('Suppress Zeros'), 'from' => $nozeros, 'to' => ''));
130
131         if ($convert)
132                 $headers[2] = _('Currency');
133     $rep = new FrontReport(_('Aged Customer Analysis'), "AgedCustomerAnalysis", user_pagesize(), 9, $orientation);
134     if ($orientation == 'L')
135         recalculate_cols($cols);
136
137     $rep->Font();
138     $rep->Info($params, $cols, $headers, $aligns);
139     $rep->NewPage();
140
141         $total = array(0,0,0,0, 0);
142
143         $sql = "SELECT debtor_no, name, curr_code FROM ".TB_PREF."debtors_master";
144         if ($fromcust != ALL_TEXT)
145                 $sql .= " WHERE debtor_no=".db_escape($fromcust);
146         $sql .= " ORDER BY name";
147         $result = db_query($sql, "The customers could not be retrieved");
148
149         while ($myrow=db_fetch($result))
150         {
151                 if (!$convert && $currency != $myrow['curr_code'])
152                         continue;
153
154                 if ($convert) $rate = get_exchange_rate_from_home_currency($myrow['curr_code'], $to);
155                 else $rate = 1.0;
156                 $custrec = get_customer_details($myrow['debtor_no'], $to, $show_all);
157                 if (!$custrec)
158                         continue;
159                 $custrec['Balance'] *= $rate;
160                 $custrec['Due'] *= $rate;
161                 $custrec['Overdue1'] *= $rate;
162                 $custrec['Overdue2'] *= $rate;
163                 $str = array($custrec["Balance"] - $custrec["Due"],
164                         $custrec["Due"]-$custrec["Overdue1"],
165                         $custrec["Overdue1"]-$custrec["Overdue2"],
166                         $custrec["Overdue2"],
167                         $custrec["Balance"]);
168                 if ($no_zeros && floatcmp(array_sum($str), 0) == 0) continue;
169
170                 $rep->fontSize += 2;
171                 $rep->TextCol(0, 2, $myrow["name"]);
172                 if ($convert) $rep->TextCol(2, 3,       $myrow['curr_code']);
173                 $rep->fontSize -= 2;
174                 $total[0] += ($custrec["Balance"] - $custrec["Due"]);
175                 $total[1] += ($custrec["Due"]-$custrec["Overdue1"]);
176                 $total[2] += ($custrec["Overdue1"]-$custrec["Overdue2"]);
177                 $total[3] += $custrec["Overdue2"];
178                 $total[4] += $custrec["Balance"];
179                 for ($i = 0; $i < count($str); $i++)
180                         $rep->AmountCol($i + 3, $i + 4, $str[$i], $dec);
181                 $rep->NewLine(1, 2);
182                 if (!$summaryOnly)
183                 {
184                         $res = get_invoices($myrow['debtor_no'], $to, $show_all);
185                 if (db_num_rows($res)==0)
186                                 continue;
187                 $rep->Line($rep->row + 4);
188                         while ($trans=db_fetch($res))
189                         {
190                                 $rep->NewLine(1, 2);
191                         $rep->TextCol(0, 1, $systypes_array[$trans['type']], -2);
192                                 $rep->TextCol(1, 2,     $trans['reference'], -2);
193                                 $rep->DateCol(2, 3, $trans['tran_date'], true, -2);
194
195                                 foreach ($trans as $i => $value)
196                                         $trans[$i] = (float)$trans[$i] * $rate;
197                                 $str = array($trans["Balance"] - $trans["Due"],
198                                         $trans["Due"]-$trans["Overdue1"],
199                                         $trans["Overdue1"]-$trans["Overdue2"],
200                                         $trans["Overdue2"],
201                                         $trans["Balance"]);
202                                 for ($i = 0; $i < count($str); $i++)
203                                         $rep->AmountCol($i + 3, $i + 4, $str[$i], $dec);
204                         }
205                         $rep->Line($rep->row - 8);
206                         $rep->NewLine(2);
207                 }
208         }
209         if ($summaryOnly)
210         {
211         $rep->Line($rep->row  + 4);
212         $rep->NewLine();
213         }
214         $rep->fontSize += 2;
215         $rep->TextCol(0, 3, _('Grand Total'));
216         $rep->fontSize -= 2;
217         $serie = array();
218         for ($i = 0; $i < count($total); $i++)
219         {
220                 $rep->AmountCol($i + 3, $i + 4, $total[$i], $dec);
221                 if ($graphics && $i < count($total) - 1)
222                 {
223                         $serie[] = abs($total[$i]);
224                 }
225         }
226         $rep->Line($rep->row - 8);
227         if ($graphics)
228         {
229                 $pg->setStream('png');
230                 $pg->addSerie(_('Balances'), $serie);
231                 $pg->setLabels(array(_('Current'), $nowdue, $pastdue1, $pastdue2));
232                 $pg->setTitle($rep->title);
233                 $pg->setXTitle(_("Days"));
234                 $pg->setYTitle(_("Amount"));
235                 $pg->setDTitle(number_format2($total[4]));
236                 $pg->setValues(true);
237                 $pg->latin_notation = ($SysPrefs->decseps[user_dec_sep()] != ".");
238                 $filename = company_path(). "/pdf_files/". random_id().".png";
239                 $pg->display($filename);
240                 //sleep(5);
241                 $w = $pg->width / 1.5;
242                 $h = $pg->height / 1.5;
243                 $x = ($rep->pageWidth - $w) / 2;
244                 $rep->NewLine(2);
245                 if ($rep->row - $h < $rep->bottomMargin)
246                         $rep->NewPage();
247                 $rep->AddImage($filename, $x, $rep->row - $h, $w, $h);
248         }
249         $rep->NewLine();
250     $rep->End();
251 }