Fiscal Year delete . now removes all transactions and convert into relevant open...
[fa-stable.git] / admin / fiscalyears.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 $page_security = 9;
13 $path_to_root="..";
14 include_once($path_to_root . "/includes/session.inc");
15
16 include_once($path_to_root . "/includes/date_functions.inc");
17 include_once($path_to_root . "/admin/db/company_db.inc");
18 include_once($path_to_root . "/includes/ui.inc");
19 include_once($path_to_root . "/admin/db/maintenance_db.inc");
20 $js = "";
21 if ($use_date_picker)
22         $js .= get_js_date_picker();
23 page(_("Fiscal Years"), false, false, "", $js);
24
25 simple_page_mode(true);
26 //---------------------------------------------------------------------------------------------
27
28 function is_date_in_fiscalyears($date)
29 {
30         $date = date2sql($date);
31         $sql = "SELECT * FROM ".TB_PREF."fiscal_year WHERE '$date' >= begin AND '$date' <= end";
32
33         $result = db_query($sql, "could not get all fiscal years");
34         return db_fetch($result) !== false;
35 }
36
37 function is_bad_begin_date($date)
38 {
39         $bdate = date2sql($date);
40         $sql = "SELECT MAX(end) FROM ".TB_PREF."fiscal_year WHERE begin < '$bdate'";
41
42         $result = db_query($sql, "could not retrieve last fiscal years");
43         $row = db_fetch_row($result);
44         if ($row[0] === null)
45                 return false;
46         $max = add_days(sql2date($row[0]), 1);
47         return ($max !== $date);
48 }
49
50 function check_years_before($date, $closed=false)
51 {
52         $date = date2sql($date);
53         $sql = "SELECT COUNT(*) FROM ".TB_PREF."fiscal_year WHERE begin < '$date'";
54         if (!$closed)
55                 $sql .= " AND closed=0";
56
57         $result = db_query($sql, "could not check fiscal years before");
58         $row = db_fetch_row($result);
59         return ($row[0] > 0);
60 }
61
62 function check_data()
63 {
64         if (!is_date($_POST['from_date']) || is_date_in_fiscalyears($_POST['from_date']) || is_bad_begin_date($_POST['from_date']))
65         {
66                 display_error( _("Invalid BEGIN date in fiscal year."));
67                 set_focus('from_date');
68                 return false;
69         }
70         if (!is_date($_POST['to_date']) || is_date_in_fiscalyears($_POST['to_date']))
71         {
72                 display_error( _("Invalid END date in fiscal year."));
73                 set_focus('to_date');
74                 return false;
75         }
76         if (date1_greater_date2($_POST['from_date'], $_POST['to_date']))
77         {
78                 display_error( _("BEGIN date bigger than END date."));
79                 set_focus('from_date');
80                 return false;
81         }
82         return true;
83 }
84 //---------------------------------------------------------------------------------------------
85 function close_year($year)
86 {
87         $myrow = get_fiscalyear($year);
88         $to = $myrow['end'];
89         // retrieve total balances from balance sheet accounts
90     $sql = "SELECT SUM(amount) FROM ".TB_PREF."gl_trans INNER JOIN ".TB_PREF."chart_master ON account=account_code
91         INNER JOIN ".TB_PREF."chart_types ON account_type=id INNER JOIN ".TB_PREF."chart_class ON class_id=cid 
92                 WHERE balance_sheet=1 AND tran_date <= '$to'";
93         $result = db_query($sql, "The total balance could not be calculated");
94
95         $row = db_fetch_row($result);
96         $balance = round2($row[0], user_price_dec());
97
98         begin_transaction();
99         $to = sql2date($to);
100
101         if ($balance != 0.0)
102         {
103                 $co = get_company_prefs();
104
105                 $trans_type = systypes::journal_entry();
106                 $trans_id = get_next_trans_no($trans_type);
107
108                 add_gl_trans($trans_type, $trans_id, $to, $co['retained_earnings_act'],
109                         0, 0, _("Closing Year"), -$balance);
110                 add_gl_trans($trans_type, $trans_id, $to, $co['profit_loss_year_act'],
111                         0, 0, _("Closing Year"), $balance);
112
113         }       
114                 close_transactions($to);
115                 commit_transaction();
116 }
117
118 function open_year($year)
119 {
120         $myrow = get_fiscalyear($year);
121         $from = sql2date($myrow['begin']);
122
123         begin_transaction();
124         open_transactions($from);
125         commit_transaction();
126 }
127
128 function handle_submit()
129 {
130         global $selected_id, $Mode;
131
132         if ($selected_id != -1)
133         {
134                 if ($_POST['closed'] == 1)
135                 {
136                         if (check_years_before($_POST['from_date'], false))
137                         {
138                                 display_error( _("Cannot CLOSE this year because there are open fiscal years before"));
139                                 set_focus('closed');
140                                 return false;
141                         }       
142                         close_year($selected_id);
143                 }       
144                 else
145                         open_year($selected_id);
146                 update_fiscalyear($selected_id, $_POST['closed']);
147                 display_notification(_('Selected fiscal year has been updated'));
148         }
149         else
150         {
151                 if (!check_data())
152                         return false;
153                 add_fiscalyear($_POST['from_date'], $_POST['to_date'], $_POST['closed']);
154                 display_notification(_('New fiscal year has been added'));
155         }
156         $Mode = 'RESET';
157 }
158
159 //---------------------------------------------------------------------------------------------
160
161 function check_can_delete($selected_id)
162 {
163         $myrow = get_fiscalyear($selected_id);
164         // PREVENT DELETES IF DEPENDENT RECORDS IN gl_trans
165         if (check_years_before(sql2date($myrow['begin']), true))
166         {
167                 display_error(_("Cannot delete this fiscal year because thera are fiscal years before."));
168                 return false;
169         }
170         if ($myrow['closed'] == 0)
171         {
172                 display_error(_("Cannot delete this fiscal year because the fiscal year is not closed."));
173                 return false;
174         }
175         return true;
176 }
177
178 //---------------------------------------------------------------------------------------------
179 function delete_attachments_and_comments($type_no, $trans_no)
180 {
181         global $comp_path;
182         
183         $sql = "SELECT * FROM ".TB_PREF."attachments WHERE type_no = $type_no AND trans_no = $trans_no";
184         $result = db_query($sql, "Could not retrieve attachments");
185         while ($row = db_fetch($result))
186         {
187                 $dir =  $comp_path."/".user_company(). "/attachments";
188                 if (file_exists($dir."/".$row['unique_name']))
189                         unlink($dir."/".$row['unique_name']);
190                 $sql = "DELETE FROM ".TB_PREF."attachments WHERE  type_no = $type_no AND trans_no = $trans_no";
191                 db_query($sql, "Could not delete attachment");
192         }       
193         $sql = "DELETE FROM ".TB_PREF."comments WHERE  type = $type_no AND id = $trans_no";
194         db_query($sql, "Could not delete comments");
195 }       
196
197 function delete_this_fiscalyear($selected_id)
198 {
199         global $db_connections;
200         
201         db_backup($db_connections[$_SESSION["wa_current_user"]->company], 'Security backup before Fiscal Year Removal');
202         begin_transaction();
203         $ref = _("Open Balance");
204         $myrow = get_fiscalyear($selected_id);
205         $to = $myrow['end'];
206         $sql = "SELECT order_no FROM ".TB_PREF."sales_orders WHERE ord_date <= '$to'";
207         $result = db_query($sql, "Could not retrieve sales orders");
208         while ($row = db_fetch($result))
209         {
210                 $sql = "SELECT SUM(qty_sent), SUM(quantity) FROM ".TB_PREF."sales_order_details WHERE order_no = {$row['order_no']}";
211                 $res = db_query($sql, "Could not retrieve sales order details");
212                 $row2 = db_fetch_row($res);
213                 if ($row2[0] == $row2[1])
214                 {
215                         $sql = "DELETE FROM ".TB_PREF."sales_order_details WHERE order_no = {$row['order_no']}";
216                         db_query($sql, "Could not delete sales order details");
217                         $sql = "DELETE FROM ".TB_PREF."sales_orders WHERE order_no = {$row['order_no']}";
218                         db_query($sql, "Could not delete sales order");
219                         delete_attachments_and_comments(systypes::sales_order(), $row['order_no']);
220                 }
221         }
222         $sql = "SELECT order_no FROM ".TB_PREF."purch_orders WHERE ord_date <= '$to'";
223         $result = db_query($sql, "Could not retrieve purchase orders");
224         while ($row = db_fetch($result))
225         {
226                 $sql = "SELECT SUM(quantity_ordered), SUM(quantity_received) FROM ".TB_PREF."purch_order_details WHERE order_no = {$row['order_no']}";
227                 $res = db_query($sql, "Could not retrieve purchase order details");
228                 $row2 = db_fetch_row($res);
229                 if ($row2[0] == $row2[1])
230                 {
231                         $sql = "DELETE FROM ".TB_PREF."purch_order_details WHERE order_no = {$row['order_no']}";
232                         db_query($sql, "Could not delete purchase order details");
233                         $sql = "DELETE FROM ".TB_PREF."purch_orders WHERE order_no = {$row['order_no']}";
234                         db_query($sql, "Could not delete purchase order");
235                         delete_attachments_and_comments(systypes::po(), $row['order_no']);
236                 }
237         }
238         $sql = "SELECT id FROM ".TB_PREF."grn_batch WHERE delivery_date <= '$to'";
239         $result = db_query($sql, "Could not retrieve grn batch");
240         while ($row = db_fetch($result))
241         {
242                 $sql = "DELETE FROM ".TB_PREF."grn_items WHERE grn_batch_id = {$row['id']}";
243                 db_query($sql, "Could not delete grn items");
244                 $sql = "DELETE FROM ".TB_PREF."grn_batch WHERE id = {$row['id']}";
245                 db_query($sql, "Could not delete grn batch");
246                 delete_attachments_and_comments(25, $row['id']);
247         }
248         $sql = "SELECT trans_no, type FROM ".TB_PREF."debtor_trans WHERE tran_date <= '$to' AND 
249                 (ov_amount + ov_gst + ov_freight + ov_freight_tax + ov_discount) = alloc";
250         $result = db_query($sql, "Could not retrieve debtor trans");
251         while ($row = db_fetch($result))
252         {
253                 $sql = "DELETE FROM ".TB_PREF."cust_allocations WHERE trans_no_from = {$row['trans_no']} AND type_no_from = {$row['type']}";
254                 db_query($sql, "Could not delete cust allocations");
255                 $sql = "DELETE FROM ".TB_PREF."debtor_trans_details WHERE debtor_trans_no = {$row['trans_no']} AND debtor_trans_type = {$row['type']}";
256                 db_query($sql, "Could not delete debtor trans details");
257                 $sql = "DELETE FROM ".TB_PREF."debtor_trans WHERE trans_no = {$row['trans_no']} AND type = {$row['type']}";
258                 db_query($sql, "Could not delete debtor trans");
259                 delete_attachments_and_comments($row['type'], $row['trans_no']);
260         }
261         $sql = "SELECT trans_no, type FROM ".TB_PREF."supp_trans WHERE tran_date <= '$to' AND 
262                 ABS(ov_amount + ov_gst + ov_discount) = alloc";
263         $result = db_query($sql, "Could not retrieve supp trans");
264         while ($row = db_fetch($result))
265         {
266                 $sql = "DELETE FROM ".TB_PREF."supp_allocations WHERE trans_no_from = {$row['trans_no']} AND type_no_from = {$row['type']}";
267                 db_query($sql, "Could not delete supp allocations");
268                 $sql = "DELETE FROM ".TB_PREF."supp_invoice_items WHERE supp_trans_no = {$row['trans_no']} AND supp_trans_type = {$row['type']}";
269                 db_query($sql, "Could not delete supp invoice items");
270                 $sql = "DELETE FROM ".TB_PREF."supp_trans WHERE trans_no = {$row['trans_no']} AND type = {$row['type']}";
271                 db_query($sql, "Could not delete supp trans");
272                 delete_attachments_and_comments($row['type'], $row['trans_no']);
273         }
274         $sql = "SELECT id FROM ".TB_PREF."workorders WHERE released_date <= '$to' AND closed=1";
275         $result = db_query($sql, "Could not retrieve supp trans");
276         while ($row = db_fetch($result))
277         {
278                 $sql = "SELECT issue_no FROM ".TB_PREF."wo_issues WHERE workorder_id = {$row['id']}"; 
279                 $res = db_query($sql, "Could not retrieve wo issues");
280                 while ($row2 = db_fetch_row($res))
281                 {
282                         $sql = "DELETE FROM ".TB_PREF."wo_issue_items WHERE issue_id = {$row2[0]}";
283                         db_query($sql, "Could not delete wo issue items");
284                 }       
285                 delete_attachments_and_comments(28, $row['id']);
286                 $sql = "DELETE FROM ".TB_PREF."wo_issues WHERE workorder_id = {$row['id']}";
287                 db_query($sql, "Could not delete wo issues");
288                 $sql = "DELETE FROM ".TB_PREF."wo_manufacture WHERE workorder_id = {$row['id']}";
289                 db_query($sql, "Could not delete wo manufacture");
290                 $sql = "DELETE FROM ".TB_PREF."wo_requirements WHERE workorder_id = {$row['id']}";
291                 db_query($sql, "Could not delete wo requirements");
292                 $sql = "DELETE FROM ".TB_PREF."workorders WHERE id = {$row['id']}";
293                 db_query($sql, "Could not delete workorders");
294                 delete_attachments_and_comments(26, $row['id']);
295         }
296         $sql = "SELECT loc_code, stock_id, SUM(qty) AS qty, SUM(qty*standard_cost) AS std_cost FROM ".TB_PREF."stock_moves WHERE tran_date <= '$to' GROUP by 
297                 loc_code, stock_id";
298         $result = db_query($sql, "Could not retrieve supp trans");
299         while ($row = db_fetch($result))
300         {
301                 $sql = "DELETE FROM ".TB_PREF."stock_moves WHERE tran_date <= '$to' AND loc_code = '{$row['loc_code']}' AND stock_id = '{$row['stock_id']}'";
302                 db_query($sql, "Could not delete stock moves");
303                 $qty = $row['qty'];
304                 $std_cost = ($qty == 0 ? 0 : round2($row['std_cost'] / $qty, user_price_dec()));
305                 $sql = "INSERT INTO ".TB_PREF."stock_moves (stock_id, loc_code, tran_date, reference, qty, standard_cost) VALUES
306                         ('{$row['stock_id']}', '{$row['loc_code']}', '$to', '$ref', $qty, $std_cost)";   
307                 db_query($sql, "Could not insert stock move");
308         }               
309         $sql = "DELETE FROM ".TB_PREF."voided WHERE date_ <= '$to'";
310         db_query($sql, "Could not delete voided items");
311         $sql = "DELETE FROM ".TB_PREF."trans_tax_details WHERE tran_date <= '$to'";
312         db_query($sql, "Could not delete trans tax details");
313         $sql = "DELETE FROM ".TB_PREF."exchange_rates WHERE date_ <= '$to'";
314         db_query($sql, "Could not delete exchange rates");
315         $sql = "DELETE FROM ".TB_PREF."budget_trans WHERE tran_date <= '$to'";
316         db_query($sql, "Could not delete exchange rates");
317         $sql = "SELECT account, SUM(amount) AS amount FROM ".TB_PREF."gl_trans WHERE tran_date <= '$to' GROUP by account";
318         $result = db_query($sql, "Could not retrieve gl trans");
319         while ($row = db_fetch($result))
320         {
321                 $sql = "DELETE FROM ".TB_PREF."gl_trans WHERE tran_date <= '$to' AND account = '{$row['account']}'";
322                 db_query($sql, "Could not delete gl trans");
323                 if (is_account_balancesheet($row['account']))
324                 {
325                         $trans_no = get_next_trans_no(0);
326                         if (is_bank_account($row['account']))
327                         {
328                                 $sql = "SELECT SUM(amount) FROM ".TB_PREF."bank_trans WHERE trans_date <= '$to' AND bank_act = '{$row['account']}'";
329                                 $res = db_query($sql, "Could not retrieve bank trans");
330                                 $row2 = db_fetch_row($res);
331                                 $sql = "DELETE FROM ".TB_PREF."bank_trans WHERE trans_date <= '$to' AND bank_act = '{$row['account']}'";
332                                 db_query($sql, "Could not delete bank trans");
333                                 $sql = "INSERT INTO ".TB_PREF."bank_trans (type, trans_no, trans_date, bank_act, ref, amount) VALUES
334                                         (0, $trans_no, '$to', '{$row['account']}', '$ref', {$row2[0]})";
335                                 db_query($sql, "Could not insert bank trans");
336                         }       
337                         $sql = "INSERT INTO ".TB_PREF."gl_trans (type, type_no, tran_date, account, memo_, amount) VALUES
338                                 (0, $trans_no, '$to', '{$row['account']}', '$ref', {$row['amount']})";
339                         db_query($sql, "Could not insert gl trans");
340                 }
341         }
342         delete_fiscalyear($selected_id);
343         commit_transaction();   
344 }
345
346 function handle_delete()
347 {
348         global $selected_id, $Mode;
349
350         if (check_can_delete($selected_id)) {
351         //only delete if used in neither customer or supplier, comp prefs, bank trans accounts
352                 delete_this_fiscalyear($selected_id);
353                 display_notification(_('Selected fiscal year has been deleted'));
354         }
355         $Mode = 'RESET';
356 }
357
358 //---------------------------------------------------------------------------------------------
359
360 function display_fiscalyears()
361 {
362         global $table_style;
363
364         $company_year = get_company_pref('f_year');
365
366         $result = get_all_fiscalyears();
367         start_form();
368         start_table($table_style);
369
370         $th = array(_("Fiscal Year Begin"), _("Fiscal Year End"), _("Closed"), "", "");
371         table_header($th);
372
373         $k=0;
374         while ($myrow=db_fetch($result))
375         {
376         if ($myrow['id'] == $company_year)
377         {
378                 start_row("class='stockmankobg'");
379         }
380         else
381                 alt_table_row_color($k);
382
383                 $from = sql2date($myrow["begin"]);
384                 $to = sql2date($myrow["end"]);
385                 if ($myrow["closed"] == 0)
386                 {
387                         $closed_text = _("No");
388                 }
389                 else
390                 {
391                         $closed_text = _("Yes");
392                 }
393                 label_cell($from);
394                 label_cell($to);
395                 label_cell($closed_text);
396                 edit_button_cell("Edit".$myrow['id'], _("Edit"));
397                 if ($myrow["id"] != $company_year)
398                         delete_button_cell("Delete".$myrow['id'], _("Delete"));
399                 else
400                         label_cell('');
401                 end_row();
402         }
403
404         end_table();
405         end_form();
406         display_note(_("The marked fiscal year is the current fiscal year which cannot be deleted."), 0, 0, "class='currentfg'");
407 }
408
409 //---------------------------------------------------------------------------------------------
410
411 function display_fiscalyear_edit($selected_id)
412 {
413         global $table_style2, $Mode;
414
415         start_form();
416         start_table($table_style2);
417
418         if ($selected_id != -1)
419         {
420                 if($Mode =='Edit')
421                 {
422                         $myrow = get_fiscalyear($selected_id);
423
424                         $_POST['from_date'] = sql2date($myrow["begin"]);
425                         $_POST['to_date']  = sql2date($myrow["end"]);
426                         $_POST['closed']  = $myrow["closed"];
427                 }
428                 hidden('from_date');
429                 hidden('to_date');
430                 label_row(_("Fiscal Year Begin:"), $_POST['from_date']);
431                 label_row(_("Fiscal Year End:"), $_POST['to_date']);
432         }
433         else
434         {
435                 date_row(_("Fiscal Year Begin:"), 'from_date', '', null, 0, 0, 1001);
436                 date_row(_("Fiscal Year End:"), 'to_date', '', null, 0, 0, 1001);
437         }
438         hidden('selected_id', $selected_id);
439
440         yesno_list_row(_("Is Closed:"), 'closed', null, "", "", false);
441
442         end_table(1);
443
444         submit_add_or_update_center($selected_id == -1, '', 'both');
445
446         end_form();
447 }
448
449 //---------------------------------------------------------------------------------------------
450
451 if ($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM')
452 {
453         handle_submit();
454 }
455
456 //---------------------------------------------------------------------------------------------
457
458 if ($Mode == 'Delete')
459 {
460         global $selected_id;
461         handle_delete($selected_id);
462 }
463
464 if ($Mode == 'RESET')
465 {
466         $selected_id = -1;
467 }
468 //---------------------------------------------------------------------------------------------
469
470 display_fiscalyears();
471
472 echo '<br>';
473
474 display_fiscalyear_edit($selected_id);
475
476 //---------------------------------------------------------------------------------------------
477
478 end_page();
479
480 ?>