Removed sparse parameter in write_customer()
[fa-stable.git] / gl / gl_journal.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 = 'SA_JOURNALENTRY';
13 $path_to_root = "..";
14 include_once($path_to_root . "/includes/ui/items_cart.inc");
15
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/data_checks.inc");
20
21 include_once($path_to_root . "/gl/includes/ui/gl_journal_ui.inc");
22 include_once($path_to_root . "/gl/includes/gl_db.inc");
23 include_once($path_to_root . "/gl/includes/gl_ui.inc");
24
25 $js = '';
26 if ($SysPrefs->use_popup_windows)
27         $js .= get_js_open_window(800, 500);
28 if (user_use_date_picker())
29         $js .= get_js_date_picker();
30
31 if (isset($_GET['ModifyGL'])) {
32         $_SESSION['page_title'] = sprintf(_("Modifying Journal Transaction # %d."), 
33                 $_GET['trans_no']);
34         $help_context = "Modifying Journal Entry";
35 } else
36         $_SESSION['page_title'] = _($help_context = "Journal Entry");
37
38 page($_SESSION['page_title'], false, false,'', $js);
39 //--------------------------------------------------------------------------------------------------
40
41 function line_start_focus() {
42   global        $Ajax;
43
44   unset($_POST['Index']);
45   $Ajax->activate('tabs');
46   unset($_POST['_code_id_edit'], $_POST['code_id'], $_POST['AmountDebit'], 
47         $_POST['AmountCredit'], $_POST['dimension_id'], $_POST['dimension2_id']);
48   set_focus('_code_id_edit');
49 }
50 //-----------------------------------------------------------------------------------------------
51
52 if (isset($_GET['AddedID'])) 
53 {
54         $trans_no = $_GET['AddedID'];
55         $trans_type = ST_JOURNAL;
56
57         display_notification_centered( _("Journal entry has been entered") . " #$trans_no");
58
59     display_note(get_gl_view_str($trans_type, $trans_no, _("&View this Journal Entry")));
60
61         reset_focus();
62         hyperlink_params($_SERVER['PHP_SELF'], _("Enter &New Journal Entry"), "NewJournal=Yes");
63
64         hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");
65
66         display_footer_exit();
67 } elseif (isset($_GET['UpdatedID'])) 
68 {
69         $trans_no = $_GET['UpdatedID'];
70         $trans_type = ST_JOURNAL;
71
72         display_notification_centered( _("Journal entry has been updated") . " #$trans_no");
73
74     display_note(get_gl_view_str($trans_type, $trans_no, _("&View this Journal Entry")));
75
76         hyperlink_no_params($path_to_root."/gl/inquiry/journal_inquiry.php", _("Return to Journal &Inquiry"));
77
78         display_footer_exit();
79 }
80 //--------------------------------------------------------------------------------------------------
81
82 if (isset($_GET['NewJournal']))
83 {
84         create_cart(0,0);
85 }
86 elseif (isset($_GET['ModifyGL']))
87 {
88         check_is_editable($_GET['trans_type'], $_GET['trans_no']);
89
90         if (!isset($_GET['trans_type']) || $_GET['trans_type']!= 0) {
91                 display_error(_("You can edit directly only journal entries created via Journal Entry page."));
92                 hyperlink_params("$path_to_root/gl/gl_journal.php", _("Entry &New Journal Entry"), "NewJournal=Yes");
93                 display_footer_exit();
94         }
95         create_cart($_GET['trans_type'], $_GET['trans_no']);
96 }
97
98 function create_cart($type=0, $trans_no=0)
99 {
100         global $Refs;
101
102         if (isset($_SESSION['journal_items']))
103         {
104                 unset ($_SESSION['journal_items']);
105         }
106
107         check_is_closed($type, $trans_no);
108         $cart = new items_cart($type);
109     $cart->order_id = $trans_no;
110
111         if ($trans_no) {
112                 $header = get_journal($type, $trans_no);
113                 $cart->event_date = sql2date($header['event_date']);
114                 $cart->doc_date = sql2date($header['doc_date']);
115                 $cart->tran_date = sql2date($header['tran_date']);
116                 $cart->currency = $header['currency'];
117                 $cart->rate = $header['rate'];
118                 $cart->source_ref = $header['source_ref'];
119                 $cart->reconcile_date = $header['reconcile_date'] ? sql2date($header['reconcile_date']) : NULL;
120
121                 $result = get_gl_trans($type, $trans_no);
122
123                 if ($result) {
124                         while ($row = db_fetch($result)) {
125                                 $curr_amount = $cart->rate ? round($row['amount']/$cart->rate, $_SESSION["wa_current_user"]->prefs->price_dec()) : $row['amount'];
126                                 if ($curr_amount)
127                                         $cart->add_gl_item($row['account'], $row['dimension_id'], $row['dimension2_id'], 
128                                                 $curr_amount, $row['memo_'], '', $row['person_id']);
129                         }
130                 }
131                 $cart->memo_ = get_comments_string($type, $trans_no);
132                 $cart->reference = $header['reference'];
133                 // update net_amounts from tax register
134
135                 // retrieve tax details
136                 $tax_info = $cart->collect_tax_info(); // tax amounts in reg are always consistent with GL, so we can read them from GL lines
137
138                 $taxes = get_trans_tax_details($type, $trans_no);
139                 while ($detail = db_fetch($taxes))
140                 {
141                         $tax_id = $detail['tax_type_id'];
142                         $cart->vat_category = $tax_info['tax_category'] = $detail['vat_category'];
143                         $tax_info['net_amount'][$tax_id] = $detail['net_amount']; // we can two records for the same tax_id, but in this case net_amount is the same
144                         $tax_info['tax_date'] = sql2date($detail['tran_date']);
145                         $tax_info['tax_group'] = $detail['tax_group_id'];
146
147                 }
148                 if (isset($tax_info['net_amount']))     // guess exempt sales/purchase if any tax has been found
149                 {
150                         $net_sum = 0;
151                         foreach($cart->gl_items as $gl)
152                                 if (!is_tax_account($gl->code_id) && !is_subledger_account($gl->code_id, $gl->person_id))
153                                         $net_sum += $gl->amount;
154
155                         $ex_net = abs($net_sum) - array_sum($tax_info['net_amount']);
156                         if ($ex_net > 0)
157                                 $tax_info['net_amount_ex'] = $ex_net;
158                 }
159                 $cart->tax_info = $tax_info;
160
161         } else {
162                 $cart->tran_date = $cart->doc_date = $cart->event_date = new_doc_date();
163                 if (!is_date_in_fiscalyear($cart->tran_date))
164                         $cart->tran_date = end_fiscalyear();
165                 $cart->reference = $Refs->get_next(ST_JOURNAL, null, $cart->tran_date);
166         }
167
168         $_POST['reconciled_date'] = $cart->reconcile_date;
169         $_POST['memo_'] = $cart->memo_;
170         $_POST['ref'] = $cart->reference;
171         $_POST['date_'] = $cart->tran_date;
172         $_POST['event_date'] = $cart->event_date;
173         $_POST['doc_date'] = $cart->doc_date;
174         $_POST['currency'] = $cart->currency;
175         $_POST['_ex_rate'] = exrate_format($cart->rate);
176         $_POST['source_ref'] = $cart->source_ref;
177         if (isset($cart->tax_info['net_amount']) || (!$trans_no && get_company_pref('default_gl_vat')))
178                 $_POST['taxable_trans'] = true;
179         $_SESSION['journal_items'] = &$cart;
180 }
181
182 function update_tax_info()
183 {
184
185         $_SESSION['journal_items']->vat_category = get_post('tax_category');
186
187         if (!isset($_SESSION['journal_items']->tax_info) || list_updated('tax_category'))
188                 $_SESSION['journal_items']->tax_info = $_SESSION['journal_items']->collect_tax_info();
189
190         foreach ($_SESSION['journal_items']->tax_info as $name => $value)
191                 if (is_array($value))
192                 {
193                         foreach ($value as $id => $amount)
194                         {
195                                 $_POST[$name.'_'.$id] = price_format($amount);
196                         }
197                 } else
198                         $_POST[$name] = $value;
199         $_POST['tax_date'] = $_SESSION['journal_items']->order_id ? $_SESSION['journal_items']->tax_info['tax_date'] : $_POST['date_'];
200 }
201
202 //-----------------------------------------------------------------------------------------------
203 if (isset($_POST['Process']))
204 {
205         $input_error = 0;
206
207         if ($_SESSION['journal_items']->count_gl_items() < 1) {
208                 display_error(_("You must enter at least one journal line."));
209                 set_focus('code_id');
210                 $input_error = 1;
211         }
212         if (abs($_SESSION['journal_items']->gl_items_total()) > 0.001)
213         {
214                 display_error(_("The journal must balance (debits equal to credits) before it can be processed."));
215                 set_focus('code_id');
216                 $input_error = 1;
217         }
218
219         if (!is_date($_POST['date_'])) 
220         {
221                 display_error(_("The entered date is invalid."));
222                 set_focus('date_');
223                 $input_error = 1;
224         } 
225         elseif (!is_date_in_fiscalyear($_POST['date_'])) 
226         {
227                 display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
228                 set_focus('date_');
229                 $input_error = 1;
230         } 
231         if (!is_date($_POST['event_date'])) 
232         {
233                 display_error(_("The entered date is invalid."));
234                 set_focus('event_date');
235                 $input_error = 1;
236         }
237         if (!is_date($_POST['doc_date'])) 
238         {
239                 display_error(_("The entered date is invalid."));
240                 set_focus('doc_date');
241                 $input_error = 1;
242         }
243         if (!check_reference($_POST['ref'], ST_JOURNAL, $_SESSION['journal_items']->order_id))
244         {
245                 set_focus('ref');
246                 $input_error = 1;
247         }
248         if (get_post('currency') != get_company_pref('curr_default'))
249                 if (isset($_POST['_ex_rate']) && !check_num('_ex_rate', 0.000001))
250                 {
251                         display_error(_("The exchange rate must be numeric and greater than zero."));
252                         set_focus('_ex_rate');
253                 $input_error = 1;
254                 }
255
256         if (get_post('_tabs_sel') == 'tax')
257         {
258                 if (!is_date($_POST['tax_date']))
259                 {
260                         display_error(_("The entered date is invalid."));
261                         set_focus('tax_date');
262                         $input_error = 1;
263                 } 
264                 elseif (!is_date_in_fiscalyear($_POST['tax_date']))
265                 {
266                         display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
267                         set_focus('tax_date');
268                         $input_error = 1;
269                 }
270                 // FIXME: check proper tax net input values, check sum of net values against total GL an issue warning
271         }
272
273         if (check_value('taxable_trans'))
274         {
275                 if (!tab_visible('tabs', 'tax'))
276                 {
277                         display_warning(_("Check tax register records before processing transaction or switch off 'Include in tax register' option."));
278                         $_POST['tabs_tax'] = true; // force tax tab select
279                         $input_error = 1;
280                 } else {
281                         $taxes = get_all_tax_types();
282                         $net_amount = 0;
283                         while ($tax = db_fetch($taxes))
284                         {
285                                 $tax_id = $tax['id'];
286                                 $net_amount += input_num('net_amount_'.$tax_id);
287                         }
288                         // in case no tax account used we have to guss tax register on customer/supplier used.
289                         if ($net_amount && !$_SESSION['journal_items']->has_taxes() && !$_SESSION['journal_items']->has_sub_accounts())
290                         {
291                                 display_error(_("Cannot determine tax register to be used. You have to make at least one posting either to tax or customer/supplier account to use tax register."));
292                                 $_POST['tabs_gl'] = true; // force gl tab select
293                                 $input_error = 1;
294                         }
295                 }
296         }
297
298         if ($input_error == 1)
299                 unset($_POST['Process']);
300 }
301
302 if (isset($_POST['Process']))
303 {
304         $cart = &$_SESSION['journal_items'];
305         $new = $cart->order_id == 0;
306
307         $cart->reference = $_POST['ref'];
308         $cart->tran_date = $_POST['date_'];
309         $cart->doc_date = $_POST['doc_date'];
310         $cart->event_date = $_POST['event_date'];
311         $cart->source_ref = $_POST['source_ref'];
312         if (isset($_POST['memo_']))
313                 $cart->memo_ = $_POST['memo_'];
314
315         $cart->currency = $_POST['currency'];
316         if ($cart->currency != get_company_pref('curr_default'))
317                 $cart->rate = input_num('_ex_rate');
318
319         if (check_value('taxable_trans'))
320         {
321                 // complete tax register data
322                 $cart->tax_info['tax_date'] = $_POST['tax_date'];
323                 //$cart->tax_info['tax_group'] = $_POST['tax_group'];
324                 $taxes = get_all_tax_types();
325                 while ($tax = db_fetch($taxes))
326                 {
327                         $tax_id = $tax['id'];
328                         $cart->tax_info['net_amount'][$tax_id] = input_num('net_amount_'.$tax_id);
329                         $cart->tax_info['rate'][$tax_id] = $tax['rate'];
330                 }
331         } else
332                 $cart->tax_info = false;
333
334         if (!get_post('reconciled'))    // clear reconcilation (if any)
335                 $cart->reconcile_date = NULL;
336
337         $trans_no = write_journal_entries($cart);
338
339         $cart->clear_items();
340         new_doc_date($_POST['date_']);
341         unset($_SESSION['journal_items']);
342
343         if($new)
344                 meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
345         else
346                 meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$trans_no");
347 }
348
349 //-----------------------------------------------------------------------------------------------
350
351 function check_item_data()
352 {
353         global $Ajax;
354
355         if (!get_post('code_id')) {
356                 display_error(_("You must select GL account."));
357                 set_focus('code_id');
358                 return false;
359         }
360         if (is_subledger_account(get_post('code_id'))) {
361                 if(!get_post('person_id')) {
362                         display_error(_("You must select subledger account."));
363                         $Ajax->activate('items_table');
364                         set_focus('person_id');
365                         return false;
366                 }
367         }
368         if (isset($_POST['dimension_id']) && $_POST['dimension_id'] != 0 && dimension_is_closed($_POST['dimension_id'])) 
369         {
370                 display_error(_("Dimension is closed."));
371                 set_focus('dimension_id');
372                 return false;
373         }
374
375         if (isset($_POST['dimension2_id']) && $_POST['dimension2_id'] != 0 && dimension_is_closed($_POST['dimension2_id'])) 
376         {
377                 display_error(_("Dimension is closed."));
378                 set_focus('dimension2_id');
379                 return false;
380         }
381
382         if (!(input_num('AmountDebit')!=0 ^ input_num('AmountCredit')!=0) )
383         {
384                 display_error(_("You must enter either a debit amount or a credit amount."));
385                 set_focus('AmountDebit');
386                 return false;
387         }
388
389         if (strlen($_POST['AmountDebit']) && !check_num('AmountDebit', 0)) 
390         {
391                 display_error(_("The debit amount entered is not a valid number or is less than zero."));
392                 set_focus('AmountDebit');
393                 return false;
394         } elseif (strlen($_POST['AmountCredit']) && !check_num('AmountCredit', 0))
395         {
396                 display_error(_("The credit amount entered is not a valid number or is less than zero."));
397                 set_focus('AmountCredit');
398                 return false;
399         }
400         
401         if (!is_tax_gl_unique(get_post('code_id'))) {
402                 display_error(_("Cannot post to GL account used by more than one tax type."));
403                 set_focus('code_id');
404                 return false;
405         }
406
407         if (!$_SESSION["wa_current_user"]->can_access('SA_BANKJOURNAL') && is_bank_account($_POST['code_id'])) 
408         {
409                 display_error(_("You cannot make a journal entry for a bank account. Please use one of the banking functions for bank transactions."));
410                 set_focus('code_id');
411                 return false;
412         }
413
414         return true;
415 }
416
417 //-----------------------------------------------------------------------------------------------
418
419 function handle_update_item()
420 {
421     if($_POST['UpdateItem'] != "" && check_item_data())
422     {
423         if (input_num('AmountDebit') > 0)
424                 $amount = input_num('AmountDebit');
425         else
426                 $amount = -input_num('AmountCredit');
427
428         $_SESSION['journal_items']->update_gl_item($_POST['Index'], $_POST['code_id'], 
429             $_POST['dimension_id'], $_POST['dimension2_id'], $amount, $_POST['LineMemo'], '', get_post('person_id'));
430         unset($_SESSION['journal_items']->tax_info);
431                 line_start_focus();
432     }
433 }
434
435 //-----------------------------------------------------------------------------------------------
436
437 function handle_delete_item($id)
438 {
439         $_SESSION['journal_items']->remove_gl_item($id);
440         unset($_SESSION['journal_items']->tax_info);
441         line_start_focus();
442 }
443
444 //-----------------------------------------------------------------------------------------------
445
446 function handle_new_item()
447 {
448         if (!check_item_data())
449                 return;
450
451         if (input_num('AmountDebit') > 0)
452                 $amount = input_num('AmountDebit');
453         else
454                 $amount = -input_num('AmountCredit');
455         
456         $_SESSION['journal_items']->add_gl_item($_POST['code_id'], $_POST['dimension_id'],
457                 $_POST['dimension2_id'], $amount, $_POST['LineMemo'], '', get_post('person_id'));
458         unset($_SESSION['journal_items']->tax_info);
459         line_start_focus();
460 }
461
462 //-----------------------------------------------------------------------------------------------
463 if (isset($_POST['_taxable_trans_update']))
464 {       if (!check_value('taxable_trans'))
465                 $_POST['tabs_gl'] = true; // force tax tab select
466         else
467                 set_focus('taxable_trans');
468         $Ajax->activate('tabs');
469 }
470
471 if (tab_closed('tabs', 'gl'))
472 {
473         $_SESSION['journal_items']->memo_ = $_POST['memo_'];
474 }
475  elseif (tab_closed('tabs', 'tax'))
476 {
477         $cart = &$_SESSION['journal_items'];
478         $cart->tax_info['tax_date'] = $_POST['tax_date'];
479         $cart->tax_info['tax_category'] = $_POST['tax_category'];
480         $cart->tax_info['tax_group'] = $_POST['tax_group'];
481         $taxes = get_all_tax_types();
482         while ($tax = db_fetch($taxes))
483         {
484                 $tax_id = $tax['id'];
485                 $cart->tax_info['net_amount'][$tax_id] = input_num('net_amount_'.$tax_id);
486                 $cart->tax_info['rate'][$tax_id] = $tax['rate'];
487         }
488 }
489 if (tab_opened('tabs', 'gl'))
490 {
491         $_POST['memo_'] = $_SESSION['journal_items']->memo_;
492 } elseif (tab_opened('tabs', 'tax'))
493 {
494         $_POST['tax_category'] = $_SESSION['journal_items']->vat_category;
495         $_SESSION['journal_items']->collect_tax_info();
496         $_POST['tax_group'] = $_SESSION['journal_items']->tax_info['tax_group'];
497         set_focus('tax_date');
498 }
499
500
501 $id = find_submit('Delete');
502 if ($id != -1)
503         handle_delete_item($id);
504
505 if (isset($_POST['AddItem'])) 
506         handle_new_item();
507
508 if (isset($_POST['UpdateItem'])) 
509         handle_update_item();
510         
511 if (isset($_POST['CancelItemChanges']))
512         line_start_focus();
513
514 if (isset($_POST['go']))
515 {
516         display_quick_entries($_SESSION['journal_items'], $_POST['quick'], input_num('totamount'), QE_JOURNAL, get_post('aux_info'));
517         $_POST['totamount'] = price_format(0); $Ajax->activate('totamount');
518         line_start_focus();
519 }
520
521 if (list_updated('tax_category'))
522 {
523         $Ajax->activate('tabs');
524 }
525
526 //-----------------------------------------------------------------------------------------------
527
528 start_form();
529
530 display_order_header($_SESSION['journal_items']);
531
532 tabbed_content_start('tabs', array(
533                 'gl' => array(_('&GL postings'), true),
534                 'tax' => array(_('&Tax register'), check_value('taxable_trans')),
535         ));
536         
537         switch (get_post('_tabs_sel')) {
538                 default:
539                 case 'gl':
540                         start_table(TABLESTYLE2, "width='90%'", 10);
541                         start_row();
542                         echo "<td>";
543                         display_gl_items(_("Rows"), $_SESSION['journal_items']);
544                         gl_options_controls();
545                         echo "</td>";
546                         end_row();
547                         end_table(1);
548                         break;
549
550                 case 'tax':
551                         update_tax_info();
552                         br();
553                         display_heading(_("Tax register record"));
554                         br();
555                         start_table(TABLESTYLE2, "width=40%");
556                         date_row(_("VAT date:"), 'tax_date', '', "colspan='3'");
557                         tax_groups_list_row(_("Tax group:"), 'tax_group');
558                         vat_category_list_row(_("VAT category:"), 'tax_category', null, true, true);
559                         end_table(1);
560
561                         start_table(TABLESTYLE2, "width=60%");
562                         table_header(array(_('Name'), _('Input Tax'), _('Output Tax'), _('Net amount')));
563                         $taxes = get_all_tax_types();
564                         while ($tax = db_fetch($taxes))
565                         {
566                                 start_row();
567                                 label_cell($tax['name'].' '.$tax['rate'].'%');
568                                 amount_cell(input_num('tax_in_'.$tax['id']));
569                                 amount_cell(input_num('tax_out_'.$tax['id']));
570
571                                 amount_cells(null, 'net_amount_'.$tax['id']);
572                                 end_row();
573                         }
574                         end_table(1);
575                         break;
576         };
577         submit_center('Process', _("Process Journal Entry"), true , 
578                 _('Process journal entry only if debits equal to credits'), 'default');
579 br();
580 tabbed_content_end();
581
582 end_form();
583
584 end_page();