Deleting a fiscal year problem. Fixed.
[fa-stable.git] / admin / db / fiscalyears_db.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 require_once($path_to_root. "/includes/ui/items_cart.inc");
13
14 // fiscal year routines
15 function add_fiscalyear($from_date, $to_date, $closed)
16 {
17         $from = date2sql($from_date);
18         $to = date2sql($to_date);
19
20         $sql = "INSERT INTO ".TB_PREF."fiscal_year (begin, end, closed)
21                 VALUES (".db_escape($from).",".db_escape($to).", ".db_escape($closed).")";
22
23         db_query($sql, "could not add fiscal year");
24 }
25
26 function update_fiscalyear($id, $closed)
27 {
28         $sql = "UPDATE ".TB_PREF."fiscal_year SET closed=".db_escape($closed)."
29                 WHERE id=".db_escape($id);
30
31         db_query($sql, "could not update fiscal year");
32 }
33
34 function get_all_fiscalyears()
35 {
36         $sql = "SELECT * FROM ".TB_PREF."fiscal_year ORDER BY begin";
37
38         return db_query($sql, "could not get all fiscal years");
39 }
40
41 function get_fiscalyear($id)
42 {
43         $sql = "SELECT * FROM ".TB_PREF."fiscal_year WHERE id=".db_escape($id);
44
45         $result = db_query($sql, "could not get fiscal year");
46
47         return db_fetch($result);
48 }
49
50 function get_current_fiscalyear()
51 {
52         $year = get_company_pref('f_year');
53
54         $sql = "SELECT * FROM ".TB_PREF."fiscal_year WHERE id=".db_escape($year);
55
56         $result = db_query($sql, "could not get current fiscal year");
57
58         return db_fetch($result);
59 }
60
61
62 function delete_fiscalyear($id)
63 {
64         begin_transaction();
65
66         $sql="DELETE FROM ".TB_PREF."fiscal_year WHERE id=".db_escape($id);
67
68         db_query($sql, "could not delete fiscal year");
69
70         commit_transaction();
71 }
72
73 function is_date_in_fiscalyears($date, $closed=true)
74 {
75         $date = date2sql($date);
76         $sql = "SELECT * FROM ".TB_PREF."fiscal_year WHERE '$date' >= begin AND '$date' <= end";
77         if (!$closed)
78                 $sql .= " AND closed=0";
79         $result = db_query($sql, "could not get all fiscal years");
80         return db_fetch($result) !== false;
81 }
82
83 function get_fiscalyear_begin_for_date($date)
84 {
85         $date = date2sql($date);
86         $sql = "SELECT begin FROM ".TB_PREF."fiscal_year WHERE '$date' >= begin AND '$date' <= end";
87         $result = db_query($sql, "could not get begin date of the fiscal year");
88         $row = db_fetch_row($result);
89         if ($row != false)
90                 return sql2date($row[0]);
91         else
92                 return begin_fiscalyear();
93 }
94
95 function check_begin_end_date($date1, $date2)
96 {
97         $sql = "SELECT MAX(end), MIN(begin) FROM ".TB_PREF."fiscal_year";
98         $result = db_query($sql, "could not retrieve last fiscal years");
99         $row = db_fetch_row($result);
100         if ($row[0] === null)
101                 return true;
102         $max = add_days(sql2date($row[0]), 1);
103         $min = add_days(sql2date($row[1]), -1);
104         return ($max === $date1 || $min === $date2);
105 }
106
107 function next_begin_date()
108 {
109         $sql = "SELECT MAX(end) FROM ".TB_PREF."fiscal_year";
110         $result = db_query($sql, "could not retrieve last fiscal years");
111         $row = db_fetch_row($result);
112         if ($row[0] === null)
113                 return false;
114         return add_days(sql2date($row[0]), 1);
115 }
116
117 function check_years_before($date, $closed=false)
118 {
119         $date = date2sql($date);
120         $sql = "SELECT COUNT(*) FROM ".TB_PREF."fiscal_year WHERE begin < '$date'";
121         if (!$closed)
122                 $sql .= " AND closed=0";
123
124         $result = db_query($sql, "could not check fiscal years before");
125         $row = db_fetch_row($result);
126         return ($row[0] > 0);
127 }
128
129 //---------------------------------------------------------------------------------------------
130 function close_year($year)
131 {
132         global $Refs;
133
134         $co = get_company_prefs();
135         if (get_gl_account($co['retained_earnings_act']) == false || get_gl_account($co['profit_loss_year_act']) == false)
136         {
137                 display_error(_("The Retained Earnings Account or the Profit and Loss Year Account has not been set in System and General GL Setup"));
138                 return false;
139         }
140         if (!is_account_balancesheet($co['retained_earnings_act']) || is_account_balancesheet($co['profit_loss_year_act']))
141         {
142                 display_error(_("The Retained Earnings Account should be a Balance Account or the Profit and Loss Year Account should be an Expense Account (preferred the last one in the Expense Class)"));
143                 return false;
144         }
145
146         begin_transaction();
147
148         $myrow = get_fiscalyear($year);
149         $to = $myrow['end'];
150         // retrieve total balances from balance sheet accounts
151     $sql = "SELECT SUM(amount) FROM ".TB_PREF."gl_trans INNER JOIN ".TB_PREF."chart_master ON account=account_code
152         INNER JOIN ".TB_PREF."chart_types ON account_type=id INNER JOIN ".TB_PREF."chart_class ON class_id=cid 
153                 WHERE ctype>=".CL_ASSETS." AND ctype <=".CL_EQUITY." AND tran_date <= '$to'";
154         $result = db_query($sql, "The total balance could not be calculated");
155
156         $row = db_fetch_row($result);
157         $balance = round2($row[0], user_price_dec());
158
159         $to = sql2date($to);
160
161         if ($balance != 0.0)
162         {
163                 $cart = new items_cart(ST_JOURNAL);
164                 $cart->reference = $Refs->get_next(ST_JOURNAL, null, $to);
165                 $cart->tran_date = $cart->doc_date = $cart->event_date = $to;
166
167                 $cart->add_gl_item($co['retained_earnings_act'], 0, 0, -$balance, _("Closing Year"), '', 0);
168                 $cart->add_gl_item($co['profit_loss_year_act'], 0, 0, $balance, _("Closing Year"), '', 0);
169                 $cart->memo_ = _("Closing Year");
170                 write_journal_entries($cart);
171         }
172         close_transactions($to);
173
174         commit_transaction();
175         return true;
176 }
177
178 function open_year($year)
179 {
180         $myrow = get_fiscalyear($year);
181         $from = sql2date($myrow['begin']);
182
183         begin_transaction();
184         close_transactions(add_days($from, -1));
185         commit_transaction();
186 }
187
188 //---------------------------------------------------------------------------------------------
189 function delete_attachments_and_comments($type_no, $trans_no)
190 {
191         
192         $sql = "SELECT * FROM ".TB_PREF."attachments WHERE type_no = $type_no AND trans_no = $trans_no";
193         $result = db_query($sql, "Could not retrieve attachments");
194         $delflag = false;
195         while ($row = db_fetch($result))
196         {
197                 $delflag = true;
198                 $dir =  company_path(). "/attachments";
199                 if (file_exists($dir."/".$row['unique_name']))
200                         unlink($dir."/".$row['unique_name']);
201         }
202         if ($delflag)
203         {
204                 $sql = "DELETE FROM ".TB_PREF."attachments WHERE  type_no = $type_no AND trans_no = $trans_no";
205                 db_query($sql, "Could not delete attachment");
206         }       
207         $sql = "DELETE FROM ".TB_PREF."comments WHERE  type = $type_no AND id = $trans_no";
208         db_query($sql, "Could not delete comments");
209         $sql = "DELETE FROM ".TB_PREF."refs WHERE  type = $type_no AND id = $trans_no";
210         db_query($sql, "Could not delete refs");
211 }       
212
213 //---------------------------------------------------------------------------------------------
214 function delete_this_fiscalyear($selected_id)
215 {
216         global $db_connections;
217         
218         db_backup($db_connections[user_company()], 'Security backup before Fiscal Year Removal');
219         begin_transaction();
220         $ref = _("Open Balance");
221         $myrow = get_fiscalyear($selected_id);
222         $to = $myrow['end'];
223         $sql = "SELECT order_no, trans_type FROM ".TB_PREF."sales_orders WHERE ord_date <= '$to' AND type <> 1"; // don't take the templates
224         $result = db_query($sql, "Could not retrieve sales orders");
225         while ($row = db_fetch($result))
226         {
227                 $sql = "SELECT SUM(qty_sent), SUM(quantity) FROM ".TB_PREF."sales_order_details WHERE order_no = {$row['order_no']} AND trans_type = {$row['trans_type']}";
228                 $res = db_query($sql, "Could not retrieve sales order details");
229                 $row2 = db_fetch_row($res);
230                 if ($row2[0] == $row2[1])
231                 {
232                         $sql = "DELETE FROM ".TB_PREF."sales_order_details WHERE order_no = {$row['order_no']} AND trans_type = {$row['trans_type']}";
233                         db_query($sql, "Could not delete sales order details");
234                         $sql = "DELETE FROM ".TB_PREF."sales_orders WHERE order_no = {$row['order_no']} AND trans_type = {$row['trans_type']}";
235                         db_query($sql, "Could not delete sales order");
236                         delete_attachments_and_comments($row['trans_type'], $row['order_no']);
237                 }
238         }
239         $sql = "SELECT order_no FROM ".TB_PREF."purch_orders WHERE ord_date <= '$to'";
240         $result = db_query($sql, "Could not retrieve purchase orders");
241         while ($row = db_fetch($result))
242         {
243                 $sql = "SELECT SUM(quantity_ordered), SUM(quantity_received) FROM ".TB_PREF."purch_order_details WHERE order_no = {$row['order_no']}";
244                 $res = db_query($sql, "Could not retrieve purchase order details");
245                 $row2 = db_fetch_row($res);
246                 if ($row2[0] == $row2[1])
247                 {
248                         $sql = "DELETE FROM ".TB_PREF."purch_order_details WHERE order_no = {$row['order_no']}";
249                         db_query($sql, "Could not delete purchase order details");
250                         $sql = "DELETE FROM ".TB_PREF."purch_orders WHERE order_no = {$row['order_no']}";
251                         db_query($sql, "Could not delete purchase order");
252                         delete_attachments_and_comments(ST_PURCHORDER, $row['order_no']);
253                 }
254         }
255         $sql = "SELECT id FROM ".TB_PREF."grn_batch WHERE delivery_date <= '$to'";
256         $result = db_query($sql, "Could not retrieve grn batch");
257         while ($row = db_fetch($result))
258         {
259                 $sql = "DELETE FROM ".TB_PREF."grn_items WHERE grn_batch_id = {$row['id']}";
260                 db_query($sql, "Could not delete grn items");
261                 $sql = "DELETE FROM ".TB_PREF."grn_batch WHERE id = {$row['id']}";
262                 db_query($sql, "Could not delete grn batch");
263                 delete_attachments_and_comments(25, $row['id']);
264         }
265         $sql = "SELECT trans_no, type FROM ".TB_PREF."debtor_trans WHERE tran_date <= '$to' AND 
266                 (ov_amount + ov_gst + ov_freight + ov_freight_tax + ov_discount) = 
267                 (SELECT SUM(amt) FROM ".TB_PREF."cust_allocations WHERE date_alloc <= '$to' AND trans_no = trans_no_to AND
268                 type = trans_type_to)";
269         $result = db_query($sql, "Could not retrieve debtor trans");
270         while ($row = db_fetch($result))
271         {
272                 if ($row['type'] == ST_SALESINVOICE)
273                 {
274                         $deliveries = get_sales_parent_numbers($row['type'], $row['trans_no']);
275                         foreach ($deliveries as $delivery)
276                         {
277                                 $sql = "DELETE FROM ".TB_PREF."debtor_trans_details WHERE debtor_trans_no = $delivery AND debtor_trans_type = ".ST_CUSTDELIVERY;
278                                 db_query($sql, "Could not delete debtor trans details");
279                                 $sql = "DELETE FROM ".TB_PREF."debtor_trans WHERE trans_no = $delivery AND type = ".ST_CUSTDELIVERY;
280                                 db_query($sql, "Could not delete debtor trans");
281                                 delete_attachments_and_comments(ST_CUSTDELIVERY, $delivery);
282                         }               
283                 }       
284                 $sql = "DELETE FROM ".TB_PREF."cust_allocations WHERE trans_no_from = {$row['trans_no']} AND trans_type_from = {$row['type']}";
285                 db_query($sql, "Could not delete cust allocations");
286                 $sql = "DELETE FROM ".TB_PREF."debtor_trans_details WHERE debtor_trans_no = {$row['trans_no']} AND debtor_trans_type = {$row['type']}";
287                 db_query($sql, "Could not delete debtor trans details");
288                 $sql = "DELETE FROM ".TB_PREF."debtor_trans WHERE trans_no = {$row['trans_no']} AND type = {$row['type']}";
289                 db_query($sql, "Could not delete debtor trans");
290                 delete_attachments_and_comments($row['type'], $row['trans_no']);
291         }
292         $sql = "SELECT trans_no, type FROM ".TB_PREF."supp_trans WHERE tran_date <= '$to' AND 
293                 ABS(ov_amount + ov_gst + ov_discount) = (SELECT ABS(SUM(amt)) FROM ".TB_PREF."supp_allocations WHERE date_alloc <= '$to' AND trans_no = trans_no_to AND type = trans_type_to)";
294         $result = db_query($sql, "Could not retrieve supp trans");
295         while ($row = db_fetch($result))
296         {
297                 $sql = "DELETE FROM ".TB_PREF."supp_allocations WHERE trans_no_from = {$row['trans_no']} AND trans_type_from = {$row['type']}";
298                 db_query($sql, "Could not delete supp allocations");
299                 $sql = "DELETE FROM ".TB_PREF."supp_invoice_items WHERE supp_trans_no = {$row['trans_no']} AND supp_trans_type = {$row['type']}";
300                 db_query($sql, "Could not delete supp invoice items");
301                 $sql = "DELETE FROM ".TB_PREF."supp_trans WHERE trans_no = {$row['trans_no']} AND type = {$row['type']}";
302                 db_query($sql, "Could not delete supp trans");
303                 delete_attachments_and_comments($row['type'], $row['trans_no']);
304         }
305         $sql = "SELECT id FROM ".TB_PREF."workorders WHERE released_date <= '$to' AND closed=1";
306         $result = db_query($sql, "Could not retrieve workorders");
307         while ($row = db_fetch($result))
308         {
309                 $sql = "SELECT issue_no FROM ".TB_PREF."wo_issues WHERE workorder_id = {$row['id']}"; 
310                 $res = db_query($sql, "Could not retrieve wo issues");
311         while ($row2 = db_fetch_row($res))
312         {
313             $sql = "DELETE FROM ".TB_PREF."wo_issue_items WHERE issue_id = {$row2[0]}";
314             db_query($sql, "Could not delete wo issue items");
315             $sql = "DELETE FROM ".TB_PREF."wo_issues WHERE workorder_id = {$row2[0]}";
316             db_query($sql, "Could not delete wo issues");
317             delete_attachments_and_comments(ST_MANUISSUE, $row2[0]);
318         }               
319                 $sql = "DELETE FROM ".TB_PREF."wo_manufacture WHERE workorder_id = {$row['id']}";
320                 db_query($sql, "Could not delete wo manufacture");
321                 $sql = "DELETE FROM ".TB_PREF."wo_requirements WHERE workorder_id = {$row['id']}";
322                 db_query($sql, "Could not delete wo requirements");
323                 $sql = "DELETE FROM ".TB_PREF."workorders WHERE id = {$row['id']}";
324                 db_query($sql, "Could not delete workorders");
325                 delete_attachments_and_comments(ST_WORKORDER, $row['id']);
326         }
327         $sql = "SELECT loc_code, stock_id, SUM(qty) AS qty,"
328             ." SUM(-qty*IF(type=".ST_SUPPRECEIVE." OR type=".ST_SUPPCREDIT.", price, standard_cost)) AS std_cost"
329             ." FROM ".TB_PREF."stock_moves WHERE tran_date <= '$to' GROUP by loc_code, stock_id";
330         $result = db_query($sql, "Could not retrieve stock moves");
331         while ($row = db_fetch($result))
332         {
333                 $sql = "DELETE FROM ".TB_PREF."stock_moves WHERE tran_date <= '$to' AND loc_code = '{$row['loc_code']}' AND stock_id = '{$row['stock_id']}'";
334                 db_query($sql, "Could not delete stock moves");
335                 $qty = $row['qty'];
336                 $std_cost = ($qty == 0 ? 0 : round2($row['std_cost'] / $qty, user_price_dec()));
337                 $sql = "INSERT INTO ".TB_PREF."stock_moves (stock_id, loc_code, tran_date, reference, qty, standard_cost) VALUES
338                         ('{$row['stock_id']}', '{$row['loc_code']}', '$to', '$ref', $qty, $std_cost)";   
339                 db_query($sql, "Could not insert stock move");
340         }               
341         $sql = "DELETE FROM ".TB_PREF."voided WHERE date_ <= '$to'";
342         db_query($sql, "Could not delete voided items");
343         $sql = "DELETE FROM ".TB_PREF."trans_tax_details WHERE tran_date <= '$to'";
344         db_query($sql, "Could not delete trans tax details");
345         $sql = "DELETE FROM ".TB_PREF."exchange_rates WHERE date_ <= '$to'";
346         db_query($sql, "Could not delete exchange rates");
347         $sql = "DELETE FROM ".TB_PREF."budget_trans WHERE tran_date <= '$to'";
348         db_query($sql, "Could not delete budget trans");
349         $sql = "SELECT account, SUM(amount) AS amount, person_type_id, person_id FROM "
350                 .TB_PREF."gl_trans WHERE tran_date <= '$to' GROUP by account, person_type_id, person_id";
351         $result = db_query($sql, "Could not retrieve gl trans");
352         $trans_no = get_next_trans_no(ST_JOURNAL);
353
354         $last_account='';
355         $new = false;
356         $total = 0.0;
357         while ($row = db_fetch($result))
358         {
359                 if ($last_account != $row['account']) // deletes all subledgers postings, so do it once for account
360                 {
361                         $sql = "DELETE FROM ".TB_PREF."gl_trans WHERE tran_date <= '$to' AND account = '{$row['account']}'";
362                         db_query($sql, "Could not delete gl trans");
363                         $last_account = $row['account'];
364                 }
365                 if (is_account_balancesheet($row['account']) && $row['amount'])
366                 {
367                         $sql = "INSERT INTO ".TB_PREF."gl_trans (type, type_no, tran_date, account, memo_, amount, person_type_id, person_id) VALUES
368                                 (".ST_JOURNAL.", $trans_no, '$to', '{$row['account']}', '$ref', {$row['amount']}, "
369                                 .db_escape($row['person_type_id'], true).", ".db_escape($row['person_id'], true).")";
370                         db_query($sql, "Could not insert gl trans");
371                         if ($row['amount'] > 0.0)
372                                 $total += $row['amount'];
373                         $new = true;
374                 }
375         }
376         if ($new)
377         {
378                 global $Refs;
379                 $trans_type = ST_JOURNAL;
380                 $date_ = sql2date($to);
381                 $reference = $Refs->get_next($trans_type, null, $date_);
382                 $Refs->save($trans_type, $trans_no, $reference);
383                 add_journal($trans_type, $trans_no, $total, $date_, get_company_currency(), $reference);
384                 $Refs->save($trans_type, $trans_no, $reference);
385                 add_audit_trail($trans_type, $trans_no, $date_);
386         }
387         $sql = "SELECT bank_act, SUM(amount) AS amount FROM ".TB_PREF."bank_trans WHERE trans_date <= '$to' GROUP BY bank_act";
388         $result = db_query($sql, "Could not retrieve bank trans");
389         while ($row = db_fetch($result))
390         {
391                 $sql = "DELETE FROM ".TB_PREF."bank_trans WHERE trans_date <= '$to' AND bank_act = '{$row['bank_act']}'";
392                 db_query($sql, "Could not delete bank trans");
393                 $sql = "INSERT INTO ".TB_PREF."bank_trans (type, trans_no, trans_date, bank_act, ref, amount) VALUES
394                         (0, 0, '$to', '{$row['bank_act']}', '$ref', {$row['amount']})";
395                 db_query($sql, "Could not insert bank trans");
396         }       
397         
398         $sql = "DELETE FROM ".TB_PREF."audit_trail WHERE gl_date <= '$to'";
399         db_query($sql, "Could not delete audit trail");
400         
401         $sql = "SELECT type, id FROM ".TB_PREF."comments WHERE type != ".ST_SALESQUOTE." AND type != ".ST_SALESORDER." AND type != ".ST_PURCHORDER;
402         $result = db_query($sql, "Could not retrieve comments");
403         while ($row = db_fetch($result))
404         {
405                 $sql = "SELECT count(*) FROM ".TB_PREF."gl_trans WHERE type = {$row['type']} AND type_no = {$row['id']}";
406                 $res = db_query($sql, "Could not retrieve gl_trans");
407                 $row2 = db_fetch_row($res);
408                 if ($row2[0] == 0) // if no link, then delete comments
409                 {
410                         $sql = "DELETE FROM ".TB_PREF."comments WHERE type = {$row['type']} AND id = {$row['id']}";
411                         db_query($sql, "Could not delete comments");
412                 }
413         }       
414         $sql = "SELECT type, id FROM ".TB_PREF."refs WHERE type != ".ST_SALESQUOTE." AND type != ".ST_SALESORDER." AND type != ".ST_PURCHORDER;
415         $result = db_query($sql, "Could not retrieve refs");
416         while ($row = db_fetch($result))
417         {
418                 $sql = "SELECT count(*) FROM ".TB_PREF."gl_trans WHERE type = {$row['type']} AND type_no = {$row['id']}";
419                 $res = db_query($sql, "Could not retrieve gl_trans");
420                 $row2 = db_fetch_row($res);
421                 if ($row2[0] == 0) // if no link, then delete refs
422                 {
423                         $sql = "DELETE FROM ".TB_PREF."refs WHERE type = {$row['type']} AND id = {$row['id']}";
424                         db_query($sql, "Could not delete refs");
425                 }
426         }       
427                 
428         delete_fiscalyear($selected_id);
429         commit_transaction();   
430 }
431
432