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