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