Drafts: Ausgelagert in Controller(2)
[kivitendo-erp.git] / bin / mozilla / gl.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
29 #
30 # Genereal Ledger
31 #
32 #======================================================================
33
34 use utf8;
35 use strict;
36
37 use POSIX qw(strftime);
38 use List::Util qw(sum);
39
40 use SL::FU;
41 use SL::GL;
42 use SL::IS;
43 use SL::PE;
44 use SL::ReportGenerator;
45 use SL::DBUtils qw(selectrow_query);
46
47 require "bin/mozilla/common.pl";
48 require "bin/mozilla/drafts.pl";
49 require "bin/mozilla/reportgenerator.pl";
50
51 # this is for our long dates
52 # $locale->text('January')
53 # $locale->text('February')
54 # $locale->text('March')
55 # $locale->text('April')
56 # $locale->text('May ')
57 # $locale->text('June')
58 # $locale->text('July')
59 # $locale->text('August')
60 # $locale->text('September')
61 # $locale->text('October')
62 # $locale->text('November')
63 # $locale->text('December')
64
65 # this is for our short month
66 # $locale->text('Jan')
67 # $locale->text('Feb')
68 # $locale->text('Mar')
69 # $locale->text('Apr')
70 # $locale->text('May')
71 # $locale->text('Jun')
72 # $locale->text('Jul')
73 # $locale->text('Aug')
74 # $locale->text('Sep')
75 # $locale->text('Oct')
76 # $locale->text('Nov')
77 # $locale->text('Dec')
78
79 sub add {
80   $main::lxdebug->enter_sub();
81
82   $main::auth->assert('general_ledger');
83
84   my $form     = $main::form;
85   my %myconfig = %main::myconfig;
86
87   return $main::lxdebug->leave_sub() if (load_draft_maybe());
88
89   $form->{title} = "Add";
90
91   $form->{callback} = "gl.pl?action=add" unless $form->{callback};
92
93   # we use this only to set a default date
94   # yep. aber er holt hier auch schon ALL_CHARTS. Aufwand / Nutzen? jb
95   GL->transaction(\%myconfig, \%$form);
96
97   $form->{rowcount}  = 2;
98
99   $form->{debit}  = 0;
100   $form->{credit} = 0;
101   $form->{tax}    = 0;
102
103   # departments
104   $form->all_departments(\%myconfig);
105   if (@{ $form->{all_departments} || [] }) {
106     $form->{selectdepartment} = "<option>\n";
107
108     map {
109       $form->{selectdepartment} .=
110         "<option>$_->{description}--$_->{id}\n"
111     } (@{ $form->{all_departments} || [] });
112   }
113
114   $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
115
116   &display_form(1);
117   $main::lxdebug->leave_sub();
118
119 }
120
121 sub prepare_transaction {
122   $main::lxdebug->enter_sub();
123
124   $main::auth->assert('general_ledger');
125
126   my $form     = $main::form;
127   my %myconfig = %main::myconfig;
128
129   GL->transaction(\%myconfig, \%$form);
130
131   $form->{amount} = $form->format_amount(\%myconfig, $form->{amount}, 2);
132
133   # departments
134   $form->all_departments(\%myconfig);
135   if (@{ $form->{all_departments} || [] }) {
136     $form->{selectdepartment} = "<option>\n";
137
138     map {
139       $form->{selectdepartment} .=
140         "<option>$_->{description}--$_->{id}\n"
141     } (@{ $form->{all_departments} || [] });
142   }
143
144   my $i        = 1;
145   my $tax      = 0;
146   my $taxaccno = "";
147   foreach my $ref (@{ $form->{GL} }) {
148     my $j = $i - 1;
149     if ($tax && ($ref->{accno} eq $taxaccno)) {
150       $form->{"tax_$j"}      = abs($ref->{amount});
151       $form->{"taxchart_$j"} = $ref->{id} . "--" . $ref->{taxrate};
152       if ($form->{taxincluded}) {
153         if ($ref->{amount} < 0) {
154           $form->{"debit_$j"} += $form->{"tax_$j"};
155         } else {
156           $form->{"credit_$j"} += $form->{"tax_$j"};
157         }
158       }
159       $form->{"project_id_$j"} = $ref->{project_id};
160
161     } else {
162       $form->{"accno_$i"} = "$ref->{accno}--$ref->{tax_id}";
163       for (qw(fx_transaction source memo)) { $form->{"${_}_$i"} = $ref->{$_} }
164       if ($ref->{amount} < 0) {
165         $form->{totaldebit} -= $ref->{amount};
166         $form->{"debit_$i"} = $ref->{amount} * -1;
167       } else {
168         $form->{totalcredit} += $ref->{amount};
169         $form->{"credit_$i"} = $ref->{amount};
170       }
171       $form->{"taxchart_$i"} = "0--0.00";
172       $form->{"project_id_$i"} = $ref->{project_id};
173       $i++;
174     }
175     if ($ref->{taxaccno} && !$tax) {
176       $taxaccno = $ref->{taxaccno};
177       $tax      = 1;
178     } else {
179       $taxaccno = "";
180       $tax      = 0;
181     }
182   }
183
184   $form->{rowcount} = $i;
185   $form->{locked}   =
186     ($form->datetonum($form->{transdate}, \%myconfig) <=
187      $form->datetonum($form->{closedto}, \%myconfig));
188
189   $main::lxdebug->leave_sub();
190 }
191
192 sub edit {
193   $main::lxdebug->enter_sub();
194
195   $main::auth->assert('general_ledger');
196
197   my $form     = $main::form;
198   my %myconfig = %main::myconfig;
199
200   prepare_transaction();
201
202   $form->{title} = "Edit";
203
204   $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
205
206   form_header();
207   display_rows();
208   form_footer();
209
210   $main::lxdebug->leave_sub();
211 }
212
213
214 sub search {
215   $::lxdebug->enter_sub;
216   $::auth->assert('general_ledger');
217
218   $::form->all_departments(\%::myconfig);
219   $::form->get_lists(
220     projects  => { key => "ALL_PROJECTS", all => 1 },
221   );
222   $::form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
223
224   $::form->header;
225   print $::form->parse_html_template('gl/search', {
226     department_label => sub { ("$_[0]{description}--$_[0]{id}")x2 },
227     employee_label => sub { "$_[0]{id}--$_[0]{name}" },
228   });
229
230   $::lxdebug->leave_sub;
231 }
232
233 sub create_subtotal_row {
234   $main::lxdebug->enter_sub();
235
236   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
237
238   my $form     = $main::form;
239   my %myconfig = %main::myconfig;
240
241   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
242
243   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
244
245   map { $totals->{$_} = 0 } @{ $subtotal_columns };
246
247   $main::lxdebug->leave_sub();
248
249   return $row;
250 }
251
252 sub generate_report {
253   $main::lxdebug->enter_sub();
254
255   $main::auth->assert('general_ledger');
256
257   my $form     = $main::form;
258   my %myconfig = %main::myconfig;
259   my $locale   = $main::locale;
260
261   # generate_report wird beim ersten Aufruf per Weiter-Knopf und POST mit der hidden Variablen sort mit Wert "datesort" (früher "transdate" als Defaultsortiervariable) Ã¼bertragen
262
263   # <form method=post action=gl.pl>
264   # <input type=hidden name=sort value=datesort>    # form->{sort} setzen
265   # <input type=hidden name=nextsub value=generate_report>
266
267   # anhand von neuer Variable datesort wird jetzt $form->{sort} auf transdate oder gldate gesetzt
268   # damit ist die Hidden Variable "sort" wahrscheinlich sogar Ã¼berflüssig
269
270   # Ã¤ndert man die Sortierreihenfolge per Klick auf eine der Ãœberschriften wird die Variable "sort" per GET Ã¼bergeben, z.B. id,transdate, gldate, ...
271   # gl.pl?action=generate_report&employee=18383--Jan%20B%c3%bcren&datesort=transdate&category=X&l_transdate=Y&l_gldate=Y&l_id=Y&l_reference=Y&l_description=Y&l_source=Y&l_debit=Y&l_credit=Y&sort=gldate&sortdir=0
272
273   if ( $form->{sort} eq 'datesort' ) {   # sollte bei einem Post (Aufruf aus Suchmaske) immer wahr sein
274       # je nachdem ob in Suchmaske "transdate" oder "gldate" ausgesucht wurde erstes Suchergebnis entsprechend sortieren
275       $form->{sort} = $form->{datesort};
276   };
277
278   # was passiert hier?
279   report_generator_set_default_sort("$form->{datesort}", 1);
280 #  report_generator_set_default_sort('transdate', 1);
281
282   GL->all_transactions(\%myconfig, \%$form);
283
284   my %acctype = ('A' => $locale->text('Asset'),
285                  'C' => $locale->text('Contra'),
286                  'L' => $locale->text('Liability'),
287                  'Q' => $locale->text('Equity'),
288                  'I' => $locale->text('Revenue'),
289                  'E' => $locale->text('Expense'),);
290
291   $form->{title} = $locale->text('Journal');
292   if ($form->{category} ne 'X') {
293     $form->{title} .= " : " . $locale->text($acctype{ $form->{category} });
294   }
295
296   $form->{landscape} = 1;
297
298   my $ml = ($form->{ml} =~ /(A|E|Q)/) ? -1 : 1;
299
300   my @columns = qw(
301     gldate         transdate        id             reference      description
302     notes          source           debit          debit_accno
303     credit         credit_accno     debit_tax      debit_tax_accno
304     credit_tax     credit_tax_accno projectnumbers balance employee
305   );
306
307   # add employee here, so that variable is still known and passed in url when choosing a different sort order in resulting table
308   my @hidden_variables = qw(accno source reference department description notes project_id datefrom dateto employee_id datesort category l_subtotal);
309   push @hidden_variables, map { "l_${_}" } @columns;
310
311   my $employee = $form->{employee_id} ? SL::DB::Employee->new(id => $form->{employee_id})->load->name : '';
312
313   my (@options, @date_options);
314   push @options,      $locale->text('Account')     . " : $form->{accno} $form->{account_description}" if ($form->{accno});
315   push @options,      $locale->text('Source')      . " : $form->{source}"                             if ($form->{source});
316   push @options,      $locale->text('Reference')   . " : $form->{reference}"                          if ($form->{reference});
317   push @options,      $locale->text('Description') . " : $form->{description}"                        if ($form->{description});
318   push @options,      $locale->text('Notes')       . " : $form->{notes}"                              if ($form->{notes});
319   push @options,      $locale->text('Employee')    . " : $employee"                                   if $employee;
320   my $datesorttext = $form->{datesort} eq 'transdate' ? $locale->text('Invoice Date') :  $locale->text('Booking Date');
321   push @date_options,      "$datesorttext"                              if ($form->{datesort} and ($form->{datefrom} or $form->{dateto}));
322   push @date_options, $locale->text('From'), $locale->date(\%myconfig, $form->{datefrom}, 1)          if ($form->{datefrom});
323   push @date_options, $locale->text('Bis'),  $locale->date(\%myconfig, $form->{dateto},   1)          if ($form->{dateto});
324   push @options,      join(' ', @date_options)                                                        if (scalar @date_options);
325
326   if ($form->{department}) {
327     my ($department) = split /--/, $form->{department};
328     push @options, $locale->text('Department') . " : $department";
329   }
330
331
332   my $callback = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
333
334   $form->{l_credit_accno}     = 'Y';
335   $form->{l_debit_accno}      = 'Y';
336   $form->{l_credit_tax}       = 'Y';
337   $form->{l_debit_tax}        = 'Y';
338 #  $form->{l_gldate}           = 'Y';  # Spalte mit gldate immer anzeigen
339   $form->{l_credit_tax_accno} = 'Y';
340   $form->{l_datesort} = 'Y';
341   $form->{l_debit_tax_accno}  = 'Y';
342   $form->{l_balance}          = $form->{accno} ? 'Y' : '';
343
344   my %column_defs = (
345     'id'               => { 'text' => $locale->text('ID'), },
346     'transdate'        => { 'text' => $locale->text('Invoice Date'), },
347     'gldate'           => { 'text' => $locale->text('Booking Date'), },
348     'reference'        => { 'text' => $locale->text('Reference'), },
349     'source'           => { 'text' => $locale->text('Source'), },
350     'description'      => { 'text' => $locale->text('Description'), },
351     'notes'            => { 'text' => $locale->text('Notes'), },
352     'debit'            => { 'text' => $locale->text('Debit'), },
353     'debit_accno'      => { 'text' => $locale->text('Debit Account'), },
354     'credit'           => { 'text' => $locale->text('Credit'), },
355     'credit_accno'     => { 'text' => $locale->text('Credit Account'), },
356     'debit_tax'        => { 'text' => $locale->text('Debit Tax'), },
357     'debit_tax_accno'  => { 'text' => $locale->text('Debit Tax Account'), },
358     'credit_tax'       => { 'text' => $locale->text('Credit Tax'), },
359     'credit_tax_accno' => { 'text' => $locale->text('Credit Tax Account'), },
360     'balance'          => { 'text' => $locale->text('Balance'), },
361     'projectnumbers'   => { 'text' => $locale->text('Project Numbers'), },
362     'employee'         => { 'text' => $locale->text('Employee'), },
363   );
364
365   foreach my $name (qw(id transdate gldate reference description debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
366     my $sortname                = $name =~ m/accno/ ? 'accno' : $name;
367     my $sortdir                 = $sortname eq $form->{sort} ? 1 - $form->{sortdir} : $form->{sortdir};
368     $column_defs{$name}->{link} = $callback . "&sort=$sortname&sortdir=$sortdir";
369   }
370
371   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
372   map { $column_defs{$_}->{visible} = 0 } qw(debit_accno credit_accno debit_tax_accno credit_tax_accno) if $form->{accno};
373
374   my %column_alignment;
375   map { $column_alignment{$_}     = 'right'  } qw(balance id debit credit debit_tax credit_tax balance);
376   map { $column_alignment{$_}     = 'center' } qw(transdate gldate reference debit_accno credit_accno debit_tax_accno credit_tax_accno);
377   map { $column_alignment{$_}     = 'left' } qw(description source notes);
378   map { $column_defs{$_}->{align} = $column_alignment{$_} } keys %column_alignment;
379
380   my $report = SL::ReportGenerator->new(\%myconfig, $form);
381
382   $report->set_columns(%column_defs);
383   $report->set_column_order(@columns);
384
385   $report->set_export_options('generate_report', @hidden_variables, qw(sort sortdir));
386
387   $report->set_sort_indicator($form->{sort} eq 'accno' ? 'debit_accno' : $form->{sort}, $form->{sortdir});
388
389   $report->set_options('top_info_text'        => join("\n", @options),
390                        'output_format'        => 'HTML',
391                        'title'                => $form->{title},
392                        'attachment_basename'  => $locale->text('general_ledger_list') . strftime('_%Y%m%d', localtime time),
393     );
394   $report->set_options_from_form();
395   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
396
397   # add sort to callback
398   $form->{callback} = "$callback&sort=" . E($form->{sort}) . "&sortdir=" . E($form->{sortdir});
399
400
401   my @totals_columns = qw(debit credit debit_tax credit_tax);
402   my %subtotals      = map { $_ => 0 } @totals_columns;
403   my %totals         = map { $_ => 0 } @totals_columns;
404   my $idx            = 0;
405
406   foreach my $ref (@{ $form->{GL} }) {
407
408     my %rows;
409
410     foreach my $key (qw(debit credit debit_tax credit_tax)) {
411       $rows{$key} = [];
412       foreach my $idx (sort keys(%{ $ref->{$key} })) {
413         my $value         = $ref->{$key}->{$idx};
414         $subtotals{$key} += $value;
415         $totals{$key}    += $value;
416         if ($key =~ /debit.*/) {
417           $ml = -1;
418         } else {
419           $ml = 1;
420         }
421         $form->{balance}  = $form->{balance} + $value * $ml;
422         push @{ $rows{$key} }, $form->format_amount(\%myconfig, $value, 2);
423       }
424     }
425
426     foreach my $key (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno ac_transdate source)) {
427       my $col = $key eq 'ac_transdate' ? 'transdate' : $key;
428       $rows{$col} = [ map { $ref->{$key}->{$_} } sort keys(%{ $ref->{$key} }) ];
429     }
430
431     my $row = { };
432     map { $row->{$_} = { 'data' => '', 'align' => $column_alignment{$_} } } @columns;
433
434     my $sh = "";
435     if ($form->{balance} < 0) {
436       $sh = " S";
437       $ml = -1;
438     } elsif ($form->{balance} > 0) {
439       $sh = " H";
440       $ml = 1;
441     }
442     my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
443     $data .= $sh;
444
445     $row->{balance}->{data}        = $data;
446     $row->{projectnumbers}->{data} = join ", ", sort { lc($a) cmp lc($b) } keys %{ $ref->{projectnumbers} };
447
448     map { $row->{$_}->{data} = $ref->{$_} } qw(id reference description notes gldate employee);
449
450     map { $row->{$_}->{data} = \@{ $rows{$_} }; } qw(transdate debit credit debit_accno credit_accno debit_tax_accno credit_tax_accno source);
451
452     foreach my $col (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
453       $row->{$col}->{link} = [ map { "${callback}&accno=" . E($_) } @{ $rows{$col} } ];
454     }
455
456     map { $row->{$_}->{data} = \@{ $rows{$_} } if ($ref->{"${_}_accno"} ne "") } qw(debit_tax credit_tax);
457
458     $row->{reference}->{link} = build_std_url("script=$ref->{module}.pl", 'action=edit', 'id=' . E($ref->{id}), 'callback');
459
460     my $row_set = [ $row ];
461
462     if ( ($form->{l_subtotal} eq 'Y' && !$form->{report_generator_csv_options_for_import} )
463         && (($idx == (scalar @{ $form->{GL} } - 1))
464             || ($ref->{ $form->{sort} } ne $form->{GL}->[$idx + 1]->{ $form->{sort} }))) {
465       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, [ qw(debit credit) ], 'listsubtotal');
466     }
467
468     $report->add_data($row_set);
469
470     $idx++;
471   }
472
473   # = 0 for balanced ledger
474   my $balanced_ledger = $totals{debit} + $totals{debit_tax} - $totals{credit} - $totals{credit_tax};
475
476   my $row = create_subtotal_row(\%totals, \@columns, \%column_alignment, [ qw(debit credit debit_tax credit_tax) ], 'listtotal');
477
478   my $sh = "";
479   if ($form->{balance} < 0) {
480     $sh = " S";
481     $ml = -1;
482   } elsif ($form->{balance} > 0) {
483     $sh = " H";
484     $ml = 1;
485   }
486   my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
487   $data .= $sh;
488
489   $row->{balance}->{data}        = $data;
490
491   if ( !$form->{report_generator_csv_options_for_import} ) {
492     $report->add_separator();
493     $report->add_data($row);
494   }
495
496   my $raw_bottom_info_text;
497
498   if (!$form->{accno} && (abs($balanced_ledger) >  0.001)) {
499     $raw_bottom_info_text .=
500         '<p><span class="unbalanced_ledger">'
501       . $locale->text('Unbalanced Ledger')
502       . ': '
503       . $form->format_amount(\%myconfig, $balanced_ledger, 3)
504       . '</span></p> ';
505   }
506
507   $raw_bottom_info_text .= $form->parse_html_template('gl/generate_report_bottom');
508
509   $report->set_options('raw_bottom_info_text' => $raw_bottom_info_text);
510
511   $report->generate_with_headers();
512
513   $main::lxdebug->leave_sub();
514 }
515
516 sub update {
517   $main::lxdebug->enter_sub();
518
519   $main::auth->assert('general_ledger');
520
521   my $form     = $main::form;
522   my %myconfig = %main::myconfig;
523
524   $form->{oldtransdate} = $form->{transdate};
525
526   my @a           = ();
527   my $count       = 0;
528   my $debittax    = 0;
529   my $credittax   = 0;
530   my $debitcount  = 0;
531   my $creditcount = 0;
532   my ($debitcredit, $amount);
533
534   my @flds =
535     qw(accno debit credit projectnumber fx_transaction source memo tax taxchart);
536
537   for my $i (1 .. $form->{rowcount}) {
538
539     unless (($form->{"debit_$i"} eq "") && ($form->{"credit_$i"} eq "")) {
540       for (qw(debit credit tax)) {
541         $form->{"${_}_$i"} =
542           $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
543       }
544
545       push @a, {};
546       $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
547       if ($debitcredit) {
548         $debitcount++;
549       } else {
550         $creditcount++;
551       }
552
553       if (($debitcount >= 2) && ($creditcount == 2)) {
554         $form->{"credit_$i"} = 0;
555         $form->{"tax_$i"}    = 0;
556         $creditcount--;
557         $form->{creditlock} = 1;
558       }
559       if (($creditcount >= 2) && ($debitcount == 2)) {
560         $form->{"debit_$i"} = 0;
561         $form->{"tax_$i"}   = 0;
562         $debitcount--;
563         $form->{debitlock} = 1;
564       }
565       if (($creditcount == 1) && ($debitcount == 2)) {
566         $form->{creditlock} = 1;
567       }
568       if (($creditcount == 2) && ($debitcount == 1)) {
569         $form->{debitlock} = 1;
570       }
571       if ($debitcredit && $credittax) {
572         $form->{"taxchart_$i"} = "0--0.00";
573       }
574       if (!$debitcredit && $debittax) {
575         $form->{"taxchart_$i"} = "0--0.00";
576       }
577       $amount =
578         ($form->{"debit_$i"} == 0)
579         ? $form->{"credit_$i"}
580         : $form->{"debit_$i"};
581       my $j = $#a;
582       if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
583         $form->{"taxchart_$i"} = "0--0.00";
584         $form->{"tax_$i"}      = 0;
585       }
586       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
587       if ($taxkey > 1) {
588         if ($debitcredit) {
589           $debittax = 1;
590         } else {
591           $credittax = 1;
592         }
593       };
594       my ($tmpnetamount,$tmpdiff);
595       ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
596
597       for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
598       $count++;
599     }
600   }
601
602   for my $i (1 .. $count) {
603     my $j = $i - 1;
604     for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
605   }
606
607   for my $i ($count + 1 .. $form->{rowcount}) {
608     for (@flds) { delete $form->{"${_}_$i"} }
609   }
610
611   $form->{rowcount} = $count + 1;
612
613   &display_form;
614   $main::lxdebug->leave_sub();
615
616 }
617
618 sub display_form {
619   my ($init) = @_;
620   $main::lxdebug->enter_sub();
621
622   $main::auth->assert('general_ledger');
623
624   my $form     = $main::form;
625   my %myconfig = %main::myconfig;
626
627   &form_header($init);
628
629   #   for $i (1 .. $form->{rowcount}) {
630   #     $form->{totaldebit} += $form->parse_amount(\%myconfig, $form->{"debit_$i"});
631   #     $form->{totalcredit} += $form->parse_amount(\%myconfig, $form->{"credit_$i"});
632   #
633   #     &form_row($i);
634   #   }
635   &display_rows($init);
636   &form_footer;
637   $main::lxdebug->leave_sub();
638
639 }
640
641 sub display_rows {
642   my ($init) = @_;
643   $main::lxdebug->enter_sub();
644
645   $main::auth->assert('general_ledger');
646
647   my $form     = $main::form;
648   my %myconfig = %main::myconfig;
649   my $cgi      = $::request->{cgi};
650
651   $form->{debit_1}     = 0 if !$form->{"debit_1"};
652   $form->{totaldebit}  = 0;
653   $form->{totalcredit} = 0;
654
655   my %project_labels = ();
656   my @project_values = ("");
657   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
658     push(@project_values, $item->{"id"});
659     $project_labels{$item->{"id"}} = $item->{"projectnumber"};
660   }
661
662   my %chart_labels = ();
663   my @chart_values = ();
664   my %charts = ();
665   my $taxchart_init;
666   foreach my $item (@{ $form->{ALL_CHARTS} }) {
667     if ($item->{charttype} eq 'H'){ #falls ÃƒÅ’berschrift
668       next;                         #ÃŒberspringen (Bug 1150)
669     }
670     my $key = $item->{accno} . "--" . $item->{tax_id};
671     $taxchart_init = $item->{tax_id} unless (@chart_values);
672     push(@chart_values, $key);
673     $chart_labels{$key} = $item->{accno} . "--" . $item->{description};
674     $charts{$item->{accno}} = $item;
675   }
676
677   my ($source, $memo, $source_hidden, $memo_hidden);
678   for my $i (1 .. $form->{rowcount}) {
679     if ($form->{show_details}) {
680       $source = qq|
681       <td><input name="source_$i" value="$form->{"source_$i"}" size="16"></td>|;
682       $memo = qq|
683       <td><input name="memo_$i" value="$form->{"memo_$i"}" size="16"></td>|;
684     } else {
685       $source_hidden = qq|
686       <input type="hidden" name="source_$i" value="$form->{"source_$i"}" size="16">|;
687       $memo_hidden = qq|
688       <input type="hidden" name="memo_$i" value="$form->{"memo_$i"}" size="16">|;
689     }
690
691     my $selected_accno_full;
692     my ($accno_row) = split(/--/, $form->{"accno_$i"});
693     my $item = $charts{$accno_row};
694     $selected_accno_full = "$item->{accno}--$item->{tax_id}";
695
696     my $selected_taxchart = $form->{"taxchart_$i"};
697     my ($selected_accno, $selected_tax_id) = split(/--/, $selected_accno_full);
698     my ($previous_accno, $previous_tax_id) = split(/--/, $form->{"previous_accno_$i"});
699
700     my %taxchart_labels = ();
701     my @taxchart_values = ();
702     my %taxcharts = ();
703     my $filter_accno;
704     $filter_accno = $::form->{ALL_CHARTS}[0]->{accno};
705     $filter_accno = $selected_accno if (!$init and $i < $form->{rowcount});
706     foreach my $item ( GL->get_tax_dropdown($filter_accno) ) {
707       my $key = $item->{id} . "--" . $item->{rate};
708       $taxchart_init = $key if ($taxchart_init == $item->{id});
709       push(@taxchart_values, $key);
710       $taxchart_labels{$key} = $item->{taxdescription} . " " . $item->{rate} * 100 . ' %';
711       $taxcharts{$item->{id}} = $item;
712     }
713
714     if ($previous_accno &&
715         ($previous_accno eq $selected_accno) &&
716         ($previous_tax_id ne $selected_tax_id)) {
717       my $item = $taxcharts{$selected_tax_id};
718       $selected_taxchart = "$item->{id}--$item->{rate}";
719     }
720
721     $selected_accno      = '' if ($init);
722     $selected_taxchart ||= $taxchart_init;
723
724     my $accno = qq|<td>| .
725       NTI($cgi->popup_menu('-name' => "accno_$i",
726                            '-id' => "accno_$i",
727                            '-onChange' => "updateTaxes($i);",
728                            '-style' => 'width:200px',
729                            '-values' => \@chart_values,
730                            '-labels' => \%chart_labels,
731                            '-default' => $selected_accno_full))
732       . $cgi->hidden('-name' => "previous_accno_$i",
733                      '-default' => $selected_accno_full)
734       . qq|</td>|;
735     my $tax_ddbox = qq|<td>| .
736       NTI($cgi->popup_menu('-name' => "taxchart_$i",
737             '-id' => "taxchart_$i",
738             '-style' => 'width:200px',
739             '-values' => \@taxchart_values,
740             '-labels' => \%taxchart_labels,
741             '-default' => $selected_taxchart))
742       . qq|</td>|;
743
744     my ($fx_transaction, $checked);
745     if ($init) {
746       if ($form->{transfer}) {
747         $fx_transaction = qq|
748         <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
749     |;
750       }
751
752     } else {
753       if ($form->{"debit_$i"} != 0) {
754         $form->{totaldebit} += $form->{"debit_$i"};
755         if (!$form->{taxincluded}) {
756           $form->{totaldebit} += $form->{"tax_$i"};
757         }
758       } else {
759         $form->{totalcredit} += $form->{"credit_$i"};
760         if (!$form->{taxincluded}) {
761           $form->{totalcredit} += $form->{"tax_$i"};
762         }
763       }
764
765       for (qw(debit credit tax)) {
766         $form->{"${_}_$i"} =
767           ($form->{"${_}_$i"})
768           ? $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
769           : "";
770       }
771
772       if ($i < $form->{rowcount}) {
773         if ($form->{transfer}) {
774           $checked = ($form->{"fx_transaction_$i"}) ? "1" : "";
775           my $x = ($checked) ? "x" : "";
776           $fx_transaction = qq|
777       <td><input type=hidden name="fx_transaction_$i" value="$checked">$x</td>
778     |;
779         }
780         $form->hide_form("accno_$i");
781
782       } else {
783         if ($form->{transfer}) {
784           $fx_transaction = qq|
785       <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
786     |;
787         }
788       }
789     }
790     my $debitreadonly  = "";
791     my $creditreadonly = "";
792     if ($i == $form->{rowcount}) {
793       if ($form->{debitlock}) {
794         $debitreadonly = "readonly";
795       } elsif ($form->{creditlock}) {
796         $creditreadonly = "readonly";
797       }
798     }
799
800     my $projectnumber =
801       NTI($cgi->popup_menu('-name' => "project_id_$i",
802                            '-values' => \@project_values,
803                            '-labels' => \%project_labels,
804                            '-default' => $form->{"project_id_$i"} ));
805     my $projectnumber_hidden = qq|
806     <input type="hidden" name="project_id_$i" value="$form->{"project_id_$i"}">|;
807
808     my $copy2credit = $i == 1 ? 'onkeyup="copy_debit_to_credit()"' : '';
809
810     print qq|<tr valign=top>
811     $accno
812     <td id="chart_balance_$i" align="right">&nbsp;</td>
813     $fx_transaction
814     <td><input name="debit_$i" size="8" value="$form->{"debit_$i"}" accesskey=$i $copy2credit $debitreadonly></td>
815     <td><input name="credit_$i" size=8 value="$form->{"credit_$i"}" $creditreadonly></td>
816     <td><input type="hidden" name="tax_$i" value="$form->{"tax_$i"}">$form->{"tax_$i"}</td>
817     $tax_ddbox|;
818
819     if ($form->{show_details}) {
820       print qq|
821     $source
822     $memo
823     <td>$projectnumber</td>
824 |;
825     } else {
826     print qq|
827     $source_hidden
828     $memo_hidden
829     $projectnumber_hidden
830     |;
831     }
832     print qq|
833   </tr>
834 |;
835   }
836
837   $form->hide_form(qw(rowcount selectaccno));
838
839   $main::lxdebug->leave_sub();
840
841 }
842
843 sub _get_radieren {
844   return ($::instance_conf->get_gl_changeable == 2) ? ($::form->current_date(\%::myconfig) eq $::form->{gldate}) : ($::instance_conf->get_gl_changeable == 1);
845 }
846
847 sub form_header {
848   $::lxdebug->enter_sub;
849   $::auth->assert('general_ledger');
850
851   my ($init) = @_;
852
853   my @old_project_ids = grep { $_ } map{ $::form->{"project_id_$_"} } 1..$::form->{rowcount};
854
855   $::form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
856                                     "all"       => 0,
857                                     "old_id"    => \@old_project_ids },
858                    "charts"    => { "key"       => "ALL_CHARTS",
859                                     "transdate" => $::form->{transdate} });
860
861   GL->get_chart_balances('charts' => $::form->{ALL_CHARTS});
862
863   my $title      = $::form->{title};
864   $::form->{title} = $::locale->text("$title General Ledger Transaction");
865   # $locale->text('Add General Ledger Transaction')
866   # $locale->text('Edit General Ledger Transaction')
867
868   map { $::form->{$_} =~ s/\"/&quot;/g }
869     qw(chart taxchart);
870
871   $::form->{selectdepartment} =~ s/ selected//;
872   $::form->{selectdepartment} =~
873     s/option>\Q$::form->{department}\E/option selected>$::form->{department}/;
874
875   if ($init) {
876     $::request->{layout}->focus("#reference");
877     $::form->{taxincluded} = "1";
878   } else {
879     $::request->{layout}->focus("#accno_$::form->{rowcount}");
880   }
881
882   $::form->{previous_id}     ||= "--";
883   $::form->{previous_gldate} ||= "--";
884
885   $::form->header;
886   print $::form->parse_html_template('gl/form_header', {
887     hide_title => $title,
888     readonly   => $::form->{id} && ($::form->{locked} || !_get_radieren()),
889   });
890
891   $::lxdebug->leave_sub;
892
893 }
894
895 sub form_footer {
896   $::lxdebug->enter_sub;
897   $::auth->assert('general_ledger');
898
899   my ($follow_ups, $follow_ups_due);
900
901   if ($::form->{id}) {
902     $follow_ups     = FU->follow_ups('trans_id' => $::form->{id});
903     $follow_ups_due = sum map { $_->{due} * 1 } @{ $follow_ups || [] };
904   }
905
906   print $::form->parse_html_template('gl/form_footer', {
907     radieren       => _get_radieren(),
908     follow_ups     => $follow_ups,
909     follow_ups_due => $follow_ups_due,
910   });
911
912   $::lxdebug->leave_sub;
913 }
914
915 sub delete {
916   $main::lxdebug->enter_sub();
917
918   my $form     = $main::form;
919   my $locale   = $main::locale;
920
921   $form->header;
922
923   print qq|
924 <form method=post action=gl.pl>
925 |;
926
927   map { $form->{$_} =~ s/\"/&quot;/g } qw(reference description);
928
929   delete $form->{header};
930
931   foreach my $key (keys %$form) {
932     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
933     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
934   }
935
936   print qq|
937 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
938
939 <h4>|
940     . $locale->text('Are you sure you want to delete Transaction')
941     . qq| $form->{reference}</h4>
942
943 <input name=action class=submit type=submit value="|
944     . $locale->text('Yes') . qq|">
945 </form>
946 |;
947   $main::lxdebug->leave_sub();
948
949 }
950
951 sub yes {
952   $main::lxdebug->enter_sub();
953
954   my $form     = $main::form;
955   my %myconfig = %main::myconfig;
956   my $locale   = $main::locale;
957
958   if (GL->delete_transaction(\%myconfig, \%$form)){
959     # saving the history
960       if(!exists $form->{addition} && $form->{id} ne "") {
961         $form->{snumbers} = qq|gltransaction_| . $form->{id};
962         $form->{addition} = "DELETED";
963         $form->{what_done} = "gl_transaction";
964         $form->save_history;
965       }
966     # /saving the history
967     $form->redirect($locale->text('Transaction deleted!'))
968   }
969   $form->error($locale->text('Cannot delete transaction!'));
970   $main::lxdebug->leave_sub();
971
972 }
973
974 sub post_transaction {
975   $main::lxdebug->enter_sub();
976
977   my $form     = $main::form;
978   my %myconfig = %main::myconfig;
979   my $locale   = $main::locale;
980
981   # check if there is something in reference and date
982   $form->isblank("reference",   $locale->text('Reference missing!'));
983   $form->isblank("transdate",   $locale->text('Transaction Date missing!'));
984   $form->isblank("description", $locale->text('Description missing!'));
985
986   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
987   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
988
989   my @a           = ();
990   my $count       = 0;
991   my $debittax    = 0;
992   my $credittax   = 0;
993   my $debitcount  = 0;
994   my $creditcount = 0;
995   my $debitcredit;
996   my %split_safety = ();
997
998   my $dbh = $form->dbconnect_noauto(\%myconfig);
999   my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
1000   $dbh->disconnect;
1001
1002   my @flds = qw(accno debit credit projectnumber fx_transaction source memo tax taxchart);
1003
1004   for my $i (1 .. $form->{rowcount}) {
1005     next if $form->{"debit_$i"} eq "" && $form->{"credit_$i"} eq "";
1006
1007     for (qw(debit credit tax)) {
1008       $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
1009     }
1010
1011     push @a, {};
1012     $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
1013
1014     $split_safety{   $form->{"debit_$i"}  <=> 0 }++;
1015     $split_safety{ - $form->{"credit_$i"} <=> 0 }++;
1016
1017     if ($debitcredit) {
1018       $debitcount++;
1019     } else {
1020       $creditcount++;
1021     }
1022
1023     if (($debitcount >= 2) && ($creditcount == 2)) {
1024       $form->{"credit_$i"} = 0;
1025       $form->{"tax_$i"}    = 0;
1026       $creditcount--;
1027       $form->{creditlock} = 1;
1028     }
1029     if (($creditcount >= 2) && ($debitcount == 2)) {
1030       $form->{"debit_$i"} = 0;
1031       $form->{"tax_$i"}   = 0;
1032       $debitcount--;
1033       $form->{debitlock} = 1;
1034     }
1035     if (($creditcount == 1) && ($debitcount == 2)) {
1036       $form->{creditlock} = 1;
1037     }
1038     if (($creditcount == 2) && ($debitcount == 1)) {
1039       $form->{debitlock} = 1;
1040     }
1041     if ($debitcredit && $credittax) {
1042       $form->{"taxchart_$i"} = "$notax_id--0.00";
1043     }
1044     if (!$debitcredit && $debittax) {
1045       $form->{"taxchart_$i"} = "$notax_id--0.00";
1046     }
1047     my $amount = ($form->{"debit_$i"} == 0)
1048             ? $form->{"credit_$i"}
1049             : $form->{"debit_$i"};
1050     my $j = $#a;
1051     if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
1052       $form->{"taxchart_$i"} = "$notax_id--0.00";
1053       $form->{"tax_$i"}      = 0;
1054     }
1055     my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
1056     if ($taxkey > 1) {
1057       if ($debitcredit) {
1058         $debittax = 1;
1059       } else {
1060         $credittax = 1;
1061       }
1062
1063       my ($tmpnetamount,$tmpdiff);
1064       ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
1065       if ($debitcredit) {
1066         $form->{"debit_$i"} = $tmpnetamount;
1067       } else {
1068         $form->{"credit_$i"} = $tmpnetamount;
1069       }
1070
1071     } else {
1072       $form->{"tax_$i"} = 0;
1073     }
1074
1075     for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
1076     $count++;
1077   }
1078
1079   if ($split_safety{-1} > 1 && $split_safety{1} > 1) {
1080     $::form->error($::locale->text("Split entry detected. The values you have entered will result in an entry with more than one position on both debit and credit. " .
1081                                    "Due to known problems involving accounting software kivitendo does not allow these."));
1082   }
1083
1084   for my $i (1 .. $count) {
1085     my $j = $i - 1;
1086     for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
1087   }
1088
1089   for my $i ($count + 1 .. $form->{rowcount}) {
1090     for (@flds) { delete $form->{"${_}_$i"} }
1091   }
1092
1093   my ($debit, $credit, $taxtotal);
1094   for my $i (1 .. $form->{rowcount}) {
1095     my $dr  = $form->{"debit_$i"};
1096     my $cr  = $form->{"credit_$i"};
1097     my $tax = $form->{"tax_$i"};
1098     if ($dr && $cr) {
1099       $form->error($locale->text('Cannot post transaction with a debit and credit entry for the same account!'));
1100     }
1101     $debit    += $dr + $tax if $dr;
1102     $credit   += $cr + $tax if $cr;
1103     $taxtotal += $tax if $form->{taxincluded}
1104   }
1105
1106   $form->{taxincluded} = 0 if !$taxtotal;
1107
1108   # this is just for the wise guys
1109
1110   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1111     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
1112   $form->error($locale->text('Cannot post transaction for a closed period!'))
1113     if ($form->date_closed($form->{"transdate"}, \%myconfig));
1114   if ($form->round_amount($debit, 2) != $form->round_amount($credit, 2)) {
1115     $form->error($locale->text('Out of balance transaction!'));
1116   }
1117
1118   if ($form->round_amount($debit, 2) + $form->round_amount($credit, 2) == 0) {
1119     $form->error($locale->text('Empty transaction!'));
1120   }
1121
1122   if ((my $errno = GL->post_transaction(\%myconfig, \%$form)) <= -1) {
1123     $errno *= -1;
1124     my @err;
1125     $err[1] = $locale->text('Cannot have a value in both Debit and Credit!');
1126     $err[2] = $locale->text('Debit and credit out of balance!');
1127     $err[3] = $locale->text('Cannot post a transaction without a value!');
1128
1129     $form->error($err[$errno]);
1130   }
1131   undef($form->{callback});
1132   # saving the history
1133   if(!exists $form->{addition} && $form->{id} ne "") {
1134     $form->{snumbers} = qq|gltransaction_| . $form->{id};
1135     $form->{addition} = "POSTED";
1136     $form->{what_done} = "gl transaction";
1137     $form->save_history;
1138   }
1139   # /saving the history
1140
1141   $main::lxdebug->leave_sub();
1142 }
1143
1144 sub post {
1145   $main::lxdebug->enter_sub();
1146
1147   $main::auth->assert('general_ledger');
1148
1149   my $form     = $main::form;
1150   my $locale   = $main::locale;
1151
1152   if ($::myconfig{mandatory_departments} && !$form->{department}) {
1153     $form->{saved_message} = $::locale->text('You have to specify a department.');
1154     update();
1155     exit;
1156   }
1157
1158   $form->{title}  = $locale->text("$form->{title} General Ledger Transaction");
1159   $form->{storno} = 0;
1160
1161   post_transaction();
1162
1163   $form->{callback} = build_std_url("action=add&DONT_LOAD_DRAFT=1", "show_details");
1164   $form->redirect($form->{callback});
1165
1166   $main::lxdebug->leave_sub();
1167 }
1168
1169 sub post_as_new {
1170   $main::lxdebug->enter_sub();
1171
1172   $main::auth->assert('general_ledger');
1173
1174   my $form     = $main::form;
1175
1176   $form->{id} = 0;
1177   &add;
1178   $main::lxdebug->leave_sub();
1179
1180 }
1181
1182 sub storno {
1183   $main::lxdebug->enter_sub();
1184
1185   $main::auth->assert('general_ledger');
1186
1187   my $form     = $main::form;
1188   my %myconfig = %main::myconfig;
1189   my $locale   = $main::locale;
1190
1191   # don't cancel cancelled transactions
1192   if (IS->has_storno(\%myconfig, $form, 'gl')) {
1193     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1194     $form->error($locale->text("Transaction has already been cancelled!"));
1195   }
1196
1197   GL->storno($form, \%myconfig, $form->{id});
1198
1199   # saving the history
1200   if(!exists $form->{addition} && $form->{id} ne "") {
1201     $form->{snumbers} = qq|gltransaction_| . $form->{id};
1202     $form->{addition} = "STORNO";
1203     $form->{what_done} = "gl_transaction";
1204     $form->save_history;
1205   }
1206   # /saving the history
1207
1208   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1209
1210   $main::lxdebug->leave_sub();
1211 }
1212
1213 sub continue {
1214   call_sub($main::form->{nextsub});
1215 }
1216
1217 sub get_tax_dropdown {
1218   $main::lxdebug->enter_sub();
1219
1220   my $form = $main::form;
1221   my @tax_accounts = GL->get_tax_dropdown($form->{accno});
1222
1223   foreach my $item (@tax_accounts) {
1224     $item->{taxdescription} = $::locale->{iconv_utf8}->convert($item->{taxdescription});
1225     $item->{taxdescription} .= ' ' . $form->round_amount($item->{rate} * 100);
1226   }
1227
1228   $form->{TAX_ACCOUNTS} = [ @tax_accounts ];
1229
1230   print $form->ajax_response_header, $form->parse_html_template("gl/update_tax_accounts");
1231
1232   $main::lxdebug->leave_sub();
1233
1234 }
1235
1236 1;