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::PurchaseInvoice;
 
  52 use SL::DB::RecordTemplate;
 
  55 use SL::Locale::String qw(t8);
 
  57 require "bin/mozilla/common.pl";
 
  58 require "bin/mozilla/reportgenerator.pl";
 
  66 # this is for our long dates
 
  67 # $locale->text('January')
 
  68 # $locale->text('February')
 
  69 # $locale->text('March')
 
  70 # $locale->text('April')
 
  71 # $locale->text('May ')
 
  72 # $locale->text('June')
 
  73 # $locale->text('July')
 
  74 # $locale->text('August')
 
  75 # $locale->text('September')
 
  76 # $locale->text('October')
 
  77 # $locale->text('November')
 
  78 # $locale->text('December')
 
  80 # this is for our short month
 
  81 # $locale->text('Jan')
 
  82 # $locale->text('Feb')
 
  83 # $locale->text('Mar')
 
  84 # $locale->text('Apr')
 
  85 # $locale->text('May')
 
  86 # $locale->text('Jun')
 
  87 # $locale->text('Jul')
 
  88 # $locale->text('Aug')
 
  89 # $locale->text('Sep')
 
  90 # $locale->text('Oct')
 
  91 # $locale->text('Nov')
 
  92 # $locale->text('Dec')
 
  94 sub _may_view_or_edit_this_invoice {
 
  95   return 1 if  $::auth->assert('ap_transactions', 1); # may edit all invoices
 
  96   return 0 if !$::form->{id};                         # creating new invoices isn't allowed without invoice_edit
 
  97   return 0 if !$::form->{globalproject_id};           # existing records without a project ID are not allowed
 
  98   return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
 
 102   my $cache = $::request->cache('ap.pl::_assert_access');
 
 104   $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice()                              if !exists $cache->{_may_view_or_edit_this_invoice};
 
 105   $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if !       $cache->{_may_view_or_edit_this_invoice};
 
 108 sub load_record_template {
 
 109   $::auth->assert('ap_transactions');
 
 111   # Load existing template and verify that its one for this module.
 
 112   my $template = SL::DB::RecordTemplate
 
 113     ->new(id => $::form->{id})
 
 115       with_object => [ qw(customer payment currency record_items record_items.chart) ],
 
 118   die "invalid template type" unless $template->template_type eq 'ap_transaction';
 
 120   $template->substitute_variables;
 
 122   # Clean the current $::form before rebuilding it from the template.
 
 123   my $form_defaults = delete $::form->{form_defaults};
 
 124   delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
 
 126   # Fill $::form from the template.
 
 127   my $today                   = DateTime->today_local;
 
 128   $::form->{title}            = "Add";
 
 129   $::form->{currency}         = $template->currency->name;
 
 130   $::form->{direct_debit}     = $template->direct_debit;
 
 131   $::form->{globalproject_id} = $template->project_id;
 
 132   $::form->{AP_chart_id}      = $template->ar_ap_chart_id;
 
 133   $::form->{transdate}        = $today->to_kivitendo;
 
 134   $::form->{duedate}          = $today->to_kivitendo;
 
 135   $::form->{rowcount}         = @{ $template->items };
 
 136   $::form->{paidaccounts}     = 1;
 
 137   $::form->{$_}               = $template->$_ for qw(department_id ordnumber taxincluded notes);
 
 139   if ($template->vendor) {
 
 140     $::form->{vendor_id} = $template->vendor_id;
 
 141     $::form->{vendor}    = $template->vendor->name;
 
 142     $::form->{duedate}     = $template->vendor->payment->calc_date(reference_date => $today)->to_kivitendo if $template->vendor->payment;
 
 146   foreach my $item (@{ $template->items }) {
 
 149     my $active_taxkey = $item->chart->get_active_taxkey;
 
 150     my $taxes         = SL::DB::Manager::Tax->get_all(
 
 151       where   => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
 
 152       sort_by => 'taxkey, rate',
 
 155     my $tax   = first { $item->tax_id          == $_->id } @{ $taxes };
 
 156     $tax    //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
 
 157     $tax    //= $taxes->[0];
 
 164     $::form->{"AP_amount_chart_id_${row}"}          = $item->chart_id;
 
 165     $::form->{"previous_AP_amount_chart_id_${row}"} = $item->chart_id;
 
 166     $::form->{"amount_${row}"}                      = $::form->format_amount(\%::myconfig, $item->amount1, 2);
 
 167     $::form->{"taxchart_${row}"}                    = $item->tax_id . '--' . $tax->rate;
 
 168     $::form->{"project_id_${row}"}                  = $item->project_id;
 
 171   $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
 
 173   flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
 
 174   flash('info', $::locale->text("Payment bookings disallowed. After the booking this record may be " .
 
 175                                 "suggested with the amount of '#1' or otherwise has to be choosen manually." .
 
 176                                 " No automatic payment booking will be done to chart '#2'.",
 
 177                                   $form_defaults->{paid_1_suggestion},
 
 178                                   $form_defaults->{AP_paid_1_suggestion},
 
 179                                 )) if $::form->{no_payment_bookings};
 
 182     keep_rows_without_amount => 1,
 
 183     dont_add_new_row         => 1,
 
 187 sub save_record_template {
 
 188   $::auth->assert('ap_transactions');
 
 190   my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
 
 191   my $js       = SL::ClientJS->new(controller => SL::Controller::Base->new);
 
 192   my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
 
 194   $js->dialog->close('#record_template_dialog');
 
 197     $_->{chart_id} && (($_->{tax_id} // '') ne '')
 
 199     +{ chart_id   => $::form->{"AP_amount_chart_id_${_}"},
 
 200        amount1    => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
 
 201        tax_id     => (split m{--}, $::form->{"taxchart_${_}"})[0],
 
 202        project_id => $::form->{"project_id_${_}"} || undef,
 
 204   } (1..($::form->{rowcount} || 1));
 
 206   $template->assign_attributes(
 
 207     template_type  => 'ap_transaction',
 
 208     template_name  => $new_name,
 
 210     currency_id    => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
 
 211     ar_ap_chart_id => $::form->{AP_chart_id}      || undef,
 
 212     vendor_id      => $::form->{vendor_id}        || undef,
 
 213     department_id  => $::form->{department_id}    || undef,
 
 214     project_id     => $::form->{globalproject_id} || undef,
 
 215     taxincluded    => $::form->{taxincluded}  ? 1 : 0,
 
 216     direct_debit   => $::form->{direct_debit} ? 1 : 0,
 
 217     ordnumber      => $::form->{ordnumber},
 
 218     notes          => $::form->{notes},
 
 228       ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
 
 233     ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
 
 238   $main::lxdebug->enter_sub();
 
 240   my $form     = $main::form;
 
 241   my %myconfig = %main::myconfig;
 
 243   $main::auth->assert('ap_transactions');
 
 245   $form->{title} = "Add";
 
 247   $form->{callback} = "ap.pl?action=add" unless $form->{callback};
 
 249   AP->get_transdate(\%myconfig, $form);
 
 250   $form->{initial_transdate} = $form->{transdate};
 
 251   create_links(dont_save => 1);
 
 252   $form->{transdate} = $form->{initial_transdate};
 
 254   if ($form->{vendor_id}) {
 
 255     my $last_used_ap_chart = SL::DB::Vendor->load_cached($form->{vendor_id})->last_used_ap_chart;
 
 256     $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
 261   $main::lxdebug->leave_sub();
 
 265   $main::lxdebug->enter_sub();
 
 267   # Delay access check to after the invoice's been loaded in
 
 268   # "create_links" so that project-specific invoice rights can be
 
 271   my $form     = $main::form;
 
 273   $form->{title} = "Edit";
 
 278   $main::lxdebug->leave_sub();
 
 282   $main::lxdebug->enter_sub();
 
 286   my $form     = $main::form;
 
 288   # get all files stored in the webdav folder
 
 289   if ($form->{invnumber} && $::instance_conf->get_webdav) {
 
 290     my $webdav = SL::Webdav->new(
 
 291       type     => 'accounts_payable',
 
 292       number   => $form->{invnumber},
 
 294     my @all_objects = $webdav->get_all_objects;
 
 295     @{ $form->{WEBDAV} } = map { { name => $_->filename,
 
 297                                    link => File::Spec->catfile($_->full_filedescriptor),
 
 303   $main::lxdebug->leave_sub();
 
 307   $main::lxdebug->enter_sub();
 
 309   # Delay access check to after the invoice's been loaded so that
 
 310   # project-specific invoice rights can be evaluated.
 
 314   my $form     = $main::form;
 
 315   my %myconfig = %main::myconfig;
 
 317   $form->create_links("AP", \%myconfig, "vendor");
 
 322   if (!$params{dont_save}) {
 
 323     %saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
 
 324     $saved{duedate} = $form->{duedate} if $form->{duedate};
 
 325     $saved{currency} = $form->{currency} if $form->{currency};
 
 326     $saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
 
 329   IR->get_vendor(\%myconfig, \%$form);
 
 331   $form->{$_}        = $saved{$_} for keys %saved;
 
 332   $form->{rowcount}  = 1;
 
 333   $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};
 
 335   # build the popup menus
 
 336   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
 
 339   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 341   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 343   $form->{employee} = "$form->{employee}--$form->{employee_id}";
 
 345   AP->setup_form($form);
 
 347   $main::lxdebug->leave_sub();
 
 351   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid paid_project_id);
 
 353     grep { $_->{paid} != 0 }
 
 356       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
 
 357     } (1..$::form->{paidaccounts});
 
 359   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
 
 361   $::form->{paidaccounts} = max scalar(@payments), 1;
 
 363   foreach my $idx (1 .. scalar(@payments)) {
 
 364     my $payment = $payments[$idx - 1];
 
 365     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
 
 370   $main::lxdebug->enter_sub();
 
 374   my $form     = $main::form;
 
 375   my %myconfig = %main::myconfig;
 
 376   my $locale   = $main::locale;
 
 377   my $cgi      = $::request->{cgi};
 
 379   $::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
 
 381   $form->{initial_focus} = !($form->{amount_1} * 1) ? 'vendor_id' : 'row_' . $form->{rowcount};
 
 383   $form->{title_} = $form->{title};
 
 384   $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
 
 386   # type=submit $locale->text('Add Accounts Payables Transaction')
 
 387   # type=submit $locale->text('Edit Accounts Payables Transaction')
 
 389   my $readonly = $form->{id} ? "readonly" : "";
 
 391   $form->{radier} = ($::instance_conf->get_ap_changeable == 2)
 
 392                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 393                       : ($::instance_conf->get_ap_changeable == 1);
 
 394   $readonly       = $form->{radier} ? "" : $readonly;
 
 396   $form->{readonly} = $readonly;
 
 398   $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 399   if ( $form->{forex} ) {
 
 400     $form->{exchangerate} = $form->{forex};
 
 404   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
 
 405   $form->{creditlimit}     = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
 
 406   $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
 
 409   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
 
 412   $form->{textarea_rows} = $rows;
 
 414   $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
 
 416   $form->get_lists("charts"    => { "key"       => "ALL_CHARTS",
 
 417                                     "transdate" => $form->{transdate} },
 
 421     { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
 
 422     @{ $form->{ALL_CHARTS} }
 
 425   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 427   my %project_labels = map { $_->id => $_->projectnumber }  @{ SL::DB::Manager::Project->get_all };
 
 430   my $default_ap_amount_chart_id;
 
 432   foreach my $item (@{ $form->{ALL_CHARTS} }) {
 
 433     if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
 
 434       $default_ap_amount_chart_id //= $item->{id};
 
 436     } elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
 
 437       push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
 
 440     $charts{$item->{accno}} = $item;
 
 443   my $follow_up_vc         = $form->{vendor_id} ? SL::DB::Vendor->load_cached($form->{vendor_id})->name : '';
 
 444   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
 
 446   $::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");
 
 447   # $form->{totalpaid} is used by the action bar setup to determine
 
 448   # whether or not canceling is allowed. Therefore it must be
 
 449   # calculated prior to the action bar setup.
 
 450   $form->{totalpaid} = sum map { $form->{"paid_${_}"} } (1..$form->{paidaccounts});
 
 452   setup_ap_display_form_action_bar();
 
 455   # get the correct date for tax
 
 456   my $transdate    = $::form->{transdate}    ? DateTime->from_kivitendo($::form->{transdate})    : DateTime->today_local;
 
 457   my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
 
 458   my $taxdate      = $deliverydate ? $deliverydate : $transdate;
 
 462   for my $i (1 .. $form->{rowcount}) {
 
 465     $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
 
 466     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
 
 468     my ($default_taxchart, $taxchart_to_use);
 
 470     if ( $form->{"taxchart_$i"} ) {
 
 471       ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
 
 473     my $amount_chart_id = $form->{"AP_amount_chart_id_$i"} || $default_ap_amount_chart_id;
 
 475     my @taxcharts       = GL->get_active_taxes_for_chart($amount_chart_id, $taxdate, $used_tax_id);
 
 476     foreach my $item (@taxcharts) {
 
 477       my $key             = $item->id . "--" . $item->rate;
 
 478       $first_taxchart   //= $item;
 
 479       $default_taxchart   = $item if $item->{is_default};
 
 480       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
 
 483     $taxchart_to_use               //= $default_taxchart // $first_taxchart;
 
 484     my $selected_taxchart            = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
 485     $form->{"selected_taxchart_$i"}  = $selected_taxchart;
 
 486     $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
 
 487     $form->{"taxcharts_$i"}          = \@taxcharts;
 
 490   $form->{taxchart_value_title_sub} = sub {
 
 493       $item->{id} .'--'. $item->{rate},
 
 494       $item->{taxkey} . ' - ' . $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
 
 498   $form->{AP_paid_value_title_sub} = sub {
 
 502       $item->{accno} .'--'. $item->{description}
 
 506   $form->{invtotal_unformatted} = $form->{invtotal};
 
 507   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
 
 511   if ( $form->{'paid_'. $form->{paidaccounts}} ) {
 
 512     $form->{paidaccounts}++;
 
 515   # default account for current assets (i.e. 1801 - SKR04)
 
 516   $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 518   for my $i (1 .. $form->{paidaccounts}) {
 
 520     if ($form->{"paid_$i"}) {
 
 521       $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
 
 523     if ($form->{"exchangerate_$i"} == 0) {
 
 524       $form->{"exchangerate_$i"} = "";
 
 526       $form->{"exchangerate_$i"} =
 
 527         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
 
 531     if (SL::DB::Default->get->payments_changeable == 0) {
 
 533       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
 
 535     if (SL::DB::Default->get->payments_changeable == 2) {
 
 537       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
 
 540     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
 
 541     if ($form->date_closed($form->{"gldate_$i"})) {
 
 545     $form->{'paidaccount_changeable_'. $i} = $changeable;
 
 547     $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
 
 548     # accno and description as info text
 
 549     $form->{'AP_paid_readonly_desc_' . $i} =  $form->{'AP_paid_' . $i} ?
 
 550        $form->{'AP_paid_' . $i} . " " . SL::DB::Manager::Chart->find_by(accno => $form->{'AP_paid_' . $i})->description
 
 554   $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
 
 556   print $form->parse_html_template('ap/form_header', {
 
 557     today => DateTime->today,
 
 558     currencies => SL::DB::Manager::Currency->get_all_sorted,
 
 561   $main::lxdebug->leave_sub();
 
 565   $::lxdebug->enter_sub;
 
 572     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
 
 574     if (@{ $follow_ups }) {
 
 575       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
 
 576       $num_follow_ups = scalar @{ $follow_ups }
 
 580   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
 
 581   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
 
 583   my $storno = $::form->{id}
 
 584             && !IS->has_storno(\%::myconfig, $::form, 'ap')
 
 585             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
 
 586             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
 
 589   print $::form->parse_html_template('ap/form_footer', {
 
 591     num_follow_ups    => $num_follow_ups,
 
 594   $::lxdebug->leave_sub;
 
 598   $::auth->assert('ap_transactions');
 
 600   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
 
 602   $::form->redirect($::locale->text("Marked as paid"));
 
 606   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
 
 607   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
 
 614   $main::lxdebug->enter_sub();
 
 616   my $form     = $main::form;
 
 617   my %myconfig = %main::myconfig;
 
 619   $main::auth->assert('ap_transactions');
 
 623   $form->{invtotal} = 0;
 
 625   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
 
 627   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 628     qw(exchangerate creditlimit creditremaining);
 
 630   my @flds  = qw(amount AP_amount_chart_id projectnumber oldprojectnumber project_id taxchart tax);
 
 632   my (@a, $j, $totaltax);
 
 633   for my $i (1 .. $form->{rowcount}) {
 
 634     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
 
 635     if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
 
 638       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
 
 640       # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
 
 642       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
 
 643       $totaltax += $form->{"tax_$i"};
 
 644       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 648   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
 
 650   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
 
 652   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 653   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 655   $form->{invdate} = $form->{transdate};
 
 657   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
 
 658     IR->get_vendor(\%::myconfig, $form);
 
 659     if (($form->{rowcount} == 1) && ($form->{amount_1} == 0)) {
 
 660       my $last_used_ap_chart = SL::DB::Vendor->load_cached($form->{vendor_id})->last_used_ap_chart;
 
 661       $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
 665   $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
 
 668     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
 
 671   for my $i (1 .. $form->{paidaccounts}) {
 
 672     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 675           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
 676       } qw(paid exchangerate);
 
 678       $totalpaid += $form->{"paid_$i"};
 
 680       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 681       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 685   $form->{creditremaining} -=
 
 686     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
 
 687      $form->{oldinvtotal});
 
 688   $form->{oldinvtotal}  = $form->{invtotal};
 
 689   $form->{oldtotalpaid} = $totalpaid;
 
 693   $main::lxdebug->leave_sub();
 
 698   $main::lxdebug->enter_sub();
 
 700   my $form     = $main::form;
 
 701   my %myconfig = %main::myconfig;
 
 702   my $locale   = $main::locale;
 
 704   $main::auth->assert('ap_transactions');
 
 705   $form->mtime_ischanged('ap');
 
 707   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 709   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 711   for my $i (1 .. $form->{paidaccounts}) {
 
 712     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 713       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 715       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 717       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 718         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 720       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 721       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 722       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 723         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 725       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 726         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 727           if ($invdate == $datepaid);
 
 728         $form->isblank("exchangerate_$i",
 
 729                        $locale->text('Exchangerate for payment missing!'));
 
 734   ($form->{AP})      = split /--/, $form->{AP};
 
 735   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
 
 736   if (AP->post_payment(\%myconfig, \%$form)) {
 
 737     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 738     $form->{what_done} = 'invoice';
 
 739     $form->{addition}  = "PAYMENT POSTED";
 
 741     $form->redirect($locale->text('Payment posted!'))
 
 743     $form->error($locale->text('Cannot post payment!'));
 
 747   $main::lxdebug->leave_sub();
 
 752   $main::lxdebug->enter_sub();
 
 754   my $form     = $main::form;
 
 755   my %myconfig = %main::myconfig;
 
 756   my $locale   = $main::locale;
 
 758   $main::auth->assert('ap_transactions');
 
 759   $form->mtime_ischanged('ap');
 
 763   # check if there is a vendor, invoice, due date and invnumber
 
 764   $form->isblank("transdate",   $locale->text("Invoice Date missing!"));
 
 765   $form->isblank("duedate",     $locale->text("Due Date missing!"));
 
 766   $form->isblank("vendor_id",   $locale->text('Vendor missing!'));
 
 767   $form->isblank("invnumber",   $locale->text('Invoice Number missing!'));
 
 768   $form->isblank("AP_chart_id", $locale->text('No contra account selected!'));
 
 770   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 771     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 776   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
 777   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 779   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 780     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
 
 781   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
 
 783   my $zero_amount_posting = 1;
 
 784   for my $i (1 .. $form->{rowcount}) {
 
 785     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
 
 786       $zero_amount_posting = 0;
 
 791   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
 
 793   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 794     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
 
 797   for my $i (1 .. $form->{paidaccounts}) {
 
 798     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 799       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 801       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 803       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 804       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 806       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 807       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 808       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 809         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 811       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 812         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 813           if ($transdate == $datepaid);
 
 814         $form->isblank("exchangerate_$i",
 
 815                        $locale->text('Exchangerate for payment missing!'));
 
 821   # if old vendor ne vendor redo form
 
 822   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
 824     $::dispatcher->end_request;
 
 828   $form->{id} = 0 if $form->{postasnew};
 
 830   if (AP->post_transaction(\%myconfig, \%$form)) {
 
 831     # create webdav folder
 
 832     if ($::instance_conf->get_webdav) {
 
 833       SL::Webdav->new(type     => 'accounts_payable',
 
 834                       number   => $form->{invnumber},
 
 838     if(!exists $form->{addition} && $form->{id} ne "") {
 
 839       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 840       $form->{addition}  = "POSTED";
 
 841       $form->{what_done} = "invoice";
 
 844     # no restore_from_session_id needed. we like to have a newly generated
 
 845     # list of invoices for bank transactions
 
 846     print $form->redirect_header($form->{callback}) if ($form->{callback} =~ /BankTransaction/);
 
 847     $form->redirect($locale->text('AP transaction posted.') . ' ' . $locale->text('ID') . ': ' . $form->{id}) unless $inline;
 
 848     # TODO Add callback/return flag in myconfig
 
 849     # With version 3.5 we can add documents, but only after posting. there should be a flag in myconfig for the user
 
 850     # $form->{callback} ||= 'ap.pl?action=edit&id=' . $form->{id} if $myconfig{no_reset_arap};
 
 853     $form->error($locale->text('Cannot post transaction!'));
 
 856   $main::lxdebug->leave_sub();
 
 860   $main::lxdebug->enter_sub();
 
 862   my $form     = $main::form;
 
 863   my %myconfig = %main::myconfig;
 
 865   $main::auth->assert('ap_transactions');
 
 867   $form->{postasnew} = 1;
 
 869   if(!exists $form->{addition} && $form->{id} ne "") {
 
 870     # does this work? post_as_new for ap doesn't immediately save the
 
 871     # invoice, because the invnumber has to be entered by hand.
 
 872     # And the value of $form->{postasnew} isn't checked when calling post
 
 873     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 874     $form->{addition}  = "POSTED AS NEW";
 
 875     $form->{what_done} = "invoice";
 
 878   # /saving the history
 
 881   $main::lxdebug->leave_sub();
 
 885   $main::lxdebug->enter_sub();
 
 887   my $form     = $main::form;
 
 888   my %myconfig = %main::myconfig;
 
 890   $main::auth->assert('ap_transactions');
 
 892   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);
 
 893   $form->{paidaccounts} = 1;
 
 896   my $today          = DateTime->today_local;
 
 897   $form->{transdate} = $today->to_kivitendo;
 
 898   $form->{duedate}   = $form->{transdate};
 
 900   if ($form->{vendor_id}) {
 
 901     my $payment_terms = SL::DB::Vendor->load_cached($form->{vendor_id})->payment;
 
 902     $form->{duedate}  = $payment_terms->calc_date(reference_date => $today)->to_kivitendo if $payment_terms;
 
 907   $main::lxdebug->leave_sub();
 
 911   my $form     = $main::form;
 
 912   my %myconfig = %main::myconfig;
 
 913   my $locale   = $main::locale;
 
 915   $main::auth->assert('ap_transactions');
 
 917   if (AP->delete_transaction(\%myconfig, \%$form)) {
 
 919     if(!exists $form->{addition}) {
 
 920       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 921       $form->{addition}  = "DELETED";
 
 922       $form->{what_done} = "invoice";
 
 925     # /saving the history
 
 926     $form->redirect($locale->text('Transaction deleted!'));
 
 928   $form->error($locale->text('Cannot delete transaction!'));
 
 932   $main::lxdebug->enter_sub();
 
 934   my $form     = $main::form;
 
 935   my %myconfig = %main::myconfig;
 
 936   my $locale   = $main::locale;
 
 938   $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
 
 940   $form->get_lists(projects => { "key" => "ALL_PROJECTS", "all" => 1 });
 
 942   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 943   # constants and subs for template
 
 944   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
 
 946   $::request->layout->add_javascripts("autocomplete_project.js");
 
 948   setup_ap_search_action_bar();
 
 951   print $form->parse_html_template('ap/search', { %myconfig });
 
 953   $main::lxdebug->leave_sub();
 
 956 sub create_subtotal_row {
 
 957   $main::lxdebug->enter_sub();
 
 959   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
 
 961   my $form     = $main::form;
 
 962   my %myconfig = %main::myconfig;
 
 964   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
 
 966   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
 
 968   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
 
 970   map { $totals->{$_} = 0 } @{ $subtotal_columns };
 
 972   $main::lxdebug->leave_sub();
 
 977 sub ap_transactions {
 
 978   $main::lxdebug->enter_sub();
 
 980   my $form     = $main::form;
 
 981   my %myconfig = %main::myconfig;
 
 982   my $locale   = $main::locale;
 
 984   report_generator_set_default_sort('transdate', 1);
 
 986   AP->ap_transactions(\%myconfig, \%$form);
 
 988   $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
 
 990   my $report = SL::ReportGenerator->new(\%myconfig, $form);
 
 993     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
 
 994        due duedate transaction_description notes employee globalprojectnumber department
 
 995        vendornumber country ustid taxzone payment_terms charts direct_debit);
 
 997   my @hidden_variables = map { "l_${_}" } @columns;
 
 998   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto
 
 999                                            parts_partnumber parts_description department_id);
 
1001   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
 
1004     'transdate'               => { 'text' => $locale->text('Date'), },
 
1005     'id'                      => { 'text' => $locale->text('ID'), },
 
1006     'type'                    => { 'text' => $locale->text('Type'), },
 
1007     'invnumber'               => { 'text' => $locale->text('Invoice'), },
 
1008     'ordnumber'               => { 'text' => $locale->text('Order'), },
 
1009     'name'                    => { 'text' => $locale->text('Vendor'), },
 
1010     'netamount'               => { 'text' => $locale->text('Amount'), },
 
1011     'tax'                     => { 'text' => $locale->text('Tax'), },
 
1012     'amount'                  => { 'text' => $locale->text('Total'), },
 
1013     'paid'                    => { 'text' => $locale->text('Paid'), },
 
1014     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
 
1015     'due'                     => { 'text' => $locale->text('Amount Due'), },
 
1016     'duedate'                 => { 'text' => $locale->text('Due Date'), },
 
1017     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
 
1018     'notes'                   => { 'text' => $locale->text('Notes'), },
 
1019     'employee'                => { 'text' => $locale->text('Employee'), },
 
1020     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
 
1021     'department'              => { 'text' => $locale->text('Department'), },
 
1022     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
 
1023     'country'                 => { 'text' => $locale->text('Country'), },
 
1024     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
 
1025     'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
 
1026     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
 
1027     'charts'                  => { 'text' => $locale->text('Chart'), },
 
1028     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
 
1031   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit department)) {
 
1032     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
 
1033     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
 
1036   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
 
1038   $form->{"l_type"} = "Y";
 
1039   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
 
1041   $report->set_columns(%column_defs);
 
1042   $report->set_column_order(@columns);
 
1044   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
 
1046   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
 
1048   my $department_description;
 
1049   $department_description = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
 
1052   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
 
1053   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
 
1054   push @options, $locale->text('Department')              . " : $department_description"                 if ($form->{department_id});
 
1055   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
 
1056   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
 
1057   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
 
1058   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
 
1059   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
 
1060   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
 
1061   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
 
1062   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
 
1063   push @options, $locale->text('Open')                                                                   if ($form->{open});
 
1064   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
 
1066   $report->set_options('top_info_text'        => join("\n", @options),
 
1067                        'output_format'        => 'HTML',
 
1068                        'title'                => $form->{title},
 
1069                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
 
1071   $report->set_options_from_form();
 
1072   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
1074   # add sort and escape callback, this one we use for the add sub
 
1075   $form->{callback} = $href .= "&sort=$form->{sort}";
 
1077   # escape callback for href
 
1078   my $callback = $form->escape($href);
 
1080   my @subtotal_columns = qw(netamount amount paid due);
 
1082   my %totals    = map { $_ => 0 } @subtotal_columns;
 
1083   my %subtotals = map { $_ => 0 } @subtotal_columns;
 
1087   foreach my $ap (@{ $form->{AP} }) {
 
1088     $ap->{tax} = $ap->{amount} - $ap->{netamount};
 
1089     $ap->{due} = $ap->{amount} - $ap->{paid};
 
1091     map { $subtotals{$_} += $ap->{$_};
 
1092           $totals{$_}    += $ap->{$_} } @subtotal_columns;
 
1094     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
 
1096     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
 
1097     my $has_storno = $ap->{storno} && !$ap->{storno_id};
 
1099     if ($ap->{invoice}) {
 
1101           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
 
1102         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
 
1103         :                     $locale->text("Invoice (one letter abbreviation)");
 
1106           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
 
1107         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
 
1108         :                     $locale->text("AP Transaction (abbreviation)");
 
1111     $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
 
1115     foreach my $column (@columns) {
 
1117         'data'  => $ap->{$column},
 
1118         'align' => $column_alignment{$column},
 
1122     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
 
1123       . "&id=" . E($ap->{id}) . "&callback=${callback}";
 
1125     my $row_set = [ $row ];
 
1127     if (($form->{l_subtotal} eq 'Y')
 
1128         && (($idx == (scalar @{ $form->{AP} } - 1))
 
1129             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
 
1130       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
 
1133     $report->add_data($row_set);
 
1138   $report->add_separator();
 
1139   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
 
1141   setup_ap_transactions_action_bar();
 
1142   $report->generate_with_headers();
 
1144   $main::lxdebug->leave_sub();
 
1148   $main::lxdebug->enter_sub();
 
1150   my $form     = $main::form;
 
1151   my %myconfig = %main::myconfig;
 
1152   my $locale   = $main::locale;
 
1154   $main::auth->assert('ap_transactions');
 
1156   if (IS->has_storno(\%myconfig, $form, 'ap')) {
 
1157     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
 
1158     $form->error($locale->text("Transaction has already been cancelled!"));
 
1161   $form->error($locale->text('Cannot post storno for a closed period!'))
 
1162     if ( $form->date_closed($form->{transdate}, \%myconfig));
 
1164   AP->storno($form, \%myconfig, $form->{id});
 
1166   # saving the history
 
1167   if(!exists $form->{addition} && $form->{id} ne "") {
 
1168     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
1169     $form->{addition}  = "STORNO";
 
1170     $form->{what_done} = "invoice";
 
1171     $form->save_history;
 
1173   # /saving the history
 
1175   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
 
1177   $main::lxdebug->leave_sub();
 
1180 sub add_from_purchase_order {
 
1181   $main::auth->assert('ap_transactions');
 
1183   return if !$::form->{id};
 
1185   my $order_id = delete $::form->{id};
 
1186   my $order    = SL::DB::Order->new(id => $order_id)->load(with => [ 'vendor', 'currency', 'payment_terms' ]);
 
1188   return if $order->type ne 'purchase_order';
 
1190   my $today                     = DateTime->today_local;
 
1191   $::form->{title}              = "Add";
 
1192   $::form->{vc}                 = 'vendor';
 
1193   $::form->{vendor_id}          = $order->customervendor->id;
 
1194   $::form->{vendor}             = $order->vendor->name;
 
1195   $::form->{convert_from_oe_id} = $order->id;
 
1196   $::form->{globalproject_id}   = $order->globalproject_id;
 
1197   $::form->{ordnumber}          = $order->number;
 
1198   $::form->{department_id}      = $order->department_id;
 
1199   $::form->{currency}           = $order->currency->name;
 
1200   $::form->{taxincluded}        = 1; # we use amount below, so tax is included
 
1201   $::form->{transdate}          = $today->to_kivitendo;
 
1202   $::form->{duedate}            = $today->to_kivitendo;
 
1203   $::form->{duedate}            = $order->payment_terms->calc_date(reference_date => $today)->to_kivitendo if $order->payment_terms;
 
1204   $::form->{deliverydate}       = $order->reqdate->to_kivitendo                                            if $order->reqdate;
 
1207   my $config_po_ap_workflow_chart_id = $::instance_conf->get_workflow_po_ap_chart_id;
 
1209   my ($first_taxchart, $default_taxchart, $taxchart_to_use);
 
1211   @taxcharts    = GL->get_active_taxes_for_chart($config_po_ap_workflow_chart_id, $::form->{transdate}) if (defined $config_po_ap_workflow_chart_id);
 
1212   foreach my $item (@taxcharts) {
 
1213     $first_taxchart   //= $item;
 
1214     $default_taxchart   = $item if $item->{is_default};
 
1216   $taxchart_to_use      = $default_taxchart // $first_taxchart;
 
1218   my %pat = $order->calculate_prices_and_taxes;
 
1220   foreach my $amount_chart (keys %{$pat{amounts}}) {
 
1221     my $tax = SL::DB::Manager::Tax->find_by(id => $pat{amounts}->{$amount_chart}->{tax_id});
 
1222     # If tax chart from order for this amount is active, use it. Use default or first tax chart for selected chart else.
 
1223     if (defined $config_po_ap_workflow_chart_id) {
 
1224       $taxchart_to_use = (first {$_->{id} == $tax->id} @taxcharts) // $taxchart_to_use;
 
1226       $taxchart_to_use = $tax;
 
1229     $::form->{"AP_amount_chart_id_$row"}          = $config_po_ap_workflow_chart_id // $amount_chart;
 
1230     $::form->{"previous_AP_amount_chart_id_$row"} = $::form->{"AP_amount_chart_id_$row"};
 
1231     $::form->{"amount_$row"}                      = $::form->format_amount(\%::myconfig, $pat{amounts}->{$amount_chart}->{amount} * (1 + $tax->rate), 2);
 
1232     $::form->{"taxchart_$row"}                    = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
1233     $::form->{"project_id_$row"}                  = $order->globalproject_id;
 
1238   my $last_used_ap_chart               = SL::DB::Vendor->load_cached($::form->{vendor_id})->last_used_ap_chart;
 
1239   $::form->{"AP_amount_chart_id_$row"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
1240   $::form->{rowcount}                  = $row;
 
1243     keep_rows_without_amount => 1,
 
1244     dont_add_new_row         => 1,
 
1248 sub setup_ap_search_action_bar {
 
1251   for my $bar ($::request->layout->get('actionbar')) {
 
1254         $::locale->text('Search'),
 
1255         submit    => [ '#form', { action => "ap_transactions" } ],
 
1256         checks    => [ 'kivi.validate_form' ],
 
1257         accesskey => 'enter',
 
1261   $::request->layout->add_javascripts('kivi.Validator.js');
 
1264 sub setup_ap_transactions_action_bar {
 
1266   my $may_edit_create = $::auth->assert('ap_transactions', 1);
 
1268   for my $bar ($::request->layout->get('actionbar')) {
 
1271         action => [ t8('Add') ],
 
1273           t8('Purchase Invoice'),
 
1274           link     => [ 'ir.pl?action=add' ],
 
1275           disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
 
1279           t8('AP Transaction'),
 
1280           link     => [ 'ap.pl?action=add' ],
 
1281           disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
 
1283       ], # end of combobox "Add"
 
1288 sub setup_ap_display_form_action_bar {
 
1289   my $transdate               = $::form->datetonum($::form->{transdate}, \%::myconfig);
 
1290   my $closedto                = $::form->datetonum($::form->{closedto},  \%::myconfig);
 
1291   my $is_closed               = $transdate <= $closedto;
 
1293   my $change_never            = $::instance_conf->get_ap_changeable == 0;
 
1294   my $change_on_same_day_only = $::instance_conf->get_ap_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
 
1296   my $is_storno               = IS->is_storno(\%::myconfig, $::form, 'ap', $::form->{id});
 
1297   my $has_storno              = IS->has_storno(\%::myconfig, $::form, 'ap');
 
1299   my $may_edit_create         = $::auth->assert('ap_transactions', 1);
 
1301   my $has_sepa_exports;
 
1302   if ($::form->{id}) {
 
1303     my $invoice = SL::DB::Manager::PurchaseInvoice->find_by(id => $::form->{id});
 
1304     $has_sepa_exports = 1 if ($invoice->find_sepa_export_items()->[0]);
 
1307   my $is_linked_bank_transaction;
 
1309       && SL::DB::Default->get->payments_changeable != 0
 
1310       && SL::DB::Manager::BankTransactionAccTrans->find_by(ap_id => $::form->{id})) {
 
1312     $is_linked_bank_transaction = 1;
 
1315   for my $bar ($::request->layout->get('actionbar')) {
 
1319         submit    => [ '#form', { action => "update" } ],
 
1320         id        => 'update_button',
 
1321         checks    => [ 'kivi.validate_form' ],
 
1322         accesskey => 'enter',
 
1323         disabled  => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
 
1329           submit   => [ '#form', { action => "post" } ],
 
1330           checks   => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting', 'kivi.AP.check_duplicate_invnumber' ],
 
1331           disabled => !$may_edit_create                           ? t8('You must not change this AP transaction.')
 
1332                     : $is_closed                                  ? t8('The billing period has already been locked.')
 
1333                     : $is_storno                                  ? t8('A canceled invoice cannot be posted.')
 
1334                     : ($::form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
 
1335                     : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
 
1336                     : $is_linked_bank_transaction                 ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1341           submit   => [ '#form', { action => "post_payment" } ],
 
1342           checks   => [ 'kivi.validate_form' ],
 
1343           disabled => !$may_edit_create           ? t8('You must not change this AP transaction.')
 
1344                     : !$::form->{id}              ? t8('This invoice has not been posted yet.')
 
1345                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1348         action => [ t8('Mark as paid'),
 
1349           submit   => [ '#form', { action => "mark_as_paid" } ],
 
1350           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
 
1351           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1352                     : !$::form->{id}    ? t8('This invoice has not been posted yet.')
 
1354           only_if  => $::instance_conf->get_is_show_mark_as_paid,
 
1356       ], # end of combobox "Post"
 
1359         action => [ t8('Storno'),
 
1360           submit   => [ '#form', { action => "storno" } ],
 
1361           checks   => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting' ],
 
1362           confirm  => t8('Do you really want to cancel this invoice?'),
 
1363           disabled => !$may_edit_create    ? t8('You must not change this AP transaction.')
 
1364                     : !$::form->{id}       ? t8('This invoice has not been posted yet.')
 
1365                     : $has_storno          ? t8('This invoice has been canceled already.')
 
1366                     : $is_storno           ? t8('Reversal invoices cannot be canceled.')
 
1367                     : $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
 
1368                     : $has_sepa_exports    ? t8('This invoice has been linked with a sepa export, undo this first.')
 
1371         action => [ t8('Delete'),
 
1372           submit   => [ '#form', { action => "delete" } ],
 
1373           confirm  => t8('Do you really want to delete this object?'),
 
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                     : $change_never               ? t8('Changing invoices has been disabled in the configuration.')
 
1377                     : $change_on_same_day_only    ? t8('Invoices can only be changed on the day they are posted.')
 
1378                     : $has_storno                 ? t8('This invoice has been canceled already.')
 
1379                     : $is_closed                  ? t8('The billing period has already been locked.')
 
1380                     : $has_sepa_exports           ? t8('This invoice has been linked with a sepa export, undo this first.')
 
1381                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
1384       ], # end of combobox "Storno"
 
1389         action => [ t8('Workflow') ],
 
1392           submit   => [ '#form', { action => "use_as_new" } ],
 
1393           checks   => [ 'kivi.validate_form' ],
 
1394           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1395                     : !$::form->{id}    ? t8('This invoice has not been posted yet.')
 
1398       ], # end of combobox "Workflow"
 
1401         action => [ t8('more') ],
 
1404           call     => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
 
1405           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
1409           call     => [ 'follow_up_window' ],
 
1410           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
1413           t8('Record templates'),
 
1414           call     => [ 'kivi.RecordTemplate.popup', 'ap_transaction' ],
 
1415           disabled => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
 
1419           call     => [ 'kivi.Draft.popup', 'ap', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
 
1420           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
 
1421                     : $::form->{id}     ? t8('This invoice has already been posted.')
 
1422                     : $is_closed        ? t8('The billing period has already been locked.')
 
1425       ], # end of combobox "more"
 
1428   $::request->layout->add_javascripts('kivi.Validator.js');