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