Security update merged from 2.1.
[fa-stable.git] / gl / bank_account_reconcile.php
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU General Public License, GPL, 
5         as published by the Free Software Foundation, either version 3 
6         of the License, or (at your option) any later version.
7     This program is distributed in the hope that it will be useful,
8     but WITHOUT ANY WARRANTY; without even the implied warranty of
9     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
10     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 /* Author Rob Mallon */
13 $page_security = 'SA_RECONCILE';
14 $path_to_root = "..";
15 include($path_to_root . "/includes/db_pager.inc");
16 include_once($path_to_root . "/includes/session.inc");
17
18 include_once($path_to_root . "/includes/date_functions.inc");
19 include_once($path_to_root . "/includes/ui.inc");
20 include_once($path_to_root . "/includes/data_checks.inc");
21
22 include_once($path_to_root . "/gl/includes/gl_db.inc");
23 include_once($path_to_root . "/includes/banking.inc");
24
25 $js = "";
26 if ($use_popup_windows)
27         $js .= get_js_open_window(800, 500);
28 if ($use_date_picker)
29         $js .= get_js_date_picker();
30
31 add_js_file('reconcile.js');
32
33 page(_("Reconcile Bank Account"), false, false, "", $js);
34
35 check_db_has_bank_accounts(_("There are no bank accounts defined in the system."));
36
37 function check_date() {
38         if (!is_date(get_post('reconcile_date'))) {
39                 display_error(_("Invalid reconcile date format"));
40                 set_focus('reconcile_date');
41                 return false;
42         }
43         return true;
44 }
45 //
46 //      This function can be used directly in table pager 
47 //      if we would like to change page layout.
48 //
49 function rec_checkbox($row)
50 {
51         $name = "rec_" .$row['id'];
52         $hidden = 'last['.$row['id'].']';
53         $value = $row['reconciled'] != '';
54
55 // save also in hidden field for testing during 'Reconcile'
56         return checkbox(null, $name, $value, true, _('Reconcile this transaction'))
57                 . hidden($hidden, $value, false);
58 }
59
60 function systype_name($dummy, $type)
61 {
62         global $systypes_array;
63         
64         return $systypes_array[$type];
65 }
66
67 function trans_view($trans)
68 {
69         return get_trans_view_str($trans["type"], $trans["trans_no"]);
70 }
71
72 function gl_view($row)
73 {
74         return get_gl_view_str($row["type"], $row["trans_no"]);
75 }
76
77 function fmt_debit($row)
78 {
79         $value = $row["amount"];
80         return $value>=0 ? price_format($value) : '';
81 }
82
83 function fmt_credit($row)
84 {
85         $value = -$row["amount"];
86         return $value>0 ? price_format($value) : '';
87 }
88
89 function fmt_person($row)
90 {
91         return payment_person_name($row["person_type_id"],$row["person_id"]);
92 }
93
94 $update_pager = false;
95 function update_data()
96 {
97         global $Ajax, $update_pager;
98         
99         unset($_POST["beg_balance"]);
100         unset($_POST["end_balance"]);
101         $Ajax->activate('summary');
102         $update_pager = true;
103 }
104 //---------------------------------------------------------------------------------------------
105 // Update db record if respective checkbox value has changed.
106 //
107 function change_tpl_flag($reconcile_id)
108 {
109         global  $Ajax;
110
111         if (!check_date()) 
112                 return false;
113
114         if (get_post('bank_date')=='')  // new reconciliation
115                 $Ajax->activate('bank_date');
116
117         $_POST['bank_date'] = date2sql(get_post('reconcile_date'));
118         $reconcile_value = check_value("rec_".$reconcile_id) 
119                                                 ? ("'".$_POST['bank_date'] ."'") : 'NULL';
120         $sql = "UPDATE ".TB_PREF."bank_trans SET reconciled=".db_escape($reconcile_value)
121         ." WHERE id=".db_escape($reconcile_id);
122
123         db_query($sql, "Can't change reconciliation status");
124         // save last reconcilation status (date, end balance)
125     $sql2="UPDATE ".TB_PREF."bank_accounts SET last_reconciled_date='"
126                         .date2sql($_POST["reconcile_date"])."',
127             ending_reconcile_balance=".input_num("end_balance")
128                         ." WHERE id=".db_escape($_POST["bank_account"]);
129
130         $result = db_query($sql2,"Error updating reconciliation information");
131         $Ajax->activate('reconciled');
132         $Ajax->activate('difference');
133         return true;
134 }
135
136 if (!isset($_POST['reconcile_date'])) { // init page
137         $_POST['reconcile_date'] = new_doc_date();
138 //      $_POST['bank_date'] = date2sql(Today());
139 }
140
141 if (list_updated('bank_account')) {
142     $Ajax->activate('bank_date');
143         update_data();
144 }
145 if (list_updated('bank_date')) {
146         $_POST['reconcile_date'] = 
147                 get_post('bank_date')=='' ? Today() : sql2date($_POST['bank_date']);
148         update_data();
149 }
150 if (get_post('_reconcile_date_changed')) {
151         $_POST['bank_date'] = check_date() ? date2sql(get_post('reconcile_date')) : '';
152     $Ajax->activate('bank_date');
153         update_data();
154 }
155
156 $id = find_submit('_rec_');
157 if ($id != -1) 
158         change_tpl_flag($id);
159
160 if (isset($_POST['Reconcile'])) {
161         set_focus('bank_date');
162         foreach($_POST['last'] as $id => $value)
163                 if ($value != check_value('rec_'.$id))
164                         if(!change_tpl_flag($id)) break;
165     $Ajax->activate('_page_body');
166 }
167
168 //------------------------------------------------------------------------------------------------
169 start_form();
170 start_table("class='tablestyle_noborder'");
171 start_row();
172 bank_accounts_list_cells(_("Account:"), 'bank_account', null, true);
173
174 bank_reconciliation_list_cells(_("Bank Statement:"), get_post('bank_account'),
175         'bank_date', null, true, _("New"));
176 end_row();
177 end_table();
178
179 $date = date2sql(get_post('reconcile_date'));
180
181 $sql = "SELECT MAX(reconciled) as last_date,
182                  SUM(IF(reconciled<='$date', amount, 0)) as end_balance,
183                  SUM(IF(reconciled<'$date', amount, 0)) as beg_balance,
184                  SUM(amount) as total
185         FROM ".TB_PREF."bank_trans trans
186         WHERE bank_act=".db_escape($_POST['bank_account']);
187 //      ." AND trans.reconciled IS NOT NULL";
188
189 $result = db_query($sql,"Cannot retrieve reconciliation data");
190
191 if ($row = db_fetch($result)) {
192         $_POST["reconciled"] = price_format($row["end_balance"]-$row["beg_balance"]);
193         $total = $row["total"];
194         if (!isset($_POST["beg_balance"])) { // new selected account/statement
195                 $_POST["last_date"] = sql2date($row["last_date"]);
196                 $_POST["beg_balance"] = price_format($row["beg_balance"]);
197                 $_POST["end_balance"] = price_format($row["end_balance"]);
198                 if (get_post('bank_date')) {
199                         // if it is the last updated bank statement retrieve ending balance
200                         $sql = "SELECT ending_reconcile_balance
201                                 FROM ".TB_PREF."bank_accounts WHERE id=".db_escape($_POST['bank_account'])
202                                 . " AND last_reconciled_date=".db_escape($_POST['bank_date']);
203                         $result = db_query($sql,"Cannot retrieve last reconciliation");
204                         $row = db_fetch($result);
205                         if($row) {
206                                 $_POST["end_balance"] = price_format($row["ending_reconcile_balance"]);
207                         }
208                 }
209         } 
210 }
211
212 echo "<hr>";
213
214 div_start('summary');
215
216 start_table($table_style);
217 $th = array(_("Reconcile Date"), _("Beginning<br>Balance"), 
218         _("Ending<br>Balance"), _("Account<br>Total"),_("Reconciled<br>Amount"), _("Difference"));
219 table_header($th);
220 start_row();
221
222 date_cells("", "reconcile_date", _('Date of bank statement to reconcile'), 
223         get_post('bank_date')=='', 0, 0, 0, null, true);
224
225 amount_cells_ex("", "beg_balance", 15);
226
227 amount_cells_ex("", "end_balance", 15);
228
229 $reconciled = input_num('reconciled');
230 $difference = input_num("end_balance") - input_num("beg_balance") - $reconciled;
231
232 amount_cell($total);
233 amount_cell($reconciled, false, '', "reconciled");
234 amount_cell($difference, false, '', "difference");
235
236 end_row();
237 end_table();
238 div_end();
239 echo "<hr>";
240 //------------------------------------------------------------------------------------------------
241
242 if (!isset($_POST['bank_account']))
243     $_POST['bank_account'] = "";
244
245 $sql = "SELECT  type, trans_no, ref, trans_date, 
246                                 amount, person_id, person_type_id, reconciled, id
247                 FROM ".TB_PREF."bank_trans
248                 WHERE ".TB_PREF."bank_trans.bank_act = ".db_escape($_POST['bank_account']) . "
249                         AND (reconciled IS NULL OR reconciled='". $date ."')
250                 ORDER BY trans_date,".TB_PREF."bank_trans.id";
251 // or   ORDER BY reconciled desc, trans_date,".TB_PREF."bank_trans.id";
252
253 $act = get_bank_account($_POST["bank_account"]);
254 display_heading($act['bank_account_name']." - ".$act['bank_curr_code']);
255
256         $cols =
257         array(
258                 _("Type") => array('fun'=>'systype_name', 'ord'=>''),
259                 _("#") => array('fun'=>'trans_view', 'ord'=>''),
260                 _("Reference"), 
261                 _("Date") => 'date',
262                 _("Debit") => array('align'=>'right', 'fun'=>'fmt_debit'), 
263                 _("Credit") => array('align'=>'right','insert'=>true, 'fun'=>'fmt_credit'), 
264             _("Person/Item") => array('fun'=>'fmt_person'), 
265                 array('insert'=>true, 'fun'=>'gl_view'),
266                 "X"=>array('insert'=>true, 'fun'=>'rec_checkbox')
267            );
268         $table =& new_db_pager('trans_tbl', $sql, $cols);
269
270         $table->width = "60%";
271         display_db_pager($table);
272
273 br(1);
274 submit_center('Reconcile', _("Reconcile"), true, '', null);
275
276 end_form();
277
278 //------------------------------------------------------------------------------------------------
279
280 end_page();
281
282 ?>