Rerun of dashboard.inc
[fa-stable.git] / includes / dashboard.inc
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 //$colors = array('#008cc9','#4db625','#ef5500','#eef100','#05c6e6', '#5ee66a'); // Current in Use       
13 $colors = Chart::$palette;
14 $align = $_SESSION['language']->dir == 'rtl' ? 'right' : 'left';
15 $style = "<style>
16 div.square {
17         display: inline-block;
18         width: 200px;
19         height:40px;
20         padding: 3px 5px 0 5px;
21         font-size:12px;
22         font-weight:normal;
23         text-align: $align;
24         line-height: 1.2;
25         color:#fff;
26         border-radius:6px;
27 }
28
29 div.square1 {
30         background:{$colors[1]};
31 }
32 div.square2 {
33         background:{$colors[2]};
34 }
35
36 .span1 {
37         width:200px;
38         padding:0;
39         margin:0;
40         font-size:16px;
41         font-weight:bold;
42         text-align: center;
43 }
44 </style>";
45
46 function dashboard($sel_app)
47 {
48         global  $style;
49         if (is_object($sel_app) && !$_SESSION["wa_current_user"]->check_application_access($selected_app))
50                 return;
51         echo $style;
52         echo "<script> 
53         function chart_update(el, id)
54         {
55                 var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
56                 xhr.onreadystatechange=function()
57                 {
58                         if (xhr.readyState==4 && xhr.status==200)
59                         {
60                                 var xxx = document.createElement('div');
61                                 xxx.innerHTML = xhr.responseText;
62                                 document.getElementById(id).innerHTML = xxx.querySelector('#'+id).innerHTML;
63                         }
64                 }
65                 xhr.open('POST', location.pathname, true);
66                 xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
67                 xhr.send('id='+id+'&'+el.id+'='+el.value+'&sel_app=$sel_app');          
68         }
69         </script>";
70         //check_for_overdue_recurrent_invoices();
71         if ($sel_app == "orders")
72                 display_customer_topten();
73         elseif ($sel_app == "AP")
74                 display_supplier_topten();
75         elseif ($sel_app == "stock")
76                 display_stock_topten();
77         elseif ($sel_app == "manuf")
78                 display_stock_topten(1);
79         elseif ($sel_app == "assets")
80                 display_stock_topten(2);
81         elseif ($sel_app == "proj")
82                 display_dimension_topten();
83         elseif ($sel_app == "GL")
84                 display_gl_info();
85         else    
86                 display_all();
87 }
88
89 function display_title($title, $id=false, $type = false, $per = '', $num = false)
90 {
91         br();
92         start_form();
93         echo "<div>";
94         echo "<span class='headingtext'>$title</span>";
95         if ($id)
96         {
97                 /*
98                 global $Ajax;
99                 echo "<span style='margin-left:10px;text-align:right;'>";
100                 $options = array('select_submit' => true ); 
101                 if (!empty($per))
102                 {
103                         $name = "per_$id";
104                         $sel1 = array(3 => "3", 4 => "4", 5 => "5", 6 => "6", 7 => "7", 8=> "8");
105                         echo array_selector($name, $per, $sel1, $options);
106                         echo " $per\n";
107                 }
108                 else
109                 {
110                         $name = "select_$id";
111                         $sel = array(1 => _("Vertical bars"), 2 => _("Horizontal bars"), 3 => _("Dots"), 4 => _("Lines"), 5 => _("Pie"), 6 => _("Donut"), 7 => _("Half Donut"), 8 => _("Splines"), 9 => _("Tables"));
112                         echo array_selector($name, $type, $sel, $options);
113                 }
114                 if (list_updated($name))
115                         $Ajax->activate($id);
116                 echo "</span>";
117                 */
118                 echo "<span style='margin-left:10px;text-align:right;'>";
119                 if (!empty($per))
120                 {
121                         $sel1 = array(3 => "3", 4 => "4", 5 => "5", 6 => "6", 7 => "7", 8=> "8");
122                         echo "<select id='per_$id' name='per_$id' style='border:1px solid #bbb;color:#555;' onchange='chart_update(this, \"$id\");'>";
123                         foreach ($sel1 as $i => $s)
124                         {
125                                 echo "<option value='$i'";
126                                 if ($num && $i == $num) 
127                                         echo " selected";
128                                 echo ">$s</option>";
129                         }
130                         echo "</select> $per\n";
131                 }
132                 else
133                 {
134                         $sel = array(1 => _("Vertical bars"), 2 => _("Horizontal bars"), 3 => _("Dots"), 4 => _("Lines"), 5 => _("Pie"), 6 => _("Donut"), 7 => _("Half Donut"), 8 => _("Splines"), 9 => _("Tables"));
135                         echo "<select id='select_$id' name='select_$id' style='border:1px solid #bbb;color:#555;' onchange='chart_update(this, \"$id\");'>";
136                         foreach ($sel as $i => $s)
137                         {
138                                 echo "<option value='$i'";
139                                 if ($type && $i == $type) 
140                                         echo " selected";
141                                 echo ">$s</option>";
142                         }
143                         echo "</select>\n";
144                 }
145                 echo "</span>";
146         }
147         echo "</div>\n";        
148         end_form();
149         br();
150 }       
151
152 function table($width='100%', $twidth=false)
153 {
154         $tstyle = ($twidth != false) ? "style='width:$twidth;'" : "";
155         echo "<table width='$width'><tr valign=top><td align='center' $tstyle>";
156 }
157
158 function td($width=false)
159 {
160         $style = ($width != false) ? "style='width:$width;'" : "";
161         echo "</td><td align='center' $style>\n";
162 }       
163
164 function table_end()
165 {
166         echo "</td></tr></table>\n";
167 }
168
169 function headers($labels)
170 {
171         echo "<tr>\n";
172         foreach ($labels as $label)
173                 echo "<td class='tableheader'>$label</td>\n";
174         echo "</tr>\n";
175 }
176
177 function display_customer_topten()
178 {
179         table('100%', '25%');
180         echo "<div class='square square1'>"._('Customers')."<p class='span1'>";
181         echo get_num_customers()."</p></div>";
182         td('25%');
183         echo "<div class='square square1'>"._('Branches')."<p class='span1'>";
184         echo get_num_branches()."</p></div>";
185         td('25%');
186         echo "<div class='square square1'>"._('Salesmen')."<p class='span1'>";
187         echo get_num_salesmen()."</p></div>";
188         td('25%');
189         echo "<div class='square square2'>"._('Overdue Invoices')."<p class='span1'>";
190         echo get_num_overdue_sales()."</p></div>";
191         table_end();
192         $pg = new chart('horizontalBar', 'c1');
193         if (isset($_POST['select_c1']))
194                 $pg->type = $_POST['select_c1'];
195         $today = calc_today();
196         table('100%', '50%');
197         $title = customer_top($today, 10, 66, $pg);
198         $total = customer_aging($today, 66);
199         td('50%');
200         source_graphic($today, $title[0], _("Customer"), $pg);
201         br(3);
202         echo "<div class='square square1'>"._('Sales Total')."<p class='span1'>";
203         echo number_format2($title[1])."</p></div>";
204         br(3);
205         echo "<div class='square square1'>"._('Aging Total')."<p class='span1'>";
206         echo number_format2($total)."</p></div>";
207         table_end();
208         table('100%', '100%');
209         customer_recurrent_invoices($today);
210         customer_trans($today);
211         table_end();
212 }
213
214 function display_supplier_topten()
215 {
216         table('100%', '25%');
217         echo "<div class='square square2'>"._('Suppliers')."<p class='span1'>";
218         echo get_num_suppliers()."</p></div>";
219         td('25%');
220         echo "<div class='square square2'>"._('New Orders')."<p class='span1'>";
221         echo get_new_purch_orders()."</p></div>";
222         td('25%');
223         echo "<div class='square square2'>"._('Invoices')."<p class='span1'>";
224         echo get_num_supp_invoices()."</p></div>";
225         td('25%');
226         echo "<div class='square square2'>"._('Overdue Invoices')."<p class='span1'>";
227         echo get_num_overdue_purch()."</p></div>";
228         table_end();
229         $pg = new chart('horizontalBar', 's1');
230         if (isset($_POST['select_s1']))
231                 $pg->type = $_POST['select_s1'];
232         $today = calc_today();
233         table('100%', '50%');
234         $title = supplier_top($today, 10, 66, $pg);
235         $total = supplier_aging($today, 66);
236         td('50%');
237         source_graphic($today, $title[0], _("Supplier"), $pg);
238         br(3);
239         echo "<div class='square square2'>"._('Purchasable Total')."<p class='span1'>";
240         echo number_format2($title[1])."</p></div>";
241         br(3);
242         echo "<div class='square square2'>"._('Aging Total')."<p class='span1'>";
243         echo number_format2($total)."</p></div>";
244         table_end();
245         table('100%', '100%');
246         supplier_trans($today);
247         table_end();
248 }
249
250 function display_stock_topten($type=0)
251 {
252         if ($type == 0)
253         {
254                 table('100%', '25%');
255                 echo "<div class='square square1'>"._('Items')."<p class='span1'>";
256                 echo get_num_items()."</p></div>";
257                 td('25%');
258                 echo "<div class='square square1'>"._('Locations')."<p class='span1'>";
259                 echo get_num_locations()."</p></div>";
260                 td('25%');
261                 echo "<div class='square square1'>"._('Kits')."<p class='span1'>";
262                 echo get_num_kits()."</p></div>";
263                 td('25%');
264                 echo "<div class='square square2'>"._('Below Reorder Level')."<p class='span1'>";
265                 echo get_num_reorder()."</p></div>";
266                 table_end();
267         }
268         elseif ($type == 1)
269         {
270                 table('100%', '25%');
271                 echo "<div class='square square1'>"._('Assembled Items')."<p class='span1'>";
272                 echo get_num_assembled()."</p></div>";
273                 td('25%');
274                 echo "<div class='square square1'>"._('Manufactured Items')."<p class='span1'>";
275                 echo get_num_manufactured()."</p></div>";
276                 td('25%');
277                 echo "<div class='square square1'>"._('Work Centres')."<p class='span1'>";
278                 echo get_num_workcentres()."</p></div>";
279                 td('25%');
280                 echo "<div class='square square1'>"._('Open Workorders')."<p class='span1'>";
281                 echo get_open_workorders()."</p></div>";
282                 table_end();
283         }
284         elseif ($type == 2)
285         {
286                 table('100%', '25%');
287                 echo "<div class='square square1'>"._('Fixed Assets')."<p class='span1'>";
288                 echo get_num_fixed_assets()."</p></div>";
289                 td('25%');
290                 echo "<div class='square square1'>"._('Locations')."<p class='span1'>";
291                 echo get_num_fixed_locations()."</p></div>";
292                 td('25%');
293                 echo "<div class='square square1'>"._('Categories')."<p class='span1'>";
294                 echo get_num_fixed_categories()."</p></div>";
295                 td('25%');
296                 echo "<div class='square square1'>"._('Fixed Asset Classes')."<p class='span1'>";
297                 echo get_num_fixed_classes()."</p></div>";
298                 table_end();
299         }
300         $pg = new chart('bar', 'i1');
301         if (isset($_POST['select_i1']))
302                 $pg->type = $_POST['select_i1'];
303         table('100%', '50%');
304         $today = calc_today();
305         $title = stock_top($today, 5, 66, $type, $pg);
306         table('50%', '25%');
307         echo "<div class='square square1'>"._('Total Sales')."<p class='span1'>";
308         echo number_format2($title[1])."</p></div>";
309         td('25%');
310         echo "<div class='square square2'>"._('Total Costs')."<p class='span1'>";
311         echo number_format2($title[2])."</p></div>";
312         table_end();
313         td('50%');
314         if ($type == 2)
315                 $source = _("Fixed Assets");
316         elseif ($type == 1)
317                 $source = _("Manufacturing");
318         else    
319                 $source = _("Items");
320         source_graphic($today, $title[0], $source, $pg);
321         echo "<div class='square'><span>"._('Total Results')."<br />";
322         echo number_format2($title[3])."</div>";
323         table_end();
324         table('100%', '100%');
325         stock_below_reorder($today, $type);
326         table_end();
327 }
328
329 function display_dimension_topten()
330 {
331         table('100%', '25%');
332         echo "<div class='square square1'>"._('Dimensions')."<p class='span1'>";
333         echo get_num_dimensions()."</p></div>";
334         td('25%');
335         echo "<div class='square square1'>"._('Type 2 Dimensions')."<p class='span1'>";
336         echo get_dim_type2()."</p></div>";
337         td('25%');
338         $res = get_dim_total();
339         $s = $res[0] < 0.0 ? 2 : 1;
340         echo "<div class='square square{$s}'>"._('Dimensions Total Balance')."<p class='span1'>";
341         echo number_format2($res[0])."</p></div>";
342         td('25%');
343         $s = $res[1] < 0.0 ? 2 : 1;
344         echo "<div class='square square{$s}'>"._('Dimensions Total Result')."<p class='span1'>";
345         echo number_format2($res[1])."</p></div>";
346         table_end();
347         $pg = new chart('bar', 'd1');
348         if (isset($_POST['select_d1']))
349                 $pg->type = $_POST['select_d1'];
350         table('100%', '50%');
351         $today = calc_today();
352         $title = dimension_top($today, 5, 66, $pg);
353         td('50%');
354         source_graphic($today, $title, _("Dimension"), $pg);
355         table_end();
356 }       
357
358 function display_gl_info()
359 {
360         $today = calc_today();
361         table('100%', '25%');
362         echo "<div class='square square1'>"._('Receivables')."<p class='span1'>";
363         echo number_format2(customer_balance($today))."</p></div>";
364         td('25%');
365         echo "<div class='square square2'>"._('Payables')."<p class='span1'>";
366         echo number_format2(-supplier_balance($today))."</p></div>";
367         td('25%');
368         echo "<div class='square square1'>"._('Todays Deposits')."<p class='span1'>";
369         echo number_format2(get_today_deposits($today))."</p></div>";
370         td('25%');
371         echo "<div class='square square2'>"._('Todays Payments')."<p class='span1'>";
372         echo number_format2(get_today_payments($today))."</p></div>";
373         table_end();
374         $pg = new chart('halfDonut', 'g1');
375         if (isset($_POST['select_g1']))
376                 $pg->type = $_POST['select_g1'];
377         table('100%', '50%');
378         $title = gl_top($today, 66, $pg);
379         source_graphic($today, $title, _("Class"), $pg);
380         gl_month_performance($today, 66, 5);
381         td('50%');
382         gl_week_performance($today, 66, 4);
383         cash_flow($today);
384         bank_balance($today, 66);
385         table_end();
386 }       
387
388 function display_all()
389 {
390         $today = calc_today();
391
392         table('100%', '25%');
393         echo "<div class='square square1'>"._('Users')."<p class='span1'>";
394         echo get_num_users()."</p></div>";
395         td('25%');
396         echo "<div class='square square1'>"._('Extensions')."<p class='span1'>";
397         echo get_num_extensions()."</p></div>";
398         td('25%');
399         echo "<div class='square square1'>"._('Languages')."<p class='span1'>";
400         echo get_num_languages()."</p></div>";
401         td('25%');
402         echo "<div class='square square1'>"._('Database Size')."<p class='span1'>";
403         echo get_database_size()."</p></div>";
404         table_end();
405         $pg = new chart('horizontalBar', 'c2');
406         if (isset($_POST['select_c2']))
407                 $pg->type = $_POST['select_c2'];
408         table('100%', '50%');
409         $title = customer_top($today, 3, 66, $pg);
410         source_graphic($today, $title[0], _("Customer"), $pg);
411         $pg = new chart('horizontalBar', 's2');
412         if (isset($_POST['select_s2']))
413                 $pg->type = $_POST['select_s2'];
414         $title = supplier_top($today, 3, 66, $pg);
415         source_graphic($today, $title[0], _("Supplier"), $pg);
416         $pg = new chart('bar', 'i2');
417         if (isset($_POST['select_i2']))
418                 $pg->type = $_POST['select_i2'];
419         $title = stock_top($today, 3, 66, 0, $pg);
420         source_graphic($today, $title[0], _("Items"), $pg);
421         td('50%');
422         dimension_top($today, 3, 66);
423         $pg = new chart('pie', 'd2');
424         if (isset($_POST['select_d2']))
425                 $pg->type = $_POST['select_d2'];
426         $title = gl_top($today, 66, $pg);
427         source_graphic($today, $title, _("Class"), $pg);
428         stock_top($today, 3, 66, 2);
429         stock_top($today, 3, 66, 1);
430         table_end();
431 }
432
433 function customer_top($today, $limit=10, $width='33', &$pg=null)
434 {
435         $begin = date2sql(begin_fiscalyear());
436         $today = date2sql($today);
437         $sql = "SELECT SUM((ov_amount + ov_discount) * rate * IF(trans.type = ".ST_CUSTCREDIT.", -1, 1)) AS total,d.debtor_no, d.name FROM ".TB_PREF."debtor_trans AS trans, ".TB_PREF."debtors_master AS d WHERE trans.debtor_no=d.debtor_no
438                 AND (trans.type = ".ST_SALESINVOICE." OR trans.type = ".ST_CUSTCREDIT.")
439                 AND tran_date >= '$begin' AND tran_date <= '$today' GROUP by d.debtor_no ORDER BY total DESC, d.debtor_no
440                 LIMIT $limit";
441         $result = db_query($sql);
442         $title = sprintf(_("Top %s customers in fiscal year"), $limit);
443         display_title($title);
444         $th = array(_("Customer"), _("Amount"));
445         start_table(TABLESTYLE, "width='$width%'");
446         headers($th);
447         check_page_security('SA_SALESTRANSVIEW');
448         $k = 0; //row colour counter
449         $names = $totals = array();
450         $sales = 0;
451         while ($myrow = db_fetch($result))
452         {
453                 $sales += round($myrow['total']);
454                 alt_table_row_color($k);
455                 $name = $myrow["debtor_no"]." ".htmlspecialchars_decode($myrow["name"]);
456                 label_cell($name);
457                 amount_cell($myrow['total']);
458                 if ($pg != null)
459                 {
460                         $names[] = $name;
461                         $totals[] = round($myrow['total']);
462                 }       
463                 end_row();
464         }
465         if ($pg != null)
466         {
467                 $pg->setLabels($names);
468                 $pg->addSerie(_('Sales'), $totals);
469         }
470         end_table(2);
471         return array($title, $sales);
472 }
473
474 function supplier_top($today, $limit=10, $width='33', &$pg=null)
475 {
476         $begin = date2sql(begin_fiscalyear());
477         $today = date2sql($today);
478         $sql = "SELECT SUM((trans.ov_amount + trans.ov_discount) * rate) AS total, s.supplier_id, s.supp_name FROM
479                 ".TB_PREF."supp_trans AS trans, ".TB_PREF."suppliers AS s WHERE trans.supplier_id=s.supplier_id
480                 AND (trans.type = ".ST_SUPPINVOICE." OR trans.type = ".ST_SUPPCREDIT.")
481                 AND tran_date >= '$begin' AND tran_date <= '$today' GROUP by s.supplier_id ORDER BY total DESC, s.supplier_id
482                 LIMIT $limit";
483         $result = db_query($sql);
484         $title = sprintf(_("Top %s suppliers in fiscal year"), $limit);
485         display_title($title);
486         $th = array(_("Supplier"), _("Amount"));
487         start_table(TABLESTYLE, "width='$width%'");
488         headers($th);
489         check_page_security('SA_SUPPTRANSVIEW');
490         $k = 0; //row colour counter
491         $names = $totals = array();
492         $total = 0;
493         while ($myrow = db_fetch($result))
494         {
495                 $total += $myrow['total'];
496                 alt_table_row_color($k);
497                 $name = $myrow["supplier_id"]." ".htmlspecialchars_decode($myrow["supp_name"]);
498                 label_cell($name);
499                 amount_cell($myrow['total']);
500                 if ($pg != null)
501                 {
502                         $names[] = $name;
503                         $totals[] = round($myrow['total']);
504                 }       
505                 end_row();
506         }
507         if ($pg != null)
508         {
509                 $pg->setLabels($names);
510                 $pg->addSerie(_('Purchases'), $totals);
511         }
512         end_table(2);
513         return array($title, $total);
514 }
515
516 function stock_top($today, $limit=10, $width='33', $type=0, &$pg=null)
517 {
518         if ($type == 2)
519                 $sec = 'SA_ASSETSANALYTIC';
520         elseif ($type == 1)
521                 $sec = 'SA_WORKORDERANALYTIC';
522         else
523                 $sec = 'SA_ITEMSTRANSVIEW';
524         $begin = date2sql(begin_fiscalyear());
525         $today = date2sql($today);
526         if ($type == 0)
527         {
528                 $sql = "SELECT SUM((trans.unit_price * trans.quantity) * d.rate) AS total, s.stock_id, s.description, 
529                         SUM(trans.quantity) AS qty, SUM((s.material_cost + s.overhead_cost + s.labour_cost) * trans.quantity) AS costs FROM
530                         ".TB_PREF."debtor_trans_details AS trans, ".TB_PREF."stock_master AS s, ".TB_PREF."debtor_trans AS d 
531                         WHERE trans.stock_id=s.stock_id AND trans.debtor_trans_type=d.type AND trans.debtor_trans_no=d.trans_no
532                         AND (d.type = ".ST_SALESINVOICE." OR d.type = ".ST_CUSTCREDIT.") ";
533         }
534         else
535         {
536                 $sql = "SELECT SUM(m.qty * (s.material_cost + s.labour_cost + s.overhead_cost)) AS total, s.stock_id, s.description, 
537                         SUM(qty) AS qty FROM ".TB_PREF."stock_master AS s, ".TB_PREF."stock_moves AS m 
538                         WHERE s.stock_id=m.stock_id ";
539                 if ($type == 1)
540                         $sql .= "AND s.mb_flag='M' AND m.type <> ".ST_CUSTDELIVERY." AND m.type <> ".ST_CUSTCREDIT." ";
541                 elseif ($type == 2)     
542                         $sql .= "AND s.mb_flag='F' ";
543         }
544         if ($type != 2)
545                 $sql .= "AND tran_date >= '$begin' ";
546         $sql .= "AND tran_date <= '$today' GROUP by s.stock_id ORDER BY total DESC, s.stock_id LIMIT $limit";
547         $result = db_query($sql);
548         if ($type == 1)
549                 $title = sprintf(_("Top %s Manufactured Items in fiscal year"), $limit);
550         elseif ($type == 2)
551                 $title = sprintf(_("Top %s Fixed Assets"), $limit);
552         else    
553                 $title = sprintf(_("Top %s Sold Items in fiscal year"), $limit);
554         display_title($title);  
555         if ($type == 0) 
556                 $th = array(_("Item"), _("Sales"), _("Costs"), _("Results"), _("Quantity"));
557         else    
558                 $th = array(_("Item"), _("Amount"), _("Quantity"));
559         start_table(TABLESTYLE, "width='$width%'");
560         headers($th);
561         check_page_security($sec);
562         $k = 0; //row colour counter
563         $names = $totals = $costs = $results = array();
564         $sales = $cost = $res = 0;
565         while ($myrow = db_fetch($result))
566         {
567                 $sales += $myrow['total'];
568                 if ($type == 0)
569                 {
570                         $cost += $myrow['costs'];
571                         $res += ($myrow['total'] - $myrow['costs']);
572                 }
573                 alt_table_row_color($k);
574                 $name = $myrow["description"];
575                 label_cell($name);
576                 amount_cell($myrow['total']);
577                 if ($type == 0)
578                 {
579                         amount_cell($myrow['costs']);
580                         amount_cell($myrow['total'] - $myrow['costs']);
581                 }
582                 qty_cell($myrow['qty']);
583                 if ($pg != NULL)
584                 {
585                         $names[] = $name;
586                         $totals[] = round($myrow['total']);     
587                         if ($type == 0)
588                         {
589                                 $costs[] = round($myrow['costs']);
590                                 $results[] = round($myrow['total'] - $myrow['costs']);
591                         }
592                 }       
593                 end_row();
594         }
595         if ($pg != null)
596         {
597                 $pg->setLabels($names);
598                 $pg->addSerie(_('Sales'), $totals);
599                 if ($type == 0)
600                 {
601                         $pg->addSerie(_('Costs'), $costs);
602                         $pg->addSerie(_('Results'), $results, 8);
603                 }
604         }
605         end_table(2);
606         return array($title, $sales, $cost, $res);
607 }
608
609 function dimension_top($today, $limit=10, $width='33', &$pg=null)
610 {
611         $begin = date2sql(begin_fiscalyear());
612         $today = date2sql($today);
613
614         $sql = "SELECT SUM(IF(c.ctype > 3, -amount, 0)) AS result, SUM(IF(c.ctype < 4, amount, 0)) AS balance, d.reference, d.name FROM ".TB_PREF."gl_trans g 
615                 LEFT JOIN ".TB_PREF."chart_master AS a ON g.account = a.account_code
616                 LEFT JOIN ".TB_PREF."chart_types AS t ON t.id = a.account_type
617                 LEFT JOIN ".TB_PREF."dimensions AS d ON (g.dimension_id = d.id OR g.dimension2_id = d.id)
618                 LEFT JOIN ".TB_PREF."chart_class AS c ON t.class_id = c.cid
619                 WHERE IF(c.ctype > 3, tran_date >= '$begin', tran_date >= '0000-00-00') 
620                 AND tran_date <= '$today'  AND d.reference IS NOT NULL GROUP BY d.reference ORDER BY result DESC LIMIT $limit";         
621         $result = db_query($sql, "Transactions could not be calculated");
622         $title = sprintf(_("Top %s Dimensions in fiscal year"), $limit);
623         display_title($title);
624         $th = array(_("Dimension"), _("Balance"), _("Result"));
625         start_table(TABLESTYLE, "width='$width%'");
626         headers($th);
627         check_page_security('SA_DIMTRANSVIEW');
628         $k = 0; //row colour counter
629         $names = $balances = $results = array();
630         while ($myrow = db_fetch($result))
631         {
632                 alt_table_row_color($k);
633                 $name = $myrow['reference']." ".$myrow["name"];
634                 label_cell($name);
635                 amount_cell($myrow['balance']);
636                 amount_cell($myrow['result']);
637                 if ($pg != null)
638                 {
639                         $names[] = $name; 
640                         $balances[] = round(abs($myrow['balance']));
641                         $results[] = round(abs($myrow['result']));
642                 }       
643                 end_row();
644         }
645         if ($pg != null)
646         {
647                 $pg->setLabels($names);
648                 $pg->setValues(true);
649                 $pg->addSerie(_('Balance'), $balances);
650                 $pg->addSerie(_('Result'), $results);
651         }
652         end_table(2);
653         return $title;
654 }
655
656 function gl_top($today, $width='33', &$pg=null)
657 {
658         $begin = date2sql(begin_fiscalyear());
659         $today = date2sql($today);
660         $sql = "SELECT SUM(IF(c.ctype > 3, -amount, amount)) AS total, c.class_name, c.ctype FROM
661                 ".TB_PREF."gl_trans,".TB_PREF."chart_master AS a, ".TB_PREF."chart_types AS t, 
662                 ".TB_PREF."chart_class AS c WHERE
663                 account = a.account_code AND a.account_type = t.id AND t.class_id = c.cid
664                 AND IF(c.ctype > 3, tran_date >= '$begin', tran_date >= '0000-00-00') 
665                 AND tran_date <= '$today' GROUP BY c.cid ORDER BY c.cid"; 
666         $result = db_query($sql, "Transactions could not be calculated");
667         $title = _("Class Balances");
668         display_title($title);
669         start_table(TABLESTYLE2, "width='$width%'");
670         check_page_security('SA_GLANALYTIC');
671         $total = 0;
672         $names = $totals = array();
673         while ($myrow = db_fetch($result))
674         {
675                 if ($myrow['ctype'] > 3)
676                 {
677                         $total += round($myrow['total']);
678                         if ($pg != null)
679                         {
680                                 $names[] = $myrow['class_name']; 
681                                 $totals[] = round(abs($myrow['total']));
682                         }       
683                 }       
684                 label_row($myrow['class_name'], number_format2($myrow['total'], user_price_dec()), 
685                         "class='label' style='font-weight:bold;'", "style='font-weight:bold;' align=right");
686         }
687         $calculated = _("Calculated Return");
688         label_row("&nbsp;", "");
689         label_row($calculated, number_format2($total, user_price_dec()), 
690                 "class='label' style='font-weight:bold;'", "style='font-weight:bold;' align=right");
691         if ($pg != null)
692         {
693                 $names[] = $calculated; 
694                 $totals[] = $total;
695                 $pg->setLabels($names);
696                 $pg->addSerie(_('Totals'), $totals);
697                 $pg->setValues(true);
698                 $pg->setDTitle(number_format2($total));
699         }
700         end_table(2);
701         return $title;
702 }
703
704 function gl_week_performance($today, $width="33", $weeks=4)
705 {
706         global $SysPrefs;
707         
708         $pg = new chart('bar', 'g3');
709         if (isset($_POST['select_g3']))
710                 $pg->type = $_POST['select_g3'];
711         if (isset($_POST['per_g3']))
712                 $weeks = $_POST['per_g3'];
713         $begin = date2sql(begin_fiscalyear());
714         $today1 = date2sql($today);
715         $sep = $SysPrefs->dateseps[user_date_sep()];
716         $sql = "SELECT week_name, sales, costs 
717                 FROM(SELECT DATE_FORMAT(tran_date, '%X{$sep}%V') AS week_name, 
718                         SUM(IF(c.ctype = 4, amount * -1, 0)) AS sales, 
719                         SUM(IF(c.ctype = 6, amount, 0)) AS costs FROM 
720                         ".TB_PREF."gl_trans, ".TB_PREF."chart_master AS a, ".TB_PREF."chart_types AS t, 
721                         ".TB_PREF."chart_class AS c WHERE(c.ctype = 4 OR c.ctype = 6) 
722                         AND account = a.account_code AND a.account_type = t.id AND t.class_id = c.cid 
723                         AND tran_date >= '$begin' AND tran_date <= '$today1' 
724                         GROUP BY week_name ORDER BY week_name DESC LIMIT 0, $weeks) b 
725                 GROUP BY week_name ORDER BY week_name ASC";
726         $result = db_query($sql, "Transactions could not be calculated");
727         $title = sprintf(_("Last %s weeks Performance"), $weeks);
728         check_page_security('SA_GLANALYTIC');
729         $week_names = $sales = $costs = $results = array();
730         while ($myrow = db_fetch($result))
731         {
732                 $week_names[] = $myrow['week_name']; 
733                 $sales[] = round($myrow['sales']);
734                 $costs[] = round($myrow['costs']);
735                 $results[] = round($myrow['sales'] - $myrow['costs']);
736         }       
737         $pg->setLabels($week_names);
738         $pg->addSerie(_('Sales'), $sales, 'bar');
739         $pg->addSerie(_('Costs'), $costs, 'bar');
740         $pg->addSerie(_('Results'), $results, 8);
741         source_graphic($today, $title, _("Week"), $pg, _("Weeks"), $weeks);
742 }
743
744 function gl_month_performance($today, $width="33", $months=5)
745 {
746         global $SysPrefs;
747         $pg = new chart('bar', 'g4');
748         if (isset($_POST['select_g4']))
749                 $pg->type = $_POST['select_g4'];
750         if (isset($_POST['per_g4']))
751                 $months = $_POST['per_g4'];
752         $begin = date2sql(begin_fiscalyear());
753         $today1 = date2sql($today);
754         $sep = $SysPrefs->dateseps[user_date_sep()];
755         $sql = "SELECT month_name, sales, costs 
756                 FROM(SELECT DATE_FORMAT(tran_date, '%Y{$sep}%m') AS month_name, 
757                         SUM(IF(c.ctype = 4, amount * -1, 0)) AS sales, 
758                         SUM(IF(c.ctype = 6, amount, 0)) AS costs FROM 
759                         ".TB_PREF."gl_trans, ".TB_PREF."chart_master AS a, ".TB_PREF."chart_types AS t, 
760                         ".TB_PREF."chart_class AS c WHERE(c.ctype = 4 OR c.ctype = 6) 
761                         AND account = a.account_code AND a.account_type = t.id AND t.class_id = c.cid 
762                         AND tran_date >= '$begin' AND tran_date <= '$today1' 
763                         GROUP BY month_name ORDER BY month_name DESC LIMIT 0, $months) b 
764                 GROUP BY month_name ORDER BY month_name ASC";
765         $result = db_query($sql, "Transactions could not be calculated");
766         $title = sprintf(_("Last %s Months Performance"), $months);
767         check_page_security('SA_GLANALYTIC');
768         $month_names = $sales = $costs = $results = array();
769         while ($myrow = db_fetch($result))
770         {
771                 $month_names[] = $myrow['month_name']; 
772                 $sales[] = round($myrow['sales']);
773                 $costs[] = round($myrow['costs']);
774                 $results[] = round($myrow['sales'] - $myrow['costs']);
775         }       
776         $pg->setLabels($month_names);
777         $pg->addSerie(_('Sales'), $sales, 'bar');
778         $pg->addSerie(_('Costs'), $costs, 'bar');
779         $pg->addSerie(_('Results'), $results, 8);
780         source_graphic($today, $title, _("Month"), $pg, _("Months"), $months);
781 }
782
783 function customer_aging($today, $width="33")
784 {
785         $pg = new chart('bar', 'c3');
786         if (isset($_POST['select_c3']))
787                 $pg->type = $_POST['select_c3'];
788         $today1 = date2sql($today);
789         $past1 = get_company_pref('past_due_days');
790         $past2 = 2 * $past1;
791         // removed - debtor_trans.alloc from all summations
792         $sign = "IF(`type` IN(".implode(',',  array(ST_CUSTCREDIT,ST_CUSTPAYMENT,ST_BANKDEPOSIT))."), -1, 1)";
793         $value = "IFNULL($sign*((trans.ov_amount + trans.ov_gst + trans.ov_freight + trans.ov_freight_tax + trans.ov_discount - 
794                 trans.alloc)*trans.rate),0)";
795         $due = "IF (trans.type=".ST_SALESINVOICE.", trans.due_date, trans.tran_date)";
796     $sql = "SELECT Sum($value) AS Balance,
797                                 Sum(IF ((TO_DAYS('$today1') - TO_DAYS($due)) > 0,$value,0)) AS Due,
798                                 Sum(IF ((TO_DAYS('$today1') - TO_DAYS($due)) > $past1,$value,0)) AS Overdue1,
799                                 Sum(IF ((TO_DAYS('$today1') - TO_DAYS($due)) > $past2,$value,0)) AS Overdue2
800                         FROM ".TB_PREF."debtors_master debtor
801                                  LEFT JOIN ".TB_PREF."debtor_trans trans ON trans.tran_date <= '$today1' AND debtor.debtor_no = trans.debtor_no AND trans.type <> ".ST_CUSTDELIVERY.","
802                                  .TB_PREF."payment_terms terms,"
803                                  .TB_PREF."credit_status credit_status
804                         WHERE
805                                         debtor.payment_terms = terms.terms_indicator
806                                 AND debtor.credit_status = credit_status.id";
807                 $sql .= " AND ABS(trans.ov_amount + trans.ov_gst + trans.ov_freight + trans.ov_freight_tax + trans.ov_discount) - trans.alloc > ".FLOAT_COMP_DELTA;
808     $result = db_query($sql,"The customer details could not be retrieved");
809
810     $row = db_fetch($result);
811
812         $title = _("Total Customers Aged Analysis");
813         check_page_security('SA_SALESTRANSVIEW');
814         $names = array();
815         $past1a = $past1 + 1;
816         $past2a = $past2 + 1;
817         $names = array(_('Current'),"1-$past1", "$past1a-$past2", "$past2+");
818         $balances = array(round($row['Balance']-$row['Due']), round($row['Due'] - $row['Overdue1']), 
819                 round($row['Overdue1'] - $row['Overdue2']), round($row['Overdue2']));
820         $total = round($row['Balance']);
821         $pg->setLabels($names);
822         $pg->addSerie(_('Balances'), $balances);
823         source_graphic($today, $title, _('Days'), $pg);
824         return $total;
825 }
826
827 function customer_balance($today)
828 {
829         $today = date2sql($today);
830         $sign = "IF(`type` IN(".implode(',',  array(ST_CUSTCREDIT,ST_CUSTPAYMENT,ST_BANKDEPOSIT))."), -1, 1)";
831         $value = "IFNULL($sign*((trans.ov_amount + trans.ov_gst + trans.ov_freight + trans.ov_freight_tax + trans.ov_discount -
832                 trans.alloc)*trans.rate),0)";
833         $due = "IF (trans.type=".ST_SALESINVOICE.", trans.due_date, trans.tran_date)";
834     $sql = "SELECT Sum($value) AS Balance
835                         FROM ".TB_PREF."debtors_master debtor
836                                  LEFT JOIN ".TB_PREF."debtor_trans trans ON trans.tran_date <= '$today' AND debtor.debtor_no = trans.debtor_no AND trans.type <> ".ST_CUSTDELIVERY."
837                         WHERE ABS(trans.ov_amount + trans.ov_gst + trans.ov_freight + trans.ov_freight_tax + trans.ov_discount) - trans.alloc > ".FLOAT_COMP_DELTA;
838     $result = db_query($sql,"The customer details could not be retrieved");
839     $row = db_fetch($result);
840         return $row[0];
841 }
842
843 function supplier_aging($today, $width="33")
844 {
845         $pg = new chart('bar', 's3'); 
846         if (isset($_POST['select_s3']))
847                 $pg->type = $_POST['select_s3'];
848         $today1 = date2sql($today);
849         $past1 = get_company_pref('past_due_days');
850         $past2 = 2 * $past1;
851         // removed - debtor_trans.alloc from all summations
852         $value = "IF (trans.type=".ST_SUPPINVOICE." OR trans.type=".ST_BANKDEPOSIT.", 
853         (trans.ov_amount + trans.ov_gst + trans.ov_discount - trans.alloc) * trans.rate,
854         (trans.ov_amount + trans.ov_gst + trans.ov_discount + trans.alloc) * trans.rate)";
855         $due = "IF (trans.type=".ST_SUPPINVOICE." OR trans.type=".ST_SUPPCREDIT.",trans.due_date,trans.tran_date)";
856     $sql = "SELECT Sum($value) AS Balance,
857                                 Sum(IF ((TO_DAYS('$today1') - TO_DAYS($due)) > 0,$value,0)) AS Due,
858                                 Sum(IF ((TO_DAYS('$today1') - TO_DAYS($due)) > $past1,$value,0)) AS Overdue1,
859                                 Sum(IF ((TO_DAYS('$today1') - TO_DAYS($due)) > $past2,$value,0)) AS Overdue2
860                         FROM ".TB_PREF."suppliers supp
861                          LEFT JOIN ".TB_PREF."supp_trans trans ON supp.supplier_id = trans.supplier_id AND trans.tran_date <= '$today1'
862                         AND ABS(trans.ov_amount + trans.ov_gst + trans.ov_discount) > ".FLOAT_COMP_DELTA."
863                         AND ABS(trans.ov_amount + trans.ov_gst + trans.ov_discount) - trans.alloc > ".FLOAT_COMP_DELTA;
864     $result = db_query($sql,"The supplier details could not be retrieved");
865
866     $row = db_fetch($result);
867
868         $title = _("Total Suppliers Aged Analysis");
869         check_page_security('SA_SUPPLIERANALYTIC');
870         $names = array();
871         $past1a = $past1 + 1;
872         $past2a = $past2 + 1;
873         $names = array(_('Current'),"1-$past1", "$past1a-$past2", "$past2+");
874         $balances = array(round($row['Balance']-$row['Due']), round($row['Due'] - $row['Overdue1']), 
875                 round($row['Overdue1'] - $row['Overdue2']), round($row['Overdue2']));
876         $total = round($row['Balance']);
877         $pg->setLabels($names);
878         $pg->addSerie(_('Balances'), $balances);
879         source_graphic($today, $title, _('Days'), $pg);
880         return $total;
881 }
882
883 function supplier_balance($today)
884 {
885         $today = date2sql($today); 
886         $value = "IF (trans.type=".ST_SUPPINVOICE." OR trans.type=".ST_BANKDEPOSIT.", 
887         (trans.ov_amount + trans.ov_gst + trans.ov_discount - trans.alloc) * trans.rate,
888         (trans.ov_amount + trans.ov_gst + trans.ov_discount + trans.alloc) * trans.rate)";
889     $sql = "SELECT Sum($value) AS Balance
890                         FROM ".TB_PREF."suppliers supplier, ".TB_PREF."supp_trans trans
891                                 WHERE supplier.supplier_id = trans.supplier_id
892                         AND trans.tran_date <= '$today'
893                         AND ABS(trans.ov_amount + trans.ov_gst + trans.ov_discount) > ".FLOAT_COMP_DELTA."
894                         AND ABS(trans.ov_amount + trans.ov_gst + trans.ov_discount) - trans.alloc > ".FLOAT_COMP_DELTA;
895     $result = db_query($sql,"The supplier details could not be retrieved");
896     $row = db_fetch($result);
897         return $row[0];
898 }
899
900 function cash_flow($today)
901 {
902         global $date_system, $SysPrefs;
903         $months = 6;
904         $pg = new chart('spline', 'g5');
905         if (isset($_POST['select_g5']))
906                 $pg->type = $_POST['select_g5'];
907         if (isset($_POST['per_g5']))
908                 $months = $_POST['per_g5'];
909         if (!is_date_in_fiscalyear($today))
910                 $today = end_fiscalyear();
911         $today1 = begin_month($today);
912         $today1 = add_months($today, -$months+1);
913         list($da, $mo, $yr) = explode_date_to_dmy($today1);
914         if ($date_system == 1)
915                 list($yr, $mo, $da) = jalali_to_gregorian($yr, $mo, $da);
916         elseif ($date_system == 2)
917                 list($yr, $mo, $da) = islamic_to_gregorian($yr, $mo, $da);
918
919         $date = array();
920
921         for ($i = 0; $i < $months; $i++)
922                 $date[$i] = date('Y-m-d',mktime(0,0,0,$mo + $i,1,$yr));
923
924         $result = get_bank_accounts();
925         $total =  array_fill(0, $months, 0);
926         $balance = array_fill(0, $months, 0);
927         while ($account=db_fetch($result))
928         { 
929                 $sql = "SELECT";
930                 for ($i = 0; $i < $months; $i++)
931                         $sql .= " SUM(CASE WHEN trans_date < '$date[$i]' THEN amount ELSE 0 END) AS per0".($i+1).",";
932                 $sql = substr($sql, 0, -1);
933                 $sql .= " FROM ".TB_PREF."bank_trans
934                         WHERE bank_act=".$account['id'];
935                 $res = db_query($sql, "Transactions for bank account could not be calculated");
936                 $bal = db_fetch($res);
937                 $is_home = is_company_currency($account['bank_curr_code']);
938                 for ($i = 1; $i <= $months; $i++)
939                         $balance[$i - 1] = $bal['per0'.$i];
940                 for ($i = 0; $i < $months; $i++)
941                 {
942                         if (!$is_home)
943                                 $balance[$i] = to_home_currency($balance[$i], $account['bank_curr_code'], sql2date($date[$i])); 
944                         $total[$i] += $balance[$i];
945                 }
946         }
947         $sep = $SysPrefs->dateseps[user_date_sep()];
948         for ($i = 0; $i < $months; $i++)
949         {
950                 $y = substr($date[$i], 0, 4);
951                 $m = substr($date[$i], 5, 2);
952                 $date[$i] = $y.$sep.$m;
953                 $total[$i] = round($total[$i]);
954         }
955         $title = sprintf(_("Last %s Months Cash Flow"), $months);
956         check_page_security('SA_BANKREP');
957         $pg->setLabels($date);
958         $pg->addSerie(_('Balances'), $total, false, true);
959         source_graphic($today, $title, _("Month"), $pg, _("Months"), $months);
960 }
961
962 function source_graphic($today, $title, $x_axis, $pg, $per = '', $num = false)
963 {
964         if (!empty($per))
965                 div_start($pg->id);
966         //$today = sql2date($today);
967         display_title("$title ($today)", $pg->id, $pg->type, $per, $num);       
968         if ($pg->isEmpty())
969         {
970                 display_note(_("No Data available yet!"), 1);
971                 return;
972         }
973         if ($pg->type == 'horizontalBar')
974         {
975                 $pg->setYTitle($x_axis);
976                 $pg->setXTitle(_("Amount"));
977         }
978         else
979         {
980                 $pg->setXTitle($x_axis);
981                 $pg->setYTitle(_("Amount"));
982         }
983         if (empty($per))
984                 div_start($pg->id);
985         $pg->display();
986         div_end();
987 }
988
989 function customer_trans($today)
990 {
991         $today = date2sql($today);
992
993         $sql = "SELECT trans.trans_no, trans.reference, trans.tran_date, trans.due_date, debtor.debtor_no, 
994                 debtor.name, branch.br_name, debtor.curr_code,
995                 (trans.ov_amount + trans.ov_gst + trans.ov_freight 
996                         + trans.ov_freight_tax + trans.ov_discount)     AS total,  
997                 (trans.ov_amount + trans.ov_gst + trans.ov_freight 
998                         + trans.ov_freight_tax + trans.ov_discount - trans.alloc) AS remainder,
999                 DATEDIFF('$today', trans.due_date) AS days      
1000                 FROM ".TB_PREF."debtor_trans as trans, ".TB_PREF."debtors_master as debtor, 
1001                         ".TB_PREF."cust_branch as branch
1002                 WHERE debtor.debtor_no = trans.debtor_no AND trans.branch_code = branch.branch_code
1003                         AND trans.type = ".ST_SALESINVOICE." AND (trans.ov_amount + trans.ov_gst + trans.ov_freight 
1004                         + trans.ov_freight_tax + trans.ov_discount - trans.alloc) > ".FLOAT_COMP_DELTA." 
1005                         AND DATEDIFF('$today', trans.due_date) > 0 ORDER BY days DESC";
1006         $result = db_query($sql);
1007         $title = db_num_rows($result) . _(" overdue Sales Invoices");
1008         display_title($title);
1009         $th = array("#", _("Ref."), _("Date"), _("Due Date"), _("Customer"), _("Branch"), _("Currency"), 
1010                 _("Total"), _("Remainder"),     _("Days"));
1011         start_table(TABLESTYLE, "width=90%");
1012         headers($th);
1013         $k = 0; //row colour counter
1014         while ($myrow = db_fetch($result))
1015         {
1016                 alt_table_row_color($k);
1017                 label_cell(get_trans_view_str(ST_SALESINVOICE, $myrow["trans_no"]));
1018                 label_cell($myrow['reference']);
1019                 label_cell(sql2date($myrow['tran_date']));
1020                 label_cell(sql2date($myrow['due_date']));
1021                 $name = $myrow["debtor_no"]." ".$myrow["name"];
1022                 label_cell($name);
1023                 label_cell($myrow['br_name']);
1024                 label_cell($myrow['curr_code']);
1025                 amount_cell($myrow['total']);
1026                 amount_cell($myrow['remainder']);
1027                 label_cell($myrow['days'], "align='right'");
1028                 end_row();
1029         }
1030         end_table(2);
1031 }
1032
1033 function calculate_next_invoice($myrow)
1034 {
1035         if ($myrow["last_sent"] == '0000-00-00')
1036                 $next = sql2date($myrow["begin"]);
1037         else
1038                 $next = sql2date($myrow["last_sent"]);
1039         $next = add_months($next, $myrow['monthly']);
1040         $next = add_days($next, $myrow['days']);
1041         return add_days($next,-1);
1042 }
1043
1044 function customer_recurrent_invoices($today)
1045 {
1046         $result = get_recurrent_invoices($today);
1047         $title = _("Overdue Recurrent Invoices");
1048         display_title($title);
1049         $th = array(_("Description"), _("Template No"),_("Customer"),_("Branch")."/"._("Group"),_("Next invoice"));
1050         start_table(TABLESTYLE, "width=90%");
1051         headers($th);
1052         $k = 0;
1053         while ($myrow = db_fetch($result)) 
1054         {
1055                 if (!$myrow['overdue'])
1056                         continue;
1057                 alt_table_row_color($k);
1058
1059                 label_cell($myrow["description"]);
1060                 label_cell(get_customer_trans_view_str(ST_SALESORDER, $myrow["order_no"]));
1061                 if ($myrow["debtor_no"] == 0)
1062                 {
1063                         label_cell("");
1064
1065                         label_cell(get_sales_group_name($myrow["group_no"]));
1066                 }
1067                 else
1068                 {
1069                         label_cell(get_customer_name($myrow["debtor_no"]));
1070                         label_cell(get_branch_name($myrow['group_no']));
1071                 }
1072                 label_cell(calculate_next_invoice($myrow),  "align='center'");
1073                 end_row();
1074         }
1075         end_table(2);
1076 }
1077
1078 function supplier_trans($today)
1079 {
1080         $today = date2sql($today);
1081         $sql = "SELECT trans.trans_no, trans.reference, trans.tran_date, trans.due_date, s.supplier_id, 
1082                 s.supp_name, s.curr_code,
1083                 (trans.ov_amount + trans.ov_gst + trans.ov_discount) AS total,  
1084                 (trans.ov_amount + trans.ov_gst + trans.ov_discount - trans.alloc) AS remainder,
1085                 DATEDIFF('$today', trans.due_date) AS days      
1086                 FROM ".TB_PREF."supp_trans as trans, ".TB_PREF."suppliers as s 
1087                 WHERE s.supplier_id = trans.supplier_id
1088                         AND trans.type = ".ST_SUPPINVOICE." AND (ABS(trans.ov_amount + trans.ov_gst + 
1089                                 trans.ov_discount) - trans.alloc) > ".FLOAT_COMP_DELTA."
1090                         AND DATEDIFF('$today', trans.due_date) > 0 ORDER BY days DESC";
1091         $result = db_query($sql);
1092         $title = db_num_rows($result) . _(" overdue Purchase Invoices");
1093         display_title($title);
1094         $th = array("#", _("Ref."), _("Date"), _("Due Date"), _("Supplier"), _("Currency"), _("Total"), 
1095                 _("Remainder"), _("Days"));
1096         start_table(TABLESTYLE, "width=90%");
1097         headers($th);
1098         $k = 0; //row colour counter
1099         while ($myrow = db_fetch($result))
1100         {
1101                 alt_table_row_color($k);
1102                 label_cell(get_trans_view_str(ST_SUPPINVOICE, $myrow["trans_no"]));
1103                 label_cell($myrow['reference']);
1104                 label_cell(sql2date($myrow['tran_date']));
1105                 label_cell(sql2date($myrow['due_date']));
1106                 $name = $myrow["supplier_id"]." ".$myrow["supp_name"];
1107                 label_cell($name);
1108                 label_cell($myrow['curr_code']);
1109                 amount_cell($myrow['total']);
1110                 amount_cell($myrow['remainder']);
1111                 label_cell($myrow['days'], "align='right'");
1112                 end_row();
1113         }
1114         end_table(2);
1115 }
1116
1117 function stock_below_reorder($today, $type)
1118 {
1119         $MB = ($type == 0 ? 'B' : ($type == 1 ? 'M' : 'F'));
1120         $today = date2sql($today);
1121
1122     $sql = "SELECT st.loc_code, l.location_name, st.stock_id, sm.description, reorders.reorder_level AS r, SUM(st.qty) AS q
1123                 FROM ".TB_PREF."stock_moves st
1124                 LEFT JOIN ".TB_PREF."voided v ON st.type=v.type AND st.trans_no=v.id
1125                 LEFT JOIN ".TB_PREF."stock_master sm ON sm.stock_id = st.stock_id 
1126                 LEFT JOIN ".TB_PREF."loc_stock reorders ON reorders.loc_code=st.loc_code AND
1127                         reorders.stock_id = st.stock_id
1128                 LEFT JOIN ".TB_PREF."locations l ON l.loc_code = st.loc_code 
1129           WHERE ISNULL(v.id) AND tran_date <= '$today' AND sm.mb_flag = 'B'
1130                         GROUP BY sm.stock_id HAVING q <= r";
1131         $result = db_query($sql,"an item reorder could not be retreived");
1132         $title = db_num_rows($result) . _(" items are below Reorder Level");
1133         display_title($title);
1134         $th = array("#", _("Location"), _("Stock Id"), _('Description'), _("Reorder"), _("qty")); 
1135         start_table(TABLESTYLE, "width=90%");
1136         headers($th);
1137         $k = 0; //row colour counter
1138         while ($myrow = db_fetch($result))
1139         {
1140                 alt_table_row_color($k);
1141                 label_cell($myrow['loc_code']);
1142                 label_cell($myrow['location_name']);
1143                 label_cell($myrow['stock_id']);
1144                 label_cell($myrow['description']);
1145                 $dec = get_qty_dec($myrow['stock_id']);         
1146                 qty_cell($myrow['r'], false, $dec);
1147                 qty_cell($myrow['q'], false, $dec);
1148                 end_row();
1149         }
1150         end_table(2);
1151 }
1152
1153 function bank_balance($today, $width)
1154 {
1155         $today = date2sql($today);
1156         $sql = "SELECT bank_act, bank_account_name, bank_curr_code, SUM(amount) balance FROM ".TB_PREF."bank_trans bt 
1157                     INNER JOIN ".TB_PREF."bank_accounts ba ON bt.bank_act = ba.id
1158                     WHERE trans_date <= '$today'
1159                     AND inactive <> 1
1160                     GROUP BY bank_act, bank_account_name
1161                                 ORDER BY bank_account_name";
1162         $result = db_query($sql);
1163         $title = _("Bank Account Balances");
1164         display_title($title);
1165         $th = array(_("Account"), _("Currency"), _("Balance"));
1166         start_table(TABLESTYLE, "width='$width%'");
1167         headers($th);
1168         $k = 0; //row colour counter
1169         while ($myrow = db_fetch($result))
1170         {
1171                 alt_table_row_color($k);
1172                 label_cell(viewer_link($myrow["bank_account_name"], 'gl/inquiry/bank_inquiry.php?bank_account='.$myrow["bank_act"]));
1173                 label_cell($myrow["bank_curr_code"]);
1174                 amount_cell($myrow['balance']);
1175                 end_row();
1176         }
1177         end_table(1);
1178 }
1179
1180 function get_num_customers()
1181 {
1182         $sql = "SELECT count(*) FROM ".TB_PREF."debtors_master";
1183         $result = db_query($sql, "Fail in count customers");
1184     $row = db_fetch($result);
1185         return $row[0];
1186 }
1187
1188 function get_num_branches()
1189 {
1190         $sql = "SELECT count(*) FROM ".TB_PREF."cust_branch";
1191         $result = db_query($sql, "Fail in count branches");
1192     $row = db_fetch($result);
1193         return $row[0];
1194 }
1195
1196 function get_num_salesmen()
1197 {
1198         $sql = "SELECT count(*) FROM ".TB_PREF."salesman";
1199         $result = db_query($sql, "Fail in count salesmen");
1200     $row = db_fetch($result);
1201         return $row[0];
1202 }
1203
1204 function get_num_overdue_sales()
1205 {
1206         $today = date2sql(calc_today());
1207
1208         $sql = "SELECT COUNT(trans.trans_no)    
1209                 FROM ".TB_PREF."debtor_trans as trans
1210                 WHERE trans.type = ".ST_SALESINVOICE." AND (trans.ov_amount + trans.ov_gst + trans.ov_freight 
1211                         + trans.ov_freight_tax + trans.ov_discount - trans.alloc) > ".FLOAT_COMP_DELTA." 
1212                         AND DATEDIFF('$today', trans.due_date) > 0";
1213         $result = db_query($sql);
1214     $row = db_fetch($result);
1215         return $row[0];
1216 }
1217
1218 function get_num_suppliers()
1219 {
1220         $sql = "SELECT count(*) FROM ".TB_PREF."suppliers";
1221         $result = db_query($sql, "Fail in count suppliers");
1222     $row = db_fetch($result);
1223         return $row[0];
1224 }
1225
1226 function get_new_purch_orders()
1227 {
1228         $sql = "SELECT count(*) FROM ".TB_PREF."purch_orders po, ".TB_PREF."purch_order_details pd WHERE po.order_no = pd.order_no AND 
1229                 quantity_received < quantity_ordered";
1230         $result = db_query($sql, "Fail in count purch orders");
1231     $row = db_fetch($result);
1232         return $row[0];
1233 }
1234
1235 function get_num_supp_invoices()
1236 {
1237         $sql = "SELECT count(*) FROM ".TB_PREF."supp_trans WHERE (ov_amount+ov_discount+ov_gst - alloc) <> 0";
1238         $result = db_query($sql, "Fail in count purch invoices");
1239     $row = db_fetch($result);
1240         return $row[0];
1241 }
1242
1243 function get_num_overdue_purch()
1244 {
1245         $today = date2sql(calc_today());
1246
1247         $sql = "SELECT COUNT(*) FROM ".TB_PREF."supp_trans WHERE (ov_amount+ov_discount+ov_gst - alloc) > ".FLOAT_COMP_DELTA." AND DATEDIFF('$today', due_date) > 0";
1248         $result = db_query($sql, "Fail in count purch invoices");
1249     $row = db_fetch($result);
1250         return $row[0];
1251 }
1252
1253 function get_num_items()
1254 {
1255         $sql = "SELECT count(*) FROM ".TB_PREF."stock_master";
1256         $result = db_query($sql, "Fail in count stock master");
1257     $row = db_fetch($result);
1258         return $row[0];
1259 }
1260
1261 function get_num_locations()
1262 {
1263         $sql = "SELECT count(*) FROM ".TB_PREF."locations";
1264         $result = db_query($sql, "Fail in count locations");
1265     $row = db_fetch($result);
1266         return $row[0];
1267 }
1268
1269 function get_num_kits()
1270 {
1271         $sql="SELECT count(*) FROM ".TB_PREF."item_codes";
1272
1273         $result = db_query($sql, "Fail in count kits");
1274     $row = db_fetch($result);
1275         return $row[0];
1276 }
1277
1278 function get_num_reorder()
1279 {
1280         $MB = 'B';
1281         $today = date2sql(calc_today());
1282
1283     $sql = "SELECT st.stock_id, reorders.reorder_level AS r, SUM(st.qty) AS q
1284                 FROM ".TB_PREF."stock_moves st
1285                 LEFT JOIN ".TB_PREF."voided v ON st.type=v.type AND st.trans_no=v.id
1286                 LEFT JOIN ".TB_PREF."stock_master sm ON sm.stock_id = st.stock_id 
1287                 LEFT JOIN ".TB_PREF."loc_stock reorders ON reorders.loc_code=st.loc_code AND
1288                         reorders.stock_id = st.stock_id
1289           WHERE ISNULL(v.id) AND tran_date <= '$today' AND sm.mb_flag = 'B'
1290                         GROUP BY st.stock_id HAVING q <= r";
1291         $result = db_query($sql,"an item reorder could not be retreived");
1292         return db_num_rows($result);
1293 }
1294
1295 function get_num_assembled()
1296 {
1297         $begin = date2sql(begin_fiscalyear());
1298         $today = date2sql(calc_today());
1299         $sql = "SELECT count(*) FROM ".TB_PREF."workorders WHERE closed = 1 AND type = ".WO_ASSEMBLY." AND released_date >= '$begin'
1300                 AND released_date <= '$today'";
1301         $result = db_query($sql, "Fail in count workorders");
1302     $row = db_fetch($result);
1303         return $row[0];
1304 }
1305
1306 function get_num_manufactured()
1307 {
1308         $begin = date2sql(begin_fiscalyear());
1309         $today = date2sql(calc_today());
1310         $sql = "SELECT count(*) FROM ".TB_PREF."workorders WHERE closed = 1 AND type = ".WO_ADVANCED." AND released_date >= '$begin'
1311                 AND released_date <= '$today'";
1312         $result = db_query($sql, "Fail in count workorders");
1313     $row = db_fetch($result);
1314         return $row[0];
1315 }
1316         
1317 function get_num_workcentres()
1318 {
1319         $sql = "SELECT count(*) FROM ".TB_PREF."workcentres";
1320         $result = db_query($sql, "Fail in count work centres");
1321     $row = db_fetch($result);
1322         return $row[0];
1323 }
1324         
1325 function get_open_workorders()
1326 {
1327         $sql = "SELECT count(*) FROM ".TB_PREF."workorders WHERE closed = 0";
1328         $result = db_query($sql, "Fail in count workorders");
1329     $row = db_fetch($result);
1330         return $row[0];
1331 }
1332
1333 function get_num_fixed_assets()
1334 {
1335         $sql = "SELECT count(*) FROM ".TB_PREF."stock_master WHERE mb_flag = 'F'";
1336         $result = db_query($sql, "Fail in count fixed assets");
1337     $row = db_fetch($result);
1338         return $row[0];
1339 }
1340
1341 function get_num_fixed_locations()
1342 {
1343         $sql = "SELECT count(*) FROM ".TB_PREF."stock_master s LEFT JOIN ".TB_PREF."loc_stock l ON s.stock_id = l.stock_id 
1344                 WHERE mb_flag = 'F'";
1345         $result = db_query($sql, "Fail in count locations");
1346     $row = db_fetch($result);
1347         return $row[0];
1348 }
1349
1350 function get_num_fixed_categories()
1351 {
1352         $sql = "SELECT count(*) FROM ".TB_PREF."stock_category c LEFT JOIN ".TB_PREF."stock_master s ON c.category_id = s.category_id 
1353                 WHERE mb_flag = 'F'";
1354         $result = db_query($sql, "Fail in count categories");
1355     $row = db_fetch($result);
1356         return $row[0];
1357 }
1358
1359 function get_num_fixed_classes()
1360 {
1361         $sql = "SELECT count(*) FROM ".TB_PREF."stock_fa_class";
1362         $result = db_query($sql, "Fail in count fa classes");
1363     $row = db_fetch($result);
1364         return $row[0];
1365 }
1366
1367 function get_num_dimensions()
1368 {
1369         $sql = "SELECT count(*) FROM ".TB_PREF."dimensions";
1370         $result = db_query($sql, "Fail in count dimensions");
1371     $row = db_fetch($result);
1372         return $row[0];
1373 }
1374
1375 function get_dim_type2()
1376 {
1377         $sql = "SELECT count(*) FROM ".TB_PREF."dimensions WHERE type_ = 2";
1378         $result = db_query($sql, "Fail in count simensions 2");
1379     $row = db_fetch($result);
1380         return $row[0];
1381 }
1382
1383 function get_dim_closed()
1384 {
1385         $sql = "SELECT count(*) FROM ".TB_PREF."dimensions WHERE closed = 1";
1386         $result = db_query($sql, "Fail in count closed dimensions");
1387     $row = db_fetch($result);
1388         return $row[0];
1389 }
1390
1391 function get_dim_total()
1392 {
1393         $begin = date2sql(begin_fiscalyear());
1394         $today = date2sql(calc_today());
1395         
1396         $sql = "SELECT SUM(IF(c.ctype > 3, -amount, 0)) AS result, SUM(IF(c.ctype < 4, amount, 0)) AS balance, d.reference, d.name FROM ".TB_PREF."gl_trans g 
1397                 LEFT JOIN ".TB_PREF."chart_master AS a ON g.account = a.account_code
1398                 LEFT JOIN ".TB_PREF."chart_types AS t ON t.id = a.account_type
1399                 LEFT JOIN ".TB_PREF."dimensions AS d ON (g.dimension_id = d.id OR g.dimension2_id = d.id)
1400                 LEFT JOIN ".TB_PREF."chart_class AS c ON t.class_id = c.cid
1401                 WHERE IF(c.ctype > 3, tran_date >= '$begin', tran_date >= '0000-00-00') 
1402                 AND tran_date <= '$today'  AND d.reference IS NOT NULL GROUP BY d.reference";   
1403         $bal = $res = 0.0;
1404         $result = db_query($sql, "Transactions could not be calculated");
1405         while ($row = db_fetch($result))
1406         {
1407                 $bal += $row['balance'];
1408                 $res += $row['result'];
1409         }       
1410         return array(round($bal), round($res)); 
1411 }
1412         
1413 function get_today_deposits($today)
1414 {
1415         $today= date2sql($today);
1416         $sql="SELECT SUM(gl.amount) FROM ".TB_PREF."gl_trans gl, ".TB_PREF."bank_accounts ba 
1417                 WHERE gl.account = ba.account_code AND gl.tran_date = '$today' AND gl.amount > 0.0";
1418         $result = db_query($sql, "could not retrieve today deposits");
1419         if ($result == false)
1420                 return 0;
1421         else
1422         {
1423                 $row = db_fetch($result);
1424                 return $row[0];
1425         }
1426 }
1427
1428 function get_today_payments($today)
1429 {
1430         $today= date2sql($today);
1431         $sql="SELECT SUM(gl.amount) FROM ".TB_PREF."gl_trans gl, ".TB_PREF."bank_accounts ba 
1432                 WHERE gl.account = ba.account_code AND gl.tran_date = '$today' AND gl.amount < 0.0";
1433         $result = db_query($sql, "could not retrieve today deposits");
1434         if ($result == false)
1435                 return 0;
1436         else
1437         {
1438                 $row = db_fetch($result);
1439                 return $row[0];
1440         }
1441 }
1442
1443 function get_num_users()
1444 {
1445         $sql = "SELECT count(*) FROM ".TB_PREF."users";
1446         $result = db_query($sql, "could not get num users");
1447     $row = db_fetch($result);
1448         return $row[0];
1449 }
1450
1451 function get_num_extensions()
1452 {
1453         global $installed_extensions;
1454         return count($installed_extensions);
1455 }
1456
1457 function get_num_languages()
1458 {
1459         global $installed_languages;
1460         return count($installed_languages);
1461 }
1462
1463 function get_database_size()
1464 {
1465         global $db_connections;
1466         $c = user_company();
1467         $dbase = $db_connections[$c]['dbname'];
1468         $tb_pref = $db_connections[$c]['tbpref'];
1469         $sql = "SHOW TABLE STATUS FROM $dbase";
1470         if (!empty($tb_pref))
1471                 $sql .= " LIKE '{$tb_pref}%'";
1472         $result = db_query($sql, "could not get database size");
1473     $size = 0;
1474     while ($row = db_fetch($result)) {
1475                 $size += $row['Data_length'];
1476                 $size += $row['Index_length'];
1477     }
1478         return number_format2(($size / 1024 / 1024), 2).' MB';
1479 }
1480
1481 function calc_today()
1482 {
1483         $today = Today();
1484         if (!is_date_in_fiscalyear($today))
1485                 $today = end_fiscalyear();
1486         return $today;
1487 }
1488