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