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