Rerun of dashboard.inc file
[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
13 function dashboard($sel_app)
14 {
15         $selected_app = $sel_app;
16
17
18         if (!$_SESSION["wa_current_user"]->check_application_access($selected_app))
19                 return;
20         // first have a look through the directory, 
21         // and remove old temporary pdfs and pngs
22         $dir = company_path(). '/pdf_files';
23
24         if ($d = @opendir($dir)) {
25                 while (($file = readdir($d)) !== false) {
26                         if (!is_file($dir.'/'.$file) || $file == 'index.php') continue;
27                 // then check to see if this one is too old
28                         $ftime = filemtime($dir.'/'.$file);
29                  // seems 3 min is enough for any report download, isn't it?
30                         if (time()-$ftime > 180){
31                                 unlink($dir.'/'.$file);
32                         }
33                 }
34                 closedir($d);
35         }
36
37         //check_for_overdue_recurrent_invoices();
38         if ($selected_app == "orders")
39                 display_customer_topten();
40         elseif ($selected_app == "AP")
41                 display_supplier_topten();
42         elseif ($selected_app == "stock")
43                 display_stock_topten();
44         elseif ($selected_app == "manuf")
45                 display_stock_topten(1);
46         elseif ($selected_app == "assets")
47                 display_stock_topten(2);
48         elseif ($selected_app == "proj")
49                 display_dimension_topten();
50         elseif ($selected_app == "GL")
51                 display_gl_info();
52         else    
53                 display_all();
54 }
55
56 function display_title($title, $colspan=2)
57 {
58         echo "<tr><td colspan=$colspan class='headingtext' style='text-align:center;border:0;height:40px;'>$title</td></tr>\n";
59 }       
60
61 function table_one()
62 {
63         echo "<table width='100%'>";
64         echo "<tr valign=top><td style='width:50%'>\n"; // outer table
65 }
66
67 function table_two()
68 {
69         echo "</td><td style='width:50%'>\n";
70 }
71
72 function table_end()
73 {
74         echo "</td></tr></table>\n";
75 }
76
77 function display_customer_topten()
78 {
79         $pg = new graph();
80
81         table_one();
82         $today = Today();
83         $title = customer_top($today, 10, 66, $pg);
84         customer_trans($today);
85         table_two();
86         source_graphic($today, $title, _("Customer"), $pg);
87         customer_recurrent_invoices($today);
88         table_end();
89 }
90
91 function display_supplier_topten()
92 {
93         $pg = new graph();
94
95         $today = Today();
96         table_one();
97         $title = supplier_top($today, 10, 66, $pg);
98         supplier_trans($today);
99         table_two();
100         source_graphic($today, $title, _("Supplier"), $pg);
101         table_end();
102 }
103
104 function display_stock_topten($type=0)
105 {
106         $pg = new graph();
107
108         table_one();
109         $today = Today();
110         $title = stock_top($today, 10, 66, $type, $pg);
111         table_two();
112         if ($type == 2)
113                 $source = _("Fixed Assets");
114         elseif ($type == 1)
115                 $source = _("Manufacturing");
116         else    
117                 $source = _("Items");
118         source_graphic($today, $title, $source, $pg);
119         table_end();
120 }
121
122 function display_dimension_topten()
123 {
124         $pg = new graph();
125
126         table_one();
127         $today = Today();
128         $title = dimension_top($today, 10, 66, $pg);
129         table_two();
130         source_graphic($today, $title, _("Dimension"), $pg, 5);
131         table_end();
132 }       
133
134 function display_gl_info()
135 {
136         $pg = new graph();
137
138         table_one();
139         $today = Today();
140         $title = gl_top($today, 66, $pg);
141         bank_balance($today, 66);
142         table_two();
143         source_graphic($today, $title, _("Class"), $pg, 5);
144         table_end();
145 }       
146
147 function display_all()
148 {
149         $today = Today();
150         $pg = new graph();
151
152         table_one();
153         $title = customer_top($today, 3, 66, $pg);
154         source_graphic($today, $title, _("Customer"), $pg);
155         $title = supplier_top($today, 3, 66, $pg);
156         source_graphic($today, $title, _("Supplier"), $pg);
157         $title = stock_top($today, 3, 66, 0, $pg);
158         source_graphic($today, $title, _("Stock"), $pg);
159         table_two();
160         dimension_top($today, 3, 66);
161         $title = gl_top($today, 66, $pg);
162         source_graphic($today, $title, _("Class"), $pg, 5);
163         stock_top($today, 3, 66, 2);
164         stock_top($today, 3, 66, 1);
165         table_end();
166 }
167
168 function customer_top($today, $limit=10, $width="33", &$pg=null)
169 {
170         $begin = begin_fiscalyear();
171         $begin1 = date2sql($begin);
172         $today1 = date2sql($today);
173         $sql = "SELECT SUM((ov_amount + ov_discount) * rate * IF(trans.type = ".ST_CUSTCREDIT.", -1, 1)) AS total,d.debtor_no, d.name FROM
174                 ".TB_PREF."debtor_trans AS trans, ".TB_PREF."debtors_master AS d WHERE trans.debtor_no=d.debtor_no
175                 AND (trans.type = ".ST_SALESINVOICE." OR trans.type = ".ST_CUSTCREDIT.")
176                 AND tran_date >= '$begin1' AND tran_date <= '$today1' GROUP by d.debtor_no ORDER BY total DESC, d.debtor_no 
177                 LIMIT $limit";
178         $result = db_query($sql);
179         $title = _("Top $limit customers in fiscal year");
180         $th = array(_("Customer"), _("Amount"));
181         start_table(TABLESTYLE, "width='$width%'");
182         display_title($title, count($th));
183         table_header($th);
184         check_page_security('SA_SALESTRANSVIEW');
185         $k = 0; //row colour counter
186         $i = 0;
187         while ($myrow = db_fetch($result))
188         {
189                 alt_table_row_color($k);
190                 $name = $myrow["debtor_no"]." ".$myrow["name"];
191                 label_cell($name);
192                 amount_cell($myrow['total']);
193                 if ($pg != null)
194                 {
195                         $pg->x[$i] = $name; 
196                         $pg->y[$i] = $myrow['total'];
197                 }       
198                 $i++;
199                 end_row();
200         }
201         end_table(2);
202         return $title;
203 }
204
205 function supplier_top($today, $limit=10, $width="33", &$pg=null)
206 {
207         $begin = begin_fiscalyear();
208         $begin1 = date2sql($begin);
209         $today1 = date2sql($today);
210         $sql = "SELECT SUM((trans.ov_amount + trans.ov_discount) * rate) AS total, s.supplier_id, s.supp_name FROM
211                 ".TB_PREF."supp_trans AS trans, ".TB_PREF."suppliers AS s WHERE trans.supplier_id=s.supplier_id
212                 AND (trans.type = ".ST_SUPPINVOICE." OR trans.type = ".ST_SUPPCREDIT.")
213                 AND tran_date >= '$begin1' AND tran_date <= '$today1' GROUP by s.supplier_id ORDER BY total DESC, s.supplier_id 
214                 LIMIT $limit";
215         $result = db_query($sql);
216         $title = _("Top $limit suppliers in fiscal year");
217         $th = array(_("Supplier"), _("Amount"));
218         start_table(TABLESTYLE, "width='$width%'");
219         display_title($title, count($th));
220         table_header($th);
221         check_page_security('SA_SUPPTRANSVIEW');
222         $k = 0; //row colour counter
223         $i = 0;
224         while ($myrow = db_fetch($result))
225         {
226                 alt_table_row_color($k);
227                 $name = $myrow["supplier_id"]." ".$myrow["supp_name"];
228                 label_cell($name);
229                 amount_cell($myrow['total']);
230                 if ($pg != null)
231                 {
232                         $pg->x[$i] = $name; 
233                         $pg->y[$i] = $myrow['total'];
234                 }       
235                 $i++;
236                 end_row();
237         }
238         end_table(2);
239         return $title;
240 }
241
242 function stock_top($today, $limit=10, $width="33", $type=0, &$pg=null)
243 {
244         if ($type == 2)
245                 $sec = 'SA_ASSETSANALYTIC';
246         elseif ($type == 1)
247                 $sec = 'SA_WORKORDERANALYTIC';
248         else
249                 $sec = 'SA_ITEMSTRANSVIEW';
250         $begin = begin_fiscalyear();
251         $begin1 = date2sql($begin);
252         $today1 = date2sql($today);
253         if ($type == 0)
254         {
255                 $sql = "SELECT SUM((trans.unit_price * trans.quantity) * d.rate) AS total, s.stock_id, s.description, 
256                         SUM(trans.quantity) AS qty FROM
257                         ".TB_PREF."debtor_trans_details AS trans, ".TB_PREF."stock_master AS s, ".TB_PREF."debtor_trans AS d 
258                         WHERE trans.stock_id=s.stock_id AND trans.debtor_trans_type=d.type AND trans.debtor_trans_no=d.trans_no
259                         AND (d.type = ".ST_SALESINVOICE." OR d.type = ".ST_CUSTCREDIT.") ";
260         }
261         else
262         {
263                 $sql = "SELECT SUM(m.qty * (s.material_cost + s.labour_cost + s.overhead_cost)) AS total, s.stock_id, s.description, 
264                         SUM(qty) AS qty FROM ".TB_PREF."stock_master AS s, ".TB_PREF."stock_moves AS m 
265                         WHERE s.stock_id=m.stock_id ";
266                 if ($type == 1)
267                         $sql .= "AND s.mb_flag='M' ";
268                 elseif ($type == 2)     
269                         $sql .= "AND s.mb_flag='F' ";
270         }
271         $sql .= "AND tran_date >= '$begin1' AND tran_date <= '$today1' GROUP by s.stock_id ORDER BY total DESC, s.stock_id 
272                 LIMIT $limit";
273         $result = db_query($sql);
274         if ($type == 1)
275                 $title = _("Top $limit Manufactured Items in fiscal year");
276         elseif ($type == 2)
277                 $title = _("Top $limit Fixed Assets in fiscal year");
278         else    
279                 $title = _("Top $limit Sold Items in fiscal year");
280         $th = array(_("Item"), _("Amount"), _("Quantity"));
281         start_table(TABLESTYLE, "width='$width%'");
282         display_title($title, count($th));      
283         table_header($th);
284         check_page_security($sec);
285         $k = 0; //row colour counter
286         $i = 0;
287         while ($myrow = db_fetch($result))
288         {
289                 alt_table_row_color($k);
290                 $name = $myrow["description"];
291                 label_cell($name);
292                 amount_cell($myrow['total']);
293                 qty_cell($myrow['qty']);
294                 if ($pg != NULL)
295                 {
296                         $pg->x[$i] = $name; 
297                         $pg->y[$i] = $myrow['total'];
298                 }       
299                 $i++;
300                 end_row();
301         }
302         end_table(2);
303 }
304
305 function dimension_top($today, $limit=10, $width="33", &$pg=null)
306 {
307
308         $begin = begin_fiscalyear();
309         $begin1 = date2sql($begin);
310         $today1 = date2sql($today);
311         $sql = "SELECT SUM(-t.amount) AS total, d.reference, d.name FROM
312                 ".TB_PREF."gl_trans AS t,".TB_PREF."dimensions AS d WHERE
313                 (t.dimension_id = d.id OR t.dimension2_id = d.id) AND
314                 t.tran_date >= '$begin1' AND t.tran_date <= '$today1' GROUP BY d.id ORDER BY total DESC LIMIT $limit";
315         $result = db_query($sql, "Transactions could not be calculated");
316         $title = _("Top $limit Dimensions in fiscal year");
317         $th = array(_("Dimension"), _("Amount"));
318         start_table(TABLESTYLE, "width='$width%'");
319         display_title($title, count($th));
320         table_header($th);
321         check_page_security('SA_DIMTRANSVIEW');
322         $k = 0; //row colour counter
323         $i = 0;
324         while ($myrow = db_fetch($result))
325         {
326                 alt_table_row_color($k);
327                 $name = $myrow['reference']." ".$myrow["name"];
328                 label_cell($name);
329                 amount_cell($myrow['total']);
330                 if ($pg != null)
331                 {
332                         $pg->x[$i] = $name; 
333                         $pg->y[$i] = abs($myrow['total']);
334                 }       
335                 $i++;
336                 end_row();
337         }
338         end_table(2);
339 }
340
341 function gl_top($today, $width="33", &$pg=null)
342 {
343         $begin = begin_fiscalyear();
344         $begin1 = date2sql($begin);
345         $today1 = date2sql($today);
346         $sql = "SELECT SUM(amount) AS total, c.class_name, c.ctype FROM
347                 ".TB_PREF."gl_trans,".TB_PREF."chart_master AS a, ".TB_PREF."chart_types AS t, 
348                 ".TB_PREF."chart_class AS c WHERE
349                 account = a.account_code AND a.account_type = t.id AND t.class_id = c.cid
350                 AND IF(c.ctype > 3, tran_date >= '$begin1', tran_date >= '0000-00-00') 
351                 AND tran_date <= '$today1' GROUP BY c.cid ORDER BY c.cid"; 
352         $result = db_query($sql, "Transactions could not be calculated");
353         $title = _("Class Balances");
354         start_table(TABLESTYLE2, "width='$width%'");
355         display_title($title);
356         check_page_security('SA_GLANALYTIC');
357         $i = 0;
358         $total = 0;
359         while ($myrow = db_fetch($result))
360         {
361                 if ($myrow['ctype'] > 3)
362                 {
363                         $total += $myrow['total'];
364                         $myrow['total'] = -$myrow['total'];
365                         if ($pg != null)
366                         {
367                                 $pg->x[$i] = $myrow['class_name']; 
368                                 $pg->y[$i] = abs($myrow['total']);
369                         }       
370                         $i++;
371                 }       
372                 label_row($myrow['class_name'], number_format2($myrow['total'], user_price_dec()), 
373                         "class='label' style='font-weight:bold;'", "style='font-weight:bold;' align=right");
374         }
375         $calculated = _("Calculated Return");
376         label_row("&nbsp;", "");
377         label_row($calculated, number_format2(-$total, user_price_dec()), 
378                 "class='label' style='font-weight:bold;'", "style='font-weight:bold;' align=right");
379         if ($pg != null)
380         {
381                 $pg->x[$i] = $calculated; 
382                 $pg->y[$i] = -$total;
383         }
384         end_table(2);
385 }
386
387 function source_graphic($today, $title, $source, $pg, $type=2)
388 {
389         $pg->title     = $title;
390         $pg->axis_x    = $source;
391         $pg->axis_y    = _("Amount");
392         $pg->graphic_1 = $today;
393         $pg->type      = $type;
394         $pg->skin      = 1;
395         $pg->built_in  = false;
396         $filename = company_path(). "/pdf_files/". uniqid("").".png";
397         $pg->display($filename, true);
398         start_table(TABLESTYLE);
399         start_row();
400         echo "<td>";
401         echo "<img src='$filename' border='0' alt='$title'>";
402         echo "</td>";
403         end_row();
404         end_table(1);
405 }
406
407 function customer_trans($today)
408 {
409         $today = date2sql($today);
410
411         $sql = "SELECT trans.trans_no, trans.reference, trans.tran_date, trans.due_date, debtor.debtor_no, 
412                 debtor.name, branch.br_name, debtor.curr_code,
413                 (trans.ov_amount + trans.ov_gst + trans.ov_freight 
414                         + trans.ov_freight_tax + trans.ov_discount)     AS total,  
415                 (trans.ov_amount + trans.ov_gst + trans.ov_freight 
416                         + trans.ov_freight_tax + trans.ov_discount - trans.alloc) AS remainder,
417                 DATEDIFF('$today', trans.due_date) AS days      
418                 FROM ".TB_PREF."debtor_trans as trans, ".TB_PREF."debtors_master as debtor, 
419                         ".TB_PREF."cust_branch as branch
420                 WHERE debtor.debtor_no = trans.debtor_no AND trans.branch_code = branch.branch_code
421                         AND trans.type = ".ST_SALESINVOICE." AND (trans.ov_amount + trans.ov_gst + trans.ov_freight 
422                         + trans.ov_freight_tax + trans.ov_discount - trans.alloc) > ".FLOAT_COMP_DELTA." 
423                         AND DATEDIFF('$today', trans.due_date) > 0 ORDER BY days DESC";
424         $result = db_query($sql);
425         $title = db_num_rows($result) . _(" overdue Sales Invoices");
426         br(1);
427         display_heading($title);
428         br();
429         $th = array("#", _("Ref."), _("Date"), _("Due Date"), _("Customer"), _("Branch"), _("Currency"), 
430                 _("Total"), _("Remainder"),     _("Days"));
431         start_table(TABLESTYLE);
432         table_header($th);
433         $k = 0; //row colour counter
434         while ($myrow = db_fetch($result))
435         {
436                 alt_table_row_color($k);
437                 label_cell(get_trans_view_str(ST_SALESINVOICE, $myrow["trans_no"]));
438                 label_cell($myrow['reference']);
439                 label_cell(sql2date($myrow['tran_date']));
440                 label_cell(sql2date($myrow['due_date']));
441                 $name = $myrow["debtor_no"]." ".$myrow["name"];
442                 label_cell($name);
443                 label_cell($myrow['br_name']);
444                 label_cell($myrow['curr_code']);
445                 amount_cell($myrow['total']);
446                 amount_cell($myrow['remainder']);
447                 label_cell($myrow['days'], "align='right'");
448                 end_row();
449         }
450         end_table(2);
451 }
452
453 function calculate_next_invoice($myrow)
454 {
455         if ($myrow["last_sent"] == '0000-00-00')
456                 $next = sql2date($myrow["begin"]);
457         else
458                 $next = sql2date($myrow["last_sent"]);
459         $next = add_months($next, $myrow['monthly']);
460         $next = add_days($next, $myrow['days']);
461         return add_days($next,-1);
462 }
463
464 function customer_recurrent_invoices($today)
465 {
466         $result = get_recurrent_invoices($today);
467         $title = _("Overdue Recurrent Invoices");
468         br(1);
469         display_heading($title);
470         br();
471         $th = array(_("Description"), _("Template No"),_("Customer"),_("Branch")."/"._("Group"),_("Next invoice"));
472         start_table(TABLESTYLE, "width=70%");
473         table_header($th);
474         $k = 0;
475         while ($myrow = db_fetch($result)) 
476         {
477                 if (!$myrow['overdue'])
478                         continue;
479                 alt_table_row_color($k);
480
481                 label_cell($myrow["description"]);
482                 label_cell(get_customer_trans_view_str(ST_SALESORDER, $myrow["order_no"]));
483                 if ($myrow["debtor_no"] == 0)
484                 {
485                         label_cell("");
486
487                         label_cell(get_sales_group_name($myrow["group_no"]));
488                 }
489                 else
490                 {
491                         label_cell(get_customer_name($myrow["debtor_no"]));
492                         label_cell(get_branch_name($myrow['group_no']));
493                 }
494                 label_cell(calculate_next_invoice($myrow),  "align='center'");
495                 end_row();
496         }
497         end_table(2);
498 }
499
500 function supplier_trans($today)
501 {
502         $today = date2sql($today);
503         $sql = "SELECT trans.trans_no, trans.reference, trans.tran_date, trans.due_date, s.supplier_id, 
504                 s.supp_name, s.curr_code,
505                 (trans.ov_amount + trans.ov_gst + trans.ov_discount) AS total,  
506                 (trans.ov_amount + trans.ov_gst + trans.ov_discount - trans.alloc) AS remainder,
507                 DATEDIFF('$today', trans.due_date) AS days      
508                 FROM ".TB_PREF."supp_trans as trans, ".TB_PREF."suppliers as s 
509                 WHERE s.supplier_id = trans.supplier_id
510                         AND trans.type = ".ST_SUPPINVOICE." AND (ABS(trans.ov_amount + trans.ov_gst + 
511                                 trans.ov_discount) - trans.alloc) > ".FLOAT_COMP_DELTA."
512                         AND DATEDIFF('$today', trans.due_date) > 0 ORDER BY days DESC";
513         $result = db_query($sql);
514         $title = db_num_rows($result) . _(" overdue Purchase Invoices");
515         br(1);
516         display_heading($title);
517         br();
518         $th = array("#", _("Ref."), _("Date"), _("Due Date"), _("Supplier"), _("Currency"), _("Total"), 
519                 _("Remainder"), _("Days"));
520         start_table(TABLESTYLE);
521         table_header($th);
522         $k = 0; //row colour counter
523         while ($myrow = db_fetch($result))
524         {
525                 alt_table_row_color($k);
526                 label_cell(get_trans_view_str(ST_SUPPINVOICE, $myrow["trans_no"]));
527                 label_cell($myrow['reference']);
528                 label_cell(sql2date($myrow['tran_date']));
529                 label_cell(sql2date($myrow['due_date']));
530                 $name = $myrow["supplier_id"]." ".$myrow["supp_name"];
531                 label_cell($name);
532                 label_cell($myrow['curr_code']);
533                 amount_cell($myrow['total']);
534                 amount_cell($myrow['remainder']);
535                 label_cell($myrow['days'], "align='right'");
536                 end_row();
537         }
538         end_table(2);
539 }
540
541 function bank_balance($today, $width)
542 {
543         $today = date2sql($today);
544         $sql = "SELECT bank_act, bank_account_name, SUM(amount) balance FROM ".TB_PREF."bank_trans bt 
545                     INNER JOIN ".TB_PREF."bank_accounts ba ON bt.bank_act = ba.id
546                     WHERE trans_date <= '$today'
547                     AND inactive <> 1
548                     GROUP BY bank_act, bank_account_name
549                                 ORDER BY bank_account_name";
550         $result = db_query($sql);
551         $title = _("Bank Account Balances");
552         br(1);
553         display_heading($title);
554         br();
555         $th = array(_("Account"), _("Balance"));
556         start_table(TABLESTYLE, "width='$width%'");
557         table_header($th);
558         $k = 0; //row colour counter
559         while ($myrow = db_fetch($result))
560         {
561                 alt_table_row_color($k);
562                 label_cell(viewer_link($myrow["bank_account_name"], 'gl/inquiry/bank_inquiry.php?bank_account='.$myrow["bank_act"]));
563                 amount_cell($myrow['balance']);
564                 end_row();
565         }
566         end_table(1);
567 }