1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
  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 #======================================================================
 
  31 # Accounts Receivables
 
  33 #======================================================================
 
  35 use POSIX qw(strftime);
 
  36 use List::Util qw(sum first max);
 
  37 use List::UtilsBy qw(sort_by);
 
  40 use SL::Controller::Base;
 
  44 use SL::DB::BankTransactionAccTrans;
 
  51 use SL::DB::RecordTemplate;
 
  53 use SL::Helper::Flash qw(flash flash_later);
 
  54 use SL::Locale::String qw(t8);
 
  55 use SL::Presenter::Tag;
 
  56 use SL::Presenter::Chart;
 
  57 use SL::ReportGenerator;
 
  59 require "bin/mozilla/common.pl";
 
  60 require "bin/mozilla/reportgenerator.pl";
 
  65 # this is for our long dates
 
  66 # $locale->text('January')
 
  67 # $locale->text('February')
 
  68 # $locale->text('March')
 
  69 # $locale->text('April')
 
  70 # $locale->text('May ')
 
  71 # $locale->text('June')
 
  72 # $locale->text('July')
 
  73 # $locale->text('August')
 
  74 # $locale->text('September')
 
  75 # $locale->text('October')
 
  76 # $locale->text('November')
 
  77 # $locale->text('December')
 
  79 # this is for our short month
 
  80 # $locale->text('Jan')
 
  81 # $locale->text('Feb')
 
  82 # $locale->text('Mar')
 
  83 # $locale->text('Apr')
 
  84 # $locale->text('May')
 
  85 # $locale->text('Jun')
 
  86 # $locale->text('Jul')
 
  87 # $locale->text('Aug')
 
  88 # $locale->text('Sep')
 
  89 # $locale->text('Oct')
 
  90 # $locale->text('Nov')
 
  91 # $locale->text('Dec')
 
  93 sub _may_view_or_edit_this_invoice {
 
  94   return 1 if  $::auth->assert('ar_transactions', 1); # may edit all invoices
 
  95   return 0 if !$::form->{id};                         # creating new invoices isn't allowed without invoice_edit
 
  96   return 0 if !$::form->{globalproject_id};           # existing records without a project ID are not allowed
 
  97   return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
 
 101   my $cache = $::request->cache('ar.pl::_assert_access');
 
 103   $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice()                              if !exists $cache->{_may_view_or_edit_this_invoice};
 
 104   $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if !       $cache->{_may_view_or_edit_this_invoice};
 
 107 sub load_record_template {
 
 108   $::auth->assert('ar_transactions');
 
 110   # Load existing template and verify that its one for this module.
 
 111   my $template = SL::DB::RecordTemplate
 
 112     ->new(id => $::form->{id})
 
 114       with_object => [ qw(customer payment currency record_items record_items.chart) ],
 
 117   die "invalid template type" unless $template->template_type eq 'ar_transaction';
 
 119   $template->substitute_variables;
 
 121   # Clean the current $::form before rebuilding it from the template.
 
 122   my $form_defaults = delete $::form->{form_defaults};
 
 123   delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
 
 125   # Fill $::form from the template.
 
 126   my $today                   = DateTime->today_local;
 
 127   $::form->{title}                   = "Add";
 
 128   $::form->{currency}                = $template->currency->name;
 
 129   $::form->{direct_debit}            = $template->direct_debit;
 
 130   $::form->{globalproject_id}        = $template->project_id;
 
 131   $::form->{transaction_description} = $template->transaction_description;
 
 132   $::form->{AR_chart_id}             = $template->ar_ap_chart_id;
 
 133   $::form->{transdate}               = $today->to_kivitendo;
 
 134   $::form->{duedate}                 = $today->to_kivitendo;
 
 135   $::form->{rowcount}                = @{ $template->items };
 
 136   $::form->{paidaccounts}            = 1;
 
 137   $::form->{$_}                      = $template->$_ for qw(department_id ordnumber taxincluded employee_id notes);
 
 139   if ($template->customer) {
 
 140     $::form->{customer_id} = $template->customer_id;
 
 141     $::form->{customer}    = $template->customer->name;
 
 142     $::form->{duedate}     = $template->customer->payment->calc_date(reference_date => $today)->to_kivitendo if $template->customer->payment;
 
 146   foreach my $item (@{ $template->items }) {
 
 149     my $active_taxkey = $item->chart->get_active_taxkey;
 
 150     my $taxes         = SL::DB::Manager::Tax->get_all(
 
 151       where   => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
 
 152       sort_by => 'taxkey, rate',
 
 155     my $tax   = first { $item->tax_id          == $_->id } @{ $taxes };
 
 156     $tax    //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
 
 157     $tax    //= $taxes->[0];
 
 164     $::form->{"AR_amount_chart_id_${row}"}          = $item->chart_id;
 
 165     $::form->{"previous_AR_amount_chart_id_${row}"} = $item->chart_id;
 
 166     $::form->{"amount_${row}"}                      = $::form->format_amount(\%::myconfig, $item->amount1, 2);
 
 167     $::form->{"taxchart_${row}"}                    = $item->tax_id . '--' . $tax->rate;
 
 168     $::form->{"project_id_${row}"}                  = $item->project_id;
 
 171   $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
 
 173   flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
 
 176     keep_rows_without_amount => 1,
 
 177     dont_add_new_row         => 1,
 
 181 sub save_record_template {
 
 182   $::auth->assert('ar_transactions');
 
 184   my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
 
 185   my $js       = SL::ClientJS->new(controller => SL::Controller::Base->new);
 
 186   my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
 
 188   $js->dialog->close('#record_template_dialog');
 
 191     $_->{chart_id} && (($_->{tax_id} // '') ne '')
 
 193     +{ chart_id   => $::form->{"AR_amount_chart_id_${_}"},
 
 194        amount1    => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
 
 195        tax_id     => (split m{--}, $::form->{"taxchart_${_}"})[0],
 
 196        project_id => $::form->{"project_id_${_}"} || undef,
 
 198   } (1..($::form->{rowcount} || 1));
 
 200   $template->assign_attributes(
 
 201     template_type           => 'ar_transaction',
 
 202     template_name           => $new_name,
 
 204     currency_id             => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
 
 205     ar_ap_chart_id          => $::form->{AR_chart_id}      || undef,
 
 206     customer_id             => $::form->{customer_id}      || undef,
 
 207     department_id           => $::form->{department_id}    || undef,
 
 208     project_id              => $::form->{globalproject_id} || undef,
 
 209     employee_id             => $::form->{employee_id}      || undef,
 
 210     taxincluded             => $::form->{taxincluded}  ? 1 : 0,
 
 211     direct_debit            => $::form->{direct_debit} ? 1 : 0,
 
 212     ordnumber               => $::form->{ordnumber},
 
 213     notes                   => $::form->{notes},
 
 214     transaction_description => $::form->{transaction_description},
 
 224       ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
 
 229     ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
 
 234   $main::lxdebug->enter_sub();
 
 236   $main::auth->assert('ar_transactions');
 
 238   my $form     = $main::form;
 
 239   my %myconfig = %main::myconfig;
 
 242   if(!exists $form->{addition} && ($form->{id} ne "")) {
 
 243     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
 
 244     $form->{addition} = "ADDED";
 
 247   # /saving the history
 
 249   $form->{title}    = "Add";
 
 250   $form->{callback} = "ar.pl?action=add" unless $form->{callback};
 
 252   AR->get_transdate(\%myconfig, $form);
 
 253   $form->{initial_transdate} = $form->{transdate};
 
 254   create_links(dont_save => 1);
 
 255   $form->{transdate} = $form->{initial_transdate};
 
 257   if ($form->{customer_id}) {
 
 258     my $last_used_ar_chart = SL::DB::Customer->load_cached($form->{customer_id})->last_used_ar_chart;
 
 259     $form->{"AR_amount_chart_id_1"} = $last_used_ar_chart->id if $last_used_ar_chart;
 
 263   $main::lxdebug->leave_sub();
 
 267   $main::lxdebug->enter_sub();
 
 269   # Delay access check to after the invoice's been loaded in
 
 270   # "create_links" so that project-specific invoice rights can be
 
 273   my $form     = $main::form;
 
 275   # show history button
 
 276   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
 
 277   #/show hhistory button
 
 278   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
 
 279   $form->{title} = "Edit";
 
 284   $main::lxdebug->leave_sub();
 
 288   $main::lxdebug->enter_sub();
 
 292   my $form     = $main::form;
 
 297   $main::lxdebug->leave_sub();
 
 300 sub _retrieve_invoice_object {
 
 301   return undef if !$::form->{id};
 
 302   return $::form->{invoice_obj} if $::form->{invoice_obj} && $::form->{invoice_obj}->id == $::form->{id};
 
 303   return SL::DB::Invoice->new(id => $::form->{id})->load;
 
 307   $main::lxdebug->enter_sub();
 
 309   # Delay access check to after the invoice's been loaded so that
 
 310   # project-specific invoice rights can be evaluated.
 
 313   my $form     = $main::form;
 
 314   my %myconfig = %main::myconfig;
 
 316   $form->create_links("AR", \%myconfig, "customer");
 
 317   $form->{invoice_obj} = _retrieve_invoice_object();
 
 322   if (!$params{dont_save}) {
 
 323     %saved = map { ($_ => $form->{$_}) } qw(direct_debit id taxincluded);
 
 324     $saved{duedate} = $form->{duedate} if $form->{duedate};
 
 325     $saved{currency} = $form->{currency} if $form->{currency};
 
 328   IS->get_customer(\%myconfig, \%$form);
 
 330   $form->{$_}          = $saved{$_} for keys %saved;
 
 331   $form->{rowcount}    = 1;
 
 332   $form->{AR_chart_id} = $form->{acc_trans} && $form->{acc_trans}->{AR} ? $form->{acc_trans}->{AR}->[0]->{chart_id} : $::instance_conf->get_ar_chart_id || $form->{AR_links}->{AR}->[0]->{chart_id};
 
 335   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 337   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 339   # build the popup menus
 
 340   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
 
 342   AR->setup_form($form);
 
 345     ($form->datetonum($form->{transdate}, \%myconfig) <=
 
 346      $form->datetonum($form->{closedto}, \%myconfig));
 
 348   $main::lxdebug->leave_sub();
 
 352   $main::lxdebug->enter_sub();
 
 356   my $form     = $main::form;
 
 357   my %myconfig = %main::myconfig;
 
 358   my $locale   = $main::locale;
 
 359   my $cgi      = $::request->{cgi};
 
 361   $form->{invoice_obj} = _retrieve_invoice_object();
 
 363   my ($title, $readonly, $exchangerate, $rows);
 
 364   my ($notes, $amount, $project);
 
 366   $form->{initial_focus} = !($form->{amount_1} * 1) ? 'customer_id' : 'row_' . $form->{rowcount};
 
 368   $title = $form->{title};
 
 369   # $locale->text('Add Accounts Receivables Transaction')
 
 370   # $locale->text('Edit Accounts Receivables Transaction')
 
 371   $form->{title} = $locale->text("$title Accounts Receivables Transaction");
 
 373   $readonly = ($form->{id}) ? "readonly" : "";
 
 375   $form->{radier} = ($::instance_conf->get_ar_changeable == 2)
 
 376                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 377                       : ($::instance_conf->get_ar_changeable == 1);
 
 378   $readonly = ($form->{radier}) ? "" : $readonly;
 
 380   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
 
 381   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 383   $rows = max 2, $form->numtextrows($form->{notes}, 50);
 
 385   my @old_project_ids = grep { $_ } map { $form->{"project_id_$_"} } 1..$form->{rowcount};
 
 387   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
 
 389                                     "old_id"    => \@old_project_ids },
 
 390                    "charts"    => { "key"       => "ALL_CHARTS",
 
 391                                     "transdate" => $form->{transdate} },
 
 394   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 396   $_->{link_split} = { map { $_ => 1 } split/:/, $_->{link} } for @{ $form->{ALL_CHARTS} };
 
 398   my %project_labels = map { $_->{id} => $_->{projectnumber} } @{ $form->{"ALL_PROJECTS"} };
 
 400   my (@AR_paid_values, %AR_paid_labels);
 
 401   my $default_ar_amount_chart_id;
 
 403   foreach my $item (@{ $form->{ALL_CHARTS} }) {
 
 404     if ($item->{link_split}{AR_amount}) {
 
 405       $default_ar_amount_chart_id //= $item->{id};
 
 407     } elsif ($item->{link_split}{AR_paid}) {
 
 408       push(@AR_paid_values, $item->{accno});
 
 409       $AR_paid_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
 
 413   my $follow_up_vc         = $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id})->name : '';
 
 414   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
 
 416   $::request->layout->add_javascripts("autocomplete_chart.js", "show_vc_details.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.GL.js", "kivi.File.js", "kivi.RecordTemplate.js", "kivi.AR.js", "kivi.CustomerVendor.js", "kivi.Validator.js");
 
 417   # get the correct date for tax
 
 418   my $transdate    = $::form->{transdate}    ? DateTime->from_kivitendo($::form->{transdate})    : DateTime->today_local;
 
 419   my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
 
 420   my $taxdate      = $deliverydate ? $deliverydate : $transdate;
 
 425   for my $i (1 .. $form->{rowcount}) {
 
 427       amount     => $form->{"amount_$i"},
 
 428       tax        => $form->{"tax_$i"},
 
 429       project_id => ($i==$form->{rowcount}) ? $form->{globalproject_id} : $form->{"project_id_$i"},
 
 432     my (%taxchart_labels, @taxchart_values, $default_taxchart, $taxchart_to_use);
 
 433     my $amount_chart_id = $form->{"AR_amount_chart_id_$i"} // $default_ar_amount_chart_id;
 
 436     if ( $form->{"taxchart_$i"} ) {
 
 437       ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
 
 439     foreach my $item ( GL->get_active_taxes_for_chart($amount_chart_id, $taxdate, $used_tax_id) ) {
 
 440       my $key             = $item->id . "--" . $item->rate;
 
 441       $first_taxchart   //= $item;
 
 442       $default_taxchart   = $item if $item->{is_default};
 
 443       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
 
 445       push(@taxchart_values, $key);
 
 446       $taxchart_labels{$key} = $item->taxkey . " - " . $item->taxdescription . " " . $item->rate * 100 . ' %';
 
 449     $taxchart_to_use    //= $default_taxchart // $first_taxchart;
 
 450     my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
 452     $transaction->{selectAR_amount} =
 
 453         SL::Presenter::Chart::picker("AR_amount_chart_id_$i", $amount_chart_id, style => "width: 400px", type => "AR_amount", class => ($form->{initial_focus} eq "row_$i" ? "initial_focus" : ""))
 
 454       . SL::Presenter::Tag::hidden_tag("previous_AR_amount_chart_id_$i", $amount_chart_id);
 
 456     $transaction->{taxchart} =
 
 457       NTI($cgi->popup_menu('-name' => "taxchart_$i",
 
 458                            '-id' => "taxchart_$i",
 
 459                            '-style' => 'width:200px',
 
 460                            '-values' => \@taxchart_values,
 
 461                            '-labels' => \%taxchart_labels,
 
 462                            '-default' => $selected_taxchart));
 
 464     push @transactions, $transaction;
 
 467   $form->{invtotal_unformatted} = $form->{invtotal};
 
 469   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
 
 471   my $now = $form->current_date(\%myconfig);
 
 474   for my $i (1 .. $form->{paidaccounts}) {
 
 476       paid             => $form->{"paid_$i"},
 
 477       exchangerate     => $form->{"exchangerate_$i"} || '',
 
 478       gldate           => $form->{"gldate_$i"},
 
 479       acc_trans_id     => $form->{"acc_trans_id_$i"},
 
 480       source           => $form->{"source_$i"},
 
 481       memo             => $form->{"memo_$i"},
 
 482       AR_paid          => $form->{"AR_paid_$i"},
 
 483       forex            => $form->{"forex_$i"},
 
 484       datepaid         => $form->{"datepaid_$i"},
 
 485       paid_project_id  => $form->{"paid_project_id_$i"},
 
 486       gldate           => $form->{"gldate_$i"},
 
 489     # default account for current assets (i.e. 1801 - SKR04) if no account is selected
 
 490     $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 492     $payment->{selectAR_paid} =
 
 493       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
 
 494                            '-id' => "AR_paid_$i",
 
 495                            '-values' => \@AR_paid_values,
 
 496                            '-labels' => \%AR_paid_labels,
 
 497                            '-default' => $payment->{AR_paid} || $form->{accno_arap}));
 
 501     $payment->{changeable} =
 
 502         SL::DB::Default->get->payments_changeable == 0 ? !$payment->{acc_trans_id} # never
 
 503       : SL::DB::Default->get->payments_changeable == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
 
 506     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
 
 507     if ($form->date_closed($payment->{"gldate_$i"})) {
 
 508         $payment->{changeable} = 0;
 
 511     push @payments, $payment;
 
 514   my @empty = grep { $_->{paid} eq '' } @payments;
 
 516     (sort_by { DateTime->from_kivitendo($_->{datepaid}) } grep { $_->{paid} ne '' } @payments),
 
 520   $form->{totalpaid} = sum map { $_->{paid} } @payments;
 
 522   my $employees = SL::DB::Manager::Employee->get_all_sorted(
 
 525         (id     => $::form->{employee_id}) x !!$::form->{employee_id},
 
 532   setup_ar_form_header_action_bar();
 
 535   print $::form->parse_html_template('ar/form_header', {
 
 536     paid_missing         => $::form->{invtotal} - $::form->{totalpaid},
 
 537     show_exch            => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
 
 538     payments             => \@payments,
 
 539     transactions         => \@transactions,
 
 540     project_labels       => \%project_labels,
 
 542     AR_chart_id          => $form->{AR_chart_id},
 
 544     follow_up_trans_info => $follow_up_trans_info,
 
 545     today                => DateTime->today,
 
 546     currencies           => scalar(SL::DB::Manager::Currency->get_all_sorted),
 
 547     employees            => $employees,
 
 550   $main::lxdebug->leave_sub();
 
 554   $main::lxdebug->enter_sub();
 
 558   my $form     = $main::form;
 
 559   my %myconfig = %main::myconfig;
 
 560   my $locale   = $main::locale;
 
 561   my $cgi      = $::request->{cgi};
 
 564     my $follow_ups = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1);
 
 565     if ( @{ $follow_ups} ) {
 
 566       $form->{follow_up_length} = scalar(@{$follow_ups});
 
 567       $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
 
 571   print $::form->parse_html_template('ar/form_footer');
 
 573   $main::lxdebug->leave_sub();
 
 577   $::auth->assert('ar_transactions');
 
 579   SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
 
 580   $::form->redirect($::locale->text("Marked as paid"));
 
 584   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
 
 585   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
 
 591   $main::lxdebug->enter_sub();
 
 593   $main::auth->assert('ar_transactions');
 
 595   my $form     = $main::form;
 
 596   my %myconfig = %main::myconfig;
 
 600   my ($totaltax, $exchangerate);
 
 602   $form->{invtotal} = 0;
 
 604   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
 
 606   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 607     qw(exchangerate creditlimit creditremaining);
 
 609   my @flds  = qw(amount AR_amount_chart_id projectnumber oldprojectnumber project_id taxchart tax);
 
 613   for my $i (1 .. $form->{rowcount}) {
 
 614     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
 
 615     if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
 
 618       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
 
 621       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
 
 623       $totaltax += $form->{"tax_$i"};
 
 624       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 629   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
 
 630   $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
 
 631   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
 
 633   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
 
 634   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 636   $form->{invdate} = $form->{transdate};
 
 638   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
 639     IS->get_customer(\%myconfig, $form);
 
 640     if (($form->{rowcount} == 1) && ($form->{amount_1} == 0)) {
 
 641       my $last_used_ar_chart = SL::DB::Customer->load_cached($form->{customer_id})->last_used_ar_chart;
 
 642       $form->{"AR_amount_chart_id_1"} = $last_used_ar_chart->id if $last_used_ar_chart;
 
 647     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
 
 649   for my $i (1 .. $form->{paidaccounts}) {
 
 650     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 653           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
 654       } qw(paid exchangerate);
 
 656       $form->{totalpaid} += $form->{"paid_$i"};
 
 658       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
 
 659       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 663   $form->{creditremaining} -=
 
 664     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
 
 665      $form->{oldinvtotal});
 
 666   $form->{oldinvtotal}  = $form->{invtotal};
 
 667   $form->{oldtotalpaid} = $form->{totalpaid};
 
 671   $main::lxdebug->leave_sub();
 
 675 # ToDO: fix $closedto and $invdate
 
 678   $main::lxdebug->enter_sub();
 
 680   $main::auth->assert('ar_transactions');
 
 682   my $form     = $main::form;
 
 683   my %myconfig = %main::myconfig;
 
 684   my $locale   = $main::locale;
 
 686   $form->mtime_ischanged('ar');
 
 687   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 689   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 691   for my $i (1 .. $form->{paidaccounts}) {
 
 693     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 694       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 696       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 698       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 699         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 701       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 702       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 703       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 704         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 706       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 707 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
 
 708         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
 
 713   ($form->{AR})      = split /--/, $form->{AR};
 
 714   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
 
 715   if (AR->post_payment(\%myconfig, \%$form)) {
 
 716     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 717     $form->{what_done} = 'invoice';
 
 718     $form->{addition}  = "PAYMENT POSTED";
 
 720     $form->redirect($locale->text('Payment posted!'))
 
 722     $form->error($locale->text('Cannot post payment!'));
 
 725   $main::lxdebug->leave_sub();
 
 730   $main::auth->assert('ar_transactions');
 
 732   my $form     = $main::form;
 
 739   $main::lxdebug->enter_sub();
 
 741   $main::auth->assert('ar_transactions');
 
 743   my $form     = $main::form;
 
 744   my %myconfig = %main::myconfig;
 
 745   my $locale   = $main::locale;
 
 749   $form->mtime_ischanged('ar');
 
 753   # check if there is an invoice number, invoice and due date
 
 754   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
 
 755   $form->isblank("duedate",   $locale->text('Due Date missing!'));
 
 756   $form->isblank("customer_id", $locale->text('Customer missing!'));
 
 758   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 759     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 764   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
 765   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 767   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 768     if ($form->date_max_future($transdate, \%myconfig));
 
 770   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
 
 772   $form->error($locale->text('Zero amount posting!'))
 
 773     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
 
 775   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 776     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
 
 780   for my $i (1 .. $form->{paidaccounts}) {
 
 781     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 782       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 784       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 786       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 787         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 789       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 790       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 791       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 792         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 794       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 795         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
 
 796         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
 
 801   # if oldcustomer ne customer redo form
 
 802   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
 804     $::dispatcher->end_request;
 
 807   $form->{AR}{receivables} = $form->{ARselected};
 
 810   $form->{id} = 0 if $form->{postasnew};
 
 811   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
 
 814   if(!exists $form->{addition} && $form->{id} ne "") {
 
 815     $form->{snumbers}  = "invnumber_$form->{invnumber}";
 
 816     $form->{what_done} = "invoice";
 
 817     $form->{addition}  = "POSTED";
 
 820   # /saving the history
 
 823     my $msg = $locale->text("AR transaction '#1' posted (ID: #2)", $form->{invnumber}, $form->{id});
 
 824     if ($::instance_conf->get_ar_add_doc && $::instance_conf->get_doc_storage) {
 
 825       my $add_doc_url = build_std_url("script=ar.pl", 'action=edit', 'id=' . E($form->{id}));
 
 826       SL::Helper::Flash::flash_later('info', $msg);
 
 827       print $form->redirect_header($add_doc_url);
 
 828       $::dispatcher->end_request;
 
 831       $form->redirect($msg);
 
 835   $main::lxdebug->leave_sub();
 
 839   $main::lxdebug->enter_sub();
 
 841   $main::auth->assert('ar_transactions');
 
 843   my $form     = $main::form;
 
 844   my %myconfig = %main::myconfig;
 
 846   $form->{postasnew} = 1;
 
 848   if(!exists $form->{addition} && $form->{id} ne "") {
 
 849     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 850     $form->{what_done} = "invoice";
 
 851     $form->{addition}  = "POSTED AS NEW";
 
 854   # /saving the history
 
 857   $main::lxdebug->leave_sub();
 
 861   $main::lxdebug->enter_sub();
 
 863   $main::auth->assert('ar_transactions');
 
 865   my $form     = $main::form;
 
 866   my %myconfig = %main::myconfig;
 
 868   map { delete $form->{$_} } qw(printed emailed queued invnumber deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
 
 869   $form->{paidaccounts} = 1;
 
 872   my $today          = DateTime->today_local;
 
 873   $form->{transdate} = $today->to_kivitendo;
 
 874   $form->{duedate}   = $form->{transdate};
 
 876   if ($form->{customer_id}) {
 
 877     my $payment_terms = SL::DB::Customer->load_cached($form->{customer_id})->payment;
 
 878     $form->{duedate}  = $payment_terms->calc_date(reference_date => $today)->to_kivitendo if $payment_terms;
 
 883   $main::lxdebug->leave_sub();
 
 887   $::auth->assert('ar_transactions');
 
 889   my $form     = $main::form;
 
 890   my %myconfig = %main::myconfig;
 
 891   my $locale   = $main::locale;
 
 893   if (AR->delete_transaction(\%myconfig, \%$form)) {
 
 895     if(!exists $form->{addition}) {
 
 896       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 897       $form->{what_done} = "invoice";
 
 898       $form->{addition}  = "DELETED";
 
 901     # /saving the history
 
 902     $form->redirect($locale->text('Transaction deleted!'));
 
 904   $form->error($locale->text('Cannot delete transaction!'));
 
 907 sub setup_ar_search_action_bar {
 
 910   for my $bar ($::request->layout->get('actionbar')) {
 
 913         $::locale->text('Search'),
 
 914         submit    => [ '#form' ],
 
 915         checks    => [ 'kivi.validate_form' ],
 
 916         accesskey => 'enter',
 
 920   $::request->layout->add_javascripts('kivi.Validator.js');
 
 923 sub setup_ar_transactions_action_bar {
 
 925   my $may_edit_create = $::auth->assert('invoice_edit', 1);
 
 927   for my $bar ($::request->layout->get('actionbar')) {
 
 930         $::locale->text('Print'),
 
 931         call     => [ 'kivi.MassInvoiceCreatePrint.showMassPrintOptionsOrDownloadDirectly' ],
 
 932         disabled => !$may_edit_create  ? t8('You do not have the permissions to access this function.')
 
 933                   : !$params{num_rows} ? $::locale->text('The report doesn\'t contain entries.')
 
 938         action => [ $::locale->text('Create new') ],
 
 940           $::locale->text('AR Transaction'),
 
 941           submit   => [ '#create_new_form', { action => 'ar_transaction' } ],
 
 942           disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
 
 945           $::locale->text('Sales Invoice'),
 
 946           submit   => [ '#create_new_form', { action => 'sales_invoice' } ],
 
 947           disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
 
 949       ], # end of combobox "Create new"
 
 955   $main::lxdebug->enter_sub();
 
 957   my $form     = $main::form;
 
 958   my %myconfig = %main::myconfig;
 
 959   my $locale   = $main::locale;
 
 960   my $cgi      = $::request->{cgi};
 
 962   $form->{title} = $locale->text('Invoices, Credit Notes & AR Transactions');
 
 964   $form->{ALL_EMPLOYEES}      = SL::DB::Manager::Employee  ->get_all_sorted(query => [ deleted => 0 ]);
 
 965   $form->{ALL_DEPARTMENTS}    = SL::DB::Manager::Department->get_all_sorted;
 
 966   $form->{ALL_BUSINESS_TYPES} = SL::DB::Manager::Business  ->get_all_sorted;
 
 967   $form->{ALL_TAXZONES}       = SL::DB::Manager::TaxZone   ->get_all_sorted;
 
 969   $form->{CT_CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
 
 970   ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
 
 971    $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CT_CUSTOM_VARIABLES},
 
 972                                                                               'include_prefix' => 'l_',
 
 973                                                                               'include_value'  => 'Y');
 
 975   # constants and subs for template
 
 976   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
 
 978   $::request->layout->add_javascripts("autocomplete_project.js");
 
 980   setup_ar_search_action_bar();
 
 983   print $form->parse_html_template('ar/search', { %myconfig });
 
 985   $main::lxdebug->leave_sub();
 
 988 sub create_subtotal_row {
 
 989   $main::lxdebug->enter_sub();
 
 991   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
 
 993   my $form     = $main::form;
 
 994   my %myconfig = %main::myconfig;
 
 996   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
 
 998   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
 
1000   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
 
1002   map { $totals->{$_} = 0 } @{ $subtotal_columns };
 
1004   $main::lxdebug->leave_sub();
 
1009 sub ar_transactions {
 
1010   $main::lxdebug->enter_sub();
 
1012   my $form     = $main::form;
 
1013   my %myconfig = %main::myconfig;
 
1014   my $locale   = $main::locale;
 
1016   my ($callback, $href, @columns);
 
1019   report_generator_set_default_sort('transdate', 1);
 
1021   AR->ar_transactions(\%myconfig, \%$form);
 
1023   $form->{title} = $locale->text('Invoices, Credit Notes & AR Transactions');
 
1025   my $report = SL::ReportGenerator->new(\%myconfig, $form);
 
1028     qw(ids transdate id type invnumber ordnumber cusordnumber donumber deliverydate name netamount tax amount paid
 
1029        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
 
1030        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone
 
1031        payment_terms charts customertype direct_debit dunning_description department attachments);
 
1033   my $ct_cvar_configs                 = CVar->get_configs('module' => 'CT');
 
1034   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
 
1035   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
 
1037   my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
 
1038   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
 
1040   my @hidden_variables = map { "l_${_}" } @columns;
 
1041   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber cusordnumber transaction_description notes project_id transdatefrom transdateto duedatefrom duedateto
 
1042                                            employee_id salesman_id business_id parts_partnumber parts_description department_id show_marked_as_closed show_not_mailed
 
1043                                            shippingpoint shipvia taxzone_id);
 
1044   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
 
1046   $href =  $params{want_binary_pdf} ? '' : build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
 
1049     'ids'                     => { raw_header_data => SL::Presenter::Tag::checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
 
1050     'transdate'               => { 'text' => $locale->text('Date'), },
 
1051     'id'                      => { 'text' => $locale->text('ID'), },
 
1052     'type'                    => { 'text' => $locale->text('Type'), },
 
1053     'invnumber'               => { 'text' => $locale->text('Invoice'), },
 
1054     'ordnumber'               => { 'text' => $locale->text('Order'), },
 
1055     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
 
1056     'donumber'                => { 'text' => $locale->text('Delivery Order'), },
 
1057     'deliverydate'            => { 'text' => $locale->text('Delivery Date'), },
 
1058     'name'                    => { 'text' => $locale->text('Customer'), },
 
1059     'netamount'               => { 'text' => $locale->text('Amount'), },
 
1060     'tax'                     => { 'text' => $locale->text('Tax'), },
 
1061     'amount'                  => { 'text' => $locale->text('Total'), },
 
1062     'paid'                    => { 'text' => $locale->text('Paid'), },
 
1063     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
 
1064     'due'                     => { 'text' => $locale->text('Amount Due'), },
 
1065     'duedate'                 => { 'text' => $locale->text('Due Date'), },
 
1066     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
 
1067     'notes'                   => { 'text' => $locale->text('Notes'), },
 
1068     'salesman'                => { 'text' => $locale->text('Salesperson'), },
 
1069     'employee'                => { 'text' => $locale->text('Employee'), },
 
1070     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
 
1071     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
 
1072     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
 
1073     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
 
1074     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
 
1075     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
 
1076     'country'                 => { 'text' => $locale->text('Country'), },
 
1077     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
 
1078     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
 
1079     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
 
1080     'charts'                  => { 'text' => $locale->text('Chart'), },
 
1081     'customertype'            => { 'text' => $locale->text('Customer type'), },
 
1082     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
 
1083     'department'              => { 'text' => $locale->text('Department'), },
 
1084     dunning_description       => { 'text' => $locale->text('Dunning level'), },
 
1085     attachments               => { 'text' => $locale->text('Attachments'), },
 
1089   foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber donumber deliverydate name datepaid employee shippingpoint shipvia transaction_description direct_debit department taxzone)) {
 
1090     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
 
1091     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
 
1094   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
 
1096   $form->{"l_type"} = "Y";
 
1097   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
 
1099   $column_defs{ids}->{visible} = 'HTML';
 
1101   $report->set_columns(%column_defs);
 
1102   $report->set_column_order(@columns);
 
1104   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
 
1106   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
 
1108   CVar->add_custom_variables_to_report('module'         => 'CT',
 
1109                                        'trans_id_field' => 'customer_id',
 
1110                                        'configs'        => $ct_cvar_configs,
 
1111                                        'column_defs'    => \%column_defs,
 
1112                                        'data'           => $form->{AR});
 
1115   if ($form->{customer}) {
 
1116     push @options, $locale->text('Customer') . " : $form->{customer}";
 
1118   if ($form->{cp_name}) {
 
1119     push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
 
1122   if ($form->{department_id}) {
 
1123     my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
 
1124     push @options, $locale->text('Department') . " : " . $department->description;
 
1126   if ($form->{invnumber}) {
 
1127     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
 
1129   if ($form->{ordnumber}) {
 
1130     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
 
1132   if ($form->{cusordnumber}) {
 
1133     push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
 
1135   if ($form->{notes}) {
 
1136     push @options, $locale->text('Notes') . " : $form->{notes}";
 
1138   if ($form->{transaction_description}) {
 
1139     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
 
1141   if ($form->{parts_partnumber}) {
 
1142     push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
 
1144   if ($form->{parts_description}) {
 
1145     push @options, $locale->text('Part Description') . " : $form->{parts_description}";
 
1147   if ($form->{transdatefrom}) {
 
1148     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
 
1150   if ($form->{transdateto}) {
 
1151     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
 
1153   if ($form->{open}) {
 
1154     push @options, $locale->text('Open');
 
1156   if ($form->{employee_id}) {
 
1157     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
 
1158     push @options, $locale->text('Employee') . ' : ' . $employee->name;
 
1160   if ($form->{salesman_id}) {
 
1161     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
 
1162     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
 
1164   if ($form->{closed}) {
 
1165     push @options, $locale->text('Closed');
 
1167   if ($form->{shipvia}) {
 
1168     push @options, $locale->text('Ship via') . " : $form->{shipvia}";
 
1170   if ($form->{shippingpoint}) {
 
1171     push @options, $locale->text('Shipping Point') . " : $form->{shippingpoint}";
 
1175   $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
 
1177   $report->set_options('top_info_text'        => join("\n", @options),
 
1178                        'raw_top_info_text'    => $form->parse_html_template('ar/ar_transactions_header'),
 
1179                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
 
1180                        'output_format'        => 'HTML',
 
1181                        'title'                => $form->{title},
 
1182                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
 
1184   $report->set_options_from_form();
 
1185   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
1187   # add sort and escape callback, this one we use for the add sub
 
1188   $form->{callback} = $href .= "&sort=$form->{sort}";
 
1190   # escape callback for href
 
1191   $callback = $form->escape($href);
 
1193   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
 
1195   my %totals    = map { $_ => 0 } @subtotal_columns;
 
1196   my %subtotals = map { $_ => 0 } @subtotal_columns;
 
1200   foreach my $ar (@{ $form->{AR} }) {
 
1201     $ar->{tax} = $ar->{amount} - $ar->{netamount};
 
1202     $ar->{due} = $ar->{amount} - $ar->{paid};
 
1204     map { $subtotals{$_} += $ar->{$_};
 
1205           $totals{$_}    += $ar->{$_} } @subtotal_columns;
 
1207     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
 
1208     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
 
1210     # Preserve $ar->{type} before changing it to the abbreviation letter for
 
1211     # getting files from file management below.
 
1212     $ar->{object_type} = $ar->{type};
 
1214     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
 
1215     my $has_storno = $ar->{storno} && !$ar->{storno_id};
 
1217     if ($ar->{type} eq 'invoice_for_advance_payment') {
 
1219         $has_storno       ? $locale->text("Invoice for Advance Payment with Storno (abbreviation)") :
 
1220         $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
 
1221                             $locale->text("Invoice for Advance Payment (one letter abbreviation)");
 
1223     } elsif ($ar->{type} eq 'final_invoice') {
 
1224       $ar->{type} = t8('Final Invoice (one letter abbreviation)');
 
1228         $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
 
1229         $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
 
1230         $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
 
1231         $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
 
1232                             $locale->text("AR Transaction (abbreviation)");
 
1235     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
 
1237     $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
 
1241     foreach my $column (@columns) {
 
1243         'data'  => $ar->{$column},
 
1244         'align' => $column_alignment{$column},
 
1248     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
 
1249       . "&id=" . E($ar->{id}) . "&callback=${callback}" unless $params{want_binary_pdf};
 
1252       raw_data =>  SL::Presenter::Tag::checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
 
1257     if ($::instance_conf->get_doc_storage && $form->{l_attachments}) {
 
1258       my @files  = SL::File->get_all_versions(object_id   => $ar->{id},
 
1259                                               object_type => $ar->{object_type} || 'invoice',
 
1260                                               file_type   => 'attachment',);
 
1261       if (scalar @files) {
 
1262         my $html            = join '<br>', map { SL::Presenter::FileObject::file_object($_) } @files;
 
1263         my $text            = join "\n",   map { $_->file_name                              } @files;
 
1264         $row->{attachments} = { 'raw_data' => $html, data => $text };
 
1266         $row->{attachments} = { };
 
1271     my $row_set = [ $row ];
 
1273     if (($form->{l_subtotal} eq 'Y')
 
1274         && (($idx == (scalar @{ $form->{AR} } - 1))
 
1275             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
 
1276       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
 
1279     $report->add_data($row_set);
 
1284   $report->add_separator();
 
1285   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
 
1287   if ($params{want_binary_pdf}) {
 
1288     $report->generate_with_headers();
 
1289     return $report->generate_pdf_content(want_binary_pdf => 1);
 
1292   $::request->layout->add_javascripts('kivi.MassInvoiceCreatePrint.js');
 
1293   setup_ar_transactions_action_bar(num_rows => scalar(@{ $form->{AR} }));
 
1295   $report->generate_with_headers();
 
1297   $main::lxdebug->leave_sub();
 
1301   $main::lxdebug->enter_sub();
 
1303   $main::auth->assert('ar_transactions');
 
1305   my $form     = $main::form;
 
1306   my %myconfig = %main::myconfig;
 
1307   my $locale   = $main::locale;
 
1309   # don't cancel cancelled transactions
 
1310   if (IS->has_storno(\%myconfig, $form, 'ar')) {
 
1311     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
 
1312     $form->error($locale->text("Transaction has already been cancelled!"));
 
1315   AR->storno($form, \%myconfig, $form->{id});
 
1317   # saving the history
 
1318   if(!exists $form->{addition} && $form->{id} ne "") {
 
1319     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
1320     $form->{addition}  = "STORNO";
 
1321     $form->{what_done} = "invoice";
 
1322     $form->save_history;
 
1324   # /saving the history
 
1326   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
 
1328   $main::lxdebug->leave_sub();
 
1331 sub setup_ar_form_header_action_bar {
 
1332   my $transdate               = $::form->datetonum($::form->{transdate}, \%::myconfig);
 
1333   my $closedto                = $::form->datetonum($::form->{closedto},  \%::myconfig);
 
1334   my $is_closed               = $transdate <= $closedto;
 
1336   my $change_never            = $::instance_conf->get_ar_changeable == 0;
 
1337   my $change_on_same_day_only = $::instance_conf->get_ar_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
 
1339   my $is_storno               = IS->is_storno(\%::myconfig, $::form, 'ar', $::form->{id});
 
1340   my $has_storno              = IS->has_storno(\%::myconfig, $::form, 'ar');
 
1341   my $may_edit_create         = $::auth->assert('ar_transactions', 1);
 
1343   my $is_linked_bank_transaction;
 
1345       && SL::DB::Default->get->payments_changeable != 0
 
1346       && SL::DB::Manager::BankTransactionAccTrans->find_by(ar_id => $::form->{id})) {
 
1348     $is_linked_bank_transaction = 1;
 
1350   for my $bar ($::request->layout->get('actionbar')) {
 
1354         submit    => [ '#form', { action => "update" } ],
 
1355         id        => 'update_button',
 
1356         checks    => [ 'kivi.validate_form' ],
 
1357         disabled  => !$may_edit_create ? t8('You must not change this AR transaction.') : undef,
 
1358         accesskey => 'enter',
 
1364           submit   => [ '#form', { action => "post" } ],
 
1365           checks   => [ 'kivi.validate_form', 'kivi.AR.check_fields_before_posting' ],
 
1366           disabled => !$may_edit_create                           ? t8('You must not change this AR transaction.')
 
1367                     : $is_closed                                  ? t8('The billing period has already been locked.')
 
1368                     : $is_storno                                  ? t8('A canceled invoice cannot be posted.')
 
1369                     : ($::form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
 
1370                     : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
 
1371                     : $is_linked_bank_transaction                 ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1376           submit   => [ '#form', { action => "post_payment" } ],
 
1377           disabled => !$may_edit_create           ? t8('You must not change this AR transaction.')
 
1378                     : !$::form->{id}              ? t8('This invoice has not been posted yet.')
 
1379                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1382         action => [ t8('Mark as paid'),
 
1383           submit   => [ '#form', { action => "mark_as_paid" } ],
 
1384           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
 
1385           disabled => !$may_edit_create ? t8('You must not change this AR transaction.')
 
1386                     : !$::form->{id}    ? t8('This invoice has not been posted yet.')
 
1388           only_if  => $::instance_conf->get_is_show_mark_as_paid,
 
1390       ], # end of combobox "Post"
 
1393         action => [ t8('Storno'),
 
1394           submit   => [ '#form', { action => "storno" } ],
 
1395           checks   => [ 'kivi.validate_form', 'kivi.AR.check_fields_before_posting' ],
 
1396           confirm  => t8('Do you really want to cancel this invoice?'),
 
1397           disabled => !$may_edit_create    ? t8('You must not change this AR transaction.')
 
1398                     : !$::form->{id}       ? t8('This invoice has not been posted yet.')
 
1399                     : $has_storno          ? t8('This invoice has been canceled already.')
 
1400                     : $is_storno           ? t8('Reversal invoices cannot be canceled.')
 
1401                     : $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
 
1404         action => [ t8('Delete'),
 
1405           submit   => [ '#form', { action => "delete" } ],
 
1406           confirm  => t8('Do you really want to delete this object?'),
 
1407           disabled => !$may_edit_create        ? t8('You must not change this AR transaction.')
 
1408                     : !$::form->{id}           ? t8('This invoice has not been posted yet.')
 
1409                     : $change_never            ? t8('Changing invoices has been disabled in the configuration.')
 
1410                     : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
 
1411                     : $is_closed               ? t8('The billing period has already been locked.')
 
1414       ], # end of combobox "Storno"
 
1419         action => [ t8('Workflow') ],
 
1422           submit   => [ '#form', { action => "use_as_new" } ],
 
1423           checks   => [ 'kivi.validate_form' ],
 
1424           disabled => !$may_edit_create ? t8('You must not change this AR transaction.')
 
1425                     : !$::form->{id} ? t8('This invoice has not been posted yet.')
 
1428       ], # end of combobox "Workflow"
 
1431         action => [ t8('more') ],
 
1434           call     => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
 
1435           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
1439           call     => [ 'follow_up_window' ],
 
1440           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
1443           t8('Record templates'),
 
1444           call     => [ 'kivi.RecordTemplate.popup', 'ar_transaction' ],
 
1445           disabled => !$may_edit_create ? t8('You must not change this AR transaction.') : undef,
 
1449           call     => [ 'kivi.Draft.popup', 'ar', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
 
1450           disabled => !$may_edit_create ? t8('You must not change this AR transaction.')
 
1451                     : $::form->{id}     ? t8('This invoice has already been posted.')
 
1452                     : $is_closed        ? t8('The billing period has already been locked.')
 
1455       ], # end of combobox "more"
 
1458   $::request->layout->add_javascripts('kivi.Validator.js');