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