Moved all SQL statements from PHP files into relevant *_db.inc files.
[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
13 // fiscal year routines
14 function add_fiscalyear($from_date, $to_date, $closed)
15 {
16         $from = date2sql($from_date);
17         $to = date2sql($to_date);
18
19         $sql = "INSERT INTO ".TB_PREF."fiscal_year (begin, end, closed)
20                 VALUES (".db_escape($from).",".db_escape($to).", ".db_escape($closed).")";
21
22         db_query($sql, "could not add fiscal year");
23 }
24
25 function update_fiscalyear($id, $closed)
26 {
27         $sql = "UPDATE ".TB_PREF."fiscal_year SET closed=".db_escape($closed)."
28                 WHERE id=".db_escape($id);
29
30         db_query($sql, "could not update fiscal year");
31 }
32
33 function get_all_fiscalyears()
34 {
35         $sql = "SELECT * FROM ".TB_PREF."fiscal_year ORDER BY begin";
36
37         return db_query($sql, "could not get all fiscal years");
38 }
39
40 function get_fiscalyear($id)
41 {
42         $sql = "SELECT * FROM ".TB_PREF."fiscal_year WHERE id=".db_escape($id);
43
44         $result = db_query($sql, "could not get fiscal year");
45
46         return db_fetch($result);
47 }
48
49 function get_current_fiscalyear()
50 {
51         global $path_to_root;
52         include_once($path_to_root . "/admin/db/company_db.inc");
53         $year = get_company_pref('f_year');
54
55         $sql = "SELECT * FROM ".TB_PREF."fiscal_year WHERE id=".db_escape($year);
56
57         $result = db_query($sql, "could not get current fiscal year");
58
59         return db_fetch($result);
60 }
61
62
63 function delete_fiscalyear($id)
64 {
65         begin_transaction();
66
67         $sql="DELETE FROM ".TB_PREF."fiscal_year WHERE id=".db_escape($id);
68
69         db_query($sql, "could not delete fiscal year");
70
71         commit_transaction();
72 }
73
74 function is_date_in_fiscalyears($date)
75 {
76         $date = date2sql($date);
77         $sql = "SELECT * FROM ".TB_PREF."fiscal_year WHERE '$date' >= begin AND '$date' <= end";
78
79         $result = db_query($sql, "could not get all fiscal years");
80         return db_fetch($result) !== false;
81 }
82
83 function is_bad_begin_date($date)
84 {
85         $bdate = date2sql($date);
86         $sql = "SELECT MAX(end) FROM ".TB_PREF."fiscal_year WHERE begin < '$bdate'";
87
88         $result = db_query($sql, "could not retrieve last fiscal years");
89         $row = db_fetch_row($result);
90         if ($row[0] === null)
91                 return false;
92         $max = add_days(sql2date($row[0]), 1);
93         return ($max !== $date);
94 }
95
96 function check_years_before($date, $closed=false)
97 {
98         $date = date2sql($date);
99         $sql = "SELECT COUNT(*) FROM ".TB_PREF."fiscal_year WHERE begin < '$date'";
100         if (!$closed)
101                 $sql .= " AND closed=0";
102
103         $result = db_query($sql, "could not check fiscal years before");
104         $row = db_fetch_row($result);
105         return ($row[0] > 0);
106 }
107
108 //---------------------------------------------------------------------------------------------
109 function close_year($year)
110 {
111         $co = get_company_prefs();
112         if (get_gl_account($co['retained_earnings_act']) == false || get_gl_account($co['profit_loss_year_act']) == false)
113         {
114                 display_error(_("The Retained Earnings Account or the Profit and Loss Year Account has not been set in System and General GL Setup"));
115                 return false;
116         }
117         begin_transaction();
118
119         $myrow = get_fiscalyear($year);
120         $to = $myrow['end'];
121         // retrieve total balances from balance sheet accounts
122     $sql = "SELECT SUM(amount) FROM ".TB_PREF."gl_trans INNER JOIN ".TB_PREF."chart_master ON account=account_code
123         INNER JOIN ".TB_PREF."chart_types ON account_type=id INNER JOIN ".TB_PREF."chart_class ON class_id=cid 
124                 WHERE ctype>=".CL_ASSETS." AND ctype <=".CL_EQUITY." AND tran_date <= '$to'";
125         $result = db_query($sql, "The total balance could not be calculated");
126
127         $row = db_fetch_row($result);
128         $balance = round2($row[0], user_price_dec());
129
130         $to = sql2date($to);
131
132         if ($balance != 0.0)
133         {
134                 $trans_type = ST_JOURNAL;
135                 $trans_id = get_next_trans_no($trans_type);
136
137                 add_gl_trans($trans_type, $trans_id, $to, $co['retained_earnings_act'],
138                         0, 0, _("Closing Year"), -$balance);
139                 add_gl_trans($trans_type, $trans_id, $to, $co['profit_loss_year_act'],
140                         0, 0, _("Closing Year"), $balance);
141
142         }       
143         close_transactions($to);
144
145         commit_transaction();
146         return true;
147 }
148
149 function open_year($year)
150 {
151         $myrow = get_fiscalyear($year);
152         $from = sql2date($myrow['begin']);
153
154         begin_transaction();
155         open_transactions($from);
156         commit_transaction();
157 }
158
159 //---------------------------------------------------------------------------------------------
160 function delete_attachments_and_comments($type_no, $trans_no)
161 {
162         global $comp_path;
163         
164         $sql = "SELECT * FROM ".TB_PREF."attachments WHERE type_no = $type_no AND trans_no = $trans_no";
165         $result = db_query($sql, "Could not retrieve attachments");
166         while ($row = db_fetch($result))
167         {
168                 $dir =  $comp_path."/".user_company(). "/attachments";
169                 if (file_exists($dir."/".$row['unique_name']))
170                         unlink($dir."/".$row['unique_name']);
171                 $sql = "DELETE FROM ".TB_PREF."attachments WHERE  type_no = $type_no AND trans_no = $trans_no";
172                 db_query($sql, "Could not delete attachment");
173         }       
174         $sql = "DELETE FROM ".TB_PREF."comments WHERE  type = $type_no AND id = $trans_no";
175         db_query($sql, "Could not delete comments");
176 }       
177
178 function delete_this_fiscalyear($selected_id)
179 {
180         global $db_connections;
181         
182         db_backup($db_connections[$_SESSION["wa_current_user"]->company], 'Security backup before Fiscal Year Removal');
183         begin_transaction();
184         $ref = _("Open Balance");
185         $myrow = get_fiscalyear($selected_id);
186         $to = $myrow['end'];
187         $sql = "SELECT order_no, trans_type FROM ".TB_PREF."sales_orders WHERE ord_date <= '$to' AND type <> 1"; // don't take the templates
188         $result = db_query($sql, "Could not retrieve sales orders");
189         while ($row = db_fetch($result))
190         {
191                 $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']}";
192                 $res = db_query($sql, "Could not retrieve sales order details");
193                 $row2 = db_fetch_row($res);
194                 if ($row2[0] == $row2[1])
195                 {
196                         $sql = "DELETE FROM ".TB_PREF."sales_order_details WHERE order_no = {$row['order_no']} AND trans_type = {$row['trans_type']}";
197                         db_query($sql, "Could not delete sales order details");
198                         $sql = "DELETE FROM ".TB_PREF."sales_orders WHERE order_no = {$row['order_no']} AND trans_type = {$row['trans_type']}";
199                         db_query($sql, "Could not delete sales order");
200                         delete_attachments_and_comments($row['trans_type'], $row['order_no']);
201                 }
202         }
203         $sql = "SELECT order_no FROM ".TB_PREF."purch_orders WHERE ord_date <= '$to'";
204         $result = db_query($sql, "Could not retrieve purchase orders");
205         while ($row = db_fetch($result))
206         {
207                 $sql = "SELECT SUM(quantity_ordered), SUM(quantity_received) FROM ".TB_PREF."purch_order_details WHERE order_no = {$row['order_no']}";
208                 $res = db_query($sql, "Could not retrieve purchase order details");
209                 $row2 = db_fetch_row($res);
210                 if ($row2[0] == $row2[1])
211                 {
212                         $sql = "DELETE FROM ".TB_PREF."purch_order_details WHERE order_no = {$row['order_no']}";
213                         db_query($sql, "Could not delete purchase order details");
214                         $sql = "DELETE FROM ".TB_PREF."purch_orders WHERE order_no = {$row['order_no']}";
215                         db_query($sql, "Could not delete purchase order");
216                         delete_attachments_and_comments(ST_PURCHORDER, $row['order_no']);
217                 }
218         }
219         $sql = "SELECT id FROM ".TB_PREF."grn_batch WHERE delivery_date <= '$to'";
220         $result = db_query($sql, "Could not retrieve grn batch");
221         while ($row = db_fetch($result))
222         {
223                 $sql = "DELETE FROM ".TB_PREF."grn_items WHERE grn_batch_id = {$row['id']}";
224                 db_query($sql, "Could not delete grn items");
225                 $sql = "DELETE FROM ".TB_PREF."grn_batch WHERE id = {$row['id']}";
226                 db_query($sql, "Could not delete grn batch");
227                 delete_attachments_and_comments(25, $row['id']);
228         }
229         $sql = "SELECT trans_no, type FROM ".TB_PREF."debtor_trans WHERE tran_date <= '$to' AND 
230                 (ov_amount + ov_gst + ov_freight + ov_freight_tax + ov_discount) = alloc";
231         $result = db_query($sql, "Could not retrieve debtor trans");
232         while ($row = db_fetch($result))
233         {
234                 if ($row['type'] == ST_SALESINVOICE)
235                 {
236                         $deliveries = get_parent_trans(ST_SALESINVOICE,$row['trans_no']);
237                         foreach ($deliveries as $delivery)
238                         {
239                                 $sql = "DELETE FROM ".TB_PREF."debtor_trans_details WHERE debtor_trans_no = $delivery AND debtor_trans_type = ".ST_CUSTDELIVERY;
240                                 db_query($sql, "Could not delete debtor trans details");
241                                 $sql = "DELETE FROM ".TB_PREF."debtor_trans WHERE trans_no = $delivery AND type = ".ST_CUSTDELIVERY;
242                                 db_query($sql, "Could not delete debtor trans");
243                         }               
244                 }       
245                 $sql = "DELETE FROM ".TB_PREF."cust_allocations WHERE trans_no_from = {$row['trans_no']} AND type_no_from = {$row['type']}";
246                 db_query($sql, "Could not delete cust allocations");
247                 $sql = "DELETE FROM ".TB_PREF."debtor_trans_details WHERE debtor_trans_no = {$row['trans_no']} AND debtor_trans_type = {$row['type']}";
248                 db_query($sql, "Could not delete debtor trans details");
249                 $sql = "DELETE FROM ".TB_PREF."debtor_trans WHERE trans_no = {$row['trans_no']} AND type = {$row['type']}";
250                 db_query($sql, "Could not delete debtor trans");
251                 delete_attachments_and_comments($row['type'], $row['trans_no']);
252         }
253         $sql = "SELECT trans_no, type FROM ".TB_PREF."supp_trans WHERE tran_date <= '$to' AND 
254                 ABS(ov_amount + ov_gst + ov_discount) = alloc";
255         $result = db_query($sql, "Could not retrieve supp trans");
256         while ($row = db_fetch($result))
257         {
258                 $sql = "DELETE FROM ".TB_PREF."supp_allocations WHERE trans_no_from = {$row['trans_no']} AND type_no_from = {$row['type']}";
259                 db_query($sql, "Could not delete supp allocations");
260                 $sql = "DELETE FROM ".TB_PREF."supp_invoice_items WHERE supp_trans_no = {$row['trans_no']} AND supp_trans_type = {$row['type']}";
261                 db_query($sql, "Could not delete supp invoice items");
262                 $sql = "DELETE FROM ".TB_PREF."supp_trans WHERE trans_no = {$row['trans_no']} AND type = {$row['type']}";
263                 db_query($sql, "Could not delete supp trans");
264                 delete_attachments_and_comments($row['type'], $row['trans_no']);
265         }
266         $sql = "SELECT id FROM ".TB_PREF."workorders WHERE released_date <= '$to' AND closed=1";
267         $result = db_query($sql, "Could not retrieve supp trans");
268         while ($row = db_fetch($result))
269         {
270                 $sql = "SELECT issue_no FROM ".TB_PREF."wo_issues WHERE workorder_id = {$row['id']}"; 
271                 $res = db_query($sql, "Could not retrieve wo issues");
272                 while ($row2 = db_fetch_row($res))
273                 {
274                         $sql = "DELETE FROM ".TB_PREF."wo_issue_items WHERE issue_id = {$row2[0]}";
275                         db_query($sql, "Could not delete wo issue items");
276                 }       
277                 delete_attachments_and_comments(28, $row['id']);
278                 $sql = "DELETE FROM ".TB_PREF."wo_issues WHERE workorder_id = {$row['id']}";
279                 db_query($sql, "Could not delete wo issues");
280                 $sql = "DELETE FROM ".TB_PREF."wo_manufacture WHERE workorder_id = {$row['id']}";
281                 db_query($sql, "Could not delete wo manufacture");
282                 $sql = "DELETE FROM ".TB_PREF."wo_requirements WHERE workorder_id = {$row['id']}";
283                 db_query($sql, "Could not delete wo requirements");
284                 $sql = "DELETE FROM ".TB_PREF."workorders WHERE id = {$row['id']}";
285                 db_query($sql, "Could not delete workorders");
286                 delete_attachments_and_comments(26, $row['id']);
287         }
288         $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 
289                 loc_code, stock_id";
290         $result = db_query($sql, "Could not retrieve supp trans");
291         while ($row = db_fetch($result))
292         {
293                 $sql = "DELETE FROM ".TB_PREF."stock_moves WHERE tran_date <= '$to' AND loc_code = '{$row['loc_code']}' AND stock_id = '{$row['stock_id']}'";
294                 db_query($sql, "Could not delete stock moves");
295                 $qty = $row['qty'];
296                 $std_cost = ($qty == 0 ? 0 : round2($row['std_cost'] / $qty, user_price_dec()));
297                 $sql = "INSERT INTO ".TB_PREF."stock_moves (stock_id, loc_code, tran_date, reference, qty, standard_cost) VALUES
298                         ('{$row['stock_id']}', '{$row['loc_code']}', '$to', '$ref', $qty, $std_cost)";   
299                 db_query($sql, "Could not insert stock move");
300         }               
301         $sql = "DELETE FROM ".TB_PREF."voided WHERE date_ <= '$to'";
302         db_query($sql, "Could not delete voided items");
303         $sql = "DELETE FROM ".TB_PREF."trans_tax_details WHERE tran_date <= '$to'";
304         db_query($sql, "Could not delete trans tax details");
305         $sql = "DELETE FROM ".TB_PREF."exchange_rates WHERE date_ <= '$to'";
306         db_query($sql, "Could not delete exchange rates");
307         $sql = "DELETE FROM ".TB_PREF."budget_trans WHERE tran_date <= '$to'";
308         db_query($sql, "Could not delete exchange rates");
309         $sql = "SELECT account, SUM(amount) AS amount FROM ".TB_PREF."gl_trans WHERE tran_date <= '$to' GROUP by account";
310         $result = db_query($sql, "Could not retrieve gl trans");
311         while ($row = db_fetch($result))
312         {
313                 $sql = "DELETE FROM ".TB_PREF."gl_trans WHERE tran_date <= '$to' AND account = '{$row['account']}'";
314                 db_query($sql, "Could not delete gl trans");
315                 if (is_account_balancesheet($row['account']))
316                 {
317                         $trans_no = get_next_trans_no(0);
318                         if (is_bank_account($row['account']))
319                         {
320                                 $sql = "SELECT SUM(amount) FROM ".TB_PREF."bank_trans WHERE trans_date <= '$to' AND bank_act = '{$row['account']}'";
321                                 $res = db_query($sql, "Could not retrieve bank trans");
322                                 $row2 = db_fetch_row($res);
323                                 $sql = "DELETE FROM ".TB_PREF."bank_trans WHERE trans_date <= '$to' AND bank_act = '{$row['account']}'";
324                                 db_query($sql, "Could not delete bank trans");
325                                 $sql = "INSERT INTO ".TB_PREF."bank_trans (type, trans_no, trans_date, bank_act, ref, amount) VALUES
326                                         (0, $trans_no, '$to', '{$row['account']}', '$ref', {$row2[0]})";
327                                 db_query($sql, "Could not insert bank trans");
328                         }       
329                         $sql = "INSERT INTO ".TB_PREF."gl_trans (type, type_no, tran_date, account, memo_, amount) VALUES
330                                 (0, $trans_no, '$to', '{$row['account']}', '$ref', {$row['amount']})";
331                         db_query($sql, "Could not insert gl trans");
332                 }
333         }
334         delete_fiscalyear($selected_id);
335         commit_transaction();   
336 }
337
338 ?>