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