2920af3a2c2d845d961cc3f9b19000387ad4a5e0
[fa-stable.git] / gl / bank_account_reconcile.php
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU Affero General Public License,
5         AGPL, as published by the Free Software Foundation, either version 
6         3 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/agpl-3.0.html>.
11 ***********************************************************************/
12 /* Author Rob Mallon */
13 $page_security = 8;
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         return systypes::name($type);
63 }
64
65 function trans_view($trans)
66 {
67         return get_trans_view_str($trans["type"], $trans["trans_no"]);
68 }
69
70 function gl_view($row)
71 {
72         return get_gl_view_str($row["type"], $row["trans_no"]);
73 }
74
75 function fmt_debit($row)
76 {
77         $value = $row["amount"];
78         return $value>=0 ? price_format($value) : '';
79 }
80
81 function fmt_credit($row)
82 {
83         $value = -$row["amount"];
84         return $value>0 ? price_format($value) : '';
85 }
86
87 function fmt_person($row)
88 {
89         return payment_person_types::person_name($row["person_type_id"],$row["person_id"]);
90 }
91
92 $update_pager = false;
93 function update_data()
94 {
95         global $Ajax, $update_pager;
96         
97         unset($_POST["beg_balance"]);
98         unset($_POST["end_balance"]);
99         $Ajax->activate('summary');
100         $update_pager = true;
101 }
102 //---------------------------------------------------------------------------------------------
103 // Update db record if respective checkbox value has changed.
104 //
105 function change_tpl_flag($reconcile_id)
106 {
107         global  $Ajax;
108
109         if (!check_date()) 
110                 return false;
111
112         if (get_post('bank_date')=='')  // new reconciliation
113                 $Ajax->activate('bank_date');
114
115         $_POST['bank_date'] = date2sql(get_post('reconcile_date'));
116         $reconcile_value = check_value("rec_".$reconcile_id) 
117                                                 ? ("'".$_POST['bank_date'] ."'") : 'NULL';
118         $sql = "UPDATE ".TB_PREF."bank_trans SET reconciled=$reconcile_value WHERE id=$reconcile_id";
119
120         db_query($sql, "Can't change reconciliation status");
121         // save last reconcilation status (date, end balance)
122     $sql2="UPDATE ".TB_PREF."bank_accounts SET last_reconciled_date='"
123                         .date2sql($_POST["reconcile_date"])."',
124             ending_reconcile_balance=".input_num("end_balance")
125                         ." WHERE id=".$_POST["bank_account"];
126
127         $result = db_query($sql2,"Error updating reconciliation information");
128         $Ajax->activate('reconciled');
129         $Ajax->activate('difference');
130         return true;
131 }
132
133 if (!isset($_POST['reconcile_date'])) { // init page
134         $_POST['reconcile_date'] = Today();
135 //      $_POST['bank_date'] = date2sql(Today());
136 }
137
138 if (list_updated('bank_account')) {
139     $Ajax->activate('bank_date');
140         update_data();
141 }
142 if (list_updated('bank_date')) {
143         $_POST['reconcile_date'] = 
144                 get_post('bank_date')=='' ? Today() : sql2date($_POST['bank_date']);
145         update_data();
146 }
147 if (get_post('_reconcile_date_changed')) {
148         $_POST['bank_date'] = check_date() ? date2sql(get_post('reconcile_date')) : '';
149     $Ajax->activate('bank_date');
150         update_data();
151 }
152
153 $id = find_submit('_rec_');
154 if ($id != -1) 
155         change_tpl_flag($id);
156
157 if (isset($_POST['Reconcile'])) {
158         set_focus('bank_date');
159         foreach($_POST['last'] as $id => $value)
160                 if ($value != check_value('rec_'.$id))
161                         if(!change_tpl_flag($id)) break;
162     $Ajax->activate('_page_body');
163 }
164
165 //------------------------------------------------------------------------------------------------
166 start_form();
167 start_table("class='tablestyle_noborder'");
168 start_row();
169 bank_accounts_list_cells(_("Account:"), 'bank_account', null, true);
170
171 bank_reconciliation_list_cells(_("Bank Statement:"), get_post('bank_account'),
172         'bank_date', null, true, _("New"));
173 end_row();
174 end_table();
175
176 $date = date2sql(get_post('reconcile_date'));
177
178 $sql = "SELECT MAX(reconciled) as last_date,
179                  SUM(IF(reconciled<='$date', amount, 0)) as end_balance,
180                  SUM(IF(reconciled<'$date', amount, 0)) as beg_balance,
181                  SUM(amount) as total
182         FROM ".TB_PREF."bank_trans trans
183         WHERE bank_act=".$_POST['bank_account'];
184 //      ." AND trans.reconciled IS NOT NULL";
185
186 $result = db_query($sql,"Cannot retrieve reconciliation data");
187
188 if ($row = db_fetch($result)) {
189         $_POST["reconciled"] = price_format($row["end_balance"]-$row["beg_balance"]);
190         $total = $row["total"];
191         if (!isset($_POST["beg_balance"])) { // new selected account/statement
192                 $_POST["last_date"] = sql2date($row["last_date"]);
193                 $_POST["beg_balance"] = price_format($row["beg_balance"]);
194                 $_POST["end_balance"] = price_format($row["end_balance"]);
195                 if (get_post('bank_date')) {
196                         // if it is the last updated bank statement retrieve ending balance
197                         $sql = "SELECT ending_reconcile_balance
198                                 FROM ".TB_PREF."bank_accounts WHERE id=".$_POST['bank_account']
199                                 . " AND last_reconciled_date='".$_POST['bank_date']."'";
200                         $result = db_query($sql,"Cannot retrieve last reconciliation");
201                         $row = db_fetch($result);
202                         if($row) {
203                                 $_POST["end_balance"] = price_format($row["ending_reconcile_balance"]);
204                         }
205                 }
206         } 
207 }
208
209 echo "<hr>";
210
211 div_start('summary');
212
213 start_table($table_style);
214 $th = array(_("Reconcile Date"), _("Beginning<br>Balance"), 
215         _("Ending<br>Balance"), _("Account<br>Total"),_("Reconciled<br>Amount"), _("Difference"));
216 table_header($th);
217 start_row();
218
219 date_cells("", "reconcile_date", _('Date of bank statement to reconcile'), 
220         null, 0, 0, 0, null, true);
221
222 amount_cells_ex("", "beg_balance", 15);
223
224 amount_cells_ex("", "end_balance", 15);
225
226 $reconciled = input_num('reconciled');
227 $difference = input_num("end_balance") - input_num("beg_balance") - $reconciled;
228
229 amount_cell($total);
230 amount_cell($reconciled, false, '', "reconciled");
231 amount_cell($difference, false, '', "difference");
232
233 end_row();
234 end_table();
235 div_end();
236 echo "<hr>";
237 //------------------------------------------------------------------------------------------------
238
239 if (!isset($_POST['bank_account']))
240     $_POST['bank_account'] = "";
241
242 $sql = "SELECT  type, trans_no, ref, trans_date, 
243                                 amount, person_id, person_type_id, reconciled, id
244                 FROM ".TB_PREF."bank_trans
245                 WHERE ".TB_PREF."bank_trans.bank_act = '" . $_POST['bank_account'] . "'
246                         AND (reconciled IS NULL OR reconciled='". $date ."')
247                 ORDER BY trans_date,".TB_PREF."bank_trans.id";
248 // or   ORDER BY reconciled desc, trans_date,".TB_PREF."bank_trans.id";
249
250 $act = get_bank_account($_POST["bank_account"]);
251 display_heading($act['bank_account_name']." - ".$act['bank_curr_code']);
252
253         $cols =
254         array(
255                 _("Type") => array('fun'=>'systype_name', 'ord'=>''),
256                 _("#") => array('fun'=>'trans_view', 'ord'=>''),
257                 _("Reference"), 
258                 _("Date") => 'date',
259                 _("Debit") => array('align'=>'right', 'fun'=>'fmt_debit'), 
260                 _("Credit") => array('align'=>'right','insert'=>true, 'fun'=>'fmt_credit'), 
261             _("Person/Item") => array('fun'=>'fmt_person'), 
262                 array('insert'=>true, 'fun'=>'gl_view'),
263                 "X"=>array('insert'=>true, 'fun'=>'rec_checkbox')
264            );
265         $table =& new_db_pager('trans_tbl', $sql, $cols);
266         if ($update_pager) {
267                 $table->set_sql($sql);
268                 $table->set_columns($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 ?>