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