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