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 flash_later);
 
  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->{payment_id}       = $template->payment_id;
 
 134   $::form->{AP_chart_id}      = $template->ar_ap_chart_id;
 
 135   $::form->{transdate}        = $today->to_kivitendo;
 
 136   $::form->{duedate}          = $today->to_kivitendo;
 
 137   $::form->{rowcount}         = @{ $template->items };
 
 138   $::form->{paidaccounts}     = 1;
 
 139   $::form->{$_}               = $template->$_ for qw(department_id ordnumber taxincluded notes);
 
 141   if ($template->vendor) {
 
 142     $::form->{vendor_id} = $template->vendor_id;
 
 143     $::form->{vendor}    = $template->vendor->name;
 
 144     $::form->{duedate}     = $template->vendor->payment->calc_date(reference_date => $today)->to_kivitendo if $template->vendor->payment;
 
 148   foreach my $item (@{ $template->items }) {
 
 151     my $active_taxkey = $item->chart->get_active_taxkey;
 
 152     my $taxes         = SL::DB::Manager::Tax->get_all(
 
 153       where   => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
 
 154       sort_by => 'taxkey, rate',
 
 157     my $tax   = first { $item->tax_id          == $_->id } @{ $taxes };
 
 158     $tax    //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
 
 159     $tax    //= $taxes->[0];
 
 166     $::form->{"AP_amount_chart_id_${row}"}          = $item->chart_id;
 
 167     $::form->{"previous_AP_amount_chart_id_${row}"} = $item->chart_id;
 
 168     $::form->{"amount_${row}"}                      = $::form->format_amount(\%::myconfig, $item->amount1, 2);
 
 169     $::form->{"taxchart_${row}"}                    = $item->tax_id . '--' . $tax->rate;
 
 170     $::form->{"project_id_${row}"}                  = $item->project_id;
 
 173   $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
 
 175   flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
 
 176   flash('info', $::locale->text("Payment bookings disallowed. After the booking this record may be " .
 
 177                                 "suggested with the amount of '#1' or otherwise has to be choosen manually." .
 
 178                                 " No automatic payment booking will be done to chart '#2'.",
 
 179                                   $form_defaults->{paid_1_suggestion},
 
 180                                   $form_defaults->{AP_paid_1_suggestion},
 
 181                                 )) if $::form->{no_payment_bookings};
 
 184     keep_rows_without_amount => 1,
 
 185     dont_add_new_row         => 1,
 
 189 sub save_record_template {
 
 190   $::auth->assert('ap_transactions');
 
 192   my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
 
 193   my $js       = SL::ClientJS->new(controller => SL::Controller::Base->new);
 
 194   my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
 
 196   $js->dialog->close('#record_template_dialog');
 
 199     $_->{chart_id} && (($_->{tax_id} // '') ne '')
 
 201     +{ chart_id   => $::form->{"AP_amount_chart_id_${_}"},
 
 202        amount1    => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
 
 203        tax_id     => (split m{--}, $::form->{"taxchart_${_}"})[0],
 
 204        project_id => $::form->{"project_id_${_}"} || undef,
 
 206   } (1..($::form->{rowcount} || 1));
 
 208   $template->assign_attributes(
 
 209     template_type  => 'ap_transaction',
 
 210     template_name  => $new_name,
 
 212     currency_id    => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
 
 213     ar_ap_chart_id => $::form->{AP_chart_id}      || undef,
 
 214     vendor_id      => $::form->{vendor_id}        || undef,
 
 215     department_id  => $::form->{department_id}    || undef,
 
 216     project_id     => $::form->{globalproject_id} || undef,
 
 217     payment_id     => $::form->{payment_id}       || undef,
 
 218     taxincluded    => $::form->{taxincluded}  ? 1 : 0,
 
 219     direct_debit   => $::form->{direct_debit} ? 1 : 0,
 
 220     ordnumber      => $::form->{ordnumber},
 
 221     notes          => $::form->{notes},
 
 231       ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
 
 236     ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
 
 241   $main::lxdebug->enter_sub();
 
 243   my $form     = $main::form;
 
 244   my %myconfig = %main::myconfig;
 
 246   $main::auth->assert('ap_transactions');
 
 248   $form->{title} = "Add";
 
 250   $form->{callback} = "ap.pl?action=add" unless $form->{callback};
 
 252   AP->get_transdate(\%myconfig, $form);
 
 253   $form->{initial_transdate} = $form->{transdate};
 
 254   create_links(dont_save => 1);
 
 255   $form->{transdate} = $form->{initial_transdate};
 
 257   if ($form->{vendor_id}) {
 
 258     my $vendor = SL::DB::Vendor->load_cached($form->{vendor_id});
 
 260     # set initial payment terms
 
 261     $form->{payment_id} = $vendor->payment_id;
 
 263     my $last_used_ap_chart = $vendor->last_used_ap_chart;
 
 264     $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
 269   $main::lxdebug->leave_sub();
 
 273   $main::lxdebug->enter_sub();
 
 275   # Delay access check to after the invoice's been loaded in
 
 276   # "create_links" so that project-specific invoice rights can be
 
 279   my $form     = $main::form;
 
 281   $form->{title} = "Edit";
 
 286   $main::lxdebug->leave_sub();
 
 290   $main::lxdebug->enter_sub();
 
 294   my $form     = $main::form;
 
 296   # get all files stored in the webdav folder
 
 297   if ($form->{invnumber} && $::instance_conf->get_webdav) {
 
 298     my $webdav = SL::Webdav->new(
 
 299       type     => 'accounts_payable',
 
 300       number   => $form->{invnumber},
 
 302     my @all_objects = $webdav->get_all_objects;
 
 303     @{ $form->{WEBDAV} } = map { { name => $_->filename,
 
 305                                    link => File::Spec->catfile($_->full_filedescriptor),
 
 311   $main::lxdebug->leave_sub();
 
 315   $main::lxdebug->enter_sub();
 
 317   # Delay access check to after the invoice's been loaded so that
 
 318   # project-specific invoice rights can be evaluated.
 
 322   my $form     = $main::form;
 
 323   my %myconfig = %main::myconfig;
 
 325   $form->create_links("AP", \%myconfig, "vendor");
 
 330   if (!$params{dont_save}) {
 
 331     %saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
 
 332     $saved{duedate} = $form->{duedate} if $form->{duedate};
 
 333     $saved{currency} = $form->{currency} if $form->{currency};
 
 334     $saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
 
 337   IR->get_vendor(\%myconfig, \%$form);
 
 339   $form->{$_}        = $saved{$_} for keys %saved;
 
 340   $form->{rowcount}  = 1;
 
 341   $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};
 
 343   # build the popup menus
 
 344   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
 
 347   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 349   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 351   $form->{employee} = "$form->{employee}--$form->{employee_id}";
 
 353   AP->setup_form($form);
 
 355   $main::lxdebug->leave_sub();
 
 359   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid paid_project_id);
 
 361     grep { $_->{paid} != 0 }
 
 364       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
 
 365     } (1..$::form->{paidaccounts});
 
 367   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
 
 369   $::form->{paidaccounts} = max scalar(@payments), 1;
 
 371   foreach my $idx (1 .. scalar(@payments)) {
 
 372     my $payment = $payments[$idx - 1];
 
 373     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
 
 378   $main::lxdebug->enter_sub();
 
 382   my $form     = $main::form;
 
 383   my %myconfig = %main::myconfig;
 
 384   my $locale   = $main::locale;
 
 385   my $cgi      = $::request->{cgi};
 
 387   $::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
 
 389   $form->{initial_focus} = !($form->{amount_1} * 1) ? 'vendor_id' : 'row_' . $form->{rowcount};
 
 391   $form->{title_} = $form->{title};
 
 392   $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
 
 394   # type=submit $locale->text('Add Accounts Payables Transaction')
 
 395   # type=submit $locale->text('Edit Accounts Payables Transaction')
 
 397   my $readonly = $form->{id} ? "readonly" : "";
 
 399   $form->{radier} = ($::instance_conf->get_ap_changeable == 2)
 
 400                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 401                       : ($::instance_conf->get_ap_changeable == 1);
 
 402   $readonly       = $form->{radier} ? "" : $readonly;
 
 404   $form->{readonly} = $readonly;
 
 406   $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 407   if ( $form->{forex} ) {
 
 408     $form->{exchangerate} = $form->{forex};
 
 412   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
 
 413   $form->{creditlimit}     = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
 
 414   $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
 
 417   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
 
 420   $form->{textarea_rows} = $rows;
 
 422   $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
 
 424   $form->get_lists("charts"    => { "key"       => "ALL_CHARTS",
 
 425                                     "transdate" => $form->{transdate} },
 
 429     { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
 
 430     @{ $form->{ALL_CHARTS} }
 
 433   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 435   my %project_labels = map { $_->id => $_->projectnumber }  @{ SL::DB::Manager::Project->get_all };
 
 438   my $default_ap_amount_chart_id;
 
 440   foreach my $item (@{ $form->{ALL_CHARTS} }) {
 
 441     if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
 
 442       $default_ap_amount_chart_id //= $item->{id};
 
 444     } elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
 
 445       push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
 
 448     $charts{$item->{accno}} = $item;
 
 451   my $follow_up_vc         = $form->{vendor_id} ? SL::DB::Vendor->load_cached($form->{vendor_id})->name : '';
 
 452   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
 
 454   $::request->layout->add_javascripts("autocomplete_chart.js", "show_vc_details.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.SalesPurchase.js", "kivi.GL.js", "kivi.RecordTemplate.js", "kivi.File.js", "kivi.AP.js", "kivi.CustomerVendor.js", "kivi.Validator.js", "autocomplete_project.js");
 
 455   # $form->{totalpaid} is used by the action bar setup to determine
 
 456   # whether or not canceling is allowed. Therefore it must be
 
 457   # calculated prior to the action bar setup.
 
 458   $form->{totalpaid} = sum map { $form->{"paid_${_}"} } (1..$form->{paidaccounts});
 
 460   setup_ap_display_form_action_bar();
 
 463   # get the correct date for tax
 
 464   my $transdate    = $::form->{transdate}    ? DateTime->from_kivitendo($::form->{transdate})    : DateTime->today_local;
 
 465   my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
 
 466   my $taxdate      = $deliverydate ? $deliverydate : $transdate;
 
 470   for my $i (1 .. $form->{rowcount}) {
 
 473     $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
 
 474     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
 
 476     my ($default_taxchart, $taxchart_to_use);
 
 478     if ( $form->{"taxchart_$i"} ) {
 
 479       ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
 
 481     my $amount_chart_id = $form->{"AP_amount_chart_id_$i"} || $default_ap_amount_chart_id;
 
 483     my @taxcharts       = GL->get_active_taxes_for_chart($amount_chart_id, $taxdate, $used_tax_id);
 
 484     foreach my $item (@taxcharts) {
 
 485       my $key             = $item->id . "--" . $item->rate;
 
 486       $first_taxchart   //= $item;
 
 487       $default_taxchart   = $item if $item->{is_default};
 
 488       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
 
 491     $taxchart_to_use               //= $default_taxchart // $first_taxchart;
 
 492     my $selected_taxchart            = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
 493     $form->{"selected_taxchart_$i"}  = $selected_taxchart;
 
 494     $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
 
 495     $form->{"taxcharts_$i"}          = \@taxcharts;
 
 498   $form->{taxchart_value_title_sub} = sub {
 
 501       $item->{id} .'--'. $item->{rate},
 
 502       $item->{taxkey} . ' - ' . $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
 
 506   $form->{AP_paid_value_title_sub} = sub {
 
 510       $item->{accno} .'--'. $item->{description}
 
 514   $form->{invtotal_unformatted} = $form->{invtotal};
 
 515   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
 
 519   if ( $form->{'paid_'. $form->{paidaccounts}} ) {
 
 520     $form->{paidaccounts}++;
 
 523   # default account for current assets (i.e. 1801 - SKR04)
 
 524   $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 526   for my $i (1 .. $form->{paidaccounts}) {
 
 528     if ($form->{"paid_$i"}) {
 
 529       $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
 
 531     if ($form->{"exchangerate_$i"} == 0) {
 
 532       $form->{"exchangerate_$i"} = "";
 
 534       $form->{"exchangerate_$i"} =
 
 535         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
 
 539     if (SL::DB::Default->get->payments_changeable == 0) {
 
 541       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
 
 543     if (SL::DB::Default->get->payments_changeable == 2) {
 
 545       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
 
 548     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
 
 549     if ($form->date_closed($form->{"gldate_$i"})) {
 
 553     $form->{'paidaccount_changeable_'. $i} = $changeable;
 
 555     $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
 
 556     # accno and description as info text
 
 557     $form->{'AP_paid_readonly_desc_' . $i} =  $form->{'AP_paid_' . $i} ?
 
 558        $form->{'AP_paid_' . $i} . " " . SL::DB::Manager::Chart->find_by(accno => $form->{'AP_paid_' . $i})->description
 
 562   $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
 
 564   $form->{payment_id} = $form->{invoice_obj}->{payment_id} // $form->{payment_id};
 
 565   print $form->parse_html_template('ap/form_header', {
 
 566     today => DateTime->today,
 
 567     currencies => SL::DB::Manager::Currency->get_all_sorted,
 
 568     payment_terms => SL::DB::Manager::PaymentTerm->get_all_sorted(query => [ or => [ obsolete => 0, id => $form->{payment_id}*1 ]]),
 
 571   $main::lxdebug->leave_sub();
 
 575   $::lxdebug->enter_sub;
 
 582     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
 
 584     if (@{ $follow_ups }) {
 
 585       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
 
 586       $num_follow_ups = scalar @{ $follow_ups }
 
 590   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
 
 591   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
 
 593   my $storno = $::form->{id}
 
 594             && !IS->has_storno(\%::myconfig, $::form, 'ap')
 
 595             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
 
 596             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
 
 599   print $::form->parse_html_template('ap/form_footer', {
 
 601     num_follow_ups    => $num_follow_ups,
 
 604   $::lxdebug->leave_sub;
 
 608   $::auth->assert('ap_transactions');
 
 610   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
 
 612   $::form->redirect($::locale->text("Marked as paid"));
 
 616   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
 
 617   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
 
 624   $main::lxdebug->enter_sub();
 
 626   my $form     = $main::form;
 
 627   my %myconfig = %main::myconfig;
 
 629   $main::auth->assert('ap_transactions');
 
 633   $form->{invtotal} = 0;
 
 635   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
 
 637   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 638     qw(exchangerate creditlimit creditremaining);
 
 640   my @flds  = qw(amount AP_amount_chart_id projectnumber oldprojectnumber project_id taxchart tax);
 
 642   my (@a, $j, $totaltax);
 
 643   for my $i (1 .. $form->{rowcount}) {
 
 644     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
 
 645     if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
 
 648       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
 
 650       # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
 
 652       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
 
 653       $totaltax += $form->{"tax_$i"};
 
 654       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 658   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
 
 660   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
 
 662   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 663   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 665   $form->{invdate} = $form->{transdate};
 
 667   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
 
 668     IR->get_vendor(\%::myconfig, $form);
 
 670     my $vendor = SL::DB::Vendor->load_cached($form->{vendor_id});
 
 672     # reset payment to new vendor
 
 673     $form->{payment_id} = $vendor->payment_id;
 
 675     if (($form->{rowcount} == 1) && ($form->{amount_1} == 0)) {
 
 676       my $last_used_ap_chart = $vendor->last_used_ap_chart;
 
 677       $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
 681   $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
 
 684     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
 
 687   for my $i (1 .. $form->{paidaccounts}) {
 
 688     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 691           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
 692       } qw(paid exchangerate);
 
 694       $totalpaid += $form->{"paid_$i"};
 
 696       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 697       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 701   $form->{creditremaining} -=
 
 702     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
 
 703      $form->{oldinvtotal});
 
 704   $form->{oldinvtotal}  = $form->{invtotal};
 
 705   $form->{oldtotalpaid} = $totalpaid;
 
 709   $main::lxdebug->leave_sub();
 
 714   $main::lxdebug->enter_sub();
 
 716   my $form     = $main::form;
 
 717   my %myconfig = %main::myconfig;
 
 718   my $locale   = $main::locale;
 
 720   $main::auth->assert('ap_transactions');
 
 721   $form->mtime_ischanged('ap');
 
 723   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 725   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 727   for my $i (1 .. $form->{paidaccounts}) {
 
 728     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 729       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 731       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 733       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 734         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 736       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 737       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 738       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 739         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 741       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 742         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 743           if ($invdate == $datepaid);
 
 744         $form->isblank("exchangerate_$i",
 
 745                        $locale->text('Exchangerate for payment missing!'));
 
 750   ($form->{AP})      = split /--/, $form->{AP};
 
 751   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
 
 752   if (AP->post_payment(\%myconfig, \%$form)) {
 
 753     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 754     $form->{what_done} = 'invoice';
 
 755     $form->{addition}  = "PAYMENT POSTED";
 
 757     $form->redirect($locale->text('Payment posted!'))
 
 759     $form->error($locale->text('Cannot post payment!'));
 
 763   $main::lxdebug->leave_sub();
 
 768   $main::lxdebug->enter_sub();
 
 770   my $form     = $main::form;
 
 771   my %myconfig = %main::myconfig;
 
 772   my $locale   = $main::locale;
 
 774   $main::auth->assert('ap_transactions');
 
 775   $form->mtime_ischanged('ap');
 
 779   # check if there is a vendor, invoice, due date and invnumber
 
 780   $form->isblank("transdate",   $locale->text("Invoice Date missing!"));
 
 781   $form->isblank("duedate",     $locale->text("Due Date missing!"));
 
 782   $form->isblank("vendor_id",   $locale->text('Vendor missing!'));
 
 783   $form->isblank("invnumber",   $locale->text('Invoice Number missing!'));
 
 784   $form->isblank("AP_chart_id", $locale->text('No contra account selected!'));
 
 786   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 787     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 792   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
 793   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 795   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 796     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
 
 797   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
 
 799   my $zero_amount_posting = 1;
 
 800   for my $i (1 .. $form->{rowcount}) {
 
 801     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
 
 802       $zero_amount_posting = 0;
 
 807   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
 
 809   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 810     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
 
 813   for my $i (1 .. $form->{paidaccounts}) {
 
 814     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 815       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 817       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 819       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 820       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 822       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 823       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 824       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 825         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 827       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 828         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 829           if ($transdate == $datepaid);
 
 830         $form->isblank("exchangerate_$i",
 
 831                        $locale->text('Exchangerate for payment missing!'));
 
 837   # if old vendor ne vendor redo form
 
 838   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
 840     $::dispatcher->end_request;
 
 844   $form->{id} = 0 if $form->{postasnew};
 
 846   if (AP->post_transaction(\%myconfig, \%$form)) {
 
 847     # create webdav folder
 
 848     if ($::instance_conf->get_webdav) {
 
 849       SL::Webdav->new(type     => 'accounts_payable',
 
 850                       number   => $form->{invnumber},
 
 854     if(!exists $form->{addition} && $form->{id} ne "") {
 
 855       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 856       $form->{addition}  = "POSTED";
 
 857       $form->{what_done} = "invoice";
 
 862       my $msg = $locale->text("AP transaction '#1' posted (ID: #2)", $form->{invnumber}, $form->{id});
 
 863       if ($form->{callback} =~ /BankTransaction/) {
 
 864         # no restore_from_session_id needed. we like to have a newly generated
 
 865         # list of invoices for bank transactions
 
 866         SL::Helper::Flash::flash_later('info', $msg);
 
 867         print $form->redirect_header($form->{callback});
 
 868         $::dispatcher->end_request;
 
 870       } elsif ('doc-tab' eq $form->{after_action}) {
 
 871         # Redirect with callback containing a fragment does not work (by now)
 
 872         # because the callback info is stored in the session an parsing the
 
 873         # callback parameters does not support fragments (see SL::Form::redirect).
 
 874         # So use flash_later for the message and redirect_headers for redirecting.
 
 875         my $add_doc_url = build_std_url("script=ap.pl", 'action=edit', 'id=' . E($form->{id}), 'fragment=ui-tabs-docs');
 
 876         SL::Helper::Flash::flash_later('info', $msg);
 
 877         print $form->redirect_header($add_doc_url);
 
 878         $::dispatcher->end_request;
 
 881         $form->redirect($msg);
 
 886     $form->error($locale->text('Cannot post transaction!'));
 
 889   $main::lxdebug->leave_sub();
 
 893   $main::lxdebug->enter_sub();
 
 895   my $form     = $main::form;
 
 896   my %myconfig = %main::myconfig;
 
 898   $main::auth->assert('ap_transactions');
 
 900   $form->{postasnew} = 1;
 
 902   if(!exists $form->{addition} && $form->{id} ne "") {
 
 903     # does this work? post_as_new for ap doesn't immediately save the
 
 904     # invoice, because the invnumber has to be entered by hand.
 
 905     # And the value of $form->{postasnew} isn't checked when calling post
 
 906     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 907     $form->{addition}  = "POSTED AS NEW";
 
 908     $form->{what_done} = "invoice";
 
 911   # /saving the history
 
 914   $main::lxdebug->leave_sub();
 
 918   $main::lxdebug->enter_sub();
 
 920   my $form     = $main::form;
 
 921   my %myconfig = %main::myconfig;
 
 923   $main::auth->assert('ap_transactions');
 
 925   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);
 
 926   $form->{paidaccounts} = 1;
 
 929   my $today          = DateTime->today_local;
 
 930   $form->{transdate} = $today->to_kivitendo;
 
 931   $form->{duedate}   = $form->{transdate};
 
 933   if ($form->{vendor_id}) {
 
 934     my $payment_terms = SL::DB::Vendor->load_cached($form->{vendor_id})->payment;
 
 935     $form->{duedate}  = $payment_terms->calc_date(reference_date => $today)->to_kivitendo if $payment_terms;
 
 940   $main::lxdebug->leave_sub();
 
 944   my $form     = $main::form;
 
 945   my %myconfig = %main::myconfig;
 
 946   my $locale   = $main::locale;
 
 948   $main::auth->assert('ap_transactions');
 
 950   if (AP->delete_transaction(\%myconfig, \%$form)) {
 
 952     if(!exists $form->{addition}) {
 
 953       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 954       $form->{addition}  = "DELETED";
 
 955       $form->{what_done} = "invoice";
 
 958     # /saving the history
 
 959     $form->redirect($locale->text('Transaction deleted!'));
 
 961   $form->error($locale->text('Cannot delete transaction!'));
 
 965   $main::lxdebug->enter_sub();
 
 967   my $form     = $main::form;
 
 968   my %myconfig = %main::myconfig;
 
 969   my $locale   = $main::locale;
 
 971   $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
 
 973   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 974   # constants and subs for template
 
 975   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
 
 977   $::request->layout->add_javascripts("autocomplete_project.js");
 
 979   setup_ap_search_action_bar();
 
 982   print $form->parse_html_template('ap/search', { %myconfig });
 
 984   $main::lxdebug->leave_sub();
 
 987 sub create_subtotal_row {
 
 988   $main::lxdebug->enter_sub();
 
 990   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
 
 992   my $form     = $main::form;
 
 993   my %myconfig = %main::myconfig;
 
 995   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
 
 997   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
 
 999   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
 
1001   map { $totals->{$_} = 0 } @{ $subtotal_columns };
 
1003   $main::lxdebug->leave_sub();
 
1008 sub ap_transactions {
 
1009   $main::lxdebug->enter_sub();
 
1011   my $form     = $main::form;
 
1012   my %myconfig = %main::myconfig;
 
1013   my $locale   = $main::locale;
 
1015   report_generator_set_default_sort('transdate', 1);
 
1017   AP->ap_transactions(\%myconfig, \%$form);
 
1019   $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
 
1021   my $report = SL::ReportGenerator->new(\%myconfig, $form);
 
1024     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
 
1025        due duedate transaction_description notes employee globalprojectnumber department
 
1026        vendornumber country ustid taxzone payment_terms charts debit_chart direct_debit
 
1029   my @hidden_variables = map { "l_${_}" } @columns;
 
1030   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto
 
1031                                            parts_partnumber parts_description department_id);
 
1033   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
 
1036     'transdate'               => { 'text' => $locale->text('Date'), },
 
1037     'id'                      => { 'text' => $locale->text('ID'), },
 
1038     'type'                    => { 'text' => $locale->text('Type'), },
 
1039     'invnumber'               => { 'text' => $locale->text('Invoice'), },
 
1040     'ordnumber'               => { 'text' => $locale->text('Order'), },
 
1041     'name'                    => { 'text' => $locale->text('Vendor'), },
 
1042     'netamount'               => { 'text' => $locale->text('Amount'), },
 
1043     'tax'                     => { 'text' => $locale->text('Tax'), },
 
1044     'amount'                  => { 'text' => $locale->text('Total'), },
 
1045     'paid'                    => { 'text' => $locale->text('Paid'), },
 
1046     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
 
1047     'due'                     => { 'text' => $locale->text('Amount Due'), },
 
1048     'duedate'                 => { 'text' => $locale->text('Due Date'), },
 
1049     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
 
1050     'notes'                   => { 'text' => $locale->text('Notes'), },
 
1051     'employee'                => { 'text' => $locale->text('Employee'), },
 
1052     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
 
1053     'department'              => { 'text' => $locale->text('Department'), },
 
1054     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
 
1055     'country'                 => { 'text' => $locale->text('Country'), },
 
1056     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
 
1057     'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
 
1058     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
 
1059     'charts'                  => { 'text' => $locale->text('Chart'), },
 
1060     'debit_chart'             => { 'text' => $locale->text('Debit Account'), },
 
1061     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
 
1062     'insertdate'              => { 'text' => $locale->text('Insert Date'), },
 
1065   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit department)) {
 
1066     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
 
1067     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
 
1070   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
 
1072   $form->{"l_type"} = "Y";
 
1073   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
 
1075   $report->set_columns(%column_defs);
 
1076   $report->set_column_order(@columns);
 
1078   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
 
1080   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
 
1082   my $department_description;
 
1083   $department_description = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
 
1084   my $project_description;
 
1085   $project_description = SL::DB::Manager::Project->find_by(id => $form->{project_id})->description if $form->{project_id};
 
1088   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
 
1089   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
 
1090   push @options, $locale->text('Department')              . " : $department_description"                 if ($form->{department_id});
 
1091   push @options, $locale->text('Project')                 . " : $project_description"                    if ($project_description);
 
1092   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
 
1093   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
 
1094   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
 
1095   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
 
1096   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
 
1097   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
 
1098   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
 
1099   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
 
1100   push @options, $locale->text('Open')                                                                   if ($form->{open});
 
1101   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
 
1103   $report->set_options('top_info_text'        => join("\n", @options),
 
1104                        'output_format'        => 'HTML',
 
1105                        'title'                => $form->{title},
 
1106                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
 
1108   $report->set_options_from_form();
 
1109   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
1111   # add sort and escape callback, this one we use for the add sub
 
1112   $form->{callback} = $href .= "&sort=$form->{sort}";
 
1114   # escape callback for href
 
1115   my $callback = $form->escape($href);
 
1117   my @subtotal_columns = qw(netamount amount paid due);
 
1119   my %totals    = map { $_ => 0 } @subtotal_columns;
 
1120   my %subtotals = map { $_ => 0 } @subtotal_columns;
 
1124   foreach my $ap (@{ $form->{AP} }) {
 
1125     $ap->{tax} = $ap->{amount} - $ap->{netamount};
 
1126     $ap->{due} = $ap->{amount} - $ap->{paid};
 
1128     map { $subtotals{$_} += $ap->{$_};
 
1129           $totals{$_}    += $ap->{$_} } @subtotal_columns;
 
1131     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
 
1133     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
 
1134     my $has_storno = $ap->{storno} && !$ap->{storno_id};
 
1136     if ($ap->{invoice}) {
 
1138           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
 
1139         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
 
1140         :                     $locale->text("Invoice (one letter abbreviation)");
 
1143           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
 
1144         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
 
1145         :                     $locale->text("AP Transaction (abbreviation)");
 
1148     $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
 
1152     foreach my $column (@columns) {
 
1154         'data'  => $ap->{$column},
 
1155         'align' => $column_alignment{$column},
 
1159     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
 
1160       . "&id=" . E($ap->{id}) . "&callback=${callback}";
 
1162     my $row_set = [ $row ];
 
1164     if (($form->{l_subtotal} eq 'Y')
 
1165         && (($idx == (scalar @{ $form->{AP} } - 1))
 
1166             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
 
1167       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
 
1170     $report->add_data($row_set);
 
1175   $report->add_separator();
 
1176   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
 
1178   setup_ap_transactions_action_bar();
 
1179   $report->generate_with_headers();
 
1181   $main::lxdebug->leave_sub();
 
1185   $main::lxdebug->enter_sub();
 
1187   my $form     = $main::form;
 
1188   my %myconfig = %main::myconfig;
 
1189   my $locale   = $main::locale;
 
1191   $main::auth->assert('ap_transactions');
 
1193   if (IS->has_storno(\%myconfig, $form, 'ap')) {
 
1194     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
 
1195     $form->error($locale->text("Transaction has already been cancelled!"));
 
1198   $form->error($locale->text('Cannot post storno for a closed period!'))
 
1199     if ( $form->date_closed($form->{transdate}, \%myconfig));
 
1201   AP->storno($form, \%myconfig, $form->{id});
 
1203   # saving the history
 
1204   if(!exists $form->{addition} && $form->{id} ne "") {
 
1205     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
1206     $form->{addition}  = "STORNO";
 
1207     $form->{what_done} = "invoice";
 
1208     $form->save_history;
 
1210   # /saving the history
 
1212   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
 
1214   $main::lxdebug->leave_sub();
 
1217 sub add_from_purchase_order {
 
1218   $main::auth->assert('ap_transactions');
 
1220   return if !$::form->{id};
 
1222   my $order_id = delete $::form->{id};
 
1223   my $order    = SL::DB::Order->new(id => $order_id)->load(with => [ 'vendor', 'currency', 'payment_terms' ]);
 
1225   return if $order->type ne 'purchase_order';
 
1227   my $today                     = DateTime->today_local;
 
1228   $::form->{title}              = "Add";
 
1229   $::form->{vc}                 = 'vendor';
 
1230   $::form->{vendor_id}          = $order->customervendor->id;
 
1231   $::form->{vendor}             = $order->vendor->name;
 
1232   $::form->{convert_from_oe_id} = $order->id;
 
1233   $::form->{globalproject_id}   = $order->globalproject_id;
 
1234   $::form->{ordnumber}          = $order->number;
 
1235   $::form->{department_id}      = $order->department_id;
 
1236   $::form->{currency}           = $order->currency->name;
 
1237   $::form->{taxincluded}        = 1; # we use amount below, so tax is included
 
1238   $::form->{transdate}          = $today->to_kivitendo;
 
1239   $::form->{duedate}            = $today->to_kivitendo;
 
1240   $::form->{duedate}            = $order->payment_terms->calc_date(reference_date => $today)->to_kivitendo if $order->payment_terms;
 
1241   $::form->{deliverydate}       = $order->reqdate->to_kivitendo                                            if $order->reqdate;
 
1244   my $config_po_ap_workflow_chart_id = $::instance_conf->get_workflow_po_ap_chart_id;
 
1246   my ($first_taxchart, $default_taxchart, $taxchart_to_use);
 
1248   @taxcharts    = GL->get_active_taxes_for_chart($config_po_ap_workflow_chart_id, $::form->{transdate}) if (defined $config_po_ap_workflow_chart_id);
 
1249   foreach my $item (@taxcharts) {
 
1250     $first_taxchart   //= $item;
 
1251     $default_taxchart   = $item if $item->{is_default};
 
1253   $taxchart_to_use      = $default_taxchart // $first_taxchart;
 
1255   my %pat = $order->calculate_prices_and_taxes;
 
1257   foreach my $amount_chart (keys %{$pat{amounts}}) {
 
1258     my $tax = SL::DB::Manager::Tax->find_by(id => $pat{amounts}->{$amount_chart}->{tax_id});
 
1259     # If tax chart from order for this amount is active, use it. Use default or first tax chart for selected chart else.
 
1260     if (defined $config_po_ap_workflow_chart_id) {
 
1261       $taxchart_to_use = (first {$_->{id} == $tax->id} @taxcharts) // $taxchart_to_use;
 
1263       $taxchart_to_use = $tax;
 
1266     $::form->{"AP_amount_chart_id_$row"}          = $config_po_ap_workflow_chart_id // $amount_chart;
 
1267     $::form->{"previous_AP_amount_chart_id_$row"} = $::form->{"AP_amount_chart_id_$row"};
 
1268     $::form->{"amount_$row"}                      = $::form->format_amount(\%::myconfig, $pat{amounts}->{$amount_chart}->{amount} * (1 + $tax->rate), 2);
 
1269     $::form->{"taxchart_$row"}                    = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
1270     $::form->{"project_id_$row"}                  = $order->globalproject_id;
 
1275   my $last_used_ap_chart               = SL::DB::Vendor->load_cached($::form->{vendor_id})->last_used_ap_chart;
 
1276   $::form->{"AP_amount_chart_id_$row"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
1277   $::form->{rowcount}                  = $row;
 
1280     keep_rows_without_amount => 1,
 
1281     dont_add_new_row         => 1,
 
1285 sub setup_ap_search_action_bar {
 
1288   for my $bar ($::request->layout->get('actionbar')) {
 
1291         $::locale->text('Search'),
 
1292         submit    => [ '#form', { action => "ap_transactions" } ],
 
1293         checks    => [ 'kivi.validate_form' ],
 
1294         accesskey => 'enter',
 
1298   $::request->layout->add_javascripts('kivi.Validator.js');
 
1301 sub setup_ap_transactions_action_bar {
 
1303   my $may_edit_create = $::auth->assert('ap_transactions', 1);
 
1305   for my $bar ($::request->layout->get('actionbar')) {
 
1308         action => [ t8('Add') ],
 
1310           t8('Purchase Invoice'),
 
1311           link     => [ 'ir.pl?action=add' ],
 
1312           disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
 
1316           t8('AP Transaction'),
 
1317           link     => [ 'ap.pl?action=add' ],
 
1318           disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
 
1320       ], # end of combobox "Add"
 
1325 sub setup_ap_display_form_action_bar {
 
1326   my $transdate               = $::form->datetonum($::form->{transdate}, \%::myconfig);
 
1327   my $closedto                = $::form->datetonum($::form->{closedto},  \%::myconfig);
 
1328   my $is_closed               = $transdate <= $closedto;
 
1330   my $change_never            = $::instance_conf->get_ap_changeable == 0;
 
1331   my $change_on_same_day_only = $::instance_conf->get_ap_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
 
1333   my $is_storno               = IS->is_storno(\%::myconfig, $::form, 'ap', $::form->{id});
 
1334   my $has_storno              = IS->has_storno(\%::myconfig, $::form, 'ap');
 
1336   my $may_edit_create         = $::auth->assert('ap_transactions', 1);
 
1338   my $has_sepa_exports;
 
1339   if ($::form->{id}) {
 
1340     my $invoice = SL::DB::Manager::PurchaseInvoice->find_by(id => $::form->{id});
 
1341     $has_sepa_exports = 1 if ($invoice->find_sepa_export_items()->[0]);
 
1344   my $is_linked_bank_transaction;
 
1346       && SL::DB::Default->get->payments_changeable != 0
 
1347       && SL::DB::Manager::BankTransactionAccTrans->find_by(ap_id => $::form->{id})) {
 
1349     $is_linked_bank_transaction = 1;
 
1352   my $create_post_action = sub {
 
1353     # $_[0]: description
 
1354     # $_[1]: after_action
 
1357       submit   => [ '#form', { action => "post", after_action => $_[1] } ],
 
1358       checks   => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting', 'kivi.AP.check_duplicate_invnumber' ],
 
1359       disabled => !$may_edit_create                           ? t8('You must not change this AP transaction.')
 
1360                 : $is_closed                                  ? t8('The billing period has already been locked.')
 
1361                 : $is_storno                                  ? t8('A canceled invoice cannot be posted.')
 
1362                 : ($::form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
 
1363                 : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
 
1364                 : $is_linked_bank_transaction                 ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1370   if ($::instance_conf->get_ap_add_doc && $::instance_conf->get_doc_storage) {
 
1371     @post_entries = ( $create_post_action->(t8('Post'), 'doc-tab'),
 
1372                       $create_post_action->(t8('Post and new booking')) );
 
1373   } elsif ($::instance_conf->get_doc_storage) {
 
1374     @post_entries = ( $create_post_action->(t8('Post')),
 
1375                       $create_post_action->(t8('Post and upload document'), 'doc-tab') );
 
1377     @post_entries = ( $create_post_action->(t8('Post')) );
 
1380   for my $bar ($::request->layout->get('actionbar')) {
 
1384         submit    => [ '#form', { action => "update" } ],
 
1385         id        => 'update_button',
 
1386         checks    => [ 'kivi.validate_form' ],
 
1387         accesskey => 'enter',
 
1388         disabled  => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
 
1394           submit   => [ '#form', { action => "post_payment" } ],
 
1395           checks   => [ 'kivi.validate_form' ],
 
1396           disabled => !$may_edit_create           ? t8('You must not change this AP transaction.')
 
1397                     : !$::form->{id}              ? t8('This invoice has not been posted yet.')
 
1398                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1401         action => [ t8('Mark as paid'),
 
1402           submit   => [ '#form', { action => "mark_as_paid" } ],
 
1403           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
 
1404           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1405                     : !$::form->{id}    ? t8('This invoice has not been posted yet.')
 
1407           only_if  => $::instance_conf->get_is_show_mark_as_paid,
 
1409       ], # end of combobox "Post"
 
1412         action => [ t8('Storno'),
 
1413           submit   => [ '#form', { action => "storno" } ],
 
1414           checks   => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting' ],
 
1415           confirm  => t8('Do you really want to cancel this invoice?'),
 
1416           disabled => !$may_edit_create    ? t8('You must not change this AP transaction.')
 
1417                     : !$::form->{id}       ? t8('This invoice has not been posted yet.')
 
1418                     : $has_storno          ? t8('This invoice has been canceled already.')
 
1419                     : $is_storno           ? t8('Reversal invoices cannot be canceled.')
 
1420                     : $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
 
1421                     : $has_sepa_exports    ? t8('This invoice has been linked with a sepa export, undo this first.')
 
1424         action => [ t8('Delete'),
 
1425           submit   => [ '#form', { action => "delete" } ],
 
1426           confirm  => t8('Do you really want to delete this object?'),
 
1427           disabled => !$may_edit_create           ? t8('You must not change this AP transaction.')
 
1428                     : !$::form->{id}              ? t8('This invoice has not been posted yet.')
 
1429                     : $change_never               ? t8('Changing invoices has been disabled in the configuration.')
 
1430                     : $change_on_same_day_only    ? t8('Invoices can only be changed on the day they are posted.')
 
1431                     : $has_storno                 ? t8('This invoice has been canceled already.')
 
1432                     : $is_closed                  ? t8('The billing period has already been locked.')
 
1433                     : $has_sepa_exports           ? t8('This invoice has been linked with a sepa export, undo this first.')
 
1434                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1437       ], # end of combobox "Storno"
 
1442         action => [ t8('Workflow') ],
 
1445           submit   => [ '#form', { action => "use_as_new" } ],
 
1446           checks   => [ 'kivi.validate_form' ],
 
1447           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1448                     : !$::form->{id}    ? t8('This invoice has not been posted yet.')
 
1451       ], # end of combobox "Workflow"
 
1454         action => [ t8('more') ],
 
1457           call     => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
 
1458           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
1462           call     => [ 'follow_up_window' ],
 
1463           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
1466           t8('Record templates'),
 
1467           call     => [ 'kivi.RecordTemplate.popup', 'ap_transaction' ],
 
1468           disabled => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
 
1472           call     => [ 'kivi.Draft.popup', 'ap', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
 
1473           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1474                     : $::form->{id}     ? t8('This invoice has already been posted.')
 
1475                     : $is_closed        ? t8('The billing period has already been locked.')
 
1478       ], # end of combobox "more"
 
1481   $::request->layout->add_javascripts('kivi.Validator.js');