1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (c) 1998-2002
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  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.
 
  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,
 
  29 #======================================================================
 
  33 #======================================================================
 
  38 use POSIX qw(strftime);
 
  39 use List::Util qw(first sum);
 
  41 use SL::DB::RecordTemplate;
 
  42 use SL::DB::BankTransactionAccTrans;
 
  46 use SL::Helper::Flash qw(flash);
 
  48 use SL::ReportGenerator;
 
  49 use SL::DBUtils qw(selectrow_query selectall_hashref_query);
 
  51 use SL::Locale::String qw(t8);
 
  52 use SL::Helper::GlAttachments qw(count_gl_attachments);
 
  53 use SL::Presenter::Tag;
 
  54 use SL::Presenter::Chart;
 
  55 require "bin/mozilla/common.pl";
 
  56 require "bin/mozilla/reportgenerator.pl";
 
  58 # this is for our long dates
 
  59 # $locale->text('January')
 
  60 # $locale->text('February')
 
  61 # $locale->text('March')
 
  62 # $locale->text('April')
 
  63 # $locale->text('May ')
 
  64 # $locale->text('June')
 
  65 # $locale->text('July')
 
  66 # $locale->text('August')
 
  67 # $locale->text('September')
 
  68 # $locale->text('October')
 
  69 # $locale->text('November')
 
  70 # $locale->text('December')
 
  72 # this is for our short month
 
  73 # $locale->text('Jan')
 
  74 # $locale->text('Feb')
 
  75 # $locale->text('Mar')
 
  76 # $locale->text('Apr')
 
  77 # $locale->text('May')
 
  78 # $locale->text('Jun')
 
  79 # $locale->text('Jul')
 
  80 # $locale->text('Aug')
 
  81 # $locale->text('Sep')
 
  82 # $locale->text('Oct')
 
  83 # $locale->text('Nov')
 
  84 # $locale->text('Dec')
 
  86 sub load_record_template {
 
  87   $::auth->assert('gl_transactions');
 
  89   # Load existing template and verify that its one for this module.
 
  90   my $template = SL::DB::RecordTemplate
 
  91     ->new(id => $::form->{id})
 
  93       with_object => [ qw(customer payment currency record_items record_items.chart) ],
 
  96   die "invalid template type" unless $template->template_type eq 'gl_transaction';
 
  98   $template->substitute_variables;
 
  99   my $payment_suggestion =  $::form->{form_defaults}->{amount_1};
 
 101   # Clean the current $::form before rebuilding it from the template.
 
 102   my $form_defaults = delete $::form->{form_defaults};
 
 103   delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
 
 106   GL->transaction(\%::myconfig, $dummy_form);
 
 108   # Fill $::form from the template.
 
 109   my $today                   = DateTime->today_local;
 
 110   $::form->{title}            = "Add";
 
 111   $::form->{transdate}        = $today->to_kivitendo;
 
 112   $::form->{duedate}          = $today->to_kivitendo;
 
 113   $::form->{rowcount}         = @{ $template->items };
 
 114   $::form->{paidaccounts}     = 1;
 
 115   $::form->{$_}               = $template->$_     for qw(department_id taxincluded ob_transaction cb_transaction reference description show_details);
 
 116   $::form->{$_}               = $dummy_form->{$_} for qw(closedto revtrans previous_id previous_gldate);
 
 119   foreach my $item (@{ $template->items }) {
 
 122     my $active_taxkey = $item->chart->get_active_taxkey;
 
 123     my $taxes         = SL::DB::Manager::Tax->get_all(
 
 124       where   => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
 
 125       sort_by => 'taxkey, rate',
 
 128     my $tax   = first { $item->tax_id          == $_->id } @{ $taxes };
 
 129     $tax    //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
 
 130     $tax    //= $taxes->[0];
 
 137     $::form->{"accno_id_${row}"}          = $item->chart_id;
 
 138     $::form->{"previous_accno_id_${row}"} = $item->chart_id;
 
 139     $::form->{"debit_${row}"}             = $::form->format_amount(\%::myconfig, ($payment_suggestion ? $payment_suggestion : $item->amount1), 2) if $item->amount1 * 1;
 
 140     $::form->{"credit_${row}"}            = $::form->format_amount(\%::myconfig, ($payment_suggestion ? $payment_suggestion : $item->amount2), 2) if $item->amount2 * 1;
 
 141     $::form->{"taxchart_${row}"}          = $item->tax_id . '--' . $tax->rate;
 
 142     $::form->{"${_}_${row}"}              = $item->$_ for qw(source memo project_id);
 
 145   $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
 
 147   flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
 
 150     keep_rows_without_amount => 1,
 
 151     dont_add_new_row         => 1,
 
 155 sub save_record_template {
 
 156   $::auth->assert('gl_transactions');
 
 158   my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
 
 159   my $js       = SL::ClientJS->new(controller => SL::Controller::Base->new);
 
 160   my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
 
 162   $js->dialog->close('#record_template_dialog');
 
 165     $_->{chart_id} && (($_->{tax_id} // '') ne '')
 
 167     +{ chart_id   => $::form->{"accno_id_${_}"},
 
 168        amount1    => $::form->parse_amount(\%::myconfig, $::form->{"debit_${_}"}),
 
 169        amount2    => $::form->parse_amount(\%::myconfig, $::form->{"credit_${_}"}),
 
 170        tax_id     => (split m{--}, $::form->{"taxchart_${_}"})[0],
 
 171        project_id => $::form->{"project_id_${_}"} || undef,
 
 172        source     => $::form->{"source_${_}"},
 
 173        memo       => $::form->{"memo_${_}"},
 
 175   } (1..($::form->{rowcount} || 1));
 
 177   $template->assign_attributes(
 
 178     template_type  => 'gl_transaction',
 
 179     template_name  => $new_name,
 
 181     currency_id    => $::instance_conf->get_currency_id,
 
 182     department_id  => $::form->{department_id}    || undef,
 
 183     project_id     => $::form->{globalproject_id} || undef,
 
 184     taxincluded    => $::form->{taxincluded}     ? 1 : 0,
 
 185     ob_transaction => $::form->{ob_transaction}  ? 1 : 0,
 
 186     cb_transaction => $::form->{cb_transaction}  ? 1 : 0,
 
 187     reference      => $::form->{reference},
 
 188     description    => $::form->{description},
 
 189     show_details   => $::form->{show_details},
 
 199       ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
 
 204     ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
 
 209   $main::lxdebug->enter_sub();
 
 211   $main::auth->assert('gl_transactions');
 
 213   my $form     = $main::form;
 
 214   my %myconfig = %main::myconfig;
 
 216   $form->{title} = "Add";
 
 218   $form->{callback} = "gl.pl?action=add" unless $form->{callback};
 
 220   # we use this only to set a default date
 
 221   # yep. aber er holt hier auch schon ALL_CHARTS. Aufwand / Nutzen? jb
 
 222   GL->transaction(\%myconfig, \%$form);
 
 224   $form->{rowcount}  = 2;
 
 230   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 232   $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
 
 235   $main::lxdebug->leave_sub();
 
 239 sub prepare_transaction {
 
 240   $main::lxdebug->enter_sub();
 
 242   $main::auth->assert('gl_transactions');
 
 244   my $form     = $main::form;
 
 245   my %myconfig = %main::myconfig;
 
 247   GL->transaction(\%myconfig, \%$form);
 
 249   $form->{amount} = $form->format_amount(\%myconfig, $form->{amount}, 2);
 
 251   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 256   foreach my $ref (@{ $form->{GL} }) {
 
 258     if ($tax && ($ref->{accno} eq $taxaccno)) {
 
 259       $form->{"tax_$j"}      = abs($ref->{amount});
 
 260       $form->{"taxchart_$j"} = $ref->{id} . "--" . $ref->{taxrate};
 
 261       if ($form->{taxincluded}) {
 
 262         if ($ref->{amount} < 0) {
 
 263           $form->{"debit_$j"} += $form->{"tax_$j"};
 
 265           $form->{"credit_$j"} += $form->{"tax_$j"};
 
 268       $form->{"project_id_$j"} = $ref->{project_id};
 
 271       $form->{"accno_id_$i"} = $ref->{chart_id};
 
 272       for (qw(fx_transaction source memo)) { $form->{"${_}_$i"} = $ref->{$_} }
 
 273       if ($ref->{amount} < 0) {
 
 274         $form->{totaldebit} -= $ref->{amount};
 
 275         $form->{"debit_$i"} = $ref->{amount} * -1;
 
 277         $form->{totalcredit} += $ref->{amount};
 
 278         $form->{"credit_$i"} = $ref->{amount};
 
 280       $form->{"taxchart_$i"} = $ref->{id}."--0.00000";
 
 281       $form->{"project_id_$i"} = $ref->{project_id};
 
 284     if ($ref->{taxaccno} && !$tax) {
 
 285       $taxaccno = $ref->{taxaccno};
 
 293   $form->{rowcount} = $i;
 
 295     ($form->datetonum($form->{transdate}, \%myconfig) <=
 
 296      $form->datetonum($form->{closedto}, \%myconfig));
 
 298   $main::lxdebug->leave_sub();
 
 302   $main::lxdebug->enter_sub();
 
 304   $main::auth->assert('gl_transactions');
 
 306   my $form     = $main::form;
 
 307   my %myconfig = %main::myconfig;
 
 309   prepare_transaction();
 
 311   $form->{title} = "Edit";
 
 313   $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
 
 315   if ($form->{id} && $::instance_conf->get_webdav) {
 
 316     my $webdav = SL::Webdav->new(
 
 317       type     => 'general_ledger',
 
 318       number   => $form->{id},
 
 320     my @all_objects = $webdav->get_all_objects;
 
 321     @{ $form->{WEBDAV} } = map { { name => $_->filename,
 
 323                                    link => File::Spec->catfile($_->full_filedescriptor),
 
 330   $main::lxdebug->leave_sub();
 
 335   $::lxdebug->enter_sub;
 
 336   $::auth->assert('general_ledger | gl_transactions');
 
 339     projects  => { key => "ALL_PROJECTS", all => 1 },
 
 341   $::form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
 
 342   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 344   setup_gl_search_action_bar();
 
 347   print $::form->parse_html_template('gl/search', {
 
 348     employee_label => sub { "$_[0]{id}--$_[0]{name}" },
 
 351   $::lxdebug->leave_sub;
 
 354 sub create_subtotal_row {
 
 355   $main::lxdebug->enter_sub();
 
 357   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
 
 359   my $form     = $main::form;
 
 360   my %myconfig = %main::myconfig;
 
 362   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
 
 364   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
 
 366   map { $totals->{$_} = 0 } @{ $subtotal_columns };
 
 368   $main::lxdebug->leave_sub();
 
 373 sub generate_report {
 
 374   $main::lxdebug->enter_sub();
 
 376   $main::auth->assert('general_ledger | gl_transactions');
 
 378   my $form     = $main::form;
 
 379   my %myconfig = %main::myconfig;
 
 380   my $locale   = $main::locale;
 
 382   # 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
 
 384   # <form method=post action=gl.pl>
 
 385   # <input type=hidden name=sort value=datesort>    # form->{sort} setzen
 
 386   # <input type=hidden name=nextsub value=generate_report>
 
 388   # anhand von neuer Variable datesort wird jetzt $form->{sort} auf transdate oder gldate gesetzt
 
 389   # damit ist die Hidden Variable "sort" wahrscheinlich sogar Ã¼berflüssig
 
 391   # Ã¤ndert man die Sortierreihenfolge per Klick auf eine der Ãœberschriften wird die Variable "sort" per GET Ã¼bergeben, z.B. id,transdate, gldate, ...
 
 392   # 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
 
 394   if ( $form->{sort} eq 'datesort' ) {   # sollte bei einem Post (Aufruf aus Suchmaske) immer wahr sein
 
 395       # je nachdem ob in Suchmaske "transdate" oder "gldate" ausgesucht wurde erstes Suchergebnis entsprechend sortieren
 
 396       $form->{sort} = $form->{datesort};
 
 400   report_generator_set_default_sort("$form->{datesort}", 1);
 
 401 #  report_generator_set_default_sort('transdate', 1);
 
 403   GL->all_transactions(\%myconfig, \%$form);
 
 405   my %acctype = ('A' => $locale->text('Asset'),
 
 406                  'C' => $locale->text('Contra'),
 
 407                  'L' => $locale->text('Liability'),
 
 408                  'Q' => $locale->text('Equity'),
 
 409                  'I' => $locale->text('Revenue'),
 
 410                  'E' => $locale->text('Expense'),);
 
 412   $form->{title} = $locale->text('Journal');
 
 413   if ($form->{category} ne 'X') {
 
 414     $form->{title} .= " : " . $locale->text($acctype{ $form->{category} });
 
 417   $form->{landscape} = 1;
 
 419   my $ml = ($form->{ml} =~ /(A|E|Q)/) ? -1 : 1;
 
 422     transdate      gldate   id      reference      description
 
 423     notes          source   doccnt  debit          debit_accno
 
 424     credit         credit_accno     debit_tax      debit_tax_accno
 
 425     credit_tax     credit_tax_accno projectnumbers balance employee
 
 428   # add employee here, so that variable is still known and passed in url when choosing a different sort order in resulting table
 
 429   my @hidden_variables = qw(accno source reference description notes project_id datefrom dateto employee_id datesort category l_subtotal department_id);
 
 430   push @hidden_variables, map { "l_${_}" } @columns;
 
 432   my $employee = $form->{employee_id} ? SL::DB::Employee->new(id => $form->{employee_id})->load->name : '';
 
 434   my (@options, @date_options);
 
 435   push @options,      $locale->text('Account')     . " : $form->{accno} $form->{account_description}" if ($form->{accno});
 
 436   push @options,      $locale->text('Source')      . " : $form->{source}"                             if ($form->{source});
 
 437   push @options,      $locale->text('Reference')   . " : $form->{reference}"                          if ($form->{reference});
 
 438   push @options,      $locale->text('Description') . " : $form->{description}"                        if ($form->{description});
 
 439   push @options,      $locale->text('Notes')       . " : $form->{notes}"                              if ($form->{notes});
 
 440   push @options,      $locale->text('Employee')    . " : $employee"                                   if $employee;
 
 441   my $datesorttext = $form->{datesort} eq 'transdate' ? $locale->text('Transdate') :  $locale->text('Gldate');
 
 442   push @date_options,      "$datesorttext"                              if ($form->{datesort} and ($form->{datefrom} or $form->{dateto}));
 
 443   push @date_options, $locale->text('From'), $locale->date(\%myconfig, $form->{datefrom}, 1)          if ($form->{datefrom});
 
 444   push @date_options, $locale->text('Bis'),  $locale->date(\%myconfig, $form->{dateto},   1)          if ($form->{dateto});
 
 445   push @options,      join(' ', @date_options)                                                        if (scalar @date_options);
 
 447   if ($form->{department_id}) {
 
 448     my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
 
 449     push @options, $locale->text('Department') . " : " . $department->description;
 
 452   my $callback = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
 
 454   $form->{l_credit_accno}     = 'Y';
 
 455   $form->{l_debit_accno}      = 'Y';
 
 456   $form->{l_credit_tax}       = 'Y';
 
 457   $form->{l_debit_tax}        = 'Y';
 
 458 #  $form->{l_gldate}           = 'Y';  # Spalte mit gldate immer anzeigen
 
 459   $form->{l_credit_tax_accno} = 'Y';
 
 460   $form->{l_datesort} = 'Y';
 
 461   $form->{l_debit_tax_accno}  = 'Y';
 
 462   $form->{l_balance}          = $form->{accno} ? 'Y' : '';
 
 463   $form->{l_doccnt}           = $form->{l_source} ? 'Y' : '';
 
 466     'id'               => { 'text' => $locale->text('ID'), },
 
 467     'transdate'        => { 'text' => $locale->text('Transdate'), },
 
 468     'gldate'           => { 'text' => $locale->text('Gldate'), },
 
 469     'reference'        => { 'text' => $locale->text('Reference'), },
 
 470     'source'           => { 'text' => $locale->text('Source'), },
 
 471     'doccnt'           => { 'text' => $locale->text('Document Count'), },
 
 472     'description'      => { 'text' => $locale->text('Description'), },
 
 473     'notes'            => { 'text' => $locale->text('Notes'), },
 
 474     'debit'            => { 'text' => $locale->text('Debit'), },
 
 475     'debit_accno'      => { 'text' => $locale->text('Debit Account'), },
 
 476     'credit'           => { 'text' => $locale->text('Credit'), },
 
 477     'credit_accno'     => { 'text' => $locale->text('Credit Account'), },
 
 478     'debit_tax'        => { 'text' => $locale->text('Debit Tax'), },
 
 479     'debit_tax_accno'  => { 'text' => $locale->text('Debit Tax Account'), },
 
 480     'credit_tax'       => { 'text' => $locale->text('Credit Tax'), },
 
 481     'credit_tax_accno' => { 'text' => $locale->text('Credit Tax Account'), },
 
 482     'balance'          => { 'text' => $locale->text('Balance'), },
 
 483     'projectnumbers'   => { 'text' => $locale->text('Project Numbers'), },
 
 484     'employee'         => { 'text' => $locale->text('Employee'), },
 
 487   foreach my $name (qw(id transdate gldate reference description debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
 
 488     my $sortname                = $name =~ m/accno/ ? 'accno' : $name;
 
 489     my $sortdir                 = $sortname eq $form->{sort} ? 1 - $form->{sortdir} : $form->{sortdir};
 
 490     $column_defs{$name}->{link} = $callback . "&sort=$sortname&sortdir=$sortdir";
 
 493   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
 
 494   map { $column_defs{$_}->{visible} = 0 } qw(debit_accno credit_accno debit_tax_accno credit_tax_accno) if $form->{accno};
 
 496   my %column_alignment;
 
 497   map { $column_alignment{$_}     = 'right'  } qw(balance id debit credit debit_tax credit_tax balance);
 
 498   map { $column_alignment{$_}     = 'center' } qw(transdate gldate reference debit_accno credit_accno debit_tax_accno credit_tax_accno);
 
 499   map { $column_alignment{$_}     = 'left' } qw(description source notes);
 
 500   map { $column_defs{$_}->{align} = $column_alignment{$_} } keys %column_alignment;
 
 502   my $report = SL::ReportGenerator->new(\%myconfig, $form);
 
 504   $report->set_columns(%column_defs);
 
 505   $report->set_column_order(@columns);
 
 507   $form->{l_attachments} = 'Y';
 
 508   $report->set_export_options('generate_report', @hidden_variables, qw(sort sortdir l_attachments));
 
 510   $report->set_sort_indicator($form->{sort} eq 'accno' ? 'debit_accno' : $form->{sort}, $form->{sortdir});
 
 512   $report->set_options('top_info_text'        => join("\n", @options),
 
 513                        'output_format'        => 'HTML',
 
 514                        'title'                => $form->{title},
 
 515                        'attachment_basename'  => $locale->text('general_ledger_list') . strftime('_%Y%m%d', localtime time),
 
 517   $report->set_options_from_form();
 
 518   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
 520   # add sort to callback
 
 521   $form->{callback} = "$callback&sort=" . E($form->{sort}) . "&sortdir=" . E($form->{sortdir});
 
 524   my @totals_columns = qw(debit credit debit_tax credit_tax);
 
 525   my %subtotals      = map { $_ => 0 } @totals_columns;
 
 526   my %totals         = map { $_ => 0 } @totals_columns;
 
 529   foreach my $ref (@{ $form->{GL} }) {
 
 533     foreach my $key (qw(debit credit debit_tax credit_tax)) {
 
 535       foreach my $idx (sort keys(%{ $ref->{$key} })) {
 
 536         my $value         = $ref->{$key}->{$idx};
 
 537         $subtotals{$key} += $value;
 
 538         $totals{$key}    += $value;
 
 539         if ($key =~ /debit.*/) {
 
 544         $form->{balance}  = $form->{balance} + $value * $ml;
 
 545         push @{ $rows{$key} }, $form->format_amount(\%myconfig, $value, 2);
 
 549     foreach my $key (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno ac_transdate source)) {
 
 550       my $col = $key eq 'ac_transdate' ? 'transdate' : $key;
 
 551       $rows{$col} = [ map { $ref->{$key}->{$_} } sort keys(%{ $ref->{$key} }) ];
 
 555     map { $row->{$_} = { 'data' => '', 'align' => $column_alignment{$_} } } @columns;
 
 557     if ( $form->{l_doccnt} ) {
 
 558       $row->{doccnt}->{data} = SL::Helper::GlAttachments->count_gl_pdf_attachments($ref->{id},$ref->{type});
 
 562     if ($form->{balance} < 0) {
 
 565     } elsif ($form->{balance} > 0) {
 
 569     my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
 
 572     $row->{balance}->{data}        = $data;
 
 573     $row->{projectnumbers}->{data} = join ", ", sort { lc($a) cmp lc($b) } keys %{ $ref->{projectnumbers} };
 
 575     map { $row->{$_}->{data} = $ref->{$_} } qw(id reference description notes gldate employee);
 
 577     map { $row->{$_}->{data} = \@{ $rows{$_} }; } qw(transdate debit credit debit_accno credit_accno debit_tax_accno credit_tax_accno source);
 
 579     foreach my $col (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
 
 580       $row->{$col}->{link} = [ map { "${callback}&accno=" . E($_) } @{ $rows{$col} } ];
 
 583     map { $row->{$_}->{data} = \@{ $rows{$_} } if ($ref->{"${_}_accno"} ne "") } qw(debit_tax credit_tax);
 
 585     $row->{reference}->{link} = build_std_url("script=$ref->{module}.pl", 'action=edit', 'id=' . E($ref->{id}), 'callback');
 
 587     my $row_set = [ $row ];
 
 589     if ( ($form->{l_subtotal} eq 'Y' && !$form->{report_generator_csv_options_for_import} )
 
 590         && (($idx == (scalar @{ $form->{GL} } - 1))
 
 591             || ($ref->{ $form->{sort} } ne $form->{GL}->[$idx + 1]->{ $form->{sort} }))) {
 
 592       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, [ qw(debit credit) ], 'listsubtotal');
 
 595     $report->add_data($row_set);
 
 600   # = 0 for balanced ledger
 
 601   my $balanced_ledger = $totals{debit} + $totals{debit_tax} - $totals{credit} - $totals{credit_tax};
 
 603   my $row = create_subtotal_row(\%totals, \@columns, \%column_alignment, [ qw(debit credit debit_tax credit_tax) ], 'listtotal');
 
 606   if ($form->{balance} < 0) {
 
 609   } elsif ($form->{balance} > 0) {
 
 613   my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
 
 616   $row->{balance}->{data}        = $data;
 
 618   if ( !$form->{report_generator_csv_options_for_import} ) {
 
 619     $report->add_separator();
 
 620     $report->add_data($row);
 
 623   my $raw_bottom_info_text;
 
 625   if (!$form->{accno} && (abs($balanced_ledger) >  0.001)) {
 
 626     $raw_bottom_info_text .=
 
 627         '<p><span class="unbalanced_ledger">'
 
 628       . $locale->text('Unbalanced Ledger')
 
 630       . $form->format_amount(\%myconfig, $balanced_ledger, 3)
 
 634   $raw_bottom_info_text .= $form->parse_html_template('gl/generate_report_bottom');
 
 636   $report->set_options('raw_bottom_info_text' => $raw_bottom_info_text);
 
 638   setup_gl_transactions_action_bar(num_rows => scalar(@{$form->{GL}}));
 
 640   $report->generate_with_headers();
 
 642   $main::lxdebug->leave_sub();
 
 646   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
 
 647   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
 
 654   $main::lxdebug->enter_sub();
 
 656   $main::auth->assert('gl_transactions');
 
 658   my $form     = $main::form;
 
 659   my %myconfig = %main::myconfig;
 
 661   $form->{oldtransdate} = $form->{transdate};
 
 669   my ($debitcredit, $amount);
 
 671   my $dbh = SL::DB->client->dbh;
 
 672   my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
 
 673   my $zerotaxes  = selectall_hashref_query($form, $dbh, "SELECT id FROM tax WHERE rate = 0", );
 
 676     qw(accno debit credit projectnumber fx_transaction source memo tax taxchart);
 
 678   for my $i (1 .. $form->{rowcount}) {
 
 679     $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) for qw(debit credit tax);
 
 681     next if !$form->{"debit_$i"} && !$form->{"credit_$i"} && !$params{keep_rows_without_amount};
 
 684     $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
 
 691     if (($debitcount >= 2) && ($creditcount == 2)) {
 
 692       $form->{"credit_$i"} = 0;
 
 693       $form->{"tax_$i"}    = 0;
 
 695       $form->{creditlock} = 1;
 
 697     if (($creditcount >= 2) && ($debitcount == 2)) {
 
 698       $form->{"debit_$i"} = 0;
 
 699       $form->{"tax_$i"}   = 0;
 
 701       $form->{debitlock} = 1;
 
 703     if (($creditcount == 1) && ($debitcount == 2)) {
 
 704       $form->{creditlock} = 1;
 
 706     if (($creditcount == 2) && ($debitcount == 1)) {
 
 707       $form->{debitlock} = 1;
 
 709     if ($debitcredit && $credittax) {
 
 710       $form->{"taxchart_$i"} = "$notax_id--0.00";
 
 712     if (!$debitcredit && $debittax) {
 
 713       $form->{"taxchart_$i"} = "$notax_id--0.00";
 
 716       ($form->{"debit_$i"} == 0)
 
 717       ? $form->{"credit_$i"}
 
 718       : $form->{"debit_$i"};
 
 720     if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
 
 721       $form->{"taxchart_$i"} = "$notax_id--0.00";
 
 722       $form->{"tax_$i"}      = 0;
 
 724     my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
 
 725     my $iswithouttax = grep { $_->{id} == $taxkey } @{ $zerotaxes };
 
 726     if (!$iswithouttax) {
 
 733     my ($tmpnetamount,$tmpdiff);
 
 734     ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
 
 736     for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
 
 740   for my $i (1 .. $count) {
 
 742     for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
 
 745   for my $i ($count + 1 .. $form->{rowcount}) {
 
 746     for (@flds) { delete $form->{"${_}_$i"} }
 
 749   $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
 
 752   $main::lxdebug->leave_sub();
 
 758   $main::lxdebug->enter_sub();
 
 760   $main::auth->assert('gl_transactions');
 
 762   my $form     = $main::form;
 
 763   my %myconfig = %main::myconfig;
 
 767   #   for $i (1 .. $form->{rowcount}) {
 
 768   #     $form->{totaldebit} += $form->parse_amount(\%myconfig, $form->{"debit_$i"});
 
 769   #     $form->{totalcredit} += $form->parse_amount(\%myconfig, $form->{"credit_$i"});
 
 773   &display_rows($init);
 
 775   $main::lxdebug->leave_sub();
 
 781   $main::lxdebug->enter_sub();
 
 783   $main::auth->assert('gl_transactions');
 
 785   my $form     = $main::form;
 
 786   my %myconfig = %main::myconfig;
 
 787   my $cgi      = $::request->{cgi};
 
 789   my %balances = GL->get_chart_balances(map { $_->{id} } @{ $form->{ALL_CHARTS} });
 
 791   $form->{debit_1}     = 0 if !$form->{"debit_1"};
 
 792   $form->{totaldebit}  = 0;
 
 793   $form->{totalcredit} = 0;
 
 795   my %project_labels = ();
 
 796   my @project_values = ("");
 
 797   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
 
 798     push(@project_values, $item->{"id"});
 
 799     $project_labels{$item->{"id"}} = $item->{"projectnumber"};
 
 802   my %charts_by_id  = map { ($_->{id} => $_) } @{ $::form->{ALL_CHARTS} };
 
 803   my $default_chart = $::form->{ALL_CHARTS}[0];
 
 804   my $transdate     = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
 
 806   my ($source, $memo, $source_hidden, $memo_hidden);
 
 807   for my $i (1 .. $form->{rowcount}) {
 
 808     if ($form->{show_details}) {
 
 810       <td><input name="source_$i" value="$form->{"source_$i"}" size="16"></td>|;
 
 812       <td><input name="memo_$i" value="$form->{"memo_$i"}" size="16"></td>|;
 
 815       <input type="hidden" name="source_$i" value="$form->{"source_$i"}" size="16">|;
 
 817       <input type="hidden" name="memo_$i" value="$form->{"memo_$i"}" size="16">|;
 
 820     my %taxchart_labels = ();
 
 821     my @taxchart_values = ();
 
 823     my $accno_id = $::form->{"accno_id_$i"};
 
 824     my $chart    = $charts_by_id{$accno_id} // $default_chart;
 
 825     $accno_id    = $chart->{id};
 
 826     my ($first_taxchart, $default_taxchart, $taxchart_to_use);
 
 828     foreach my $item ( GL->get_active_taxes_for_chart($accno_id, $transdate) ) {
 
 829       my $key             = $item->id . "--" . $item->rate;
 
 830       $first_taxchart   //= $item;
 
 831       $default_taxchart   = $item if $item->{is_default};
 
 832       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
 
 834       push(@taxchart_values, $key);
 
 835       $taxchart_labels{$key} = $item->taxdescription . " " . $item->rate * 100 . ' %';
 
 838     $taxchart_to_use    //= $default_taxchart // $first_taxchart;
 
 839     my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
 841     my $accno = qq|<td>| .
 
 842       SL::Presenter::Chart::picker("accno_id_$i", $accno_id, style => "width: 300px") .
 
 843       SL::Presenter::Tag::hidden_tag("previous_accno_id_$i", $accno_id)
 
 845     my $tax_ddbox = qq|<td>| .
 
 846       NTI($cgi->popup_menu('-name' => "taxchart_$i",
 
 847             '-id' => "taxchart_$i",
 
 848             '-style' => 'width:200px',
 
 849             '-values' => \@taxchart_values,
 
 850             '-labels' => \%taxchart_labels,
 
 851             '-default' => $selected_taxchart))
 
 854     my ($fx_transaction, $checked);
 
 856       if ($form->{transfer}) {
 
 857         $fx_transaction = qq|
 
 858         <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
 
 863       if ($form->{"debit_$i"} != 0) {
 
 864         $form->{totaldebit} += $form->{"debit_$i"};
 
 865         if (!$form->{taxincluded}) {
 
 866           $form->{totaldebit} += $form->{"tax_$i"};
 
 869         $form->{totalcredit} += $form->{"credit_$i"};
 
 870         if (!$form->{taxincluded}) {
 
 871           $form->{totalcredit} += $form->{"tax_$i"};
 
 875       for (qw(debit credit tax)) {
 
 878           ? $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
 
 882       if ($i < $form->{rowcount}) {
 
 883         if ($form->{transfer}) {
 
 884           $checked = ($form->{"fx_transaction_$i"}) ? "1" : "";
 
 885           my $x = ($checked) ? "x" : "";
 
 886           $fx_transaction = qq|
 
 887       <td><input type=hidden name="fx_transaction_$i" value="$checked">$x</td>
 
 890         $form->hide_form("accno_$i");
 
 893         if ($form->{transfer}) {
 
 894           $fx_transaction = qq|
 
 895       <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
 
 900     my $debitreadonly  = "";
 
 901     my $creditreadonly = "";
 
 902     if ($i == $form->{rowcount}) {
 
 903       if ($form->{debitlock}) {
 
 904         $debitreadonly = "readonly";
 
 905       } elsif ($form->{creditlock}) {
 
 906         $creditreadonly = "readonly";
 
 911       NTI($cgi->popup_menu('-name' => "project_id_$i",
 
 912                            '-values' => \@project_values,
 
 913                            '-labels' => \%project_labels,
 
 914                            '-default' => $form->{"project_id_$i"} ));
 
 915     my $projectnumber_hidden = qq|
 
 916     <input type="hidden" name="project_id_$i" value="$form->{"project_id_$i"}">|;
 
 918     my $copy2credit = $i == 1 ? 'onkeyup="copy_debit_to_credit()"' : '';
 
 919     my $balance     = $form->format_amount(\%::myconfig, $balances{$accno_id} // 0, 2, 'DRCR');
 
 921     # if we have a bt_chart_id we disallow changing the amount of the bank account
 
 922     if ($form->{bt_chart_id}) {
 
 923       $debitreadonly = $creditreadonly = "readonly" if ($form->{"accno_id_$i"} eq $form->{bt_chart_id});
 
 924       $copy2credit   = '' if $i == 1;   # and disallow copy2credit
 
 927     print qq|<tr valign=top>
 
 929     <td id="chart_balance_$i" align="right">${balance}</td>
 
 931     <td><input name="debit_$i" size="8" value="$form->{"debit_$i"}" accesskey=$i $copy2credit $debitreadonly></td>
 
 932     <td><input name="credit_$i" size=8 value="$form->{"credit_$i"}" $creditreadonly></td>
 
 933     <td><input type="hidden" name="tax_$i" value="$form->{"tax_$i"}">$form->{"tax_$i"}</td>
 
 936     if ($form->{show_details}) {
 
 940     <td>$projectnumber</td>
 
 946     $projectnumber_hidden
 
 954   $form->hide_form(qw(rowcount selectaccno));
 
 956   $main::lxdebug->leave_sub();
 
 961   return ($::instance_conf->get_gl_changeable == 2) ? ($::form->current_date(\%::myconfig) eq $::form->{gldate}) : ($::instance_conf->get_gl_changeable == 1);
 
 964 sub setup_gl_action_bar {
 
 967   my $change_never            = $::instance_conf->get_gl_changeable == 0;
 
 968   my $change_on_same_day_only = $::instance_conf->get_gl_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
 
 969   my $is_linked_bank_transaction;
 
 971   if ($form->{id} && SL::DB::Manager::BankTransactionAccTrans->find_by(gl_id => $form->{id})) {
 
 972     $is_linked_bank_transaction = 1;
 
 975   for my $bar ($::request->layout->get('actionbar')) {
 
 979         submit    => [ '#form', { action => 'update' } ],
 
 980         id        => 'update_button',
 
 981         accesskey => 'enter',
 
 985         submit   => [ '#form', { action => 'post' } ],
 
 986         disabled => $form->{locked}                           ? t8('The billing period has already been locked.')
 
 987                   : $form->{storno}                           ? t8('A canceled general ledger transaction cannot be posted.')
 
 988                   : ($form->{id} && $change_never)            ? t8('Changing general ledger transaction has been disabled in the configuration.')
 
 989                   : ($form->{id} && $change_on_same_day_only) ? t8('General ledger transactions can only be changed on the day they are posted.')
 
 990                   : $is_linked_bank_transaction               ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
 994         action => [ t8('Storno'),
 
 995           submit   => [ '#form', { action => 'storno' } ],
 
 996           confirm  => t8('Do you really want to cancel this general ledger transaction?'),
 
 997           disabled => !$form->{id}                ? t8('This general ledger transaction has not been posted yet.')
 
 998                     : $form->{storno}             ? t8('A canceled general ledger transaction cannot be canceled again.')
 
 999                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1002         action => [ t8('Delete'),
 
1003           submit   => [ '#form', { action => 'delete' } ],
 
1004           confirm  => t8('Do you really want to delete this object?'),
 
1005           disabled => !$form->{id}             ? t8('This invoice has not been posted yet.')
 
1006                     : $form->{locked}          ? t8('The billing period has already been locked.')
 
1007                     : $change_never            ? t8('Changing invoices has been disabled in the configuration.')
 
1008                     : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
 
1009                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1010                     : $form->{storno}             ? t8('A canceled general ledger transaction cannot be deleted.')
 
1013       ], # end of combobox "Storno"
 
1016         action => [ t8('more') ],
 
1019           call     => [ 'set_history_window', $form->{id} * 1, 'id' ],
 
1020           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
1024           call     => [ 'follow_up_window' ],
 
1025           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
1028           t8('Record templates'),
 
1029           call => [ 'kivi.RecordTemplate.popup', 'gl_transaction' ],
 
1033           call     => [ 'kivi.Draft.popup', 'gl', 'unknown', $form->{draft_id}, $form->{draft_description} ],
 
1034           disabled => $form->{id}     ? t8('This invoice has already been posted.')
 
1035                     : $form->{locked} ? t8('The billing period has already been locked.')
 
1038       ], # end of combobox "more"
 
1043 sub setup_gl_search_action_bar {
 
1046   for my $bar ($::request->layout->get('actionbar')) {
 
1050         submit    => [ '#form', { action => 'continue', nextsub => 'generate_report' } ],
 
1051         accesskey => 'enter',
 
1057 sub setup_gl_transactions_action_bar {
 
1060   for my $bar ($::request->layout->get('actionbar')) {
 
1063         action => [ $::locale->text('Create new') ],
 
1065           $::locale->text('GL Transaction'),
 
1066           submit => [ '#create_new_form', { action => 'gl_transaction' } ],
 
1069           $::locale->text('AR Transaction'),
 
1070           submit => [ '#create_new_form', { action => 'ar_transaction' } ],
 
1073           $::locale->text('AP Transaction'),
 
1074           submit => [ '#create_new_form', { action => 'ap_transaction' } ],
 
1077           $::locale->text('Sales Invoice'),
 
1078           submit => [ '#create_new_form', { action => 'sales_invoice'  } ],
 
1081           $::locale->text('Vendor Invoice'),
 
1082           submit => [ '#create_new_form', { action => 'vendor_invoice' } ],
 
1084       ], # end of combobox "Create new"
 
1090   $::lxdebug->enter_sub;
 
1091   $::auth->assert('gl_transactions');
 
1095   $::request->layout->add_javascripts("autocomplete_chart.js", "kivi.File.js", "kivi.GL.js", "kivi.RecordTemplate.js");
 
1097   my @old_project_ids = grep { $_ } map{ $::form->{"project_id_$_"} } 1..$::form->{rowcount};
 
1099   $::form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
 
1101                                     "old_id"    => \@old_project_ids },
 
1103                    "charts"    => { "key"       => "ALL_CHARTS",
 
1104                                     "transdate" => $::form->{transdate} });
 
1106   # we cannot book on charttype header
 
1107   @{ $::form->{ALL_CHARTS} } = grep { $_->{charttype} ne 'H' }  @{ $::form->{ALL_CHARTS} };
 
1108   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
1110   my $title      = $::form->{title};
 
1111   $::form->{title} = $::locale->text("$title General Ledger Transaction");
 
1112   # $locale->text('Add General Ledger Transaction')
 
1113   # $locale->text('Edit General Ledger Transaction')
 
1115   map { $::form->{$_} =~ s/\"/"/g }
 
1119     $::request->{layout}->focus("#reference");
 
1120     $::form->{taxincluded} = "1";
 
1122     $::request->{layout}->focus("#accno_id_$::form->{rowcount}_name");
 
1125   $::form->{previous_id}     ||= "--";
 
1126   $::form->{previous_gldate} ||= "--";
 
1128   setup_gl_action_bar();
 
1131   print $::form->parse_html_template('gl/form_header', {
 
1132     hide_title => $title,
 
1133     readonly   => $::form->{id} && ($::form->{locked} || !_get_radieren()),
 
1136   $::lxdebug->leave_sub;
 
1141   $::lxdebug->enter_sub;
 
1142   $::auth->assert('gl_transactions');
 
1144   my ($follow_ups, $follow_ups_due);
 
1146   if ($::form->{id}) {
 
1147     $follow_ups     = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
 
1148     $follow_ups_due = sum map { $_->{due} * 1 } @{ $follow_ups || [] };
 
1151   print $::form->parse_html_template('gl/form_footer', {
 
1152     radieren       => _get_radieren(),
 
1153     follow_ups     => $follow_ups,
 
1154     follow_ups_due => $follow_ups_due,
 
1157   $::lxdebug->leave_sub;
 
1161   $main::lxdebug->enter_sub();
 
1163   my $form     = $main::form;
 
1164   my %myconfig = %main::myconfig;
 
1165   my $locale   = $main::locale;
 
1167   if (GL->delete_transaction(\%myconfig, \%$form)){
 
1168     # saving the history
 
1169       if(!exists $form->{addition} && $form->{id} ne "") {
 
1170         $form->{snumbers} = qq|gltransaction_| . $form->{id};
 
1171         $form->{addition} = "DELETED";
 
1172         $form->{what_done} = "gl_transaction";
 
1173         $form->save_history;
 
1175     # /saving the history
 
1176     $form->redirect($locale->text('Transaction deleted!'))
 
1178   $form->error($locale->text('Cannot delete transaction!'));
 
1179   $main::lxdebug->leave_sub();
 
1183 sub post_transaction {
 
1184   $main::lxdebug->enter_sub();
 
1186   my $form     = $main::form;
 
1187   my %myconfig = %main::myconfig;
 
1188   my $locale   = $main::locale;
 
1190   # check if there is something in reference and date
 
1191   $form->isblank("reference",   $locale->text('Reference missing!'));
 
1192   $form->isblank("transdate",   $locale->text('Transaction Date missing!'));
 
1193   $form->isblank("description", $locale->text('Description missing!'));
 
1195   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
1196   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
1203   my $creditcount = 0;
 
1205   my %split_safety = ();
 
1207   my $dbh = SL::DB->client->dbh;
 
1208   my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
 
1209   my $zerotaxes  = selectall_hashref_query($form, $dbh, "SELECT id FROM tax WHERE rate = 0", );
 
1211   my @flds = qw(accno debit credit projectnumber fx_transaction source memo tax taxchart);
 
1213   for my $i (1 .. $form->{rowcount}) {
 
1214     next if $form->{"debit_$i"} eq "" && $form->{"credit_$i"} eq "";
 
1216     for (qw(debit credit tax)) {
 
1217       $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
 
1221     $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
 
1223     $split_safety{   $form->{"debit_$i"}  <=> 0 }++;
 
1224     $split_safety{ - $form->{"credit_$i"} <=> 0 }++;
 
1232     if (($debitcount >= 2) && ($creditcount == 2)) {
 
1233       $form->{"credit_$i"} = 0;
 
1234       $form->{"tax_$i"}    = 0;
 
1236       $form->{creditlock} = 1;
 
1238     if (($creditcount >= 2) && ($debitcount == 2)) {
 
1239       $form->{"debit_$i"} = 0;
 
1240       $form->{"tax_$i"}   = 0;
 
1242       $form->{debitlock} = 1;
 
1244     if (($creditcount == 1) && ($debitcount == 2)) {
 
1245       $form->{creditlock} = 1;
 
1247     if (($creditcount == 2) && ($debitcount == 1)) {
 
1248       $form->{debitlock} = 1;
 
1250     if ($debitcredit && $credittax) {
 
1251       $form->{"taxchart_$i"} = "$notax_id--0.00";
 
1253     if (!$debitcredit && $debittax) {
 
1254       $form->{"taxchart_$i"} = "$notax_id--0.00";
 
1256     my $amount = ($form->{"debit_$i"} == 0)
 
1257             ? $form->{"credit_$i"}
 
1258             : $form->{"debit_$i"};
 
1260     if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
 
1261       $form->{"taxchart_$i"} = "$notax_id--0.00";
 
1262       $form->{"tax_$i"}      = 0;
 
1264     my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
 
1265     my $iswithouttax = grep { $_->{id} == $taxkey } @{ $zerotaxes };
 
1266     if (!$iswithouttax) {
 
1273       my ($tmpnetamount,$tmpdiff);
 
1274       ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
 
1276         $form->{"debit_$i"} = $tmpnetamount;
 
1278         $form->{"credit_$i"} = $tmpnetamount;
 
1282       $form->{"tax_$i"} = 0;
 
1285     for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
 
1289   if ($split_safety{-1} > 1 && $split_safety{1} > 1) {
 
1290     $::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. " .
 
1291                                    "Due to known problems involving accounting software kivitendo does not allow these."));
 
1294   for my $i (1 .. $count) {
 
1296     for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
 
1299   for my $i ($count + 1 .. $form->{rowcount}) {
 
1300     for (@flds) { delete $form->{"${_}_$i"} }
 
1303   my ($debit, $credit, $taxtotal);
 
1304   for my $i (1 .. $form->{rowcount}) {
 
1305     my $dr  = $form->{"debit_$i"};
 
1306     my $cr  = $form->{"credit_$i"};
 
1307     my $tax = $form->{"tax_$i"};
 
1309       $form->error($locale->text('Cannot post transaction with a debit and credit entry for the same account!'));
 
1311     $debit    += $dr + $tax if $dr;
 
1312     $credit   += $cr + $tax if $cr;
 
1313     $taxtotal += $tax if $form->{taxincluded}
 
1316   $form->{taxincluded} = 0 if !$taxtotal;
 
1318   # this is just for the wise guys
 
1320   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
1321     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
 
1322   $form->error($locale->text('Cannot post transaction for a closed period!'))
 
1323     if ($form->date_closed($form->{"transdate"}, \%myconfig));
 
1324   if ($form->round_amount($debit, 2) != $form->round_amount($credit, 2)) {
 
1325     $form->error($locale->text('Out of balance transaction!'));
 
1328   if ($form->round_amount($debit, 2) + $form->round_amount($credit, 2) == 0) {
 
1329     $form->error($locale->text('Empty transaction!'));
 
1333   # start transaction (post + history + (optional) banktrans)
 
1334   SL::DB->client->with_transaction(sub {
 
1336     if ((my $errno = GL->post_transaction(\%myconfig, \%$form)) <= -1) {
 
1339       $err[1] = $locale->text('Cannot have a value in both Debit and Credit!');
 
1340       $err[2] = $locale->text('Debit and credit out of balance!');
 
1341       $err[3] = $locale->text('Cannot post a transaction without a value!');
 
1345     # saving the history
 
1346     if(!exists $form->{addition} && $form->{id} ne "") {
 
1347       $form->{snumbers} = qq|gltransaction_| . $form->{id};
 
1348       $form->{addition} = "POSTED";
 
1349       $form->{what_done} = "gl transaction";
 
1350       $form->save_history;
 
1353     # Case BankTransaction: update RecordLink and BankTransaction
 
1354     if ($form->{callback} =~ /BankTransaction/ && $form->{bt_id}) {
 
1355       # set invoice_amount - we only rely on bt_id in form, do all other stuff ui independent
 
1356       # die if we have a unlogic or NYI case and abort the whole transaction
 
1357       my ($bt, $chart_id, $payment);
 
1358       require SL::DB::Manager::BankTransaction;
 
1360       $bt = SL::DB::Manager::BankTransaction->find_by(id => $::form->{bt_id});
 
1361       die "No bank transaction found" unless $bt;
 
1363       $chart_id = SL::DB::Manager::BankAccount->find_by(id => $bt->local_bank_account_id)->chart_id;
 
1364       die "no chart id:" unless $chart_id;
 
1366       $payment = SL::DB::Manager::AccTransaction->get_all(where => [ trans_id => $::form->{id},
 
1367                                                                      chart_link => { like => '%_paid%' },
 
1368                                                                      chart_id => $chart_id                  ]);
 
1369       die "guru meditation error: Can only assign amount to one bank account booking" if scalar @{ $payment } > 1;
 
1371       # credit/debit * -1 matches the sign for bt.amount and bt.invoice_amount
 
1372       die "Can only assign the full (partial) bank amount to a single general ledger booking"
 
1373         unless $bt->not_assigned_amount == $payment->[0]->amount * -1;
 
1375       $bt->update_attributes(invoice_amount => $bt->invoice_amount + ($payment->[0]->amount * -1));
 
1377       # create record_link
 
1379         from_table => 'bank_transactions',
 
1380         from_id    => $::form->{bt_id},
 
1382         to_id      => $::form->{id},
 
1384       SL::DB::RecordLink->new(%props)->save;
 
1385       # and tighten holy acc_trans_id for this bank_transaction
 
1387         acc_trans_id        => $payment->[0]->acc_trans_id,
 
1388         bank_transaction_id => $bt->id,
 
1389         gl_id               => $payment->[0]->trans_id,
 
1391       my $bta = SL::DB::BankTransactionAccTrans->new(%props_acc);
 
1396   }) or do { die SL::DB->client->error };
 
1398   if ($form->{callback} =~ /BankTransaction/ && $form->{bt_id}) {
 
1399     print $form->redirect_header($form->{callback});
 
1400     $form->redirect($locale->text('GL transaction posted.') . ' ' . $locale->text('ID') . ': ' . $form->{id});
 
1404   undef($form->{callback});
 
1405   $main::lxdebug->leave_sub();
 
1409   $main::lxdebug->enter_sub();
 
1411   $main::auth->assert('gl_transactions');
 
1413   my $form     = $main::form;
 
1414   my $locale   = $main::locale;
 
1416   if ($::myconfig{mandatory_departments} && !$form->{department_id}) {
 
1417     $form->error($locale->text('You have to specify a department.'));
 
1420   $form->{title}  = $locale->text("$form->{title} General Ledger Transaction");
 
1421   $form->{storno} = 0;
 
1424   if ($::instance_conf->get_webdav) {
 
1425     SL::Webdav->new(type     => 'general_ledger',
 
1426                     number   => $form->{id},
 
1430   $form->{callback} = build_std_url("action=add", "show_details");
 
1431   $form->redirect($::locale->text("General ledger transaction '#1' posted", $form->{reference}));
 
1433   $main::lxdebug->leave_sub();
 
1437   $main::lxdebug->enter_sub();
 
1439   $main::auth->assert('gl_transactions');
 
1441   my $form     = $main::form;
 
1445   $main::lxdebug->leave_sub();
 
1450   $main::lxdebug->enter_sub();
 
1452   $main::auth->assert('gl_transactions');
 
1454   my $form     = $main::form;
 
1455   my %myconfig = %main::myconfig;
 
1456   my $locale   = $main::locale;
 
1458   # don't cancel cancelled transactions
 
1459   if (IS->has_storno(\%myconfig, $form, 'gl')) {
 
1460     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
 
1461     $form->error($locale->text("Transaction has already been cancelled!"));
 
1464   GL->storno($form, \%myconfig, $form->{id});
 
1466   # saving the history
 
1467   if(!exists $form->{addition} && $form->{id} ne "") {
 
1468     $form->{snumbers} = qq|gltransaction_| . $form->{id};
 
1469     $form->{addition} = "STORNO";
 
1470     $form->{what_done} = "gl_transaction";
 
1471     $form->save_history;
 
1473   # /saving the history
 
1475   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
 
1477   $main::lxdebug->leave_sub();
 
1481   call_sub($main::form->{nextsub});
 
1484 sub get_tax_dropdown {
 
1485   my $transdate    = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
 
1486   my @tax_accounts = GL->get_active_taxes_for_chart($::form->{accno_id}, $transdate);
 
1487   my $html         = $::form->parse_html_template("gl/update_tax_accounts", { TAX_ACCOUNTS => \@tax_accounts });
 
1489   print $::form->ajax_response_header, $html;
 
1492 sub get_chart_balance {
 
1493   my %balances = GL->get_chart_balances($::form->{accno_id});
 
1494   my $balance  = $::form->format_amount(\%::myconfig, $balances{ $::form->{accno_id} }, 2, 'DRCR');
 
1496   print $::form->ajax_response_header, $balance;