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   delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
 
 108   # Fill $::form from the template.
 
 109   my $today                   = DateTime->today_local;
 
 110   $::form->{title}            = "Add";
 
 111   $::form->{currency}         = $template->currency->name;
 
 112   $::form->{direct_debit}     = $template->direct_debit;
 
 113   $::form->{globalproject_id} = $template->project_id;
 
 114   $::form->{AP_chart_id}      = $template->ar_ap_chart_id;
 
 115   $::form->{transdate}        = $today->to_kivitendo;
 
 116   $::form->{duedate}          = $today->to_kivitendo;
 
 117   $::form->{rowcount}         = @{ $template->items } + 1;
 
 118   $::form->{paidaccounts}     = 1;
 
 119   $::form->{$_}               = $template->$_ for qw(department_id ordnumber taxincluded notes);
 
 121   if ($template->vendor) {
 
 122     $::form->{vendor_id} = $template->vendor_id;
 
 123     $::form->{vendor}    = $template->vendor->name;
 
 124     $::form->{duedate}     = $template->vendor->payment->calc_date(reference_date => $today)->to_kivitendo if $template->vendor->payment;
 
 128   foreach my $item (@{ $template->items }) {
 
 131     my $active_taxkey = $item->chart->get_active_taxkey;
 
 132     my $taxes         = SL::DB::Manager::Tax->get_all(
 
 133       where   => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
 
 134       sort_by => 'taxkey, rate',
 
 137     my $tax   = first { $item->tax_id          == $_->id } @{ $taxes };
 
 138     $tax    //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
 
 139     $tax    //= $taxes->[0];
 
 146     $::form->{"AP_amount_chart_id_${row}"}          = $item->chart_id;
 
 147     $::form->{"previous_AP_amount_chart_id_${row}"} = $item->chart_id;
 
 148     $::form->{"amount_${row}"}                      = $::form->format_amount(\%::myconfig, $item->amount1, 2);
 
 149     $::form->{"taxchart_${row}"}                    = $item->tax_id . '--' . $tax->rate;
 
 150     $::form->{"project_id_${row}"}                  = $item->project_id;
 
 153   flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
 
 158 sub save_record_template {
 
 159   $::auth->assert('ap_transactions');
 
 161   my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
 
 162   my $js       = SL::ClientJS->new(controller => SL::Controller::Base->new);
 
 163   my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
 
 165   $js->dialog->close('#record_template_dialog');
 
 168     $_->{chart_id} && (($_->{tax_id} // '') ne '') && ($_->{amount1} != 0)
 
 170     +{ chart_id   => $::form->{"AP_amount_chart_id_${_}"},
 
 171        amount1    => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
 
 172        tax_id     => (split m{--}, $::form->{"taxchart_${_}"})[0],
 
 173        project_id => $::form->{"project_id_${_}"} || undef,
 
 175   } (1..($::form->{rowcount} || 1));
 
 177   $template->assign_attributes(
 
 178     template_type  => 'ap_transaction',
 
 179     template_name  => $new_name,
 
 181     currency_id    => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
 
 182     ar_ap_chart_id => $::form->{AP_chart_id}      || undef,
 
 183     vendor_id      => $::form->{vendor_id}        || undef,
 
 184     department_id  => $::form->{department_id}    || undef,
 
 185     project_id     => $::form->{globalproject_id} || undef,
 
 186     taxincluded    => $::form->{taxincluded}  ? 1 : 0,
 
 187     direct_debit   => $::form->{direct_debit} ? 1 : 0,
 
 188     ordnumber      => $::form->{ordnumber},
 
 189     notes          => $::form->{notes},
 
 199       ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
 
 204     ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
 
 209   $main::lxdebug->enter_sub();
 
 211   my $form     = $main::form;
 
 212   my %myconfig = %main::myconfig;
 
 214   $main::auth->assert('ap_transactions');
 
 216   $form->{title} = "Add";
 
 218   $form->{callback} = "ap.pl?action=add" unless $form->{callback};
 
 220   AP->get_transdate(\%myconfig, $form);
 
 221   $form->{initial_transdate} = $form->{transdate};
 
 222   create_links(dont_save => 1);
 
 223   $form->{transdate} = $form->{initial_transdate};
 
 225   if ($form->{vendor_id}) {
 
 226     my $last_used_ap_chart = SL::DB::Vendor->load_cached($form->{vendor_id})->last_used_ap_chart;
 
 227     $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
 232   $main::lxdebug->leave_sub();
 
 236   $main::lxdebug->enter_sub();
 
 238   my $form     = $main::form;
 
 240   $main::auth->assert('ap_transactions');
 
 242   $form->{title} = "Edit";
 
 247   $main::lxdebug->leave_sub();
 
 251   $main::lxdebug->enter_sub();
 
 253   my $form     = $main::form;
 
 255   $main::auth->assert('ap_transactions');
 
 257   # get all files stored in the webdav folder
 
 258   if ($form->{invnumber} && $::instance_conf->get_webdav) {
 
 259     my $webdav = SL::Webdav->new(
 
 260       type     => 'accounts_payable',
 
 261       number   => $form->{invnumber},
 
 263     my $webdav_path = $webdav->webdav_path;
 
 264     my @all_objects = $webdav->get_all_objects;
 
 265     @{ $form->{WEBDAV} } = map { { name => $_->filename,
 
 267                                    link => File::Spec->catfile($_->full_filedescriptor),
 
 273   $main::lxdebug->leave_sub();
 
 277   $main::lxdebug->enter_sub();
 
 281   my $form     = $main::form;
 
 282   my %myconfig = %main::myconfig;
 
 284   $main::auth->assert('ap_transactions');
 
 286   $form->create_links("AP", \%myconfig, "vendor");
 
 288   if (!$params{dont_save}) {
 
 289     %saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
 
 290     $saved{duedate} = $form->{duedate} if $form->{duedate};
 
 291     $saved{currency} = $form->{currency} if $form->{currency};
 
 292     $saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
 
 295   IR->get_vendor(\%myconfig, \%$form);
 
 297   $form->{$_}        = $saved{$_} for keys %saved;
 
 298   $form->{rowcount}  = 1;
 
 299   $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};
 
 301   # build the popup menus
 
 302   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
 
 305   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 307   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 309   $form->{employee} = "$form->{employee}--$form->{employee_id}";
 
 311   AP->setup_form($form);
 
 314     ($form->datetonum($form->{transdate}, \%myconfig) <=
 
 315      $form->datetonum($form->{closedto}, \%myconfig));
 
 317   $main::lxdebug->leave_sub();
 
 321   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid paid_project_id);
 
 323     grep { $_->{paid} != 0 }
 
 326       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
 
 327     } (1..$::form->{paidaccounts});
 
 329   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
 
 331   $::form->{paidaccounts} = max scalar(@payments), 1;
 
 333   foreach my $idx (1 .. scalar(@payments)) {
 
 334     my $payment = $payments[$idx - 1];
 
 335     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
 
 340   $main::lxdebug->enter_sub();
 
 342   my $form     = $main::form;
 
 343   my %myconfig = %main::myconfig;
 
 344   my $locale   = $main::locale;
 
 345   my $cgi      = $::request->{cgi};
 
 347   $main::auth->assert('ap_transactions');
 
 349   $::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
 
 351   $form->{initial_focus} = !($form->{amount_1} * 1) ? 'vendor_id' : 'row_' . $form->{rowcount};
 
 353   $form->{title_} = $form->{title};
 
 354   $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
 
 356   # type=submit $locale->text('Add Accounts Payables Transaction')
 
 357   # type=submit $locale->text('Edit Accounts Payables Transaction')
 
 359   my $readonly = $form->{id} ? "readonly" : "";
 
 361   $form->{radier} = ($::instance_conf->get_ap_changeable == 2)
 
 362                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 363                       : ($::instance_conf->get_ap_changeable == 1);
 
 364   $readonly       = $form->{radier} ? "" : $readonly;
 
 366   $form->{readonly} = $readonly;
 
 368   $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 369   if ( $form->{forex} ) {
 
 370     $form->{exchangerate} = $form->{forex};
 
 374   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
 
 375   $form->{creditlimit}     = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
 
 376   $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
 
 379   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
 
 382   $form->{textarea_rows} = $rows;
 
 384   $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
 
 386   my @old_project_ids = ();
 
 389       if ($form->{"project_id_$_"}) {
 
 390         push(@old_project_ids, $form->{"project_id_$_"});
 
 393     (1..$form->{"rowcount"})
 
 396   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
 
 398                                     "old_id"    => \@old_project_ids },
 
 399                    "charts"    => { "key"       => "ALL_CHARTS",
 
 400                                     "transdate" => $form->{transdate} },
 
 401                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
 
 402                                     "module"    => "AP" },);
 
 405     { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
 
 406     @{ $form->{ALL_CHARTS} }
 
 409   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
 
 411   my %project_labels = ();
 
 412   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
 
 413     $project_labels{$item->{id}} = $item->{projectnumber};
 
 417   my $default_ap_amount_chart_id;
 
 419   foreach my $item (@{ $form->{ALL_CHARTS} }) {
 
 420     if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
 
 421       $default_ap_amount_chart_id //= $item->{id};
 
 423     } elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
 
 424       push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
 
 427     $charts{$item->{accno}} = $item;
 
 430   my $follow_up_vc         = $form->{vendor_id} ? SL::DB::Vendor->load_cached($form->{vendor_id})->name : '';
 
 431   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
 
 433   $::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");
 
 434   my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
 
 439   for my $i (1 .. $form->{rowcount}) {
 
 442     $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
 
 443     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
 
 445     my ($default_taxchart, $taxchart_to_use);
 
 446     my $amount_chart_id   = $form->{"AP_amount_chart_id_$i"} || $default_ap_amount_chart_id;
 
 447     my $chart_has_changed = $::form->{"previous_AP_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AP_amount_chart_id_$i"});
 
 448     my @taxcharts         = GL->get_active_taxes_for_chart($amount_chart_id, $transdate);
 
 450     foreach my $item (@taxcharts) {
 
 451       my $key             = $item->id . "--" . $item->rate;
 
 452       $first_taxchart   //= $item;
 
 453       $default_taxchart   = $item if $item->{is_default};
 
 454       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
 
 457     $taxchart_to_use                 = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
 
 458     my $selected_taxchart            = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
 459     $form->{"selected_taxchart_$i"}  = $selected_taxchart;
 
 460     $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
 
 461     $form->{"taxcharts_$i"}          = \@taxcharts;
 
 464   $form->{taxchart_value_title_sub} = sub {
 
 467       $item->{id} .'--'. $item->{rate},
 
 468       $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
 
 472   $form->{AP_paid_value_title_sub} = sub {
 
 476       $item->{accno} .'--'. $item->{description}
 
 480   $form->{invtotal_unformatted} = $form->{invtotal};
 
 481   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
 
 483   $form->{totalpaid} = 0;
 
 487   if ( $form->{'paid_'. $form->{paidaccounts}} ) {
 
 488     $form->{paidaccounts}++;
 
 491   # default account for current assets (i.e. 1801 - SKR04)
 
 492   $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 494   for my $i (1 .. $form->{paidaccounts}) {
 
 495     $form->{totalpaid} += $form->{"paid_$i"};
 
 498     if ($form->{"paid_$i"}) {
 
 499       $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
 
 501     if ($form->{"exchangerate_$i"} == 0) {
 
 502       $form->{"exchangerate_$i"} = "";
 
 504       $form->{"exchangerate_$i"} =
 
 505         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
 
 509     if (SL::DB::Default->get->payments_changeable == 0) {
 
 511       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
 
 513     if (SL::DB::Default->get->payments_changeable == 2) {
 
 515       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
 
 518     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
 
 519     if ($form->date_closed($form->{"gldate_$i"})) {
 
 523     $form->{'paidaccount_changeable_'. $i} = $changeable;
 
 525     $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
 
 528   $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
 
 530   print $form->parse_html_template('ap/form_header', {
 
 531     today => DateTime->today,
 
 532     currencies => SL::DB::Manager::Currency->get_all_sorted,
 
 535   $main::lxdebug->leave_sub();
 
 539   $::lxdebug->enter_sub;
 
 540   $::auth->assert('ap_transactions');
 
 545     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
 
 547     if (@{ $follow_ups }) {
 
 548       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
 
 549       $num_follow_ups = scalar @{ $follow_ups }
 
 553   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
 
 554   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
 
 556   my $storno = $::form->{id}
 
 557             && !IS->has_storno(\%::myconfig, $::form, 'ap')
 
 558             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
 
 559             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
 
 562   print $::form->parse_html_template('ap/form_footer', {
 
 564     num_follow_ups    => $num_follow_ups,
 
 565     show_post_draft   => ($transdate > $closedto) && !$::form->{id},
 
 566     show_storno       => $storno,
 
 569   $::lxdebug->leave_sub;
 
 573   $::auth->assert('ap_transactions');
 
 575   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
 
 577   $::form->redirect($::locale->text("Marked as paid"));
 
 581   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
 
 582   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
 
 587   $main::lxdebug->enter_sub();
 
 589   my $form     = $main::form;
 
 590   my %myconfig = %main::myconfig;
 
 592   $main::auth->assert('ap_transactions');
 
 596   $form->{invtotal} = 0;
 
 598   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
 
 600   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 601     qw(exchangerate creditlimit creditremaining);
 
 603   my @flds  = qw(amount AP_amount projectnumber oldprojectnumber project_id taxchart);
 
 605   my (@a, $j, $totaltax);
 
 606   for my $i (1 .. $form->{rowcount}) {
 
 607     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
 
 608     if ($form->{"amount_$i"}) {
 
 611       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
 
 613       # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
 
 615       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
 
 617       $totaltax += $form->{"tax_$i"};
 
 618       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 622   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
 
 624   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
 
 626   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 627   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 629   $form->{invdate} = $form->{transdate};
 
 631   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
 
 632     IR->get_vendor(\%::myconfig, $form);
 
 635   $form->{rowcount} = $count + 1;
 
 638     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
 
 641   for my $i (1 .. $form->{paidaccounts}) {
 
 642     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 645           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
 646       } qw(paid exchangerate);
 
 648       $totalpaid += $form->{"paid_$i"};
 
 650       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 651       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 655   $form->{creditremaining} -=
 
 656     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
 
 657      $form->{oldinvtotal});
 
 658   $form->{oldinvtotal}  = $form->{invtotal};
 
 659   $form->{oldtotalpaid} = $totalpaid;
 
 663   $main::lxdebug->leave_sub();
 
 668   $main::lxdebug->enter_sub();
 
 670   my $form     = $main::form;
 
 671   my %myconfig = %main::myconfig;
 
 672   my $locale   = $main::locale;
 
 674   $main::auth->assert('ap_transactions');
 
 675   $form->mtime_ischanged('ap');
 
 677   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 679   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 681   for my $i (1 .. $form->{paidaccounts}) {
 
 682     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 683       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 685       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 687       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 688         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 690       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 691       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 692       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 693         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 695       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 696         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 697           if ($invdate == $datepaid);
 
 698         $form->isblank("exchangerate_$i",
 
 699                        $locale->text('Exchangerate for payment missing!'));
 
 704   ($form->{AP})      = split /--/, $form->{AP};
 
 705   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
 
 706   if (AP->post_payment(\%myconfig, \%$form)) {
 
 707     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 708     $form->{what_done} = 'invoice';
 
 709     $form->{addition}  = "PAYMENT POSTED";
 
 711     $form->redirect($locale->text('Payment posted!'))
 
 713     $form->error($locale->text('Cannot post payment!'));
 
 717   $main::lxdebug->leave_sub();
 
 722   $main::lxdebug->enter_sub();
 
 724   my $form     = $main::form;
 
 725   my %myconfig = %main::myconfig;
 
 726   my $locale   = $main::locale;
 
 728   $main::auth->assert('ap_transactions');
 
 729   $form->mtime_ischanged('ap');
 
 733   # check if there is a vendor, invoice, due date and invnumber
 
 734   $form->isblank("transdate", $locale->text("Invoice Date missing!"));
 
 735   $form->isblank("duedate",   $locale->text("Due Date missing!"));
 
 736   $form->isblank("vendor_id", $locale->text('Vendor missing!'));
 
 737   $form->isblank("invnumber", $locale->text('Invoice Number missing!'));
 
 739   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 740     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 745   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
 746   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 748   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 749     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
 
 750   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
 
 752   my $zero_amount_posting = 1;
 
 753   for my $i (1 .. $form->{rowcount}) {
 
 754     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
 
 755       $zero_amount_posting = 0;
 
 760   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
 
 762   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 763     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
 
 766   for my $i (1 .. $form->{paidaccounts}) {
 
 767     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 768       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 770       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 772       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 773       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 775       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 776       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 777       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 778         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 780       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 781         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 782           if ($transdate == $datepaid);
 
 783         $form->isblank("exchangerate_$i",
 
 784                        $locale->text('Exchangerate for payment missing!'));
 
 790   # if old vendor ne vendor redo form
 
 791   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
 793     $::dispatcher->end_request;
 
 797   $form->{id} = 0 if $form->{postasnew};
 
 799   if (AP->post_transaction(\%myconfig, \%$form)) {
 
 800     # create webdav folder
 
 801     if ($::instance_conf->get_webdav) {
 
 802       SL::Webdav->new(type     => 'accounts_payable',
 
 803                       number   => $form->{invnumber},
 
 807     if(!exists $form->{addition} && $form->{id} ne "") {
 
 808       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 809       $form->{addition}  = "POSTED";
 
 810       $form->{what_done} = "invoice";
 
 813     # /saving the history
 
 814     # Dieser Text wird niemals ausgegeben: Probleme beim redirect?
 
 815     $form->redirect($locale->text('AP transaction posted.')) unless $inline;
 
 817     $form->error($locale->text('Cannot post transaction!'));
 
 820   $main::lxdebug->leave_sub();
 
 824   $main::lxdebug->enter_sub();
 
 826   my $form     = $main::form;
 
 827   my %myconfig = %main::myconfig;
 
 829   $main::auth->assert('ap_transactions');
 
 831   $form->{postasnew} = 1;
 
 833   if(!exists $form->{addition} && $form->{id} ne "") {
 
 834     # does this work? post_as_new for ap doesn't immediately save the
 
 835     # invoice, because the invnumber has to be entered by hand.
 
 836     # And the value of $form->{postasnew} isn't checked when calling post
 
 837     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 838     $form->{addition}  = "POSTED AS NEW";
 
 839     $form->{what_done} = "invoice";
 
 842   # /saving the history
 
 845   $main::lxdebug->leave_sub();
 
 849   $main::lxdebug->enter_sub();
 
 851   my $form     = $main::form;
 
 852   my %myconfig = %main::myconfig;
 
 854   $main::auth->assert('ap_transactions');
 
 856   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);
 
 857   $form->{paidaccounts} = 1;
 
 859   $form->{invdate} = $form->current_date(\%myconfig);
 
 862   $main::lxdebug->leave_sub();
 
 866   $main::lxdebug->enter_sub();
 
 868   my $form     = $main::form;
 
 869   my $locale   = $main::locale;
 
 871   $main::auth->assert('ap_transactions');
 
 873   $form->{title} = $locale->text('Confirm!');
 
 877   delete $form->{header};
 
 880 <form method=post action=$form->{script}>
 
 883   foreach my $key (keys %$form) {
 
 884     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
 
 885     $form->{$key} =~ s/\"/"/g;
 
 886     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
 
 890 <h2 class=confirm>$form->{title}</h2>
 
 893     . $locale->text('Are you sure you want to delete Transaction')
 
 894     . qq| $form->{invnumber}</h4>
 
 896 <input name=action class=submit type=submit value="|
 
 897     . $locale->text('Yes') . qq|">
 
 901   $main::lxdebug->leave_sub();
 
 905   $main::lxdebug->enter_sub();
 
 907   my $form     = $main::form;
 
 908   my %myconfig = %main::myconfig;
 
 909   my $locale   = $main::locale;
 
 911   $main::auth->assert('ap_transactions');
 
 913   if (AP->delete_transaction(\%myconfig, \%$form)) {
 
 915     if(!exists $form->{addition}) {
 
 916       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 917       $form->{addition}  = "DELETED";
 
 918       $form->{what_done} = "invoice";
 
 921     # /saving the history
 
 922     $form->redirect($locale->text('Transaction deleted!'));
 
 924   $form->error($locale->text('Cannot delete transaction!'));
 
 926   $main::lxdebug->leave_sub();
 
 930   $main::lxdebug->enter_sub();
 
 932   $main::auth->assert('vendor_invoice_edit');
 
 934   my $form     = $main::form;
 
 935   my %myconfig = %main::myconfig;
 
 936   my $locale   = $main::locale;
 
 938   $form->{title}    = $locale->text('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");
 
 949   print $form->parse_html_template('ap/search', { %myconfig });
 
 951   $main::lxdebug->leave_sub();
 
 954 sub create_subtotal_row {
 
 955   $main::lxdebug->enter_sub();
 
 957   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
 
 959   my $form     = $main::form;
 
 960   my %myconfig = %main::myconfig;
 
 962   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
 
 964   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
 
 966   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
 
 968   map { $totals->{$_} = 0 } @{ $subtotal_columns };
 
 970   $main::lxdebug->leave_sub();
 
 975 sub ap_transactions {
 
 976   $main::lxdebug->enter_sub();
 
 978   my $form     = $main::form;
 
 979   my %myconfig = %main::myconfig;
 
 980   my $locale   = $main::locale;
 
 982   $main::auth->assert('vendor_invoice_edit');
 
 984   report_generator_set_default_sort('transdate', 1);
 
 986   AP->ap_transactions(\%myconfig, \%$form);
 
 988   $form->{title} = $locale->text('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
 
 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);
 
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     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
 
1022     'country'                 => { 'text' => $locale->text('Country'), },
 
1023     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
 
1024     'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
 
1025     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
 
1026     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
 
1027     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
 
1030   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
 
1031     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
 
1032     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
 
1035   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
 
1037   $form->{"l_type"} = "Y";
 
1038   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
 
1040   $report->set_columns(%column_defs);
 
1041   $report->set_column_order(@columns);
 
1043   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
 
1045   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
 
1048   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
 
1049   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
 
1050   push @options, $locale->text('Department')              . " : $form->{department}"                     if ($form->{department});
 
1051   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
 
1052   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
 
1053   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
 
1054   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
 
1055   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
 
1056   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
 
1057   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
 
1058   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
 
1059   push @options, $locale->text('Open')                                                                   if ($form->{open});
 
1060   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
 
1062   $report->set_options('top_info_text'        => join("\n", @options),
 
1063                        'raw_bottom_info_text' => $form->parse_html_template('ap/ap_transactions_bottom'),
 
1064                        'output_format'        => 'HTML',
 
1065                        'title'                => $form->{title},
 
1066                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
 
1068   $report->set_options_from_form();
 
1069   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
1071   # add sort and escape callback, this one we use for the add sub
 
1072   $form->{callback} = $href .= "&sort=$form->{sort}";
 
1074   # escape callback for href
 
1075   my $callback = $form->escape($href);
 
1077   my @subtotal_columns = qw(netamount amount paid due);
 
1079   my %totals    = map { $_ => 0 } @subtotal_columns;
 
1080   my %subtotals = map { $_ => 0 } @subtotal_columns;
 
1084   foreach my $ap (@{ $form->{AP} }) {
 
1085     $ap->{tax} = $ap->{amount} - $ap->{netamount};
 
1086     $ap->{due} = $ap->{amount} - $ap->{paid};
 
1088     map { $subtotals{$_} += $ap->{$_};
 
1089           $totals{$_}    += $ap->{$_} } @subtotal_columns;
 
1091     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
 
1093     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
 
1094     my $has_storno = $ap->{storno} && !$ap->{storno_id};
 
1096     if ($ap->{invoice}) {
 
1098           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
 
1099         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
 
1100         :                     $locale->text("Invoice (one letter abbreviation)");
 
1103           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
 
1104         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
 
1105         :                     $locale->text("AP Transaction (abbreviation)");
 
1108     $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
 
1112     foreach my $column (@columns) {
 
1114         'data'  => $ap->{$column},
 
1115         'align' => $column_alignment{$column},
 
1119     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
 
1120       . "&id=" . E($ap->{id}) . "&callback=${callback}";
 
1122     my $row_set = [ $row ];
 
1124     if (($form->{l_subtotal} eq 'Y')
 
1125         && (($idx == (scalar @{ $form->{AP} } - 1))
 
1126             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
 
1127       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
 
1130     $report->add_data($row_set);
 
1135   $report->add_separator();
 
1136   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
 
1138   $report->generate_with_headers();
 
1140   $main::lxdebug->leave_sub();
 
1144   $main::lxdebug->enter_sub();
 
1146   my $form     = $main::form;
 
1147   my %myconfig = %main::myconfig;
 
1148   my $locale   = $main::locale;
 
1150   $main::auth->assert('ap_transactions');
 
1152   if (IS->has_storno(\%myconfig, $form, 'ap')) {
 
1153     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
 
1154     $form->error($locale->text("Transaction has already been cancelled!"));
 
1157   $form->error($locale->text('Cannot post storno for a closed period!'))
 
1158     if ( $form->date_closed($form->{transdate}, \%myconfig));
 
1160   AP->storno($form, \%myconfig, $form->{id});
 
1162   # saving the history
 
1163   if(!exists $form->{addition} && $form->{id} ne "") {
 
1164     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
1165     $form->{addition}  = "STORNO";
 
1166     $form->{what_done} = "invoice";
 
1167     $form->save_history;
 
1169   # /saving the history
 
1171   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
 
1173   $main::lxdebug->leave_sub();