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