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;
 
  46 use SL::DB::BankTransactionAccTrans;
 
  51 use SL::DB::PaymentTerm;
 
  52 use SL::DB::PurchaseInvoice;
 
  53 use SL::DB::RecordTemplate;
 
  56 use SL::Locale::String qw(t8);
 
  58 require "bin/mozilla/common.pl";
 
  59 require "bin/mozilla/reportgenerator.pl";
 
  67 # this is for our long dates
 
  68 # $locale->text('January')
 
  69 # $locale->text('February')
 
  70 # $locale->text('March')
 
  71 # $locale->text('April')
 
  72 # $locale->text('May ')
 
  73 # $locale->text('June')
 
  74 # $locale->text('July')
 
  75 # $locale->text('August')
 
  76 # $locale->text('September')
 
  77 # $locale->text('October')
 
  78 # $locale->text('November')
 
  79 # $locale->text('December')
 
  81 # this is for our short month
 
  82 # $locale->text('Jan')
 
  83 # $locale->text('Feb')
 
  84 # $locale->text('Mar')
 
  85 # $locale->text('Apr')
 
  86 # $locale->text('May')
 
  87 # $locale->text('Jun')
 
  88 # $locale->text('Jul')
 
  89 # $locale->text('Aug')
 
  90 # $locale->text('Sep')
 
  91 # $locale->text('Oct')
 
  92 # $locale->text('Nov')
 
  93 # $locale->text('Dec')
 
  95 sub _may_view_or_edit_this_invoice {
 
  96   return 1 if  $::auth->assert('ap_transactions', 1); # may edit all invoices
 
  97   return 0 if !$::form->{id};                         # creating new invoices isn't allowed without invoice_edit
 
  98   return 0 if !$::form->{globalproject_id};           # existing records without a project ID are not allowed
 
  99   return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
 
 103   my $cache = $::request->cache('ap.pl::_assert_access');
 
 105   $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice()                              if !exists $cache->{_may_view_or_edit_this_invoice};
 
 106   $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if !       $cache->{_may_view_or_edit_this_invoice};
 
 109 sub load_record_template {
 
 110   $::auth->assert('ap_transactions');
 
 112   # Load existing template and verify that its one for this module.
 
 113   my $template = SL::DB::RecordTemplate
 
 114     ->new(id => $::form->{id})
 
 116       with_object => [ qw(customer payment currency record_items record_items.chart) ],
 
 119   die "invalid template type" unless $template->template_type eq 'ap_transaction';
 
 121   $template->substitute_variables;
 
 123   # Clean the current $::form before rebuilding it from the template.
 
 124   my $form_defaults = delete $::form->{form_defaults};
 
 125   delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
 
 127   # Fill $::form from the template.
 
 128   my $today                   = DateTime->today_local;
 
 129   $::form->{title}            = "Add";
 
 130   $::form->{currency}         = $template->currency->name;
 
 131   $::form->{direct_debit}     = $template->direct_debit;
 
 132   $::form->{globalproject_id} = $template->project_id;
 
 133   $::form->{AP_chart_id}      = $template->ar_ap_chart_id;
 
 134   $::form->{transdate}        = $today->to_kivitendo;
 
 135   $::form->{duedate}          = $today->to_kivitendo;
 
 136   $::form->{rowcount}         = @{ $template->items };
 
 137   $::form->{paidaccounts}     = 1;
 
 138   $::form->{$_}               = $template->$_ for qw(department_id ordnumber taxincluded notes);
 
 140   if ($template->vendor) {
 
 141     $::form->{vendor_id} = $template->vendor_id;
 
 142     $::form->{vendor}    = $template->vendor->name;
 
 143     $::form->{duedate}     = $template->vendor->payment->calc_date(reference_date => $today)->to_kivitendo if $template->vendor->payment;
 
 147   foreach my $item (@{ $template->items }) {
 
 150     my $active_taxkey = $item->chart->get_active_taxkey;
 
 151     my $taxes         = SL::DB::Manager::Tax->get_all(
 
 152       where   => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
 
 153       sort_by => 'taxkey, rate',
 
 156     my $tax   = first { $item->tax_id          == $_->id } @{ $taxes };
 
 157     $tax    //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
 
 158     $tax    //= $taxes->[0];
 
 165     $::form->{"AP_amount_chart_id_${row}"}          = $item->chart_id;
 
 166     $::form->{"previous_AP_amount_chart_id_${row}"} = $item->chart_id;
 
 167     $::form->{"amount_${row}"}                      = $::form->format_amount(\%::myconfig, $item->amount1, 2);
 
 168     $::form->{"taxchart_${row}"}                    = $item->tax_id . '--' . $tax->rate;
 
 169     $::form->{"project_id_${row}"}                  = $item->project_id;
 
 172   $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
 
 174   flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
 
 175   flash('info', $::locale->text("Payment bookings disallowed. After the booking this record may be " .
 
 176                                 "suggested with the amount of '#1' or otherwise has to be choosen manually." .
 
 177                                 " No automatic payment booking will be done to chart '#2'.",
 
 178                                   $form_defaults->{paid_1_suggestion},
 
 179                                   $form_defaults->{AP_paid_1_suggestion},
 
 180                                 )) if $::form->{no_payment_bookings};
 
 183     keep_rows_without_amount => 1,
 
 184     dont_add_new_row         => 1,
 
 188 sub save_record_template {
 
 189   $::auth->assert('ap_transactions');
 
 191   my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
 
 192   my $js       = SL::ClientJS->new(controller => SL::Controller::Base->new);
 
 193   my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
 
 195   $js->dialog->close('#record_template_dialog');
 
 198     $_->{chart_id} && (($_->{tax_id} // '') ne '')
 
 200     +{ chart_id   => $::form->{"AP_amount_chart_id_${_}"},
 
 201        amount1    => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
 
 202        tax_id     => (split m{--}, $::form->{"taxchart_${_}"})[0],
 
 203        project_id => $::form->{"project_id_${_}"} || undef,
 
 205   } (1..($::form->{rowcount} || 1));
 
 207   $template->assign_attributes(
 
 208     template_type  => 'ap_transaction',
 
 209     template_name  => $new_name,
 
 211     currency_id    => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
 
 212     ar_ap_chart_id => $::form->{AP_chart_id}      || undef,
 
 213     vendor_id      => $::form->{vendor_id}        || undef,
 
 214     department_id  => $::form->{department_id}    || undef,
 
 215     project_id     => $::form->{globalproject_id} || undef,
 
 216     taxincluded    => $::form->{taxincluded}  ? 1 : 0,
 
 217     direct_debit   => $::form->{direct_debit} ? 1 : 0,
 
 218     ordnumber      => $::form->{ordnumber},
 
 219     notes          => $::form->{notes},
 
 229       ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
 
 234     ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
 
 239   $main::lxdebug->enter_sub();
 
 241   my $form     = $main::form;
 
 242   my %myconfig = %main::myconfig;
 
 244   $main::auth->assert('ap_transactions');
 
 246   $form->{title} = "Add";
 
 248   $form->{callback} = "ap.pl?action=add" unless $form->{callback};
 
 250   AP->get_transdate(\%myconfig, $form);
 
 251   $form->{initial_transdate} = $form->{transdate};
 
 252   create_links(dont_save => 1);
 
 253   $form->{transdate} = $form->{initial_transdate};
 
 255   if ($form->{vendor_id}) {
 
 256     my $vendor = SL::DB::Vendor->load_cached($form->{vendor_id});
 
 258     # set initial payment terms
 
 259     $form->{payment_id} = $vendor->payment_id;
 
 261     my $last_used_ap_chart = $vendor->last_used_ap_chart;
 
 262     $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
 267   $main::lxdebug->leave_sub();
 
 271   $main::lxdebug->enter_sub();
 
 273   # Delay access check to after the invoice's been loaded in
 
 274   # "create_links" so that project-specific invoice rights can be
 
 277   my $form     = $main::form;
 
 279   $form->{title} = "Edit";
 
 284   $main::lxdebug->leave_sub();
 
 288   $main::lxdebug->enter_sub();
 
 292   my $form     = $main::form;
 
 294   # get all files stored in the webdav folder
 
 295   if ($form->{invnumber} && $::instance_conf->get_webdav) {
 
 296     my $webdav = SL::Webdav->new(
 
 297       type     => 'accounts_payable',
 
 298       number   => $form->{invnumber},
 
 300     my @all_objects = $webdav->get_all_objects;
 
 301     @{ $form->{WEBDAV} } = map { { name => $_->filename,
 
 303                                    link => File::Spec->catfile($_->full_filedescriptor),
 
 309   $main::lxdebug->leave_sub();
 
 313   $main::lxdebug->enter_sub();
 
 315   # Delay access check to after the invoice's been loaded so that
 
 316   # project-specific invoice rights can be evaluated.
 
 320   my $form     = $main::form;
 
 321   my %myconfig = %main::myconfig;
 
 323   $form->create_links("AP", \%myconfig, "vendor");
 
 328   if (!$params{dont_save}) {
 
 329     %saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
 
 330     $saved{duedate} = $form->{duedate} if $form->{duedate};
 
 331     $saved{currency} = $form->{currency} if $form->{currency};
 
 332     $saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
 
 335   IR->get_vendor(\%myconfig, \%$form);
 
 337   $form->{$_}        = $saved{$_} for keys %saved;
 
 338   $form->{rowcount}  = 1;
 
 339   $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};
 
 341   # build the popup menus
 
 342   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
 
 345   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 347   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 349   $form->{employee} = "$form->{employee}--$form->{employee_id}";
 
 351   AP->setup_form($form);
 
 353   $main::lxdebug->leave_sub();
 
 357   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid paid_project_id);
 
 359     grep { $_->{paid} != 0 }
 
 362       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
 
 363     } (1..$::form->{paidaccounts});
 
 365   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
 
 367   $::form->{paidaccounts} = max scalar(@payments), 1;
 
 369   foreach my $idx (1 .. scalar(@payments)) {
 
 370     my $payment = $payments[$idx - 1];
 
 371     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
 
 376   $main::lxdebug->enter_sub();
 
 380   my $form     = $main::form;
 
 381   my %myconfig = %main::myconfig;
 
 382   my $locale   = $main::locale;
 
 383   my $cgi      = $::request->{cgi};
 
 385   $::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
 
 387   $form->{initial_focus} = !($form->{amount_1} * 1) ? 'vendor_id' : 'row_' . $form->{rowcount};
 
 389   $form->{title_} = $form->{title};
 
 390   $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
 
 392   # type=submit $locale->text('Add Accounts Payables Transaction')
 
 393   # type=submit $locale->text('Edit Accounts Payables Transaction')
 
 395   my $readonly = $form->{id} ? "readonly" : "";
 
 397   $form->{radier} = ($::instance_conf->get_ap_changeable == 2)
 
 398                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 399                       : ($::instance_conf->get_ap_changeable == 1);
 
 400   $readonly       = $form->{radier} ? "" : $readonly;
 
 402   $form->{readonly} = $readonly;
 
 404   $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 405   if ( $form->{forex} ) {
 
 406     $form->{exchangerate} = $form->{forex};
 
 410   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
 
 411   $form->{creditlimit}     = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
 
 412   $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
 
 415   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
 
 418   $form->{textarea_rows} = $rows;
 
 420   $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
 
 422   $form->get_lists("charts"    => { "key"       => "ALL_CHARTS",
 
 423                                     "transdate" => $form->{transdate} },
 
 427     { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
 
 428     @{ $form->{ALL_CHARTS} }
 
 431   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 433   my %project_labels = map { $_->id => $_->projectnumber }  @{ SL::DB::Manager::Project->get_all };
 
 436   my $default_ap_amount_chart_id;
 
 438   foreach my $item (@{ $form->{ALL_CHARTS} }) {
 
 439     if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
 
 440       $default_ap_amount_chart_id //= $item->{id};
 
 442     } elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
 
 443       push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
 
 446     $charts{$item->{accno}} = $item;
 
 449   my $follow_up_vc         = $form->{vendor_id} ? SL::DB::Vendor->load_cached($form->{vendor_id})->name : '';
 
 450   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
 
 452   $::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", "autocomplete_project.js");
 
 453   # $form->{totalpaid} is used by the action bar setup to determine
 
 454   # whether or not canceling is allowed. Therefore it must be
 
 455   # calculated prior to the action bar setup.
 
 456   $form->{totalpaid} = sum map { $form->{"paid_${_}"} } (1..$form->{paidaccounts});
 
 458   setup_ap_display_form_action_bar();
 
 461   # get the correct date for tax
 
 462   my $transdate    = $::form->{transdate}    ? DateTime->from_kivitendo($::form->{transdate})    : DateTime->today_local;
 
 463   my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
 
 464   my $taxdate      = $deliverydate ? $deliverydate : $transdate;
 
 468   for my $i (1 .. $form->{rowcount}) {
 
 471     $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
 
 472     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
 
 474     my ($default_taxchart, $taxchart_to_use);
 
 476     if ( $form->{"taxchart_$i"} ) {
 
 477       ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
 
 479     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, $taxdate, $used_tax_id);
 
 482     foreach my $item (@taxcharts) {
 
 483       my $key             = $item->id . "--" . $item->rate;
 
 484       $first_taxchart   //= $item;
 
 485       $default_taxchart   = $item if $item->{is_default};
 
 486       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
 
 489     $taxchart_to_use               //= $default_taxchart // $first_taxchart;
 
 490     my $selected_taxchart            = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
 491     $form->{"selected_taxchart_$i"}  = $selected_taxchart;
 
 492     $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
 
 493     $form->{"taxcharts_$i"}          = \@taxcharts;
 
 496   $form->{taxchart_value_title_sub} = sub {
 
 499       $item->{id} .'--'. $item->{rate},
 
 500       $item->{taxkey} . ' - ' . $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
 
 504   $form->{AP_paid_value_title_sub} = sub {
 
 508       $item->{accno} .'--'. $item->{description}
 
 512   $form->{invtotal_unformatted} = $form->{invtotal};
 
 513   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
 
 517   if ( $form->{'paid_'. $form->{paidaccounts}} ) {
 
 518     $form->{paidaccounts}++;
 
 521   # default account for current assets (i.e. 1801 - SKR04)
 
 522   $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 524   for my $i (1 .. $form->{paidaccounts}) {
 
 526     if ($form->{"paid_$i"}) {
 
 527       $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
 
 529     if ($form->{"exchangerate_$i"} == 0) {
 
 530       $form->{"exchangerate_$i"} = "";
 
 532       $form->{"exchangerate_$i"} =
 
 533         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
 
 537     if (SL::DB::Default->get->payments_changeable == 0) {
 
 539       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
 
 541     if (SL::DB::Default->get->payments_changeable == 2) {
 
 543       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
 
 546     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
 
 547     if ($form->date_closed($form->{"gldate_$i"})) {
 
 551     $form->{'paidaccount_changeable_'. $i} = $changeable;
 
 553     $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
 
 554     # accno and description as info text
 
 555     $form->{'AP_paid_readonly_desc_' . $i} =  $form->{'AP_paid_' . $i} ?
 
 556        $form->{'AP_paid_' . $i} . " " . SL::DB::Manager::Chart->find_by(accno => $form->{'AP_paid_' . $i})->description
 
 560   $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
 
 562   print $form->parse_html_template('ap/form_header', {
 
 563     today => DateTime->today,
 
 564     currencies => SL::DB::Manager::Currency->get_all_sorted,
 
 565     payment_terms => SL::DB::Manager::PaymentTerm->get_all_sorted(query => [ or => [ obsolete => 0, id => $::form->{payment_id}*1 ]]),
 
 568   $main::lxdebug->leave_sub();
 
 572   $::lxdebug->enter_sub;
 
 579     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
 
 581     if (@{ $follow_ups }) {
 
 582       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
 
 583       $num_follow_ups = scalar @{ $follow_ups }
 
 587   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
 
 588   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
 
 590   my $storno = $::form->{id}
 
 591             && !IS->has_storno(\%::myconfig, $::form, 'ap')
 
 592             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
 
 593             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
 
 596   print $::form->parse_html_template('ap/form_footer', {
 
 598     num_follow_ups    => $num_follow_ups,
 
 601   $::lxdebug->leave_sub;
 
 605   $::auth->assert('ap_transactions');
 
 607   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
 
 609   $::form->redirect($::locale->text("Marked as paid"));
 
 613   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
 
 614   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
 
 621   $main::lxdebug->enter_sub();
 
 623   my $form     = $main::form;
 
 624   my %myconfig = %main::myconfig;
 
 626   $main::auth->assert('ap_transactions');
 
 630   $form->{invtotal} = 0;
 
 632   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
 
 634   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 635     qw(exchangerate creditlimit creditremaining);
 
 637   my @flds  = qw(amount AP_amount_chart_id projectnumber oldprojectnumber project_id taxchart tax);
 
 639   my (@a, $j, $totaltax);
 
 640   for my $i (1 .. $form->{rowcount}) {
 
 641     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
 
 642     if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
 
 645       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
 
 647       # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
 
 649       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
 
 650       $totaltax += $form->{"tax_$i"};
 
 651       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 655   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
 
 657   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
 
 659   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 660   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 662   $form->{invdate} = $form->{transdate};
 
 664   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
 
 665     IR->get_vendor(\%::myconfig, $form);
 
 667     my $vendor = SL::DB::Vendor->load_cached($form->{vendor_id});
 
 669     # reset payment to new vendor
 
 670     $form->{payment_id} = $vendor->payment_id;
 
 672     if (($form->{rowcount} == 1) && ($form->{amount_1} == 0)) {
 
 673       my $last_used_ap_chart = $vendor->last_used_ap_chart;
 
 674       $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
 678   $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
 
 681     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
 
 684   for my $i (1 .. $form->{paidaccounts}) {
 
 685     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 688           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
 689       } qw(paid exchangerate);
 
 691       $totalpaid += $form->{"paid_$i"};
 
 693       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 694       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 698   $form->{creditremaining} -=
 
 699     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
 
 700      $form->{oldinvtotal});
 
 701   $form->{oldinvtotal}  = $form->{invtotal};
 
 702   $form->{oldtotalpaid} = $totalpaid;
 
 706   $main::lxdebug->leave_sub();
 
 711   $main::lxdebug->enter_sub();
 
 713   my $form     = $main::form;
 
 714   my %myconfig = %main::myconfig;
 
 715   my $locale   = $main::locale;
 
 717   $main::auth->assert('ap_transactions');
 
 718   $form->mtime_ischanged('ap');
 
 720   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 722   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 724   for my $i (1 .. $form->{paidaccounts}) {
 
 725     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 726       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 728       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 730       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 731         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 733       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 734       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 735       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 736         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 738       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 739         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 740           if ($invdate == $datepaid);
 
 741         $form->isblank("exchangerate_$i",
 
 742                        $locale->text('Exchangerate for payment missing!'));
 
 747   ($form->{AP})      = split /--/, $form->{AP};
 
 748   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
 
 749   if (AP->post_payment(\%myconfig, \%$form)) {
 
 750     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 751     $form->{what_done} = 'invoice';
 
 752     $form->{addition}  = "PAYMENT POSTED";
 
 754     $form->redirect($locale->text('Payment posted!'))
 
 756     $form->error($locale->text('Cannot post payment!'));
 
 760   $main::lxdebug->leave_sub();
 
 765   $main::lxdebug->enter_sub();
 
 767   my $form     = $main::form;
 
 768   my %myconfig = %main::myconfig;
 
 769   my $locale   = $main::locale;
 
 771   $main::auth->assert('ap_transactions');
 
 772   $form->mtime_ischanged('ap');
 
 776   # check if there is a vendor, invoice, due date and invnumber
 
 777   $form->isblank("transdate",   $locale->text("Invoice Date missing!"));
 
 778   $form->isblank("duedate",     $locale->text("Due Date missing!"));
 
 779   $form->isblank("vendor_id",   $locale->text('Vendor missing!'));
 
 780   $form->isblank("invnumber",   $locale->text('Invoice Number missing!'));
 
 781   $form->isblank("AP_chart_id", $locale->text('No contra account selected!'));
 
 783   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 784     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 789   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
 790   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 792   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 793     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
 
 794   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
 
 796   my $zero_amount_posting = 1;
 
 797   for my $i (1 .. $form->{rowcount}) {
 
 798     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
 
 799       $zero_amount_posting = 0;
 
 804   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
 
 806   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 807     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
 
 810   for my $i (1 .. $form->{paidaccounts}) {
 
 811     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 812       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 814       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 816       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 817       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 819       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 820       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 821       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 822         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 824       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 825         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 826           if ($transdate == $datepaid);
 
 827         $form->isblank("exchangerate_$i",
 
 828                        $locale->text('Exchangerate for payment missing!'));
 
 834   # if old vendor ne vendor redo form
 
 835   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
 837     $::dispatcher->end_request;
 
 841   $form->{id} = 0 if $form->{postasnew};
 
 843   if (AP->post_transaction(\%myconfig, \%$form)) {
 
 844     # create webdav folder
 
 845     if ($::instance_conf->get_webdav) {
 
 846       SL::Webdav->new(type     => 'accounts_payable',
 
 847                       number   => $form->{invnumber},
 
 851     if(!exists $form->{addition} && $form->{id} ne "") {
 
 852       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 853       $form->{addition}  = "POSTED";
 
 854       $form->{what_done} = "invoice";
 
 857     # no restore_from_session_id needed. we like to have a newly generated
 
 858     # list of invoices for bank transactions
 
 859     print $form->redirect_header($form->{callback}) if ($form->{callback} =~ /BankTransaction/);
 
 860     $form->redirect($locale->text('AP transaction posted.') . ' ' . $locale->text('ID') . ': ' . $form->{id}) unless $inline;
 
 861     # TODO Add callback/return flag in myconfig
 
 862     # With version 3.5 we can add documents, but only after posting. there should be a flag in myconfig for the user
 
 863     # $form->{callback} ||= 'ap.pl?action=edit&id=' . $form->{id} if $myconfig{no_reset_arap};
 
 866     $form->error($locale->text('Cannot post transaction!'));
 
 869   $main::lxdebug->leave_sub();
 
 873   $main::lxdebug->enter_sub();
 
 875   my $form     = $main::form;
 
 876   my %myconfig = %main::myconfig;
 
 878   $main::auth->assert('ap_transactions');
 
 880   $form->{postasnew} = 1;
 
 882   if(!exists $form->{addition} && $form->{id} ne "") {
 
 883     # does this work? post_as_new for ap doesn't immediately save the
 
 884     # invoice, because the invnumber has to be entered by hand.
 
 885     # And the value of $form->{postasnew} isn't checked when calling post
 
 886     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 887     $form->{addition}  = "POSTED AS NEW";
 
 888     $form->{what_done} = "invoice";
 
 891   # /saving the history
 
 894   $main::lxdebug->leave_sub();
 
 898   $main::lxdebug->enter_sub();
 
 900   my $form     = $main::form;
 
 901   my %myconfig = %main::myconfig;
 
 903   $main::auth->assert('ap_transactions');
 
 905   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 convert_from_oe_id);
 
 906   $form->{paidaccounts} = 1;
 
 909   my $today          = DateTime->today_local;
 
 910   $form->{transdate} = $today->to_kivitendo;
 
 911   $form->{duedate}   = $form->{transdate};
 
 913   if ($form->{vendor_id}) {
 
 914     my $payment_terms = SL::DB::Vendor->load_cached($form->{vendor_id})->payment;
 
 915     $form->{duedate}  = $payment_terms->calc_date(reference_date => $today)->to_kivitendo if $payment_terms;
 
 920   $main::lxdebug->leave_sub();
 
 924   my $form     = $main::form;
 
 925   my %myconfig = %main::myconfig;
 
 926   my $locale   = $main::locale;
 
 928   $main::auth->assert('ap_transactions');
 
 930   if (AP->delete_transaction(\%myconfig, \%$form)) {
 
 932     if(!exists $form->{addition}) {
 
 933       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 934       $form->{addition}  = "DELETED";
 
 935       $form->{what_done} = "invoice";
 
 938     # /saving the history
 
 939     $form->redirect($locale->text('Transaction deleted!'));
 
 941   $form->error($locale->text('Cannot delete transaction!'));
 
 945   $main::lxdebug->enter_sub();
 
 947   my $form     = $main::form;
 
 948   my %myconfig = %main::myconfig;
 
 949   my $locale   = $main::locale;
 
 951   $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
 
 953   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 954   # constants and subs for template
 
 955   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
 
 957   $::request->layout->add_javascripts("autocomplete_project.js");
 
 959   setup_ap_search_action_bar();
 
 962   print $form->parse_html_template('ap/search', { %myconfig });
 
 964   $main::lxdebug->leave_sub();
 
 967 sub create_subtotal_row {
 
 968   $main::lxdebug->enter_sub();
 
 970   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
 
 972   my $form     = $main::form;
 
 973   my %myconfig = %main::myconfig;
 
 975   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
 
 977   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
 
 979   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
 
 981   map { $totals->{$_} = 0 } @{ $subtotal_columns };
 
 983   $main::lxdebug->leave_sub();
 
 988 sub ap_transactions {
 
 989   $main::lxdebug->enter_sub();
 
 991   my $form     = $main::form;
 
 992   my %myconfig = %main::myconfig;
 
 993   my $locale   = $main::locale;
 
 995   report_generator_set_default_sort('transdate', 1);
 
 997   AP->ap_transactions(\%myconfig, \%$form);
 
 999   $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
 
1001   my $report = SL::ReportGenerator->new(\%myconfig, $form);
 
1004     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
 
1005        due duedate transaction_description notes employee globalprojectnumber department
 
1006        vendornumber country ustid taxzone payment_terms charts direct_debit);
 
1008   my @hidden_variables = map { "l_${_}" } @columns;
 
1009   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto
 
1010                                            parts_partnumber parts_description department_id);
 
1012   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
 
1015     'transdate'               => { 'text' => $locale->text('Date'), },
 
1016     'id'                      => { 'text' => $locale->text('ID'), },
 
1017     'type'                    => { 'text' => $locale->text('Type'), },
 
1018     'invnumber'               => { 'text' => $locale->text('Invoice'), },
 
1019     'ordnumber'               => { 'text' => $locale->text('Order'), },
 
1020     'name'                    => { 'text' => $locale->text('Vendor'), },
 
1021     'netamount'               => { 'text' => $locale->text('Amount'), },
 
1022     'tax'                     => { 'text' => $locale->text('Tax'), },
 
1023     'amount'                  => { 'text' => $locale->text('Total'), },
 
1024     'paid'                    => { 'text' => $locale->text('Paid'), },
 
1025     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
 
1026     'due'                     => { 'text' => $locale->text('Amount Due'), },
 
1027     'duedate'                 => { 'text' => $locale->text('Due Date'), },
 
1028     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
 
1029     'notes'                   => { 'text' => $locale->text('Notes'), },
 
1030     'employee'                => { 'text' => $locale->text('Employee'), },
 
1031     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
 
1032     'department'              => { 'text' => $locale->text('Department'), },
 
1033     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
 
1034     'country'                 => { 'text' => $locale->text('Country'), },
 
1035     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
 
1036     'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
 
1037     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
 
1038     'charts'                  => { 'text' => $locale->text('Chart'), },
 
1039     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
 
1042   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit department)) {
 
1043     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
 
1044     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
 
1047   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
 
1049   $form->{"l_type"} = "Y";
 
1050   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
 
1052   $report->set_columns(%column_defs);
 
1053   $report->set_column_order(@columns);
 
1055   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
 
1057   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
 
1059   my $department_description;
 
1060   $department_description = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
 
1063   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
 
1064   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
 
1065   push @options, $locale->text('Department')              . " : $department_description"                 if ($form->{department_id});
 
1066   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
 
1067   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
 
1068   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
 
1069   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
 
1070   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
 
1071   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
 
1072   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
 
1073   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
 
1074   push @options, $locale->text('Open')                                                                   if ($form->{open});
 
1075   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
 
1077   $report->set_options('top_info_text'        => join("\n", @options),
 
1078                        'output_format'        => 'HTML',
 
1079                        'title'                => $form->{title},
 
1080                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
 
1082   $report->set_options_from_form();
 
1083   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
1085   # add sort and escape callback, this one we use for the add sub
 
1086   $form->{callback} = $href .= "&sort=$form->{sort}";
 
1088   # escape callback for href
 
1089   my $callback = $form->escape($href);
 
1091   my @subtotal_columns = qw(netamount amount paid due);
 
1093   my %totals    = map { $_ => 0 } @subtotal_columns;
 
1094   my %subtotals = map { $_ => 0 } @subtotal_columns;
 
1098   foreach my $ap (@{ $form->{AP} }) {
 
1099     $ap->{tax} = $ap->{amount} - $ap->{netamount};
 
1100     $ap->{due} = $ap->{amount} - $ap->{paid};
 
1102     map { $subtotals{$_} += $ap->{$_};
 
1103           $totals{$_}    += $ap->{$_} } @subtotal_columns;
 
1105     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
 
1107     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
 
1108     my $has_storno = $ap->{storno} && !$ap->{storno_id};
 
1110     if ($ap->{invoice}) {
 
1112           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
 
1113         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
 
1114         :                     $locale->text("Invoice (one letter abbreviation)");
 
1117           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
 
1118         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
 
1119         :                     $locale->text("AP Transaction (abbreviation)");
 
1122     $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
 
1126     foreach my $column (@columns) {
 
1128         'data'  => $ap->{$column},
 
1129         'align' => $column_alignment{$column},
 
1133     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
 
1134       . "&id=" . E($ap->{id}) . "&callback=${callback}";
 
1136     my $row_set = [ $row ];
 
1138     if (($form->{l_subtotal} eq 'Y')
 
1139         && (($idx == (scalar @{ $form->{AP} } - 1))
 
1140             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
 
1141       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
 
1144     $report->add_data($row_set);
 
1149   $report->add_separator();
 
1150   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
 
1152   setup_ap_transactions_action_bar();
 
1153   $report->generate_with_headers();
 
1155   $main::lxdebug->leave_sub();
 
1159   $main::lxdebug->enter_sub();
 
1161   my $form     = $main::form;
 
1162   my %myconfig = %main::myconfig;
 
1163   my $locale   = $main::locale;
 
1165   $main::auth->assert('ap_transactions');
 
1167   if (IS->has_storno(\%myconfig, $form, 'ap')) {
 
1168     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
 
1169     $form->error($locale->text("Transaction has already been cancelled!"));
 
1172   $form->error($locale->text('Cannot post storno for a closed period!'))
 
1173     if ( $form->date_closed($form->{transdate}, \%myconfig));
 
1175   AP->storno($form, \%myconfig, $form->{id});
 
1177   # saving the history
 
1178   if(!exists $form->{addition} && $form->{id} ne "") {
 
1179     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
1180     $form->{addition}  = "STORNO";
 
1181     $form->{what_done} = "invoice";
 
1182     $form->save_history;
 
1184   # /saving the history
 
1186   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
 
1188   $main::lxdebug->leave_sub();
 
1191 sub add_from_purchase_order {
 
1192   $main::auth->assert('ap_transactions');
 
1194   return if !$::form->{id};
 
1196   my $order_id = delete $::form->{id};
 
1197   my $order    = SL::DB::Order->new(id => $order_id)->load(with => [ 'vendor', 'currency', 'payment_terms' ]);
 
1199   return if $order->type ne 'purchase_order';
 
1201   my $today                     = DateTime->today_local;
 
1202   $::form->{title}              = "Add";
 
1203   $::form->{vc}                 = 'vendor';
 
1204   $::form->{vendor_id}          = $order->customervendor->id;
 
1205   $::form->{vendor}             = $order->vendor->name;
 
1206   $::form->{convert_from_oe_id} = $order->id;
 
1207   $::form->{globalproject_id}   = $order->globalproject_id;
 
1208   $::form->{ordnumber}          = $order->number;
 
1209   $::form->{department_id}      = $order->department_id;
 
1210   $::form->{currency}           = $order->currency->name;
 
1211   $::form->{taxincluded}        = 1; # we use amount below, so tax is included
 
1212   $::form->{transdate}          = $today->to_kivitendo;
 
1213   $::form->{duedate}            = $today->to_kivitendo;
 
1214   $::form->{duedate}            = $order->payment_terms->calc_date(reference_date => $today)->to_kivitendo if $order->payment_terms;
 
1215   $::form->{deliverydate}       = $order->reqdate->to_kivitendo                                            if $order->reqdate;
 
1218   my $config_po_ap_workflow_chart_id = $::instance_conf->get_workflow_po_ap_chart_id;
 
1220   my ($first_taxchart, $default_taxchart, $taxchart_to_use);
 
1222   @taxcharts    = GL->get_active_taxes_for_chart($config_po_ap_workflow_chart_id, $::form->{transdate}) if (defined $config_po_ap_workflow_chart_id);
 
1223   foreach my $item (@taxcharts) {
 
1224     $first_taxchart   //= $item;
 
1225     $default_taxchart   = $item if $item->{is_default};
 
1227   $taxchart_to_use      = $default_taxchart // $first_taxchart;
 
1229   my %pat = $order->calculate_prices_and_taxes;
 
1231   foreach my $amount_chart (keys %{$pat{amounts}}) {
 
1232     my $tax = SL::DB::Manager::Tax->find_by(id => $pat{amounts}->{$amount_chart}->{tax_id});
 
1233     # If tax chart from order for this amount is active, use it. Use default or first tax chart for selected chart else.
 
1234     if (defined $config_po_ap_workflow_chart_id) {
 
1235       $taxchart_to_use = (first {$_->{id} == $tax->id} @taxcharts) // $taxchart_to_use;
 
1237       $taxchart_to_use = $tax;
 
1240     $::form->{"AP_amount_chart_id_$row"}          = $config_po_ap_workflow_chart_id // $amount_chart;
 
1241     $::form->{"previous_AP_amount_chart_id_$row"} = $::form->{"AP_amount_chart_id_$row"};
 
1242     $::form->{"amount_$row"}                      = $::form->format_amount(\%::myconfig, $pat{amounts}->{$amount_chart}->{amount} * (1 + $tax->rate), 2);
 
1243     $::form->{"taxchart_$row"}                    = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
1244     $::form->{"project_id_$row"}                  = $order->globalproject_id;
 
1249   my $last_used_ap_chart               = SL::DB::Vendor->load_cached($::form->{vendor_id})->last_used_ap_chart;
 
1250   $::form->{"AP_amount_chart_id_$row"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
1251   $::form->{rowcount}                  = $row;
 
1254     keep_rows_without_amount => 1,
 
1255     dont_add_new_row         => 1,
 
1259 sub setup_ap_search_action_bar {
 
1262   for my $bar ($::request->layout->get('actionbar')) {
 
1265         $::locale->text('Search'),
 
1266         submit    => [ '#form', { action => "ap_transactions" } ],
 
1267         checks    => [ 'kivi.validate_form' ],
 
1268         accesskey => 'enter',
 
1272   $::request->layout->add_javascripts('kivi.Validator.js');
 
1275 sub setup_ap_transactions_action_bar {
 
1277   my $may_edit_create = $::auth->assert('ap_transactions', 1);
 
1279   for my $bar ($::request->layout->get('actionbar')) {
 
1282         action => [ t8('Add') ],
 
1284           t8('Purchase Invoice'),
 
1285           link     => [ 'ir.pl?action=add' ],
 
1286           disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
 
1290           t8('AP Transaction'),
 
1291           link     => [ 'ap.pl?action=add' ],
 
1292           disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
 
1294       ], # end of combobox "Add"
 
1299 sub setup_ap_display_form_action_bar {
 
1300   my $transdate               = $::form->datetonum($::form->{transdate}, \%::myconfig);
 
1301   my $closedto                = $::form->datetonum($::form->{closedto},  \%::myconfig);
 
1302   my $is_closed               = $transdate <= $closedto;
 
1304   my $change_never            = $::instance_conf->get_ap_changeable == 0;
 
1305   my $change_on_same_day_only = $::instance_conf->get_ap_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
 
1307   my $is_storno               = IS->is_storno(\%::myconfig, $::form, 'ap', $::form->{id});
 
1308   my $has_storno              = IS->has_storno(\%::myconfig, $::form, 'ap');
 
1310   my $may_edit_create         = $::auth->assert('ap_transactions', 1);
 
1312   my $has_sepa_exports;
 
1313   if ($::form->{id}) {
 
1314     my $invoice = SL::DB::Manager::PurchaseInvoice->find_by(id => $::form->{id});
 
1315     $has_sepa_exports = 1 if ($invoice->find_sepa_export_items()->[0]);
 
1318   my $is_linked_bank_transaction;
 
1320       && SL::DB::Default->get->payments_changeable != 0
 
1321       && SL::DB::Manager::BankTransactionAccTrans->find_by(ap_id => $::form->{id})) {
 
1323     $is_linked_bank_transaction = 1;
 
1326   for my $bar ($::request->layout->get('actionbar')) {
 
1330         submit    => [ '#form', { action => "update" } ],
 
1331         id        => 'update_button',
 
1332         checks    => [ 'kivi.validate_form' ],
 
1333         accesskey => 'enter',
 
1334         disabled  => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
 
1340           submit   => [ '#form', { action => "post" } ],
 
1341           checks   => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting', 'kivi.AP.check_duplicate_invnumber' ],
 
1342           disabled => !$may_edit_create                           ? t8('You must not change this AP transaction.')
 
1343                     : $is_closed                                  ? t8('The billing period has already been locked.')
 
1344                     : $is_storno                                  ? t8('A canceled invoice cannot be posted.')
 
1345                     : ($::form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
 
1346                     : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
 
1347                     : $is_linked_bank_transaction                 ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1352           submit   => [ '#form', { action => "post_payment" } ],
 
1353           checks   => [ 'kivi.validate_form' ],
 
1354           disabled => !$may_edit_create           ? t8('You must not change this AP transaction.')
 
1355                     : !$::form->{id}              ? t8('This invoice has not been posted yet.')
 
1356                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1359         action => [ t8('Mark as paid'),
 
1360           submit   => [ '#form', { action => "mark_as_paid" } ],
 
1361           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
 
1362           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1363                     : !$::form->{id}    ? t8('This invoice has not been posted yet.')
 
1365           only_if  => $::instance_conf->get_is_show_mark_as_paid,
 
1367       ], # end of combobox "Post"
 
1370         action => [ t8('Storno'),
 
1371           submit   => [ '#form', { action => "storno" } ],
 
1372           checks   => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting' ],
 
1373           confirm  => t8('Do you really want to cancel this invoice?'),
 
1374           disabled => !$may_edit_create    ? t8('You must not change this AP transaction.')
 
1375                     : !$::form->{id}       ? t8('This invoice has not been posted yet.')
 
1376                     : $has_storno          ? t8('This invoice has been canceled already.')
 
1377                     : $is_storno           ? t8('Reversal invoices cannot be canceled.')
 
1378                     : $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
 
1379                     : $has_sepa_exports    ? t8('This invoice has been linked with a sepa export, undo this first.')
 
1382         action => [ t8('Delete'),
 
1383           submit   => [ '#form', { action => "delete" } ],
 
1384           confirm  => t8('Do you really want to delete this object?'),
 
1385           disabled => !$may_edit_create           ? t8('You must not change this AP transaction.')
 
1386                     : !$::form->{id}              ? t8('This invoice has not been posted yet.')
 
1387                     : $change_never               ? t8('Changing invoices has been disabled in the configuration.')
 
1388                     : $change_on_same_day_only    ? t8('Invoices can only be changed on the day they are posted.')
 
1389                     : $has_storno                 ? t8('This invoice has been canceled already.')
 
1390                     : $is_closed                  ? t8('The billing period has already been locked.')
 
1391                     : $has_sepa_exports           ? t8('This invoice has been linked with a sepa export, undo this first.')
 
1392                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1395       ], # end of combobox "Storno"
 
1400         action => [ t8('Workflow') ],
 
1403           submit   => [ '#form', { action => "use_as_new" } ],
 
1404           checks   => [ 'kivi.validate_form' ],
 
1405           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1406                     : !$::form->{id}    ? t8('This invoice has not been posted yet.')
 
1409       ], # end of combobox "Workflow"
 
1412         action => [ t8('more') ],
 
1415           call     => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
 
1416           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
1420           call     => [ 'follow_up_window' ],
 
1421           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
1424           t8('Record templates'),
 
1425           call     => [ 'kivi.RecordTemplate.popup', 'ap_transaction' ],
 
1426           disabled => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
 
1430           call     => [ 'kivi.Draft.popup', 'ap', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
 
1431           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1432                     : $::form->{id}     ? t8('This invoice has already been posted.')
 
1433                     : $is_closed        ? t8('The billing period has already been locked.')
 
1436       ], # end of combobox "more"
 
1439   $::request->layout->add_javascripts('kivi.Validator.js');