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));
 
 159   $main::lxdebug->enter_sub();
 
 161   my $form     = $main::form;
 
 162   my %myconfig = %main::myconfig;
 
 164   $main::auth->assert('ap_transactions');
 
 166   $form->{title} = "Add";
 
 168   $form->{callback} = "ap.pl?action=add" unless $form->{callback};
 
 170   AP->get_transdate(\%myconfig, $form);
 
 171   $form->{initial_transdate} = $form->{transdate};
 
 172   create_links(dont_save => 1);
 
 173   $form->{transdate} = $form->{initial_transdate};
 
 175   if ($form->{vendor_id}) {
 
 176     my $last_used_ap_chart = SL::DB::Vendor->load_cached($form->{vendor_id})->last_used_ap_chart;
 
 177     $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
 
 182   $main::lxdebug->leave_sub();
 
 186   $main::lxdebug->enter_sub();
 
 188   my $form     = $main::form;
 
 190   $main::auth->assert('ap_transactions');
 
 192   $form->{title} = "Edit";
 
 197   $main::lxdebug->leave_sub();
 
 201   $main::lxdebug->enter_sub();
 
 203   my $form     = $main::form;
 
 205   $main::auth->assert('ap_transactions');
 
 207   # get all files stored in the webdav folder
 
 208   if ($form->{invnumber} && $::instance_conf->get_webdav) {
 
 209     my $webdav = SL::Webdav->new(
 
 210       type     => 'accounts_payable',
 
 211       number   => $form->{invnumber},
 
 213     my $webdav_path = $webdav->webdav_path;
 
 214     my @all_objects = $webdav->get_all_objects;
 
 215     @{ $form->{WEBDAV} } = map { { name => $_->filename,
 
 217                                    link => File::Spec->catfile($_->full_filedescriptor),
 
 223   $main::lxdebug->leave_sub();
 
 227   $main::lxdebug->enter_sub();
 
 231   my $form     = $main::form;
 
 232   my %myconfig = %main::myconfig;
 
 234   $main::auth->assert('ap_transactions');
 
 236   $form->create_links("AP", \%myconfig, "vendor");
 
 238   if (!$params{dont_save}) {
 
 239     %saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
 
 240     $saved{duedate} = $form->{duedate} if $form->{duedate};
 
 241     $saved{currency} = $form->{currency} if $form->{currency};
 
 242     $saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
 
 245   IR->get_vendor(\%myconfig, \%$form);
 
 247   $form->{$_}        = $saved{$_} for keys %saved;
 
 248   $form->{rowcount}  = 1;
 
 249   $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};
 
 251   # build the popup menus
 
 252   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
 
 255   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 257   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 259   $form->{employee} = "$form->{employee}--$form->{employee_id}";
 
 261   AP->setup_form($form);
 
 264     ($form->datetonum($form->{transdate}, \%myconfig) <=
 
 265      $form->datetonum($form->{closedto}, \%myconfig));
 
 267   $main::lxdebug->leave_sub();
 
 271   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid paid_project_id);
 
 273     grep { $_->{paid} != 0 }
 
 276       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
 
 277     } (1..$::form->{paidaccounts});
 
 279   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
 
 281   $::form->{paidaccounts} = max scalar(@payments), 1;
 
 283   foreach my $idx (1 .. scalar(@payments)) {
 
 284     my $payment = $payments[$idx - 1];
 
 285     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
 
 290   $main::lxdebug->enter_sub();
 
 292   my $form     = $main::form;
 
 293   my %myconfig = %main::myconfig;
 
 294   my $locale   = $main::locale;
 
 295   my $cgi      = $::request->{cgi};
 
 297   $main::auth->assert('ap_transactions');
 
 299   $::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
 
 301   $form->{initial_focus} = !($form->{amount_1} * 1) ? 'vendor_id' : 'row_' . $form->{rowcount};
 
 303   $form->{title_} = $form->{title};
 
 304   $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
 
 306   # type=submit $locale->text('Add Accounts Payables Transaction')
 
 307   # type=submit $locale->text('Edit Accounts Payables Transaction')
 
 309   my $readonly = $form->{id} ? "readonly" : "";
 
 311   $form->{radier} = ($::instance_conf->get_ap_changeable == 2)
 
 312                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 313                       : ($::instance_conf->get_ap_changeable == 1);
 
 314   $readonly       = $form->{radier} ? "" : $readonly;
 
 316   $form->{readonly} = $readonly;
 
 318   $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 319   if ( $form->{forex} ) {
 
 320     $form->{exchangerate} = $form->{forex};
 
 324   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
 
 325   $form->{creditlimit}     = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
 
 326   $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
 
 329   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
 
 332   $form->{textarea_rows} = $rows;
 
 334   $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
 
 336   my @old_project_ids = ();
 
 339       if ($form->{"project_id_$_"}) {
 
 340         push(@old_project_ids, $form->{"project_id_$_"});
 
 343     (1..$form->{"rowcount"})
 
 346   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
 
 348                                     "old_id"    => \@old_project_ids },
 
 349                    "charts"    => { "key"       => "ALL_CHARTS",
 
 350                                     "transdate" => $form->{transdate} },
 
 351                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
 
 352                                     "module"    => "AP" },);
 
 355     { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
 
 356     @{ $form->{ALL_CHARTS} }
 
 359   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
 
 361   my %project_labels = ();
 
 362   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
 
 363     $project_labels{$item->{id}} = $item->{projectnumber};
 
 367   my $default_ap_amount_chart_id;
 
 369   foreach my $item (@{ $form->{ALL_CHARTS} }) {
 
 370     if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
 
 371       $default_ap_amount_chart_id //= $item->{id};
 
 373     } elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
 
 374       push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
 
 377     $charts{$item->{accno}} = $item;
 
 380   my $follow_up_vc         = $form->{vendor_id} ? SL::DB::Vendor->load_cached($form->{vendor_id})->name : '';
 
 381   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
 
 383   $::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");
 
 384   my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
 
 389   for my $i (1 .. $form->{rowcount}) {
 
 392     $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
 
 393     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
 
 395     my ($default_taxchart, $taxchart_to_use);
 
 396     my $amount_chart_id   = $form->{"AP_amount_chart_id_$i"} || $default_ap_amount_chart_id;
 
 397     my $chart_has_changed = $::form->{"previous_AP_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AP_amount_chart_id_$i"});
 
 398     my @taxcharts         = GL->get_active_taxes_for_chart($amount_chart_id, $transdate);
 
 400     foreach my $item (@taxcharts) {
 
 401       my $key             = $item->id . "--" . $item->rate;
 
 402       $first_taxchart   //= $item;
 
 403       $default_taxchart   = $item if $item->{is_default};
 
 404       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
 
 407     $taxchart_to_use                 = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
 
 408     my $selected_taxchart            = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
 409     $form->{"selected_taxchart_$i"}  = $selected_taxchart;
 
 410     $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
 
 411     $form->{"taxcharts_$i"}          = \@taxcharts;
 
 414   $form->{taxchart_value_title_sub} = sub {
 
 417       $item->{id} .'--'. $item->{rate},
 
 418       $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
 
 422   $form->{AP_paid_value_title_sub} = sub {
 
 426       $item->{accno} .'--'. $item->{description}
 
 430   $form->{invtotal_unformatted} = $form->{invtotal};
 
 431   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
 
 433   $form->{totalpaid} = 0;
 
 437   if ( $form->{'paid_'. $form->{paidaccounts}} ) {
 
 438     $form->{paidaccounts}++;
 
 441   # default account for current assets (i.e. 1801 - SKR04)
 
 442   $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 444   for my $i (1 .. $form->{paidaccounts}) {
 
 445     $form->{totalpaid} += $form->{"paid_$i"};
 
 448     if ($form->{"paid_$i"}) {
 
 449       $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
 
 451     if ($form->{"exchangerate_$i"} == 0) {
 
 452       $form->{"exchangerate_$i"} = "";
 
 454       $form->{"exchangerate_$i"} =
 
 455         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
 
 459     if (SL::DB::Default->get->payments_changeable == 0) {
 
 461       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
 
 463     if (SL::DB::Default->get->payments_changeable == 2) {
 
 465       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
 
 468     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
 
 469     if ($form->date_closed($form->{"gldate_$i"})) {
 
 473     $form->{'paidaccount_changeable_'. $i} = $changeable;
 
 475     $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
 
 478   $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
 
 480   print $form->parse_html_template('ap/form_header', {
 
 481     today => DateTime->today,
 
 482     currencies => SL::DB::Manager::Currency->get_all_sorted,
 
 485   $main::lxdebug->leave_sub();
 
 489   $::lxdebug->enter_sub;
 
 490   $::auth->assert('ap_transactions');
 
 495     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
 
 497     if (@{ $follow_ups }) {
 
 498       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
 
 499       $num_follow_ups = scalar @{ $follow_ups }
 
 503   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
 
 504   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
 
 506   my $storno = $::form->{id}
 
 507             && !IS->has_storno(\%::myconfig, $::form, 'ap')
 
 508             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
 
 509             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
 
 512   print $::form->parse_html_template('ap/form_footer', {
 
 514     num_follow_ups    => $num_follow_ups,
 
 515     show_post_draft   => ($transdate > $closedto) && !$::form->{id},
 
 516     show_storno       => $storno,
 
 519   $::lxdebug->leave_sub;
 
 523   $::auth->assert('ap_transactions');
 
 525   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
 
 527   $::form->redirect($::locale->text("Marked as paid"));
 
 531   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
 
 532   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
 
 537   $main::lxdebug->enter_sub();
 
 539   my $form     = $main::form;
 
 540   my %myconfig = %main::myconfig;
 
 542   $main::auth->assert('ap_transactions');
 
 546   $form->{invtotal} = 0;
 
 548   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
 
 550   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 551     qw(exchangerate creditlimit creditremaining);
 
 553   my @flds  = qw(amount AP_amount projectnumber oldprojectnumber project_id taxchart);
 
 555   my (@a, $j, $totaltax);
 
 556   for my $i (1 .. $form->{rowcount}) {
 
 557     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
 
 558     if ($form->{"amount_$i"}) {
 
 561       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
 
 563       # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
 
 565       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
 
 567       $totaltax += $form->{"tax_$i"};
 
 568       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 572   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
 
 574   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
 
 576   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
 577   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 579   $form->{invdate} = $form->{transdate};
 
 581   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
 
 582     IR->get_vendor(\%::myconfig, $form);
 
 585   $form->{rowcount} = $count + 1;
 
 588     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
 
 591   for my $i (1 .. $form->{paidaccounts}) {
 
 592     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 595           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
 596       } qw(paid exchangerate);
 
 598       $totalpaid += $form->{"paid_$i"};
 
 600       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 601       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 605   $form->{creditremaining} -=
 
 606     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
 
 607      $form->{oldinvtotal});
 
 608   $form->{oldinvtotal}  = $form->{invtotal};
 
 609   $form->{oldtotalpaid} = $totalpaid;
 
 613   $main::lxdebug->leave_sub();
 
 618   $main::lxdebug->enter_sub();
 
 620   my $form     = $main::form;
 
 621   my %myconfig = %main::myconfig;
 
 622   my $locale   = $main::locale;
 
 624   $main::auth->assert('ap_transactions');
 
 625   $form->mtime_ischanged('ap');
 
 627   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 629   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 631   for my $i (1 .. $form->{paidaccounts}) {
 
 632     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 633       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 635       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 637       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 638         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 640       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 641       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 642       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 643         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 645       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 646         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 647           if ($invdate == $datepaid);
 
 648         $form->isblank("exchangerate_$i",
 
 649                        $locale->text('Exchangerate for payment missing!'));
 
 654   ($form->{AP})      = split /--/, $form->{AP};
 
 655   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
 
 656   if (AP->post_payment(\%myconfig, \%$form)) {
 
 657     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 658     $form->{what_done} = 'invoice';
 
 659     $form->{addition}  = "PAYMENT POSTED";
 
 661     $form->redirect($locale->text('Payment posted!'))
 
 663     $form->error($locale->text('Cannot post payment!'));
 
 667   $main::lxdebug->leave_sub();
 
 672   $main::lxdebug->enter_sub();
 
 674   my $form     = $main::form;
 
 675   my %myconfig = %main::myconfig;
 
 676   my $locale   = $main::locale;
 
 678   $main::auth->assert('ap_transactions');
 
 679   $form->mtime_ischanged('ap');
 
 683   # check if there is a vendor, invoice, due date and invnumber
 
 684   $form->isblank("transdate", $locale->text("Invoice Date missing!"));
 
 685   $form->isblank("duedate",   $locale->text("Due Date missing!"));
 
 686   $form->isblank("vendor_id", $locale->text('Vendor missing!'));
 
 687   $form->isblank("invnumber", $locale->text('Invoice Number missing!'));
 
 689   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 690     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 695   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
 696   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 698   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 699     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
 
 700   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
 
 702   my $zero_amount_posting = 1;
 
 703   for my $i (1 .. $form->{rowcount}) {
 
 704     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
 
 705       $zero_amount_posting = 0;
 
 710   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
 
 712   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 713     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
 
 716   for my $i (1 .. $form->{paidaccounts}) {
 
 717     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 718       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 720       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 722       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 723       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 725       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 726       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 727       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 728         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 730       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 731         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 732           if ($transdate == $datepaid);
 
 733         $form->isblank("exchangerate_$i",
 
 734                        $locale->text('Exchangerate for payment missing!'));
 
 740   # if old vendor ne vendor redo form
 
 741   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
 743     $::dispatcher->end_request;
 
 747   $form->{id} = 0 if $form->{postasnew};
 
 749   if (AP->post_transaction(\%myconfig, \%$form)) {
 
 750     # create webdav folder
 
 751     if ($::instance_conf->get_webdav) {
 
 752       SL::Webdav->new(type     => 'accounts_payable',
 
 753                       number   => $form->{invnumber},
 
 757     if(!exists $form->{addition} && $form->{id} ne "") {
 
 758       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 759       $form->{addition}  = "POSTED";
 
 760       $form->{what_done} = "invoice";
 
 763     # /saving the history
 
 764     # Dieser Text wird niemals ausgegeben: Probleme beim redirect?
 
 765     $form->redirect($locale->text('AP transaction posted.')) unless $inline;
 
 767     $form->error($locale->text('Cannot post transaction!'));
 
 770   $main::lxdebug->leave_sub();
 
 774   $main::lxdebug->enter_sub();
 
 776   my $form     = $main::form;
 
 777   my %myconfig = %main::myconfig;
 
 779   $main::auth->assert('ap_transactions');
 
 781   $form->{postasnew} = 1;
 
 783   if(!exists $form->{addition} && $form->{id} ne "") {
 
 784     # does this work? post_as_new for ap doesn't immediately save the
 
 785     # invoice, because the invnumber has to be entered by hand.
 
 786     # And the value of $form->{postasnew} isn't checked when calling post
 
 787     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 788     $form->{addition}  = "POSTED AS NEW";
 
 789     $form->{what_done} = "invoice";
 
 792   # /saving the history
 
 795   $main::lxdebug->leave_sub();
 
 799   $main::lxdebug->enter_sub();
 
 801   my $form     = $main::form;
 
 802   my %myconfig = %main::myconfig;
 
 804   $main::auth->assert('ap_transactions');
 
 806   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);
 
 807   $form->{paidaccounts} = 1;
 
 809   $form->{invdate} = $form->current_date(\%myconfig);
 
 812   $main::lxdebug->leave_sub();
 
 816   $main::lxdebug->enter_sub();
 
 818   my $form     = $main::form;
 
 819   my $locale   = $main::locale;
 
 821   $main::auth->assert('ap_transactions');
 
 823   $form->{title} = $locale->text('Confirm!');
 
 827   delete $form->{header};
 
 830 <form method=post action=$form->{script}>
 
 833   foreach my $key (keys %$form) {
 
 834     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
 
 835     $form->{$key} =~ s/\"/"/g;
 
 836     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
 
 840 <h2 class=confirm>$form->{title}</h2>
 
 843     . $locale->text('Are you sure you want to delete Transaction')
 
 844     . qq| $form->{invnumber}</h4>
 
 846 <input name=action class=submit type=submit value="|
 
 847     . $locale->text('Yes') . qq|">
 
 851   $main::lxdebug->leave_sub();
 
 855   $main::lxdebug->enter_sub();
 
 857   my $form     = $main::form;
 
 858   my %myconfig = %main::myconfig;
 
 859   my $locale   = $main::locale;
 
 861   $main::auth->assert('ap_transactions');
 
 863   if (AP->delete_transaction(\%myconfig, \%$form)) {
 
 865     if(!exists $form->{addition}) {
 
 866       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 867       $form->{addition}  = "DELETED";
 
 868       $form->{what_done} = "invoice";
 
 871     # /saving the history
 
 872     $form->redirect($locale->text('Transaction deleted!'));
 
 874   $form->error($locale->text('Cannot delete transaction!'));
 
 876   $main::lxdebug->leave_sub();
 
 880   $main::lxdebug->enter_sub();
 
 882   $main::auth->assert('vendor_invoice_edit');
 
 884   my $form     = $main::form;
 
 885   my %myconfig = %main::myconfig;
 
 886   my $locale   = $main::locale;
 
 888   $form->{title}    = $locale->text('AP Transactions');
 
 890   $form->get_lists(projects => { "key" => "ALL_PROJECTS", "all" => 1 });
 
 892   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 893   # constants and subs for template
 
 894   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
 
 896   $::request->layout->add_javascripts("autocomplete_project.js");
 
 899   print $form->parse_html_template('ap/search', { %myconfig });
 
 901   $main::lxdebug->leave_sub();
 
 904 sub create_subtotal_row {
 
 905   $main::lxdebug->enter_sub();
 
 907   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
 
 909   my $form     = $main::form;
 
 910   my %myconfig = %main::myconfig;
 
 912   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
 
 914   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
 
 916   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
 
 918   map { $totals->{$_} = 0 } @{ $subtotal_columns };
 
 920   $main::lxdebug->leave_sub();
 
 925 sub ap_transactions {
 
 926   $main::lxdebug->enter_sub();
 
 928   my $form     = $main::form;
 
 929   my %myconfig = %main::myconfig;
 
 930   my $locale   = $main::locale;
 
 932   $main::auth->assert('vendor_invoice_edit');
 
 934   report_generator_set_default_sort('transdate', 1);
 
 936   AP->ap_transactions(\%myconfig, \%$form);
 
 938   $form->{title} = $locale->text('AP Transactions');
 
 940   my $report = SL::ReportGenerator->new(\%myconfig, $form);
 
 943     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
 
 944        due duedate transaction_description notes employee globalprojectnumber
 
 945        vendornumber country ustid taxzone payment_terms charts direct_debit);
 
 947   my @hidden_variables = map { "l_${_}" } @columns;
 
 948   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto
 
 949                                            parts_partnumber parts_description);
 
 951   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
 
 954     'transdate'               => { 'text' => $locale->text('Date'), },
 
 955     'id'                      => { 'text' => $locale->text('ID'), },
 
 956     'type'                    => { 'text' => $locale->text('Type'), },
 
 957     'invnumber'               => { 'text' => $locale->text('Invoice'), },
 
 958     'ordnumber'               => { 'text' => $locale->text('Order'), },
 
 959     'name'                    => { 'text' => $locale->text('Vendor'), },
 
 960     'netamount'               => { 'text' => $locale->text('Amount'), },
 
 961     'tax'                     => { 'text' => $locale->text('Tax'), },
 
 962     'amount'                  => { 'text' => $locale->text('Total'), },
 
 963     'paid'                    => { 'text' => $locale->text('Paid'), },
 
 964     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
 
 965     'due'                     => { 'text' => $locale->text('Amount Due'), },
 
 966     'duedate'                 => { 'text' => $locale->text('Due Date'), },
 
 967     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
 
 968     'notes'                   => { 'text' => $locale->text('Notes'), },
 
 969     'employee'                => { 'text' => $locale->text('Employee'), },
 
 970     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
 
 971     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
 
 972     'country'                 => { 'text' => $locale->text('Country'), },
 
 973     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
 
 974     'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
 
 975     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
 
 976     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
 
 977     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
 
 980   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
 
 981     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
 
 982     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
 
 985   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
 
 987   $form->{"l_type"} = "Y";
 
 988   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
 
 990   $report->set_columns(%column_defs);
 
 991   $report->set_column_order(@columns);
 
 993   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
 
 995   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
 
 998   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
 
 999   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
 
1000   push @options, $locale->text('Department')              . " : $form->{department}"                     if ($form->{department});
 
1001   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
 
1002   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
 
1003   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
 
1004   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
 
1005   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
 
1006   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
 
1007   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
 
1008   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
 
1009   push @options, $locale->text('Open')                                                                   if ($form->{open});
 
1010   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
 
1012   $report->set_options('top_info_text'        => join("\n", @options),
 
1013                        'raw_bottom_info_text' => $form->parse_html_template('ap/ap_transactions_bottom'),
 
1014                        'output_format'        => 'HTML',
 
1015                        'title'                => $form->{title},
 
1016                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
 
1018   $report->set_options_from_form();
 
1019   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
1021   # add sort and escape callback, this one we use for the add sub
 
1022   $form->{callback} = $href .= "&sort=$form->{sort}";
 
1024   # escape callback for href
 
1025   my $callback = $form->escape($href);
 
1027   my @subtotal_columns = qw(netamount amount paid due);
 
1029   my %totals    = map { $_ => 0 } @subtotal_columns;
 
1030   my %subtotals = map { $_ => 0 } @subtotal_columns;
 
1034   foreach my $ap (@{ $form->{AP} }) {
 
1035     $ap->{tax} = $ap->{amount} - $ap->{netamount};
 
1036     $ap->{due} = $ap->{amount} - $ap->{paid};
 
1038     map { $subtotals{$_} += $ap->{$_};
 
1039           $totals{$_}    += $ap->{$_} } @subtotal_columns;
 
1041     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
 
1043     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
 
1044     my $has_storno = $ap->{storno} && !$ap->{storno_id};
 
1046     if ($ap->{invoice}) {
 
1048           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
 
1049         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
 
1050         :                     $locale->text("Invoice (one letter abbreviation)");
 
1053           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
 
1054         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
 
1055         :                     $locale->text("AP Transaction (abbreviation)");
 
1058     $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
 
1062     foreach my $column (@columns) {
 
1064         'data'  => $ap->{$column},
 
1065         'align' => $column_alignment{$column},
 
1069     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
 
1070       . "&id=" . E($ap->{id}) . "&callback=${callback}";
 
1072     my $row_set = [ $row ];
 
1074     if (($form->{l_subtotal} eq 'Y')
 
1075         && (($idx == (scalar @{ $form->{AP} } - 1))
 
1076             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
 
1077       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
 
1080     $report->add_data($row_set);
 
1085   $report->add_separator();
 
1086   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
 
1088   $report->generate_with_headers();
 
1090   $main::lxdebug->leave_sub();
 
1094   $main::lxdebug->enter_sub();
 
1096   my $form     = $main::form;
 
1097   my %myconfig = %main::myconfig;
 
1098   my $locale   = $main::locale;
 
1100   $main::auth->assert('ap_transactions');
 
1102   if (IS->has_storno(\%myconfig, $form, 'ap')) {
 
1103     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
 
1104     $form->error($locale->text("Transaction has already been cancelled!"));
 
1107   $form->error($locale->text('Cannot post storno for a closed period!'))
 
1108     if ( $form->date_closed($form->{transdate}, \%myconfig));
 
1110   AP->storno($form, \%myconfig, $form->{id});
 
1112   # saving the history
 
1113   if(!exists $form->{addition} && $form->{id} ne "") {
 
1114     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
1115     $form->{addition}  = "STORNO";
 
1116     $form->{what_done} = "invoice";
 
1117     $form->save_history;
 
1119   # /saving the history
 
1121   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
 
1123   $main::lxdebug->leave_sub();