Additional fixes for journal handling. Added reg_type in trans_tax_details.
[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
120                 $result = get_gl_trans($type, $trans_no);
121
122                 if ($result) {
123                         while ($row = db_fetch($result)) {
124                                 $curr_amount = $cart->rate ? round($row['amount']/$cart->rate, $_SESSION["wa_current_user"]->prefs->price_dec()) : $row['amount'];
125                                 if ($curr_amount)
126                                         $cart->add_gl_item($row['account'], $row['dimension_id'], $row['dimension2_id'], 
127                                                 $curr_amount, $row['memo_'], '', $row['person_id']);
128                         }
129                 }
130                 $cart->memo_ = get_comments_string($type, $trans_no);
131                 $cart->reference = $header['reference'];
132
133                 $_POST['ref_original'] = $cart->reference; // Store for comparison when updating
134
135                 // update net_amounts from tax register
136
137                 // retrieve tax details
138                 $tax_info = $cart->collect_tax_info(); // tax amounts in reg are always consistent with GL, so we can read them from GL lines
139
140                 $taxes = get_trans_tax_details($type, $trans_no);
141                 while ($detail = db_fetch($taxes))
142                 {
143                         $tax_id = $detail['tax_type_id'];
144                         $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
145                         $tax_info['tax_date'] = sql2date($detail['effective_date']);
146                         $tax_info['tax_group'] = $detail['tax_group_id'];
147
148                 }
149                 if (isset($tax_info['net_amount']))     // guess exempt sales/purchase if any tax has been found
150                 {
151                         $net_sum = 0;
152                         foreach($cart->gl_items as $gl)
153                                 if (!is_tax_account($gl->code_id) && !is_subledger_account($gl->code_id, $gl->person_id))
154                                         $net_sum += $gl->amount;
155
156                         $ex_net = abs($net_sum) - array_sum($tax_info['net_amount']);
157                         if ($ex_net > 0)
158                                 $tax_info['net_amount_ex'] = $ex_net;
159                 }
160                 $cart->tax_info = $tax_info;
161
162         } else {
163                 $cart->tran_date = $cart->doc_date = $cart->event_date = new_doc_date();
164                 if (!is_date_in_fiscalyear($cart->tran_date))
165                         $cart->tran_date = end_fiscalyear();
166                 $cart->reference = $Refs->get_next(ST_JOURNAL, null, $cart->tran_date);
167                 $_POST['ref_original'] = -1;
168         }
169
170         $_POST['memo_'] = $cart->memo_;
171         $_POST['ref'] = $cart->reference;
172         $_POST['date_'] = $cart->tran_date;
173         $_POST['event_date'] = $cart->event_date;
174         $_POST['doc_date'] = $cart->doc_date;
175         $_POST['currency'] = $cart->currency;
176         $_POST['_ex_rate'] = exrate_format($cart->rate);
177         $_POST['source_ref'] = $cart->source_ref;
178         if (isset($cart->tax_info['net_amount']) || (!$trans_no && get_company_pref('default_gl_vat')))
179                 $_POST['taxable_trans'] = true;
180         $_SESSION['journal_items'] = &$cart;
181 }
182
183 function update_tax_info()
184 {
185
186         if (!isset($_SESSION['journal_items']->tax_info) || list_updated('tax_category'))
187                 $_SESSION['journal_items']->tax_info = $_SESSION['journal_items']->collect_tax_info();
188
189         foreach ($_SESSION['journal_items']->tax_info as $name => $value)
190                 if (is_array($value))
191                 {
192                         foreach ($value as $id => $amount)
193                         {
194                                 $_POST[$name.'_'.$id] = price_format($amount);
195                         }
196                 } else
197                         $_POST[$name] = $value;
198         $_POST['tax_date'] = $_SESSION['journal_items']->order_id ? $_SESSION['journal_items']->tax_info['tax_date'] : $_POST['date_'];
199 }
200
201 //-----------------------------------------------------------------------------------------------
202 if (isset($_POST['Process']))
203 {
204         $input_error = 0;
205
206         if ($_SESSION['journal_items']->count_gl_items() < 1) {
207                 display_error(_("You must enter at least one journal line."));
208                 set_focus('code_id');
209                 $input_error = 1;
210         }
211         if (abs($_SESSION['journal_items']->gl_items_total()) > 0.001)
212         {
213                 display_error(_("The journal must balance (debits equal to credits) before it can be processed."));
214                 set_focus('code_id');
215                 $input_error = 1;
216         }
217
218         if (!is_date($_POST['date_'])) 
219         {
220                 display_error(_("The entered date is invalid."));
221                 set_focus('date_');
222                 $input_error = 1;
223         } 
224         elseif (!is_date_in_fiscalyear($_POST['date_'])) 
225         {
226                 display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
227                 set_focus('date_');
228                 $input_error = 1;
229         } 
230         if (!is_date($_POST['event_date'])) 
231         {
232                 display_error(_("The entered date is invalid."));
233                 set_focus('event_date');
234                 $input_error = 1;
235         }
236         if (!is_date($_POST['doc_date'])) 
237         {
238                 display_error(_("The entered date is invalid."));
239                 set_focus('doc_date');
240                 $input_error = 1;
241         }
242         if (!$Refs->is_valid($_POST['ref'])) 
243         {
244                 display_error( _("You must enter a reference."));
245                 set_focus('ref');
246                 $input_error = 1;
247         } 
248         elseif (($_POST['ref'] != $_POST['ref_original']) && $Refs->exists(ST_JOURNAL,$_POST['ref'])) 
249         {
250                 display_error( _("The entered reference is already in use."));
251                 set_focus('ref');
252                 $input_error = 1;
253         }
254         if (get_post('currency') != get_company_pref('curr_default'))
255                 if (isset($_POST['_ex_rate']) && !check_num('_ex_rate', 0.000001))
256                 {
257                         display_error(_("The exchange rate must be numeric and greater than zero."));
258                         set_focus('_ex_rate');
259                 $input_error = 1;
260                 }
261
262         if (get_post('_tabs_sel') == 'tax')
263         {
264                 if (!is_date($_POST['tax_date']))
265                 {
266                         display_error(_("The entered date is invalid."));
267                         set_focus('tax_date');
268                         $input_error = 1;
269                 } 
270                 elseif (!is_date_in_fiscalyear($_POST['tax_date']))
271                 {
272                         display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
273                         set_focus('tax_date');
274                         $input_error = 1;
275                 }
276                 // FIXME: check proper tax net input values, check sum of net values against total GL an issue warning
277         }
278
279         if (check_value('taxable_trans'))
280         {
281                 if (!tab_visible('tabs', 'tax'))
282                 {
283                         display_warning(_("Check tax register records before processing transaction or switch off 'Include in tax register' option."));
284                         $_POST['tabs_tax'] = true; // force tax tab select
285                         $input_error = 1;
286                 } else {
287                         $taxes = get_all_tax_types();
288                         $net_amount = 0;
289                         while ($tax = db_fetch($taxes))
290                         {
291                                 $tax_id = $tax['id'];
292                                 $net_amount += input_num('net_amount_'.$tax_id);
293                         }
294                         // in case no tax account used we have to guss tax register on customer/supplier used.
295                         if ($net_amount && !$_SESSION['journal_items']->has_taxes() && !$_SESSION['journal_items']->has_sub_accounts())
296                         {
297                                 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."));
298                                 $_POST['tabs_gl'] = true; // force gl tab select
299                                 $input_error = 1;
300                         }
301                 }
302         }
303
304         if ($input_error == 1)
305                 unset($_POST['Process']);
306 }
307
308 if (isset($_POST['Process']))
309 {
310         $cart = &$_SESSION['journal_items'];
311         $new = $cart->order_id == 0;
312
313         $cart->reference = $_POST['ref'];
314         $cart->tran_date = $_POST['date_'];
315         $cart->doc_date = $_POST['doc_date'];
316         $cart->event_date = $_POST['event_date'];
317         $cart->source_ref = $_POST['source_ref'];
318         if (isset($_POST['memo_']))
319                 $cart->memo_ = $_POST['memo_'];
320
321         $cart->currency = $_POST['currency'];
322         if ($cart->currency != get_company_pref('curr_default'))
323                 $cart->rate = input_num('_ex_rate');
324
325         if (check_value('taxable_trans'))
326         {
327                 // complete tax register data
328                 $cart->tax_info['tax_date'] = $_POST['tax_date'];
329                 $cart->tax_info['tax_group'] = $_POST['tax_group'];
330                 $taxes = get_all_tax_types();
331                 while ($tax = db_fetch($taxes))
332                 {
333                         $tax_id = $tax['id'];
334                         $cart->tax_info['net_amount'][$tax_id] = input_num('net_amount_'.$tax_id);
335                         $cart->tax_info['rate'][$tax_id] = $tax['rate'];
336                 }
337         } else
338                 $cart->tax_info = false;
339         $trans_no = write_journal_entries($cart);
340
341         $cart->clear_items();
342         new_doc_date($_POST['date_']);
343         unset($_SESSION['journal_items']);
344         if($new)
345                 meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
346         else
347                 meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$trans_no");
348 }
349
350 //-----------------------------------------------------------------------------------------------
351
352 function check_item_data()
353 {
354         global $Ajax;
355
356         if (!get_post('code_id')) {
357                 display_error(_("You must select GL account."));
358                 set_focus('code_id');
359                 return false;
360         }
361         if (is_subledger_account(get_post('code_id'))) {
362                 if(!get_post('person_id')) {
363                         display_error(_("You must select subledger account."));
364                         $Ajax->activate('items_table');
365                         set_focus('person_id');
366                         return false;
367                 }
368         }
369         if (isset($_POST['dimension_id']) && $_POST['dimension_id'] != 0 && dimension_is_closed($_POST['dimension_id'])) 
370         {
371                 display_error(_("Dimension is closed."));
372                 set_focus('dimension_id');
373                 return false;
374         }
375
376         if (isset($_POST['dimension2_id']) && $_POST['dimension2_id'] != 0 && dimension_is_closed($_POST['dimension2_id'])) 
377         {
378                 display_error(_("Dimension is closed."));
379                 set_focus('dimension2_id');
380                 return false;
381         }
382
383         if (!(input_num('AmountDebit')!=0 ^ input_num('AmountCredit')!=0) )
384         {
385                 display_error(_("You must enter either a debit amount or a credit amount."));
386                 set_focus('AmountDebit');
387                 return false;
388         }
389
390         if (strlen($_POST['AmountDebit']) && !check_num('AmountDebit', 0)) 
391         {
392                 display_error(_("The debit amount entered is not a valid number or is less than zero."));
393                 set_focus('AmountDebit');
394                 return false;
395         } elseif (strlen($_POST['AmountCredit']) && !check_num('AmountCredit', 0))
396         {
397                 display_error(_("The credit amount entered is not a valid number or is less than zero."));
398                 set_focus('AmountCredit');
399                 return false;
400         }
401         
402         if (!is_tax_gl_unique(get_post('code_id'))) {
403                 display_error(_("Cannot post to GL account used by more than one tax type."));
404                 set_focus('code_id');
405                 return false;
406         }
407
408         if (!$_SESSION["wa_current_user"]->can_access('SA_BANKJOURNAL') && is_bank_account($_POST['code_id'])) 
409         {
410                 display_error(_("You cannot make a journal entry for a bank account. Please use one of the banking functions for bank transactions."));
411                 set_focus('code_id');
412                 return false;
413         }
414
415         return true;
416 }
417
418 //-----------------------------------------------------------------------------------------------
419
420 function handle_update_item()
421 {
422     if($_POST['UpdateItem'] != "" && check_item_data())
423     {
424         if (input_num('AmountDebit') > 0)
425                 $amount = input_num('AmountDebit');
426         else
427                 $amount = -input_num('AmountCredit');
428
429         $_SESSION['journal_items']->update_gl_item($_POST['Index'], $_POST['code_id'], 
430             $_POST['dimension_id'], $_POST['dimension2_id'], $amount, $_POST['LineMemo'], '', get_post('person_id'));
431         unset($_SESSION['journal_items']->tax_info);
432                 line_start_focus();
433     }
434 }
435
436 //-----------------------------------------------------------------------------------------------
437
438 function handle_delete_item($id)
439 {
440         $_SESSION['journal_items']->remove_gl_item($id);
441         unset($_SESSION['journal_items']->tax_info);
442         line_start_focus();
443 }
444
445 //-----------------------------------------------------------------------------------------------
446
447 function handle_new_item()
448 {
449         if (!check_item_data())
450                 return;
451
452         if (input_num('AmountDebit') > 0)
453                 $amount = input_num('AmountDebit');
454         else
455                 $amount = -input_num('AmountCredit');
456         
457         $_SESSION['journal_items']->add_gl_item($_POST['code_id'], $_POST['dimension_id'],
458                 $_POST['dimension2_id'], $amount, $_POST['LineMemo'], '', get_post('person_id'));
459         unset($_SESSION['journal_items']->tax_info);
460         line_start_focus();
461 }
462
463 //-----------------------------------------------------------------------------------------------
464 if (isset($_POST['_taxable_trans_update']))
465 {       if (!check_value('taxable_trans'))
466                 $_POST['tabs_gl'] = true; // force tax tab select
467         else
468                 set_focus('taxable_trans');
469         $Ajax->activate('tabs');
470 }
471
472 if (tab_closed('tabs', 'gl'))
473 {
474         $_SESSION['journal_items']->memo_ = $_POST['memo_'];
475 }
476  elseif (tab_closed('tabs', 'tax'))
477 {
478         $cart = &$_SESSION['journal_items'];
479         $cart->tax_info['tax_date'] = $_POST['tax_date'];
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         set_focus('tax_date');
495 }
496
497
498 $id = find_submit('Delete');
499 if ($id != -1)
500         handle_delete_item($id);
501
502 if (isset($_POST['AddItem'])) 
503         handle_new_item();
504
505 if (isset($_POST['UpdateItem'])) 
506         handle_update_item();
507         
508 if (isset($_POST['CancelItemChanges']))
509         line_start_focus();
510
511 if (isset($_POST['go']))
512 {
513         display_quick_entries($_SESSION['journal_items'], $_POST['quick'], input_num('totamount'), QE_JOURNAL, get_post('aux_info'));
514         $_POST['totamount'] = price_format(0); $Ajax->activate('totamount');
515         line_start_focus();
516 }
517
518 if (list_updated('tax_category'))
519 {
520         $Ajax->activate('tabs');
521 }
522
523 //-----------------------------------------------------------------------------------------------
524
525 start_form();
526
527 display_order_header($_SESSION['journal_items']);
528
529 tabbed_content_start('tabs', array(
530                 'gl' => array(_('&GL postings'), true),
531                 'tax' => array(_('&Tax register'), check_value('taxable_trans')),
532         ));
533         
534         switch (get_post('_tabs_sel')) {
535                 default:
536                 case 'gl':
537                         start_table(TABLESTYLE2, "width='90%'", 10);
538                         start_row();
539                         echo "<td>";
540                         display_gl_items(_("Rows"), $_SESSION['journal_items']);
541                         gl_options_controls();
542                         echo "</td>";
543                         end_row();
544                         end_table(1);
545                         break;
546
547                 case 'tax':
548                         update_tax_info();
549                         display_heading(_("Tax register record"));
550                         start_table(TABLESTYLE2, "width=40%");
551                         date_row(_("VAT date:"), 'tax_date', '', "colspan='3'");
552                         tax_groups_list_row(_("Tax group:"), 'tax_group');
553                         end_table(1);
554
555                         start_table(TABLESTYLE2, "width=60%");
556                         table_header(array(_('Name'), _('Input Tax'), _('Output Tax'), _('Net amount')));
557                         $taxes = get_all_tax_types();
558                         while ($tax = db_fetch($taxes))
559                         {
560                                 start_row();
561                                 label_cell($tax['name'].' '.$tax['rate'].'%');
562                                 amount_cell(input_num('tax_in_'.$tax['id']));
563                                 amount_cell(input_num('tax_out_'.$tax['id']));
564
565                                 amount_cells(null, 'net_amount_'.$tax['id']);
566                                 end_row();
567                         }
568                         end_table(1);
569                         break;
570         };
571         submit_center('Process', _("Process Journal Entry"), true , 
572                 _('Process journal entry only if debits equal to credits'), 'default');
573 br();
574 tabbed_content_end();
575
576 end_form();
577
578 end_page();