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 #======================================================================
 
  33 #======================================================================
 
  35 use POSIX qw(strftime);
 
  36 use List::Util qw(first max sum);
 
  37 use List::UtilsBy qw(sort_by);
 
  42 use SL::Helper::Flash qw(flash);
 
  45 use SL::ReportGenerator;
 
  48 use SL::DB::PurchaseInvoice;
 
  49 use SL::DB::RecordTemplate;
 
  52 use SL::Locale::String qw(t8);
 
  54 require "bin/mozilla/common.pl";
 
  55 require "bin/mozilla/reportgenerator.pl";
 
  63 # this is for our long dates
 
  64 # $locale->text('January')
 
  65 # $locale->text('February')
 
  66 # $locale->text('March')
 
  67 # $locale->text('April')
 
  68 # $locale->text('May ')
 
  69 # $locale->text('June')
 
  70 # $locale->text('July')
 
  71 # $locale->text('August')
 
  72 # $locale->text('September')
 
  73 # $locale->text('October')
 
  74 # $locale->text('November')
 
  75 # $locale->text('December')
 
  77 # this is for our short month
 
  78 # $locale->text('Jan')
 
  79 # $locale->text('Feb')
 
  80 # $locale->text('Mar')
 
  81 # $locale->text('Apr')
 
  82 # $locale->text('May')
 
  83 # $locale->text('Jun')
 
  84 # $locale->text('Jul')
 
  85 # $locale->text('Aug')
 
  86 # $locale->text('Sep')
 
  87 # $locale->text('Oct')
 
  88 # $locale->text('Nov')
 
  89 # $locale->text('Dec')
 
  91 sub _may_view_or_edit_this_invoice {
 
  92   return 1 if  $::auth->assert('ap_transactions', 1); # may edit all invoices
 
  93   return 0 if !$::form->{id};                         # creating new invoices isn't allowed without invoice_edit
 
  94   return 0 if !$::form->{globalproject_id};           # existing records without a project ID are not allowed
 
  95   return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
 
  99   my $cache = $::request->cache('ap.pl::_assert_access');
 
 101   $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice()                              if !exists $cache->{_may_view_or_edit_this_invoice};
 
 102   $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if !       $cache->{_may_view_or_edit_this_invoice};
 
 105 sub load_record_template {
 
 106   $::auth->assert('ap_transactions');
 
 108   # Load existing template and verify that its one for this module.
 
 109   my $template = SL::DB::RecordTemplate
 
 110     ->new(id => $::form->{id})
 
 112       with_object => [ qw(customer payment currency record_items record_items.chart) ],
 
 115   die "invalid template type" unless $template->template_type eq 'ap_transaction';
 
 117   $template->substitute_variables;
 
 119   # Clean the current $::form before rebuilding it from the template.
 
 120   my $form_defaults = delete $::form->{form_defaults};
 
 121   delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
 
 123   # Fill $::form from the template.
 
 124   my $today                   = DateTime->today_local;
 
 125   $::form->{title}            = "Add";
 
 126   $::form->{currency}         = $template->currency->name;
 
 127   $::form->{direct_debit}     = $template->direct_debit;
 
 128   $::form->{globalproject_id} = $template->project_id;
 
 129   $::form->{AP_chart_id}      = $template->ar_ap_chart_id;
 
 130   $::form->{transdate}        = $today->to_kivitendo;
 
 131   $::form->{duedate}          = $today->to_kivitendo;
 
 132   $::form->{rowcount}         = @{ $template->items };
 
 133   $::form->{paidaccounts}     = 1;
 
 134   $::form->{$_}               = $template->$_ for qw(department_id ordnumber taxincluded notes);
 
 136   if ($template->vendor) {
 
 137     $::form->{vendor_id} = $template->vendor_id;
 
 138     $::form->{vendor}    = $template->vendor->name;
 
 139     $::form->{duedate}     = $template->vendor->payment->calc_date(reference_date => $today)->to_kivitendo if $template->vendor->payment;
 
 143   foreach my $item (@{ $template->items }) {
 
 146     my $active_taxkey = $item->chart->get_active_taxkey;
 
 147     my $taxes         = SL::DB::Manager::Tax->get_all(
 
 148       where   => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
 
 149       sort_by => 'taxkey, rate',
 
 152     my $tax   = first { $item->tax_id          == $_->id } @{ $taxes };
 
 153     $tax    //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
 
 154     $tax    //= $taxes->[0];
 
 161     $::form->{"AP_amount_chart_id_${row}"}          = $item->chart_id;
 
 162     $::form->{"previous_AP_amount_chart_id_${row}"} = $item->chart_id;
 
 163     $::form->{"amount_${row}"}                      = $::form->format_amount(\%::myconfig, $item->amount1, 2);
 
 164     $::form->{"taxchart_${row}"}                    = $item->tax_id . '--' . $tax->rate;
 
 165     $::form->{"project_id_${row}"}                  = $item->project_id;
 
 168   $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
 
 170   flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
 
 171   flash('info', $::locale->text("Payment bookings disallowed. After the booking this record may be " .
 
 172                                 "suggested with the amount of '#1' or otherwise has to be choosen manually." .
 
 173                                 " No automatic payment booking will be done to chart '#2'.",
 
 174                                   $form_defaults->{paid_1_suggestion},
 
 175                                   $form_defaults->{AP_paid_1_suggestion},
 
 176                                 )) if $::form->{no_payment_bookings};
 
 179     keep_rows_without_amount => 1,
 
 180     dont_add_new_row         => 1,
 
 184 sub save_record_template {
 
 185   $::auth->assert('ap_transactions');
 
 187   my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
 
 188   my $js       = SL::ClientJS->new(controller => SL::Controller::Base->new);
 
 189   my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
 
 191   $js->dialog->close('#record_template_dialog');
 
 194     $_->{chart_id} && (($_->{tax_id} // '') ne '')
 
 196     +{ chart_id   => $::form->{"AP_amount_chart_id_${_}"},
 
 197        amount1    => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
 
 198        tax_id     => (split m{--}, $::form->{"taxchart_${_}"})[0],
 
 199        project_id => $::form->{"project_id_${_}"} || undef,
 
 201   } (1..($::form->{rowcount} || 1));
 
 203   $template->assign_attributes(
 
 204     template_type  => 'ap_transaction',
 
 205     template_name  => $new_name,
 
 207     currency_id    => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
 
 208     ar_ap_chart_id => $::form->{AP_chart_id}      || undef,
 
 209     vendor_id      => $::form->{vendor_id}        || undef,
 
 210     department_id  => $::form->{department_id}    || undef,
 
 211     project_id     => $::form->{globalproject_id} || undef,
 
 212     taxincluded    => $::form->{taxincluded}  ? 1 : 0,
 
 213     direct_debit   => $::form->{direct_debit} ? 1 : 0,
 
 214     ordnumber      => $::form->{ordnumber},
 
 215     notes          => $::form->{notes},
 
 225       ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
 
 230     ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
 
 235   $main::lxdebug->enter_sub();
 
 237   my $form     = $main::form;
 
 238   my %myconfig = %main::myconfig;
 
 240   $main::auth->assert('ap_transactions');
 
 242   $form->{title} = "Add";
 
 244   $form->{callback} = "ap.pl?action=add" unless $form->{callback};
 
 246   AP->get_transdate(\%myconfig, $form);
 
 247   $form->{initial_transdate} = $form->{transdate};
 
 248   create_links(dont_save => 1);
 
 249   $form->{transdate} = $form->{initial_transdate};
 
 251   if ($form->{vendor_id}) {
 
 252     my $last_used_ap_chart = SL::DB::Vendor->load_cached($form->{vendor_id})->last_used_ap_chart;
 
 253     $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
 258   $main::lxdebug->leave_sub();
 
 262   $main::lxdebug->enter_sub();
 
 264   # Delay access check to after the invoice's been loaded in
 
 265   # "create_links" so that project-specific invoice rights can be
 
 268   my $form     = $main::form;
 
 270   $form->{title} = "Edit";
 
 275   $main::lxdebug->leave_sub();
 
 279   $main::lxdebug->enter_sub();
 
 283   my $form     = $main::form;
 
 285   # get all files stored in the webdav folder
 
 286   if ($form->{invnumber} && $::instance_conf->get_webdav) {
 
 287     my $webdav = SL::Webdav->new(
 
 288       type     => 'accounts_payable',
 
 289       number   => $form->{invnumber},
 
 291     my @all_objects = $webdav->get_all_objects;
 
 292     @{ $form->{WEBDAV} } = map { { name => $_->filename,
 
 294                                    link => File::Spec->catfile($_->full_filedescriptor),
 
 300   $main::lxdebug->leave_sub();
 
 304   $main::lxdebug->enter_sub();
 
 306   # Delay access check to after the invoice's been loaded so that
 
 307   # project-specific invoice rights can be evaluated.
 
 311   my $form     = $main::form;
 
 312   my %myconfig = %main::myconfig;
 
 314   $form->create_links("AP", \%myconfig, "vendor");
 
 319   if (!$params{dont_save}) {
 
 320     %saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
 
 321     $saved{duedate} = $form->{duedate} if $form->{duedate};
 
 322     $saved{currency} = $form->{currency} if $form->{currency};
 
 323     $saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
 
 326   IR->get_vendor(\%myconfig, \%$form);
 
 328   $form->{$_}        = $saved{$_} for keys %saved;
 
 329   $form->{rowcount}  = 1;
 
 330   $form->{AP_chart_id} = $form->{acc_trans} && $form->{acc_trans}->{AP} ? $form->{acc_trans}->{AP}->[0]->{chart_id} : $::instance_conf->get_ap_chart_id || $form->{AP_links}->{AP}->[0]->{chart_id};
 
 332   # build the popup menus
 
 333   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
 
 336   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 338   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 340   $form->{employee} = "$form->{employee}--$form->{employee_id}";
 
 342   AP->setup_form($form);
 
 344   $main::lxdebug->leave_sub();
 
 348   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid paid_project_id);
 
 350     grep { $_->{paid} != 0 }
 
 353       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
 
 354     } (1..$::form->{paidaccounts});
 
 356   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
 
 358   $::form->{paidaccounts} = max scalar(@payments), 1;
 
 360   foreach my $idx (1 .. scalar(@payments)) {
 
 361     my $payment = $payments[$idx - 1];
 
 362     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
 
 367   $main::lxdebug->enter_sub();
 
 371   my $form     = $main::form;
 
 372   my %myconfig = %main::myconfig;
 
 373   my $locale   = $main::locale;
 
 374   my $cgi      = $::request->{cgi};
 
 376   $::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
 
 378   $form->{initial_focus} = !($form->{amount_1} * 1) ? 'vendor_id' : 'row_' . $form->{rowcount};
 
 380   $form->{title_} = $form->{title};
 
 381   $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
 
 383   # type=submit $locale->text('Add Accounts Payables Transaction')
 
 384   # type=submit $locale->text('Edit Accounts Payables Transaction')
 
 386   my $readonly = $form->{id} ? "readonly" : "";
 
 388   $form->{radier} = ($::instance_conf->get_ap_changeable == 2)
 
 389                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 390                       : ($::instance_conf->get_ap_changeable == 1);
 
 391   $readonly       = $form->{radier} ? "" : $readonly;
 
 393   $form->{readonly} = $readonly;
 
 395   $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 396   if ( $form->{forex} ) {
 
 397     $form->{exchangerate} = $form->{forex};
 
 401   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
 
 402   $form->{creditlimit}     = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
 
 403   $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
 
 406   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
 
 409   $form->{textarea_rows} = $rows;
 
 411   $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
 
 413   my @old_project_ids = ();
 
 416       if ($form->{"project_id_$_"}) {
 
 417         push(@old_project_ids, $form->{"project_id_$_"});
 
 420     (1..$form->{"rowcount"})
 
 423   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
 
 425                                     "old_id"    => \@old_project_ids },
 
 426                    "charts"    => { "key"       => "ALL_CHARTS",
 
 427                                     "transdate" => $form->{transdate} },
 
 428                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
 
 429                                     "module"    => "AP" },);
 
 432     { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
 
 433     @{ $form->{ALL_CHARTS} }
 
 436   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 438   my %project_labels = ();
 
 439   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
 
 440     $project_labels{$item->{id}} = $item->{projectnumber};
 
 444   my $default_ap_amount_chart_id;
 
 446   foreach my $item (@{ $form->{ALL_CHARTS} }) {
 
 447     if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
 
 448       $default_ap_amount_chart_id //= $item->{id};
 
 450     } elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
 
 451       push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
 
 454     $charts{$item->{accno}} = $item;
 
 457   my $follow_up_vc         = $form->{vendor_id} ? SL::DB::Vendor->load_cached($form->{vendor_id})->name : '';
 
 458   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
 
 460   $::request->layout->add_javascripts("autocomplete_chart.js", "show_vc_details.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.GL.js", "kivi.RecordTemplate.js", "kivi.File.js", "kivi.AP.js", "kivi.CustomerVendor.js", "kivi.Validator.js");
 
 461   my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
 
 464   # $form->{totalpaid} is used by the action bar setup to determine
 
 465   # whether or not canceling is allowed. Therefore it must be
 
 466   # calculated prior to the action bar setup.
 
 467   $form->{totalpaid} = sum map { $form->{"paid_${_}"} } (1..$form->{paidaccounts});
 
 469   setup_ap_display_form_action_bar();
 
 473   for my $i (1 .. $form->{rowcount}) {
 
 476     $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
 
 477     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
 
 479     my ($default_taxchart, $taxchart_to_use);
 
 480     my $amount_chart_id = $form->{"AP_amount_chart_id_$i"} || $default_ap_amount_chart_id;
 
 481     my @taxcharts       = GL->get_active_taxes_for_chart($amount_chart_id, $transdate);
 
 483     foreach my $item (@taxcharts) {
 
 484       my $key             = $item->id . "--" . $item->rate;
 
 485       $first_taxchart   //= $item;
 
 486       $default_taxchart   = $item if $item->{is_default};
 
 487       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
 
 490     $taxchart_to_use               //= $default_taxchart // $first_taxchart;
 
 491     my $selected_taxchart            = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
 492     $form->{"selected_taxchart_$i"}  = $selected_taxchart;
 
 493     $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
 
 494     $form->{"taxcharts_$i"}          = \@taxcharts;
 
 497   $form->{taxchart_value_title_sub} = sub {
 
 500       $item->{id} .'--'. $item->{rate},
 
 501       $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
 
 505   $form->{AP_paid_value_title_sub} = sub {
 
 509       $item->{accno} .'--'. $item->{description}
 
 513   $form->{invtotal_unformatted} = $form->{invtotal};
 
 514   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
 
 518   if ( $form->{'paid_'. $form->{paidaccounts}} ) {
 
 519     $form->{paidaccounts}++;
 
 522   # default account for current assets (i.e. 1801 - SKR04)
 
 523   $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 525   for my $i (1 .. $form->{paidaccounts}) {
 
 527     if ($form->{"paid_$i"}) {
 
 528       $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
 
 530     if ($form->{"exchangerate_$i"} == 0) {
 
 531       $form->{"exchangerate_$i"} = "";
 
 533       $form->{"exchangerate_$i"} =
 
 534         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
 
 538     if (SL::DB::Default->get->payments_changeable == 0) {
 
 540       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
 
 542     if (SL::DB::Default->get->payments_changeable == 2) {
 
 544       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
 
 547     #deaktivieren von gebuchten Zahlungen ausserhalb der BĂĽcherkontrolle, vorher prĂĽfen ob heute eingegeben
 
 548     if ($form->date_closed($form->{"gldate_$i"})) {
 
 552     $form->{'paidaccount_changeable_'. $i} = $changeable;
 
 554     $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
 
 557   $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
 
 559   print $form->parse_html_template('ap/form_header', {
 
 560     today => DateTime->today,
 
 561     currencies => SL::DB::Manager::Currency->get_all_sorted,
 
 564   $main::lxdebug->leave_sub();
 
 568   $::lxdebug->enter_sub;
 
 575     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
 
 577     if (@{ $follow_ups }) {
 
 578       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
 
 579       $num_follow_ups = scalar @{ $follow_ups }
 
 583   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
 
 584   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
 
 586   my $storno = $::form->{id}
 
 587             && !IS->has_storno(\%::myconfig, $::form, 'ap')
 
 588             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
 
 589             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
 
 592   print $::form->parse_html_template('ap/form_footer', {
 
 594     num_follow_ups    => $num_follow_ups,
 
 597   $::lxdebug->leave_sub;
 
 601   $::auth->assert('ap_transactions');
 
 603   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
 
 605   $::form->redirect($::locale->text("Marked as paid"));
 
 609   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
 
 610   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
 
 617   $main::lxdebug->enter_sub();
 
 619   my $form     = $main::form;
 
 620   my %myconfig = %main::myconfig;
 
 622   $main::auth->assert('ap_transactions');
 
 626   $form->{invtotal} = 0;
 
 628   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
 
 630   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 631     qw(exchangerate creditlimit creditremaining);
 
 633   my @flds  = qw(amount AP_amount projectnumber oldprojectnumber project_id taxchart);
 
 635   my (@a, $j, $totaltax);
 
 636   for my $i (1 .. $form->{rowcount}) {
 
 637     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
 
 638     if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
 
 641       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
 
 643       # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
 
 645       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
 
 647       $totaltax += $form->{"tax_$i"};
 
 648       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 652   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
 
 654   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
 
 656   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 657   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 659   $form->{invdate} = $form->{transdate};
 
 661   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
 
 662     IR->get_vendor(\%::myconfig, $form);
 
 663     if (($form->{rowcount} == 1) && ($form->{amount_1} == 0)) {
 
 664       my $last_used_ap_chart = SL::DB::Vendor->load_cached($form->{vendor_id})->last_used_ap_chart;
 
 665       $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
 669   $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
 
 672     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
 
 675   for my $i (1 .. $form->{paidaccounts}) {
 
 676     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 679           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
 680       } qw(paid exchangerate);
 
 682       $totalpaid += $form->{"paid_$i"};
 
 684       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 685       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 689   $form->{creditremaining} -=
 
 690     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
 
 691      $form->{oldinvtotal});
 
 692   $form->{oldinvtotal}  = $form->{invtotal};
 
 693   $form->{oldtotalpaid} = $totalpaid;
 
 697   $main::lxdebug->leave_sub();
 
 702   $main::lxdebug->enter_sub();
 
 704   my $form     = $main::form;
 
 705   my %myconfig = %main::myconfig;
 
 706   my $locale   = $main::locale;
 
 708   $main::auth->assert('ap_transactions');
 
 709   $form->mtime_ischanged('ap');
 
 711   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 713   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 715   for my $i (1 .. $form->{paidaccounts}) {
 
 716     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 717       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 719       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 721       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 722         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 724       #Zusätzlich noch das Buchungsdatum in die BĂĽcherkontrolle einbeziehen
 
 725       # (Dient zur PrĂĽfung ob ZE oder ZA geprĂĽft werden soll)
 
 726       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 727         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 729       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 730         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 731           if ($invdate == $datepaid);
 
 732         $form->isblank("exchangerate_$i",
 
 733                        $locale->text('Exchangerate for payment missing!'));
 
 738   ($form->{AP})      = split /--/, $form->{AP};
 
 739   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
 
 740   if (AP->post_payment(\%myconfig, \%$form)) {
 
 741     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 742     $form->{what_done} = 'invoice';
 
 743     $form->{addition}  = "PAYMENT POSTED";
 
 745     $form->redirect($locale->text('Payment posted!'))
 
 747     $form->error($locale->text('Cannot post payment!'));
 
 751   $main::lxdebug->leave_sub();
 
 756   $main::lxdebug->enter_sub();
 
 758   my $form     = $main::form;
 
 759   my %myconfig = %main::myconfig;
 
 760   my $locale   = $main::locale;
 
 762   $main::auth->assert('ap_transactions');
 
 763   $form->mtime_ischanged('ap');
 
 767   # check if there is a vendor, invoice, due date and invnumber
 
 768   $form->isblank("transdate",   $locale->text("Invoice Date missing!"));
 
 769   $form->isblank("duedate",     $locale->text("Due Date missing!"));
 
 770   $form->isblank("vendor_id",   $locale->text('Vendor missing!'));
 
 771   $form->isblank("invnumber",   $locale->text('Invoice Number missing!'));
 
 772   $form->isblank("AP_chart_id", $locale->text('No contra account selected!'));
 
 774   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 775     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 780   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
 781   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 783   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 784     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
 
 785   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
 
 787   my $zero_amount_posting = 1;
 
 788   for my $i (1 .. $form->{rowcount}) {
 
 789     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
 
 790       $zero_amount_posting = 0;
 
 795   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
 
 797   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 798     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
 
 801   for my $i (1 .. $form->{paidaccounts}) {
 
 802     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 803       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 805       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 807       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 808       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 810       #Zusätzlich noch das Buchungsdatum in die BĂĽcherkontrolle einbeziehen
 
 811       # (Dient zur PrĂĽfung ob ZE oder ZA geprĂĽft werden soll)
 
 812       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 813         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 815       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 816         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 817           if ($transdate == $datepaid);
 
 818         $form->isblank("exchangerate_$i",
 
 819                        $locale->text('Exchangerate for payment missing!'));
 
 825   # if old vendor ne vendor redo form
 
 826   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
 828     $::dispatcher->end_request;
 
 832   $form->{id} = 0 if $form->{postasnew};
 
 834   if (AP->post_transaction(\%myconfig, \%$form)) {
 
 835     # create webdav folder
 
 836     if ($::instance_conf->get_webdav) {
 
 837       SL::Webdav->new(type     => 'accounts_payable',
 
 838                       number   => $form->{invnumber},
 
 842     if(!exists $form->{addition} && $form->{id} ne "") {
 
 843       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 844       $form->{addition}  = "POSTED";
 
 845       $form->{what_done} = "invoice";
 
 848     # no restore_from_session_id needed. we like to have a newly generated
 
 849     # list of invoices for bank transactions
 
 850     print $form->redirect_header($form->{callback}) if ($form->{callback} =~ /BankTransaction/);
 
 851     $form->redirect($locale->text('AP transaction posted.') . ' ' . $locale->text('ID') . ': ' . $form->{id}) unless $inline;
 
 852     # TODO Add callback/return flag in myconfig
 
 853     # With version 3.5 we can add documents, but only after posting. there should be a flag in myconfig for the user
 
 854     # $form->{callback} ||= 'ap.pl?action=edit&id=' . $form->{id} if $myconfig{no_reset_arap};
 
 857     $form->error($locale->text('Cannot post transaction!'));
 
 860   $main::lxdebug->leave_sub();
 
 864   $main::lxdebug->enter_sub();
 
 866   my $form     = $main::form;
 
 867   my %myconfig = %main::myconfig;
 
 869   $main::auth->assert('ap_transactions');
 
 871   $form->{postasnew} = 1;
 
 873   if(!exists $form->{addition} && $form->{id} ne "") {
 
 874     # does this work? post_as_new for ap doesn't immediately save the
 
 875     # invoice, because the invnumber has to be entered by hand.
 
 876     # And the value of $form->{postasnew} isn't checked when calling post
 
 877     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 878     $form->{addition}  = "POSTED AS NEW";
 
 879     $form->{what_done} = "invoice";
 
 882   # /saving the history
 
 885   $main::lxdebug->leave_sub();
 
 889   $main::lxdebug->enter_sub();
 
 891   my $form     = $main::form;
 
 892   my %myconfig = %main::myconfig;
 
 894   $main::auth->assert('ap_transactions');
 
 896   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);
 
 897   $form->{paidaccounts} = 1;
 
 900   my $today          = DateTime->today_local;
 
 901   $form->{transdate} = $today->to_kivitendo;
 
 902   $form->{duedate}   = $form->{transdate};
 
 904   if ($form->{vendor_id}) {
 
 905     my $payment_terms = SL::DB::Vendor->load_cached($form->{vendor_id})->payment;
 
 906     $form->{duedate}  = $payment_terms->calc_date(reference_date => $today)->to_kivitendo if $payment_terms;
 
 911   $main::lxdebug->leave_sub();
 
 915   my $form     = $main::form;
 
 916   my %myconfig = %main::myconfig;
 
 917   my $locale   = $main::locale;
 
 919   $main::auth->assert('ap_transactions');
 
 921   if (AP->delete_transaction(\%myconfig, \%$form)) {
 
 923     if(!exists $form->{addition}) {
 
 924       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 925       $form->{addition}  = "DELETED";
 
 926       $form->{what_done} = "invoice";
 
 929     # /saving the history
 
 930     $form->redirect($locale->text('Transaction deleted!'));
 
 932   $form->error($locale->text('Cannot delete transaction!'));
 
 936   $main::lxdebug->enter_sub();
 
 938   my $form     = $main::form;
 
 939   my %myconfig = %main::myconfig;
 
 940   my $locale   = $main::locale;
 
 942   $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
 
 944   $form->get_lists(projects => { "key" => "ALL_PROJECTS", "all" => 1 });
 
 946   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 947   # constants and subs for template
 
 948   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
 
 950   $::request->layout->add_javascripts("autocomplete_project.js");
 
 952   setup_ap_search_action_bar();
 
 955   print $form->parse_html_template('ap/search', { %myconfig });
 
 957   $main::lxdebug->leave_sub();
 
 960 sub create_subtotal_row {
 
 961   $main::lxdebug->enter_sub();
 
 963   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
 
 965   my $form     = $main::form;
 
 966   my %myconfig = %main::myconfig;
 
 968   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
 
 970   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
 
 972   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
 
 974   map { $totals->{$_} = 0 } @{ $subtotal_columns };
 
 976   $main::lxdebug->leave_sub();
 
 981 sub ap_transactions {
 
 982   $main::lxdebug->enter_sub();
 
 984   my $form     = $main::form;
 
 985   my %myconfig = %main::myconfig;
 
 986   my $locale   = $main::locale;
 
 988   report_generator_set_default_sort('transdate', 1);
 
 990   AP->ap_transactions(\%myconfig, \%$form);
 
 992   $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
 
 994   my $report = SL::ReportGenerator->new(\%myconfig, $form);
 
 997     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
 
 998        due duedate transaction_description notes employee globalprojectnumber
 
 999        vendornumber country ustid taxzone payment_terms charts direct_debit);
 
1001   my @hidden_variables = map { "l_${_}" } @columns;
 
1002   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto
 
1003                                            parts_partnumber parts_description);
 
1005   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
 
1008     'transdate'               => { 'text' => $locale->text('Date'), },
 
1009     'id'                      => { 'text' => $locale->text('ID'), },
 
1010     'type'                    => { 'text' => $locale->text('Type'), },
 
1011     'invnumber'               => { 'text' => $locale->text('Invoice'), },
 
1012     'ordnumber'               => { 'text' => $locale->text('Order'), },
 
1013     'name'                    => { 'text' => $locale->text('Vendor'), },
 
1014     'netamount'               => { 'text' => $locale->text('Amount'), },
 
1015     'tax'                     => { 'text' => $locale->text('Tax'), },
 
1016     'amount'                  => { 'text' => $locale->text('Total'), },
 
1017     'paid'                    => { 'text' => $locale->text('Paid'), },
 
1018     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
 
1019     'due'                     => { 'text' => $locale->text('Amount Due'), },
 
1020     'duedate'                 => { 'text' => $locale->text('Due Date'), },
 
1021     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
 
1022     'notes'                   => { 'text' => $locale->text('Notes'), },
 
1023     'employee'                => { 'text' => $locale->text('Employee'), },
 
1024     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
 
1025     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
 
1026     'country'                 => { 'text' => $locale->text('Country'), },
 
1027     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
 
1028     'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
 
1029     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
 
1030     'charts'                  => { 'text' => $locale->text('Chart'), },
 
1031     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
 
1034   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
 
1035     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
 
1036     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
 
1039   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
 
1041   $form->{"l_type"} = "Y";
 
1042   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
 
1044   $report->set_columns(%column_defs);
 
1045   $report->set_column_order(@columns);
 
1047   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
 
1049   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
 
1052   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
 
1053   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
 
1054   push @options, $locale->text('Department')              . " : $form->{department}"                     if ($form->{department});
 
1055   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
 
1056   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
 
1057   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
 
1058   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
 
1059   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
 
1060   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
 
1061   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
 
1062   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
 
1063   push @options, $locale->text('Open')                                                                   if ($form->{open});
 
1064   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
 
1066   $report->set_options('top_info_text'        => join("\n", @options),
 
1067                        'output_format'        => 'HTML',
 
1068                        'title'                => $form->{title},
 
1069                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
 
1071   $report->set_options_from_form();
 
1072   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
1074   # add sort and escape callback, this one we use for the add sub
 
1075   $form->{callback} = $href .= "&sort=$form->{sort}";
 
1077   # escape callback for href
 
1078   my $callback = $form->escape($href);
 
1080   my @subtotal_columns = qw(netamount amount paid due);
 
1082   my %totals    = map { $_ => 0 } @subtotal_columns;
 
1083   my %subtotals = map { $_ => 0 } @subtotal_columns;
 
1087   foreach my $ap (@{ $form->{AP} }) {
 
1088     $ap->{tax} = $ap->{amount} - $ap->{netamount};
 
1089     $ap->{due} = $ap->{amount} - $ap->{paid};
 
1091     map { $subtotals{$_} += $ap->{$_};
 
1092           $totals{$_}    += $ap->{$_} } @subtotal_columns;
 
1094     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
 
1096     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
 
1097     my $has_storno = $ap->{storno} && !$ap->{storno_id};
 
1099     if ($ap->{invoice}) {
 
1101           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
 
1102         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
 
1103         :                     $locale->text("Invoice (one letter abbreviation)");
 
1106           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
 
1107         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
 
1108         :                     $locale->text("AP Transaction (abbreviation)");
 
1111     $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
 
1115     foreach my $column (@columns) {
 
1117         'data'  => $ap->{$column},
 
1118         'align' => $column_alignment{$column},
 
1122     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
 
1123       . "&id=" . E($ap->{id}) . "&callback=${callback}";
 
1125     my $row_set = [ $row ];
 
1127     if (($form->{l_subtotal} eq 'Y')
 
1128         && (($idx == (scalar @{ $form->{AP} } - 1))
 
1129             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
 
1130       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
 
1133     $report->add_data($row_set);
 
1138   $report->add_separator();
 
1139   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
 
1141   setup_ap_transactions_action_bar();
 
1142   $report->generate_with_headers();
 
1144   $main::lxdebug->leave_sub();
 
1148   $main::lxdebug->enter_sub();
 
1150   my $form     = $main::form;
 
1151   my %myconfig = %main::myconfig;
 
1152   my $locale   = $main::locale;
 
1154   $main::auth->assert('ap_transactions');
 
1156   if (IS->has_storno(\%myconfig, $form, 'ap')) {
 
1157     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
 
1158     $form->error($locale->text("Transaction has already been cancelled!"));
 
1161   $form->error($locale->text('Cannot post storno for a closed period!'))
 
1162     if ( $form->date_closed($form->{transdate}, \%myconfig));
 
1164   AP->storno($form, \%myconfig, $form->{id});
 
1166   # saving the history
 
1167   if(!exists $form->{addition} && $form->{id} ne "") {
 
1168     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
1169     $form->{addition}  = "STORNO";
 
1170     $form->{what_done} = "invoice";
 
1171     $form->save_history;
 
1173   # /saving the history
 
1175   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
 
1177   $main::lxdebug->leave_sub();
 
1180 sub setup_ap_search_action_bar {
 
1183   for my $bar ($::request->layout->get('actionbar')) {
 
1186         $::locale->text('Search'),
 
1187         submit    => [ '#form', { action => "ap_transactions" } ],
 
1188         checks    => [ 'kivi.validate_form' ],
 
1189         accesskey => 'enter',
 
1193   $::request->layout->add_javascripts('kivi.Validator.js');
 
1196 sub setup_ap_transactions_action_bar {
 
1198   my $may_edit_create = $::auth->assert('vendor_invoice_edit', 1);
 
1200   for my $bar ($::request->layout->get('actionbar')) {
 
1203         action => [ t8('Add') ],
 
1205           t8('Purchase Invoice'),
 
1206           link     => [ 'ir.pl?action=add' ],
 
1207           disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
 
1211           t8('AP Transaction'),
 
1212           link     => [ 'ap.pl?action=add' ],
 
1213           disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
 
1215       ], # end of combobox "Add"
 
1220 sub setup_ap_display_form_action_bar {
 
1221   my $transdate               = $::form->datetonum($::form->{transdate}, \%::myconfig);
 
1222   my $closedto                = $::form->datetonum($::form->{closedto},  \%::myconfig);
 
1223   my $is_closed               = $transdate <= $closedto;
 
1225   my $change_never            = $::instance_conf->get_ap_changeable == 0;
 
1226   my $change_on_same_day_only = $::instance_conf->get_ap_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
 
1228   my $is_storno               = IS->is_storno(\%::myconfig, $::form, 'ap', $::form->{id});
 
1229   my $has_storno              = IS->has_storno(\%::myconfig, $::form, 'ap');
 
1231   my $may_edit_create         = $::auth->assert('vendor_invoice_edit', 1);
 
1233   my $has_sepa_exports;
 
1235   if ($::form->{id}) {
 
1236     my $invoice = SL::DB::Manager::PurchaseInvoice->find_by(id => $::form->{id});
 
1237     $has_sepa_exports = 1 if ($invoice->find_sepa_export_items()->[0]);
 
1240   for my $bar ($::request->layout->get('actionbar')) {
 
1244         submit    => [ '#form', { action => "update" } ],
 
1245         id        => 'update_button',
 
1246         checks    => [ 'kivi.validate_form' ],
 
1247         accesskey => 'enter',
 
1248         disabled  => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
 
1254           submit   => [ '#form', { action => "post" } ],
 
1255           checks   => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting', 'kivi.AP.check_duplicate_invnumber' ],
 
1256           disabled => !$may_edit_create                           ? t8('You must not change this AP transaction.')
 
1257                     : $is_closed                                  ? t8('The billing period has already been locked.')
 
1258                     : $is_storno                                  ? t8('A canceled invoice cannot be posted.')
 
1259                     : ($::form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
 
1260                     : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
 
1265           submit   => [ '#form', { action => "post_payment" } ],
 
1266           checks   => [ 'kivi.validate_form' ],
 
1267           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1268                     : !$::form->{id}    ? t8('This invoice has not been posted yet.')
 
1271         action => [ t8('Mark as paid'),
 
1272           submit   => [ '#form', { action => "mark_as_paid" } ],
 
1273           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
 
1274           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1275                     : !$::form->{id}    ? t8('This invoice has not been posted yet.')
 
1277           only_if  => $::instance_conf->get_is_show_mark_as_paid,
 
1279       ], # end of combobox "Post"
 
1282         action => [ t8('Storno'),
 
1283           submit   => [ '#form', { action => "storno" } ],
 
1284           checks   => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting' ],
 
1285           confirm  => t8('Do you really want to cancel this invoice?'),
 
1286           disabled => !$may_edit_create    ? t8('You must not change this AP transaction.')
 
1287                     : !$::form->{id}       ? t8('This invoice has not been posted yet.')
 
1288                     : $has_storno          ? t8('This invoice has been canceled already.')
 
1289                     : $is_storno           ? t8('Reversal invoices cannot be canceled.')
 
1290                     : $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
 
1291                     : $has_sepa_exports    ? t8('This invoice has been linked with a sepa export, undo this first.')
 
1294         action => [ t8('Delete'),
 
1295           submit   => [ '#form', { action => "delete" } ],
 
1296           confirm  => t8('Do you really want to delete this object?'),
 
1297           disabled => !$may_edit_create        ? t8('You must not change this AP transaction.')
 
1298                     : !$::form->{id}           ? t8('This invoice has not been posted yet.')
 
1299                     : $change_never            ? t8('Changing invoices has been disabled in the configuration.')
 
1300                     : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
 
1301                     : $has_storno              ? t8('This invoice has been canceled already.')
 
1302                     : $is_closed               ? t8('The billing period has already been locked.')
 
1303                     : $has_sepa_exports        ? t8('This invoice has been linked with a sepa export, undo this first.')
 
1306       ], # end of combobox "Storno"
 
1311         action => [ t8('Workflow') ],
 
1314           submit   => [ '#form', { action => "use_as_new" } ],
 
1315           checks   => [ 'kivi.validate_form' ],
 
1316           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1317                     : !$::form->{id}    ? t8('This invoice has not been posted yet.')
 
1320       ], # end of combobox "Workflow"
 
1323         action => [ t8('more') ],
 
1326           call     => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
 
1327           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
1331           call     => [ 'follow_up_window' ],
 
1332           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
1335           t8('Record templates'),
 
1336           call     => [ 'kivi.RecordTemplate.popup', 'ap_transaction' ],
 
1337           disabled => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
 
1341           call     => [ 'kivi.Draft.popup', 'ap', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
 
1342           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1343                     : $::form->{id}     ? t8('This invoice has already been posted.')
 
1344                     : $is_closed        ? t8('The billing period has already been locked.')
 
1347       ], # end of combobox "more"
 
1350   $::request->layout->add_javascripts('kivi.Validator.js');