1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  16 # This program is free software; you can redistribute it and/or modify
 
  17 # it under the terms of the GNU General Public License as published by
 
  18 # the Free Software Foundation; either version 2 of the License, or
 
  19 # (at your option) any later version.
 
  21 # This program is distributed in the hope that it will be useful,
 
  22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  24 # GNU General Public License for more details.
 
  25 # You should have received a copy of the GNU General Public License
 
  26 # along with this program; if not, write to the Free Software
 
  27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
  29 #======================================================================
 
  33 #======================================================================
 
  35 use POSIX qw(strftime);
 
  36 use List::Util qw(first max sum);
 
  37 use List::UtilsBy qw(sort_by);
 
  42 use SL::Helper::Flash qw(flash);
 
  45 use SL::ReportGenerator;
 
  48 use SL::DB::PurchaseInvoice;
 
  49 use SL::DB::RecordTemplate;
 
  52 use SL::Locale::String qw(t8);
 
  54 require "bin/mozilla/common.pl";
 
  55 require "bin/mozilla/reportgenerator.pl";
 
  63 # this is for our long dates
 
  64 # $locale->text('January')
 
  65 # $locale->text('February')
 
  66 # $locale->text('March')
 
  67 # $locale->text('April')
 
  68 # $locale->text('May ')
 
  69 # $locale->text('June')
 
  70 # $locale->text('July')
 
  71 # $locale->text('August')
 
  72 # $locale->text('September')
 
  73 # $locale->text('October')
 
  74 # $locale->text('November')
 
  75 # $locale->text('December')
 
  77 # this is for our short month
 
  78 # $locale->text('Jan')
 
  79 # $locale->text('Feb')
 
  80 # $locale->text('Mar')
 
  81 # $locale->text('Apr')
 
  82 # $locale->text('May')
 
  83 # $locale->text('Jun')
 
  84 # $locale->text('Jul')
 
  85 # $locale->text('Aug')
 
  86 # $locale->text('Sep')
 
  87 # $locale->text('Oct')
 
  88 # $locale->text('Nov')
 
  89 # $locale->text('Dec')
 
  91 sub load_record_template {
 
  92   $::auth->assert('ap_transactions');
 
  94   # Load existing template and verify that its one for this module.
 
  95   my $template = SL::DB::RecordTemplate
 
  96     ->new(id => $::form->{id})
 
  98       with_object => [ qw(customer payment currency record_items record_items.chart) ],
 
 101   die "invalid template type" unless $template->template_type eq 'ap_transaction';
 
 103   $template->substitute_variables;
 
 105   # Clean the current $::form before rebuilding it from the template.
 
 106   my $form_defaults = delete $::form->{form_defaults};
 
 107   delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
 
 109   # Fill $::form from the template.
 
 110   my $today                   = DateTime->today_local;
 
 111   $::form->{title}            = "Add";
 
 112   $::form->{currency}         = $template->currency->name;
 
 113   $::form->{direct_debit}     = $template->direct_debit;
 
 114   $::form->{globalproject_id} = $template->project_id;
 
 115   $::form->{AP_chart_id}      = $template->ar_ap_chart_id;
 
 116   $::form->{transdate}        = $today->to_kivitendo;
 
 117   $::form->{duedate}          = $today->to_kivitendo;
 
 118   $::form->{rowcount}         = @{ $template->items };
 
 119   $::form->{paidaccounts}     = 1;
 
 120   $::form->{$_}               = $template->$_ for qw(department_id ordnumber taxincluded notes);
 
 122   if ($template->vendor) {
 
 123     $::form->{vendor_id} = $template->vendor_id;
 
 124     $::form->{vendor}    = $template->vendor->name;
 
 125     $::form->{duedate}     = $template->vendor->payment->calc_date(reference_date => $today)->to_kivitendo if $template->vendor->payment;
 
 129   foreach my $item (@{ $template->items }) {
 
 132     my $active_taxkey = $item->chart->get_active_taxkey;
 
 133     my $taxes         = SL::DB::Manager::Tax->get_all(
 
 134       where   => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
 
 135       sort_by => 'taxkey, rate',
 
 138     my $tax   = first { $item->tax_id          == $_->id } @{ $taxes };
 
 139     $tax    //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
 
 140     $tax    //= $taxes->[0];
 
 147     $::form->{"AP_amount_chart_id_${row}"}          = $item->chart_id;
 
 148     $::form->{"previous_AP_amount_chart_id_${row}"} = $item->chart_id;
 
 149     $::form->{"amount_${row}"}                      = $::form->format_amount(\%::myconfig, $item->amount1, 2);
 
 150     $::form->{"taxchart_${row}"}                    = $item->tax_id . '--' . $tax->rate;
 
 151     $::form->{"project_id_${row}"}                  = $item->project_id;
 
 154   $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
 
 156   flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
 
 159     keep_rows_without_amount => 1,
 
 160     dont_add_new_row         => 1,
 
 164 sub save_record_template {
 
 165   $::auth->assert('ap_transactions');
 
 167   my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
 
 168   my $js       = SL::ClientJS->new(controller => SL::Controller::Base->new);
 
 169   my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
 
 171   $js->dialog->close('#record_template_dialog');
 
 174     $_->{chart_id} && (($_->{tax_id} // '') ne '')
 
 176     +{ chart_id   => $::form->{"AP_amount_chart_id_${_}"},
 
 177        amount1    => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
 
 178        tax_id     => (split m{--}, $::form->{"taxchart_${_}"})[0],
 
 179        project_id => $::form->{"project_id_${_}"} || undef,
 
 181   } (1..($::form->{rowcount} || 1));
 
 183   $template->assign_attributes(
 
 184     template_type  => 'ap_transaction',
 
 185     template_name  => $new_name,
 
 187     currency_id    => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
 
 188     ar_ap_chart_id => $::form->{AP_chart_id}      || undef,
 
 189     vendor_id      => $::form->{vendor_id}        || undef,
 
 190     department_id  => $::form->{department_id}    || undef,
 
 191     project_id     => $::form->{globalproject_id} || undef,
 
 192     taxincluded    => $::form->{taxincluded}  ? 1 : 0,
 
 193     direct_debit   => $::form->{direct_debit} ? 1 : 0,
 
 194     ordnumber      => $::form->{ordnumber},
 
 195     notes          => $::form->{notes},
 
 205       ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
 
 210     ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
 
 215   $main::lxdebug->enter_sub();
 
 217   my $form     = $main::form;
 
 218   my %myconfig = %main::myconfig;
 
 220   $main::auth->assert('ap_transactions');
 
 222   $form->{title} = "Add";
 
 224   $form->{callback} = "ap.pl?action=add" unless $form->{callback};
 
 226   AP->get_transdate(\%myconfig, $form);
 
 227   $form->{initial_transdate} = $form->{transdate};
 
 228   create_links(dont_save => 1);
 
 229   $form->{transdate} = $form->{initial_transdate};
 
 231   if ($form->{vendor_id}) {
 
 232     my $last_used_ap_chart = SL::DB::Vendor->load_cached($form->{vendor_id})->last_used_ap_chart;
 
 233     $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
 238   $main::lxdebug->leave_sub();
 
 242   $main::lxdebug->enter_sub();
 
 244   my $form     = $main::form;
 
 246   $main::auth->assert('ap_transactions');
 
 248   $form->{title} = "Edit";
 
 253   $main::lxdebug->leave_sub();
 
 257   $main::lxdebug->enter_sub();
 
 259   my $form     = $main::form;
 
 261   $main::auth->assert('ap_transactions');
 
 263   # get all files stored in the webdav folder
 
 264   if ($form->{invnumber} && $::instance_conf->get_webdav) {
 
 265     my $webdav = SL::Webdav->new(
 
 266       type     => 'accounts_payable',
 
 267       number   => $form->{invnumber},
 
 269     my $webdav_path = $webdav->webdav_path;
 
 270     my @all_objects = $webdav->get_all_objects;
 
 271     @{ $form->{WEBDAV} } = map { { name => $_->filename,
 
 273                                    link => File::Spec->catfile($_->full_filedescriptor),
 
 279   $main::lxdebug->leave_sub();
 
 283   $main::lxdebug->enter_sub();
 
 287   my $form     = $main::form;
 
 288   my %myconfig = %main::myconfig;
 
 290   $main::auth->assert('ap_transactions');
 
 292   $form->create_links("AP", \%myconfig, "vendor");
 
 294   if (!$params{dont_save}) {
 
 295     %saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
 
 296     $saved{duedate} = $form->{duedate} if $form->{duedate};
 
 297     $saved{currency} = $form->{currency} if $form->{currency};
 
 298     $saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
 
 301   IR->get_vendor(\%myconfig, \%$form);
 
 303   $form->{$_}        = $saved{$_} for keys %saved;
 
 304   $form->{rowcount}  = 1;
 
 305   $form->{AP_chart_id} = $form->{acc_trans} && $form->{acc_trans}->{AP} ? $form->{acc_trans}->{AP}->[0]->{chart_id} : $form->{AP_links}->{AP}->[0]->{chart_id};
 
 307   # build the popup menus
 
 308   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
 
 311   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 313   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 315   $form->{employee} = "$form->{employee}--$form->{employee_id}";
 
 317   AP->setup_form($form);
 
 320     ($form->datetonum($form->{transdate}, \%myconfig) <=
 
 321      $form->datetonum($form->{closedto}, \%myconfig));
 
 323   $main::lxdebug->leave_sub();
 
 327   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid paid_project_id);
 
 329     grep { $_->{paid} != 0 }
 
 332       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
 
 333     } (1..$::form->{paidaccounts});
 
 335   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
 
 337   $::form->{paidaccounts} = max scalar(@payments), 1;
 
 339   foreach my $idx (1 .. scalar(@payments)) {
 
 340     my $payment = $payments[$idx - 1];
 
 341     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
 
 346   $main::lxdebug->enter_sub();
 
 348   my $form     = $main::form;
 
 349   my %myconfig = %main::myconfig;
 
 350   my $locale   = $main::locale;
 
 351   my $cgi      = $::request->{cgi};
 
 353   $main::auth->assert('ap_transactions');
 
 355   $::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
 
 357   $form->{initial_focus} = !($form->{amount_1} * 1) ? 'vendor_id' : 'row_' . $form->{rowcount};
 
 359   $form->{title_} = $form->{title};
 
 360   $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
 
 362   # type=submit $locale->text('Add Accounts Payables Transaction')
 
 363   # type=submit $locale->text('Edit Accounts Payables Transaction')
 
 365   my $readonly = $form->{id} ? "readonly" : "";
 
 367   $form->{radier} = ($::instance_conf->get_ap_changeable == 2)
 
 368                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 369                       : ($::instance_conf->get_ap_changeable == 1);
 
 370   $readonly       = $form->{radier} ? "" : $readonly;
 
 372   $form->{readonly} = $readonly;
 
 374   $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 375   if ( $form->{forex} ) {
 
 376     $form->{exchangerate} = $form->{forex};
 
 380   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
 
 381   $form->{creditlimit}     = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
 
 382   $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
 
 385   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
 
 388   $form->{textarea_rows} = $rows;
 
 390   $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
 
 392   my @old_project_ids = ();
 
 395       if ($form->{"project_id_$_"}) {
 
 396         push(@old_project_ids, $form->{"project_id_$_"});
 
 399     (1..$form->{"rowcount"})
 
 402   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
 
 404                                     "old_id"    => \@old_project_ids },
 
 405                    "charts"    => { "key"       => "ALL_CHARTS",
 
 406                                     "transdate" => $form->{transdate} },
 
 407                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
 
 408                                     "module"    => "AP" },);
 
 411     { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
 
 412     @{ $form->{ALL_CHARTS} }
 
 415   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
 
 417   my %project_labels = ();
 
 418   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
 
 419     $project_labels{$item->{id}} = $item->{projectnumber};
 
 423   my $default_ap_amount_chart_id;
 
 425   foreach my $item (@{ $form->{ALL_CHARTS} }) {
 
 426     if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
 
 427       $default_ap_amount_chart_id //= $item->{id};
 
 429     } elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
 
 430       push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
 
 433     $charts{$item->{accno}} = $item;
 
 436   my $follow_up_vc         = $form->{vendor_id} ? SL::DB::Vendor->load_cached($form->{vendor_id})->name : '';
 
 437   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
 
 439   $::request->layout->add_javascripts("autocomplete_chart.js", "autocomplete_customer.js", "show_vc_details.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.GL.js", "kivi.RecordTemplate.js", "kivi.File.js");
 
 440   my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
 
 445   for my $i (1 .. $form->{rowcount}) {
 
 448     $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
 
 449     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
 
 451     my ($default_taxchart, $taxchart_to_use);
 
 452     my $amount_chart_id   = $form->{"AP_amount_chart_id_$i"} || $default_ap_amount_chart_id;
 
 453     my $chart_has_changed = $::form->{"previous_AP_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AP_amount_chart_id_$i"});
 
 454     my @taxcharts         = GL->get_active_taxes_for_chart($amount_chart_id, $transdate);
 
 456     foreach my $item (@taxcharts) {
 
 457       my $key             = $item->id . "--" . $item->rate;
 
 458       $first_taxchart   //= $item;
 
 459       $default_taxchart   = $item if $item->{is_default};
 
 460       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
 
 463     $taxchart_to_use                 = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
 
 464     my $selected_taxchart            = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
 465     $form->{"selected_taxchart_$i"}  = $selected_taxchart;
 
 466     $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
 
 467     $form->{"taxcharts_$i"}          = \@taxcharts;
 
 470   $form->{taxchart_value_title_sub} = sub {
 
 473       $item->{id} .'--'. $item->{rate},
 
 474       $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
 
 478   $form->{AP_paid_value_title_sub} = sub {
 
 482       $item->{accno} .'--'. $item->{description}
 
 486   $form->{invtotal_unformatted} = $form->{invtotal};
 
 487   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
 
 489   $form->{totalpaid} = 0;
 
 493   if ( $form->{'paid_'. $form->{paidaccounts}} ) {
 
 494     $form->{paidaccounts}++;
 
 497   # default account for current assets (i.e. 1801 - SKR04)
 
 498   $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 500   for my $i (1 .. $form->{paidaccounts}) {
 
 501     $form->{totalpaid} += $form->{"paid_$i"};
 
 504     if ($form->{"paid_$i"}) {
 
 505       $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
 
 507     if ($form->{"exchangerate_$i"} == 0) {
 
 508       $form->{"exchangerate_$i"} = "";
 
 510       $form->{"exchangerate_$i"} =
 
 511         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
 
 515     if (SL::DB::Default->get->payments_changeable == 0) {
 
 517       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
 
 519     if (SL::DB::Default->get->payments_changeable == 2) {
 
 521       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
 
 524     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
 
 525     if ($form->date_closed($form->{"gldate_$i"})) {
 
 529     $form->{'paidaccount_changeable_'. $i} = $changeable;
 
 531     $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
 
 534   $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
 
 536   print $form->parse_html_template('ap/form_header', {
 
 537     today => DateTime->today,
 
 538     currencies => SL::DB::Manager::Currency->get_all_sorted,
 
 541   $main::lxdebug->leave_sub();
 
 545   $::lxdebug->enter_sub;
 
 546   $::auth->assert('ap_transactions');
 
 551     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
 
 553     if (@{ $follow_ups }) {
 
 554       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
 
 555       $num_follow_ups = scalar @{ $follow_ups }
 
 559   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
 
 560   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
 
 562   my $storno = $::form->{id}
 
 563             && !IS->has_storno(\%::myconfig, $::form, 'ap')
 
 564             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
 
 565             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
 
 568   print $::form->parse_html_template('ap/form_footer', {
 
 570     num_follow_ups    => $num_follow_ups,
 
 571     show_post_draft   => ($transdate > $closedto) && !$::form->{id},
 
 572     show_storno       => $storno,
 
 575   $::lxdebug->leave_sub;
 
 579   $::auth->assert('ap_transactions');
 
 581   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
 
 583   $::form->redirect($::locale->text("Marked as paid"));
 
 587   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
 
 588   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
 
 595   $main::lxdebug->enter_sub();
 
 597   my $form     = $main::form;
 
 598   my %myconfig = %main::myconfig;
 
 600   $main::auth->assert('ap_transactions');
 
 604   $form->{invtotal} = 0;
 
 606   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
 
 608   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 609     qw(exchangerate creditlimit creditremaining);
 
 611   my @flds  = qw(amount AP_amount projectnumber oldprojectnumber project_id taxchart);
 
 613   my (@a, $j, $totaltax);
 
 614   for my $i (1 .. $form->{rowcount}) {
 
 615     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
 
 616     if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
 
 619       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
 
 621       # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
 
 623       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
 
 625       $totaltax += $form->{"tax_$i"};
 
 626       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 630   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
 
 632   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
 
 634   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 635   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 637   $form->{invdate} = $form->{transdate};
 
 639   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
 
 640     IR->get_vendor(\%::myconfig, $form);
 
 643   $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
 
 646     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
 
 649   for my $i (1 .. $form->{paidaccounts}) {
 
 650     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 653           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
 654       } qw(paid exchangerate);
 
 656       $totalpaid += $form->{"paid_$i"};
 
 658       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 659       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 663   $form->{creditremaining} -=
 
 664     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
 
 665      $form->{oldinvtotal});
 
 666   $form->{oldinvtotal}  = $form->{invtotal};
 
 667   $form->{oldtotalpaid} = $totalpaid;
 
 671   $main::lxdebug->leave_sub();
 
 676   $main::lxdebug->enter_sub();
 
 678   my $form     = $main::form;
 
 679   my %myconfig = %main::myconfig;
 
 680   my $locale   = $main::locale;
 
 682   $main::auth->assert('ap_transactions');
 
 683   $form->mtime_ischanged('ap');
 
 685   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 687   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 689   for my $i (1 .. $form->{paidaccounts}) {
 
 690     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 691       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 693       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 695       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 696         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 698       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 699       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 700       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 701         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 703       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 704         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 705           if ($invdate == $datepaid);
 
 706         $form->isblank("exchangerate_$i",
 
 707                        $locale->text('Exchangerate for payment missing!'));
 
 712   ($form->{AP})      = split /--/, $form->{AP};
 
 713   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
 
 714   if (AP->post_payment(\%myconfig, \%$form)) {
 
 715     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 716     $form->{what_done} = 'invoice';
 
 717     $form->{addition}  = "PAYMENT POSTED";
 
 719     $form->redirect($locale->text('Payment posted!'))
 
 721     $form->error($locale->text('Cannot post payment!'));
 
 725   $main::lxdebug->leave_sub();
 
 730   $main::lxdebug->enter_sub();
 
 732   my $form     = $main::form;
 
 733   my %myconfig = %main::myconfig;
 
 734   my $locale   = $main::locale;
 
 736   $main::auth->assert('ap_transactions');
 
 737   $form->mtime_ischanged('ap');
 
 741   # check if there is a vendor, invoice, due date and invnumber
 
 742   $form->isblank("transdate", $locale->text("Invoice Date missing!"));
 
 743   $form->isblank("duedate",   $locale->text("Due Date missing!"));
 
 744   $form->isblank("vendor_id", $locale->text('Vendor missing!'));
 
 745   $form->isblank("invnumber", $locale->text('Invoice Number missing!'));
 
 747   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 748     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 753   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
 754   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 756   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 757     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
 
 758   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
 
 760   my $zero_amount_posting = 1;
 
 761   for my $i (1 .. $form->{rowcount}) {
 
 762     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
 
 763       $zero_amount_posting = 0;
 
 768   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
 
 770   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 771     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
 
 774   for my $i (1 .. $form->{paidaccounts}) {
 
 775     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 776       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 778       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 780       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 781       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 783       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 784       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 785       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 786         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 788       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 789         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 790           if ($transdate == $datepaid);
 
 791         $form->isblank("exchangerate_$i",
 
 792                        $locale->text('Exchangerate for payment missing!'));
 
 798   # if old vendor ne vendor redo form
 
 799   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
 801     $::dispatcher->end_request;
 
 805   $form->{id} = 0 if $form->{postasnew};
 
 807   if (AP->post_transaction(\%myconfig, \%$form)) {
 
 808     # create webdav folder
 
 809     if ($::instance_conf->get_webdav) {
 
 810       SL::Webdav->new(type     => 'accounts_payable',
 
 811                       number   => $form->{invnumber},
 
 815     if(!exists $form->{addition} && $form->{id} ne "") {
 
 816       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 817       $form->{addition}  = "POSTED";
 
 818       $form->{what_done} = "invoice";
 
 821     # /saving the history
 
 822     # Dieser Text wird niemals ausgegeben: Probleme beim redirect?
 
 823     $form->redirect($locale->text('AP transaction posted.')) unless $inline;
 
 825     $form->error($locale->text('Cannot post transaction!'));
 
 828   $main::lxdebug->leave_sub();
 
 832   $main::lxdebug->enter_sub();
 
 834   my $form     = $main::form;
 
 835   my %myconfig = %main::myconfig;
 
 837   $main::auth->assert('ap_transactions');
 
 839   $form->{postasnew} = 1;
 
 841   if(!exists $form->{addition} && $form->{id} ne "") {
 
 842     # does this work? post_as_new for ap doesn't immediately save the
 
 843     # invoice, because the invnumber has to be entered by hand.
 
 844     # And the value of $form->{postasnew} isn't checked when calling post
 
 845     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 846     $form->{addition}  = "POSTED AS NEW";
 
 847     $form->{what_done} = "invoice";
 
 850   # /saving the history
 
 853   $main::lxdebug->leave_sub();
 
 857   $main::lxdebug->enter_sub();
 
 859   my $form     = $main::form;
 
 860   my %myconfig = %main::myconfig;
 
 862   $main::auth->assert('ap_transactions');
 
 864   map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
 
 865   $form->{paidaccounts} = 1;
 
 867   $form->{invdate} = $form->current_date(\%myconfig);
 
 870   $main::lxdebug->leave_sub();
 
 874   $main::lxdebug->enter_sub();
 
 876   my $form     = $main::form;
 
 877   my $locale   = $main::locale;
 
 879   $main::auth->assert('ap_transactions');
 
 881   $form->{title} = $locale->text('Confirm!');
 
 885   delete $form->{header};
 
 888 <form method=post action=$form->{script}>
 
 891   foreach my $key (keys %$form) {
 
 892     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
 
 893     $form->{$key} =~ s/\"/"/g;
 
 894     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
 
 898 <h2 class=confirm>$form->{title}</h2>
 
 901     . $locale->text('Are you sure you want to delete Transaction')
 
 902     . qq| $form->{invnumber}</h4>
 
 904 <input name=action class=submit type=submit value="|
 
 905     . $locale->text('Yes') . qq|">
 
 909   $main::lxdebug->leave_sub();
 
 913   $main::lxdebug->enter_sub();
 
 915   my $form     = $main::form;
 
 916   my %myconfig = %main::myconfig;
 
 917   my $locale   = $main::locale;
 
 919   $main::auth->assert('ap_transactions');
 
 921   if (AP->delete_transaction(\%myconfig, \%$form)) {
 
 923     if(!exists $form->{addition}) {
 
 924       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 925       $form->{addition}  = "DELETED";
 
 926       $form->{what_done} = "invoice";
 
 929     # /saving the history
 
 930     $form->redirect($locale->text('Transaction deleted!'));
 
 932   $form->error($locale->text('Cannot delete transaction!'));
 
 934   $main::lxdebug->leave_sub();
 
 938   $main::lxdebug->enter_sub();
 
 940   $main::auth->assert('vendor_invoice_edit');
 
 942   my $form     = $main::form;
 
 943   my %myconfig = %main::myconfig;
 
 944   my $locale   = $main::locale;
 
 946   $form->{title}    = $locale->text('AP Transactions');
 
 948   $form->get_lists(projects => { "key" => "ALL_PROJECTS", "all" => 1 });
 
 950   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 951   # constants and subs for template
 
 952   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
 
 954   $::request->layout->add_javascripts("autocomplete_project.js");
 
 957   print $form->parse_html_template('ap/search', { %myconfig });
 
 959   $main::lxdebug->leave_sub();
 
 962 sub create_subtotal_row {
 
 963   $main::lxdebug->enter_sub();
 
 965   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
 
 967   my $form     = $main::form;
 
 968   my %myconfig = %main::myconfig;
 
 970   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
 
 972   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
 
 974   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
 
 976   map { $totals->{$_} = 0 } @{ $subtotal_columns };
 
 978   $main::lxdebug->leave_sub();
 
 983 sub ap_transactions {
 
 984   $main::lxdebug->enter_sub();
 
 986   my $form     = $main::form;
 
 987   my %myconfig = %main::myconfig;
 
 988   my $locale   = $main::locale;
 
 990   $main::auth->assert('vendor_invoice_edit');
 
 992   report_generator_set_default_sort('transdate', 1);
 
 994   AP->ap_transactions(\%myconfig, \%$form);
 
 996   $form->{title} = $locale->text('AP Transactions');
 
 998   my $report = SL::ReportGenerator->new(\%myconfig, $form);
 
1001     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
 
1002        due duedate transaction_description notes employee globalprojectnumber
 
1003        vendornumber country ustid taxzone payment_terms charts direct_debit);
 
1005   my @hidden_variables = map { "l_${_}" } @columns;
 
1006   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto
 
1007                                            parts_partnumber parts_description);
 
1009   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
 
1012     'transdate'               => { 'text' => $locale->text('Date'), },
 
1013     'id'                      => { 'text' => $locale->text('ID'), },
 
1014     'type'                    => { 'text' => $locale->text('Type'), },
 
1015     'invnumber'               => { 'text' => $locale->text('Invoice'), },
 
1016     'ordnumber'               => { 'text' => $locale->text('Order'), },
 
1017     'name'                    => { 'text' => $locale->text('Vendor'), },
 
1018     'netamount'               => { 'text' => $locale->text('Amount'), },
 
1019     'tax'                     => { 'text' => $locale->text('Tax'), },
 
1020     'amount'                  => { 'text' => $locale->text('Total'), },
 
1021     'paid'                    => { 'text' => $locale->text('Paid'), },
 
1022     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
 
1023     'due'                     => { 'text' => $locale->text('Amount Due'), },
 
1024     'duedate'                 => { 'text' => $locale->text('Due Date'), },
 
1025     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
 
1026     'notes'                   => { 'text' => $locale->text('Notes'), },
 
1027     'employee'                => { 'text' => $locale->text('Employee'), },
 
1028     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
 
1029     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
 
1030     'country'                 => { 'text' => $locale->text('Country'), },
 
1031     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
 
1032     'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
 
1033     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
 
1034     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
 
1035     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
 
1038   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
 
1039     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
 
1040     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
 
1043   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
 
1045   $form->{"l_type"} = "Y";
 
1046   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
 
1048   $report->set_columns(%column_defs);
 
1049   $report->set_column_order(@columns);
 
1051   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
 
1053   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
 
1056   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
 
1057   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
 
1058   push @options, $locale->text('Department')              . " : $form->{department}"                     if ($form->{department});
 
1059   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
 
1060   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
 
1061   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
 
1062   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
 
1063   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
 
1064   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
 
1065   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
 
1066   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
 
1067   push @options, $locale->text('Open')                                                                   if ($form->{open});
 
1068   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
 
1070   $report->set_options('top_info_text'        => join("\n", @options),
 
1071                        'raw_bottom_info_text' => $form->parse_html_template('ap/ap_transactions_bottom'),
 
1072                        'output_format'        => 'HTML',
 
1073                        'title'                => $form->{title},
 
1074                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
 
1076   $report->set_options_from_form();
 
1077   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
1079   # add sort and escape callback, this one we use for the add sub
 
1080   $form->{callback} = $href .= "&sort=$form->{sort}";
 
1082   # escape callback for href
 
1083   my $callback = $form->escape($href);
 
1085   my @subtotal_columns = qw(netamount amount paid due);
 
1087   my %totals    = map { $_ => 0 } @subtotal_columns;
 
1088   my %subtotals = map { $_ => 0 } @subtotal_columns;
 
1092   foreach my $ap (@{ $form->{AP} }) {
 
1093     $ap->{tax} = $ap->{amount} - $ap->{netamount};
 
1094     $ap->{due} = $ap->{amount} - $ap->{paid};
 
1096     map { $subtotals{$_} += $ap->{$_};
 
1097           $totals{$_}    += $ap->{$_} } @subtotal_columns;
 
1099     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
 
1101     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
 
1102     my $has_storno = $ap->{storno} && !$ap->{storno_id};
 
1104     if ($ap->{invoice}) {
 
1106           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
 
1107         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
 
1108         :                     $locale->text("Invoice (one letter abbreviation)");
 
1111           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
 
1112         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
 
1113         :                     $locale->text("AP Transaction (abbreviation)");
 
1116     $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
 
1120     foreach my $column (@columns) {
 
1122         'data'  => $ap->{$column},
 
1123         'align' => $column_alignment{$column},
 
1127     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
 
1128       . "&id=" . E($ap->{id}) . "&callback=${callback}";
 
1130     my $row_set = [ $row ];
 
1132     if (($form->{l_subtotal} eq 'Y')
 
1133         && (($idx == (scalar @{ $form->{AP} } - 1))
 
1134             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
 
1135       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
 
1138     $report->add_data($row_set);
 
1143   $report->add_separator();
 
1144   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
 
1146   $report->generate_with_headers();
 
1148   $main::lxdebug->leave_sub();
 
1152   $main::lxdebug->enter_sub();
 
1154   my $form     = $main::form;
 
1155   my %myconfig = %main::myconfig;
 
1156   my $locale   = $main::locale;
 
1158   $main::auth->assert('ap_transactions');
 
1160   if (IS->has_storno(\%myconfig, $form, 'ap')) {
 
1161     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
 
1162     $form->error($locale->text("Transaction has already been cancelled!"));
 
1165   $form->error($locale->text('Cannot post storno for a closed period!'))
 
1166     if ( $form->date_closed($form->{transdate}, \%myconfig));
 
1168   AP->storno($form, \%myconfig, $form->{id});
 
1170   # saving the history
 
1171   if(!exists $form->{addition} && $form->{id} ne "") {
 
1172     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
1173     $form->{addition}  = "STORNO";
 
1174     $form->{what_done} = "invoice";
 
1175     $form->save_history;
 
1177   # /saving the history
 
1179   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
 
1181   $main::lxdebug->leave_sub();