0000593,0001093: Prepayments made against orders implemented.
[fa-stable.git] / includes / db_pager.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 //      Controler part of database table pager with column sort.
14 //      To display actual html object call display_db_pager($name) inside
15 //  any form.
16 //
17 //      View definition you will find in the following file:
18 include_once($path_to_root."/includes/ui/db_pager_view.inc");
19
20 class db_pager {
21         var $sql;
22         var $name;
23         var $columns;           // column definitions (head, type, order)
24
25         var $marker;            // marker check function
26         var $marker_txt;        
27         var $marker_class;
28         var $notice_class;
29         var $width;                     // table width (default '95%')
30         var $header_fun;        // additional row between title and body
31         var $header_class;
32         var $footer_fun;
33         var $footer_class;
34         var $data = array();
35
36         var $curr_page,
37                 $max_page,
38             $last_page, 
39             $prev_page, 
40             $next_page,
41             $first_page;
42
43         var $page_len,
44             $rec_count;
45
46         var $order = array();
47
48         var     $extra_where;
49         
50         var $ready = false; // this var is false after change in sql before first
51                                                 // and before first query.
52         var $inactive_ctrl = false;
53         var $main_tbl;          // table and key field name for inactive ctrl and edit/delete links
54         var $key;       // key field name
55         
56         //  db_pager constructor
57         //  accepts $sql like 'SELECT ...[FROM ...][WHERE ...][GROUP ...][ORDER ...]'
58         //      $name is base name for pager controls
59         function db_pager($sql, $name, $table = null, $page_len=0) 
60         {
61                 $this->width = "95%";
62                 if ($page_len == 0) $page_len = user_query_size();
63                 $this->name = $name;
64                 $this->page_len = $page_len;
65                 $this->set_sql($sql);
66         }
67         //
68         //      Parse base sql select query.
69         //
70         function set_sql($sql)
71         {
72                 if ($sql != $this->sql) {
73                     $this->sql = $sql;
74                     $this->ready = false;
75                 }
76         }
77         //
78         //      Set additional constraint on record set
79         //
80         function set_where($where = null)
81         {
82                 if ($where) {
83                 if (!is_array($where))
84                           $where = array($where);
85
86                     if (count($where) == count($this->extra_where) &&
87                                 !count(array_diff($this->extra_where, $where)))
88                                  return;
89                 }
90                 $this->extra_where = $where;
91                 $this->ready = false;
92         }
93         //
94         //      Set query result page
95         //
96         function change_page($page=null) 
97         {
98             $this->set_page($page);
99             $this->query();
100             return true;
101         }
102         //
103         //      Change sort column direction 
104         //      in order asc->desc->none->asc
105         //
106         function sort_table($col) 
107         {
108             $ord = $this->columns[$col]['ord'];
109             $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
110             $this->columns[$col]['ord'] = $ord;
111             $n = array_search($col, $this->order);
112             if ($n !== false)
113                         unset($this->order[$n]);
114                 if ($ord != '')
115                         array_unshift($this->order, $col); // store column number as first
116             $this->set_page(1);
117             $this->query();
118
119             return true;
120         }
121         //
122         // Query database
123         //
124         function query() 
125         {
126                 global $Ajax;
127
128                 $Ajax->activate("_{$this->name}_span");
129             $this->data = array();
130             if (!$this->_init()) 
131                   return false;
132
133             if ($this->rec_count == 0) return true;
134
135             $sql = $this->_sql_gen(false);
136
137             $result = db_query($sql, 'Error browsing database: '.$sql );
138
139             if ($result) {
140                 // setting field names for subsequent queries
141                         $c = 0;
142                   // add result field names to column defs for 
143                   // col value retrieve and sort purposes 
144                    $cnt = min(db_num_fields($result), count($this->columns));
145                         for ($c = $i = 0; $c < $cnt; $c++) {
146                                 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert'])) {
147 //                                      if (!@($this->columns[$c]['type']=='skip'))
148                                                 $this->columns[$c]['name']= db_field_name($result, $i);
149                                         if (!@($this->columns[$c]['type']=='insert'))
150                                         $i++;
151                                         }
152                         }
153                         while ($row = db_fetch_assoc($result)) {
154                                 $this->data[] = $row;
155                         }
156                 } else 
157                   return false;
158                 return true;
159         }
160         //
161         //      Calculates page numbers for html controls.
162         //
163         function set_page($to) 
164         {
165             switch($to) {
166                 case 'next':
167                     $page = $this->curr_page+1; break;
168                 case 'prev':
169                     $page = $this->curr_page-1; break;
170                 case 'last':
171                     $page = $this->last_page; break;
172                 default:
173                     if (is_numeric($to)) {
174                          $page = $to; break;
175                     }
176                 case 'first':
177                     $page = 1; break;
178             }
179           if ($page < 1) 
180             $page = 1;
181           $max = $this->max_page;
182           if ($page > $max) 
183             $page = $max;
184           $this->curr_page = $page;
185           $this->next_page = ($page < $max) ? $page+1 : null;
186           $this->prev_page = ($page > 1) ? ($page-1) : null;
187           $this->last_page = ($page < $max) ? $max : null;
188           $this->first_page = ($page != 1) ? 1: null;
189         }
190         //
191         //      Set column definitions
192         //  $flds: array( fldname1, fldname2=>type,...)
193         function set_columns($flds)
194         {
195                 $this->columns = $this->order = array();
196                 if (!is_array($flds)) {
197                         $flds = array($flds);
198                 }
199                 foreach ($flds as $colnum=>$coldef) {
200                         if (is_string($colnum)) {       // 'colname'=>params
201                           $h = $colnum;
202                           $c = $coldef;
203                         } else {                        //  n=>params
204                                 if (is_array($coldef)) {
205                                         $h = '';
206                                         $c = $coldef;
207                                 } else {
208                                         $h = $coldef;
209                                         $c = 'text';
210                                 }
211                         }
212                         if (is_string($c))                      // params is simple column type
213                           $c = array('type'=>$c);
214
215                         if (!isset($c['type']))
216                           $c['type'] = 'text';
217
218                         switch($c['type']) {
219                                 case 'inactive': 
220                                         $this->inactive_ctrl = true;
221                                 case 'insert':
222                                 default:
223                                         $c['head'] = $h; break;
224                                 case 'skip':            // skip the column (no header)
225                                         unset($c['head']); break;
226                         }
227                         if (@$c['ord'])
228                                 array_push($this->order, count($this->columns));
229                         $this->columns[] = $c;
230                 }
231         }
232         //
233         // Generate db query from base sql
234         // $count==false - for current page data retrieval 
235         // $count==true  - for total records count
236         //
237         function _sql_gen($count=false) 
238         {
239
240                 if (count($this->extra_where)) {
241                     $where = ' WHERE ('.implode(' AND ', $this->extra_where).')';
242                 } else
243                         $where = '';
244
245                 if ($count)
246                         return "SELECT COUNT(*) FROM ($this->sql) $where AS _dummyname";
247
248
249             $ord = array();
250
251                 $sql = "SELECT * FROM ($this->sql) $where AS _dummyname";
252
253             foreach ($this->order as $n) {
254                 $col = $this->columns[$n];
255                 if (isset($col['ord'])) {
256                         if ( $col['ord'] != '' && isset($col['name'])) {
257                             $ord[] = $col['name'] .' '. $col['ord'];
258                             }
259                         }
260             }
261             if (count($ord)) {
262                         $sql .= " ORDER BY " . implode($ord, ',');
263                 }
264
265             $page_len = $this->page_len;
266             $offset = ($this->curr_page - 1) * $page_len;
267
268
269             $sql .= " LIMIT $offset, $page_len";
270
271                 return $sql;
272
273         }
274         //
275         //      Initialization after changing record set
276         //
277         function _init() 
278         {
279                 global $go_debug;
280
281             if ($this->ready == false ) {
282                         $sql = $this->_sql_gen(true);
283                         $result = db_query($sql, 'Error reading record set');
284                         if ($result == false) 
285                                 return false;
286                         $row = db_fetch_row($result);
287                         $this->rec_count = $row[0];
288                         $this->max_page = $this->page_len ?
289                                 ceil($this->rec_count/$this->page_len) : 0;
290
291                         if ($go_debug) { // FIX - need column name parsing, but for now:
292                                 // check if field names are set explicite in col def
293                                 // for all initially ordered columns
294                             foreach ($this->columns as $col) {
295                                 if (isset($col['ord']) && $col['ord'] != '' 
296                                                 &&  !isset($col['name'])) {
297                                                         display_warning("Result field names must be set
298                                                                 for all initially ordered db_pager columns.");
299                                 }
300                                 }
301                 }
302                         $this->set_page(1);
303                         $this->ready = true;
304             }
305         return true;
306         }
307         //
308         //      Set current page in response to user control.
309         //
310         function select_records() 
311         {
312                 global $Ajax;
313                 
314                 $page = find_submit($this->name.'_page_', false);
315                 $sort = find_submit($this->name.'_sort_', true);
316                 if ($page) {
317                         $this->change_page($page);
318                         if ($page == 'next' && !$this->next_page ||
319                                 $page == 'last' && !$this->last_page)
320                                         set_focus($this->name.'_page_prev');
321                         if ($page == 'prev' && !$this->prev_page ||
322                                 $page == 'first' && !$this->first_page)
323                                         set_focus($this->name.'_page_next');
324                 } elseif ($sort != -1) {
325                         $this->sort_table($sort);
326                 } else
327                         $this->query();
328         }
329         //
330         //      Set check function to mark some rows.
331         //      
332         function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
333         {
334                 $this->marker = $func;
335                 $this->marker_txt = $notice;
336                 $this->marker_class = $markercl;
337                 $this->notice_class = $msgclass;
338         }
339         //
340         //      Set handler to display additional row between titles and pager body.
341         //      Return array of column contents.
342         //
343         function set_header($func, $headercl='inquirybg')
344         {
345                 $this->header_fun = $func;
346                 $this->header_class = $headercl;
347         }
348         //
349         //      Set handler to display additional row between pager body and navibar.
350         //      Return array of column contents.
351         //
352         function set_footer($func, $footercl='inquirybg')
353         {
354                 $this->footer_fun = $func;
355                 $this->footer_class = $footercl;
356         }
357         //
358         //      Setter for table editors with inactive cell control.
359         //
360         function set_inactive_ctrl($table, $key) {
361                 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
362         }
363         //
364         //      Helper for display inactive control cells
365         //
366         function inactive_control_cell(&$row)
367         {
368                 if ($this->inactive_ctrl) {
369 //                      return inactive_control_cell($row[$this->inactive_ctrl['key']],
370 //                               $row['inactive'], $this->inactive_ctrl['table'], 
371 //                               $this->inactive_ctrl['key']);
372
373                         global  $Ajax;
374
375                         $key = $this->key ?
376                                 $this->key : $this->columns[0]['name'];         // TODO - support for complex keys
377                         $id = $row[$key];
378                         $table = $this->main_tbl;
379                         $name = "Inactive". $id;
380                         $value = $row['inactive'] ? 1:0;
381
382                         if (check_value('show_inactive')) {
383                                 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') || 
384                                         get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
385                                         update_record_status($id, !$value, $table, $key);
386                                         $value = !$value;
387                                 }
388                                 echo '<td align="center">'. checkbox(null, $name, $value, true, '', "align='center'")
389                                 . hidden("LInact[$id]", $value, false) . '</td>';       
390                         }
391                 } else
392                         return '';
393         }
394
395 };
396 //-----------------------------------------------------------------------------
397 //      Creates new db_pager $_SESSION object on first page call.
398 //  Retrieves from $_SESSION var on subsequent $_POST calls
399 //
400 //  $name - base name for pager controls and $_SESSION object name
401 //  $sql  - base sql for data inquiry. Order of fields implies
402 //              pager columns order.
403 //      $coldef - array of column definitions. Example definitions
404 //              Column with title 'User name' and default text format:
405 //                              'User name'
406 //              Skipped field from sql query. Data for the field is not displayed:
407 //                              'dummy' => 'skip'
408 //              Column without title, data retrieved form row data with function func():
409 //                              array('fun'=>'func')
410 //              Inserted column with title 'Some', formated with function rowfun().
411 //      formated as date:
412 //                              'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
413 //              Column with name 'Another', formatted as date, 
414 // sortable with ascending start order (available orders: asc,desc, '').
415 //                              'Another' => array('type'=>'date', 'ord'=>'asc')
416 //
417 //      All available column format types you will find in db_pager_view.inc file.
418 //              If query result has more fields than count($coldef), rest of data is ignored
419 //  during display, but can be used in format handlers for 'spec' and 'insert' 
420 //      type columns.
421
422 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0)  {
423
424     if (isset($_SESSION[$name]) &&
425                  ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
426                 unset($_SESSION[$name]); // kill pager if sql has changed
427         }
428         if (!isset($_SESSION[$name])) {
429             $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
430                 $_SESSION[$name]->main_tbl = $table;
431                 $_SESSION[$name]->key = $key;
432                 $_SESSION[$name]->set_sql($sql);
433                 $_SESSION[$name]->set_columns($coldef);
434         }
435         
436         return  $_SESSION[$name];
437
438 }
439 //
440 //      Force pager initialization.
441 //
442 function refresh_pager($name)
443 {
444         if (isset($_SESSION[$name]))
445                 $_SESSION[$name]->ready = false;
446 }
447 ?>