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