am: fehlendes include für Historiensuche(2)
[kivitendo-erp.git] / bin / mozilla / ap.pl
index e31f322..dc02d13 100644 (file)
@@ -24,7 +24,8 @@
 # GNU General Public License for more details.
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, write to the Free Software
-# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+# MA 02110-1335, USA.
 #======================================================================
 #
 # Accounts Payables
 #======================================================================
 
 use POSIX qw(strftime);
-use List::Util qw(sum);
+use List::Util qw(max sum);
+use List::UtilsBy qw(sort_by);
 
 use SL::AP;
 use SL::FU;
+use SL::GL;
 use SL::IR;
 use SL::IS;
-use SL::PE;
 use SL::ReportGenerator;
+use SL::DB::Default;
+use SL::DB::PurchaseInvoice;
+use SL::Webdav;
+use SL::Locale::String qw(t8);
 
 require "bin/mozilla/arap.pl";
 require "bin/mozilla/common.pl";
-require "bin/mozilla/drafts.pl";
 require "bin/mozilla/reportgenerator.pl";
 
 use strict;
@@ -86,18 +91,22 @@ sub add {
   my $form     = $main::form;
   my %myconfig = %main::myconfig;
 
-  $main::auth->assert('general_ledger');
-
-  return $main::lxdebug->leave_sub() if (load_draft_maybe());
+  $main::auth->assert('ap_transactions');
 
   $form->{title} = "Add";
 
-  $form->{callback} = "ap.pl?action=add&DONT_LOAD_DRAFT=1" unless $form->{callback};
+  $form->{callback} = "ap.pl?action=add" unless $form->{callback};
 
   AP->get_transdate(\%myconfig, $form);
   $form->{initial_transdate} = $form->{transdate};
-  &create_links;
+  create_links(dont_save => 1);
   $form->{transdate} = $form->{initial_transdate};
+
+  if ($form->{vendor_id}) {
+    my $last_used_ap_chart = SL::DB::Vendor->load_cached($form->{vendor_id})->last_used_ap_chart;
+    $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
+  }
+
   &display_form;
 
   $main::lxdebug->leave_sub();
@@ -108,11 +117,11 @@ sub edit {
 
   my $form     = $main::form;
 
-  $main::auth->assert('general_ledger');
+  $main::auth->assert('ap_transactions');
 
   $form->{title} = "Edit";
 
-  &create_links;
+  create_links();
   &display_form;
 
   $main::lxdebug->leave_sub();
@@ -123,8 +132,21 @@ sub display_form {
 
   my $form     = $main::form;
 
-  $main::auth->assert('general_ledger');
+  $main::auth->assert('ap_transactions');
 
+  # get all files stored in the webdav folder
+  if ($form->{invnumber} && $::instance_conf->get_webdav) {
+    my $webdav = SL::Webdav->new(
+      type     => 'accounts_payable',
+      number   => $form->{invnumber},
+    );
+    my $webdav_path = $webdav->webdav_path;
+    my @all_objects = $webdav->get_all_objects;
+    @{ $form->{WEBDAV} } = map { { name => $_->filename,
+                                   type => t8('File'),
+                                   link => File::Spec->catfile($_->full_filedescriptor),
+                               } } @all_objects;
+  }
   &form_header;
   &form_footer;
 
@@ -134,49 +156,46 @@ sub display_form {
 sub create_links {
   $main::lxdebug->enter_sub();
 
+  my %params   = @_;
+
   my $form     = $main::form;
   my %myconfig = %main::myconfig;
 
-  $main::auth->assert('general_ledger');
+  $main::auth->assert('ap_transactions');
 
   $form->create_links("AP", \%myconfig, "vendor");
-  my $taxincluded = $form->{taxincluded};
-  my $duedate     = $form->{duedate};
+  my %saved;
+  if (!$params{dont_save}) {
+    %saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
+    $saved{duedate} = $form->{duedate} if $form->{duedate};
+    $saved{currency} = $form->{currency} if $form->{currency};
+    $saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
+  }
 
   IR->get_vendor(\%myconfig, \%$form);
-  $form->{taxincluded} = $taxincluded;
-  $form->{duedate}   = $duedate if $duedate;
+
+  $form->{$_}        = $saved{$_} for keys %saved;
   $form->{oldvendor} = "$form->{vendor}--$form->{vendor_id}";
   $form->{rowcount}  = 1;
+  $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};
 
   # build the popup menus
   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
 
-  # notes
-  $form->{notes} = $form->{intnotes} unless $form->{notes};
-
   # currencies
   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
-  map { $form->{selectcurrency} .= "<option>$_\n" } $form->get_all_currencies(\%myconfig);
+  $form->{selectcurrency} = "";
+  map { my $quoted = H($_); $form->{selectcurrency} .= "<option value=\"${quoted}\">${quoted}\n" } $form->get_all_currencies(\%myconfig);
 
   # vendors
   if (@{ $form->{all_vendor} || [] }) {
     $form->{vendor} = qq|$form->{vendor}--$form->{vendor_id}|;
-    map { $form->{selectvendor} .= "<option>$_->{name}--$_->{id}\n" }
+    map { my $quoted = H($_->{name} . "--" . $_->{id}); $form->{selectvendor} .= "<option value=\"${quoted}\">${quoted}\n" }
       (@{ $form->{all_vendor} });
   }
 
-  # departments
-  if (@{ $form->{all_departments} || [] }) {
-    $form->{selectdepartment} = "<option>\n";
-    $form->{department}       = "$form->{department}--$form->{department_id}";
-
-    map {
-      $form->{selectdepartment} .=
-        "<option>$_->{description}--$_->{id}\n"
-    } (@{ $form->{all_departments} || [] });
-  }
+  $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
 
   $form->{employee} = "$form->{employee}--$form->{employee_id}";
 
@@ -189,6 +208,25 @@ sub create_links {
   $main::lxdebug->leave_sub();
 }
 
+sub _sort_payments {
+  my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid paid_project_id);
+  my @payments =
+    grep { $_->{paid} != 0 }
+    map  {
+      my $idx = $_;
+      +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
+    } (1..$::form->{paidaccounts});
+
+  @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
+
+  $::form->{paidaccounts} = max scalar(@payments), 1;
+
+  foreach my $idx (1 .. scalar(@payments)) {
+    my $payment = $payments[$idx - 1];
+    $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
+  }
+}
+
 sub form_header {
   $main::lxdebug->enter_sub();
 
@@ -197,114 +235,60 @@ sub form_header {
   my $locale   = $main::locale;
   my $cgi      = $::request->{cgi};
 
-  $main::auth->assert('general_ledger');
+  $main::auth->assert('ap_transactions');
 
-  my $title = $form->{title};
-  $form->{title} = $locale->text("$title Accounts Payables Transaction");
+  $::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
 
-  $form->{taxincluded} = ($form->{taxincluded}) ? "checked" : "";
+  $form->{initial_focus} = !($form->{amount_1} * 1) ? 'vendor' : 'row_' . $form->{rowcount};
+
+  $form->{title_} = $form->{title};
+  $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
 
   # type=submit $locale->text('Add Accounts Payables Transaction')
   # type=submit $locale->text('Edit Accounts Payables Transaction')
 
-  $form->{javascript} = qq|<script type="text/javascript">
-  <!--
-  function setTaxkey(accno, row) {
-    var taxkey = accno.options[accno.selectedIndex].value;
-    var reg = /--([0-9]*)/;
-    var found = reg.exec(taxkey);
-    var index = found[1];
-    index = parseInt(index);
-    var tax = 'taxchart_' + row;
-    for (var i = 0; i < document.getElementById(tax).options.length; ++i) {
-      var reg2 = new RegExp("^"+ index, "");
-      if (reg2.exec(document.getElementById(tax).options[i].value)) {
-        document.getElementById(tax).options[i].selected = true;
-        break;
-      }
-    }
-  };
-  //-->
-  </script>|;
-  # show history button
-  $form->{javascript} .= qq|<script type="text/javascript" src="js/show_history.js"></script>|;
-  #/show hhistory button
-
   # set option selected
-  foreach my $item (qw(vendor currency department)) {
+  foreach my $item (qw(vendor currency)) {
+    my $to_replace         =  H($form->{$item});
     $form->{"select$item"} =~ s/ selected//;
-    $form->{"select$item"} =~
-      s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
+    $form->{"select$item"} =~ s/>\Q${to_replace}\E/ selected>${to_replace}/;
   }
-  my $readonly = ($form->{id}) ? "readonly" : "";
+  my $readonly = $form->{id} ? "readonly" : "";
 
-  $form->{radier} = ($form->current_date(\%myconfig) eq $form->{gldate}) ? 1 : 0;
-  $readonly       = ($form->{radier}) ? "" : $readonly;
+  $form->{radier} = ($::instance_conf->get_ap_changeable == 2)
+                      ? ($form->current_date(\%myconfig) eq $form->{gldate})
+                      : ($::instance_conf->get_ap_changeable == 1);
+  $readonly       = $form->{radier} ? "" : $readonly;
 
-  $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
-  $form->{exchangerate} = $form->{forex} if $form->{forex};
+  $form->{readonly} = $readonly;
+
+  $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
+  if ( $form->{forex} ) {
+    $form->{exchangerate} = $form->{forex};
+  }
 
   # format amounts
   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
   $form->{creditlimit}     = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
   $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
 
-  my $exchangerate = qq|
-<input type=hidden name=forex value=$form->{forex}>
-|;
-  if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
-    if ($form->{forex}) {
-      $exchangerate .= qq|
-            <tr>
-              <th align=right>| . $locale->text('Exchangerate') . qq|</th>
-              <td><input type=hidden name=exchangerate value=$form->{exchangerate}>$form->{exchangerate}</td>
-           </tr>
-|;
-    } else {
-      $exchangerate .= qq|
-             <th align=right>| . $locale->text('Exchangerate') . qq|</th>
-             <td><input name=exchangerate size=10 value=$form->{exchangerate}></td>
-|;
-    }
-  }
-
-  my $taxincluded = "";
-
-  $taxincluded = qq|
-            <tr>
-              <td align=right><input name=taxincluded class=checkbox type=checkbox value=1 $form->{taxincluded}></td>
-              <th align=left nowrap>|
-    . $locale->text('Tax Included') . qq|</th>
-            </tr>
-|;
-
   my $rows;
   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
     $rows = 2;
   }
-  my $notes =
-    qq|<textarea name=notes rows=$rows cols=50 wrap=soft $readonly>$form->{notes}</textarea>|;
-
-  my $department;
-  $department = qq|
-              <tr>
-                <th align="right" nowrap>| . $locale->text('Department') . qq|</th>
-                <td colspan=3><select name=department>$form->{selectdepartment}</select>
-                <input type=hidden name=selectdepartment value="$form->{selectdepartment}">
-                </td>
-              </tr>
-| if $form->{selectdepartment};
-
-  my $n = ($form->{creditremaining} =~ /-/) ? "0" : "1";
-
-  my $vendor =
-    ($form->{selectvendor})
-    ? qq|<select name="vendor" onchange="document.getElementById('update_button').click();">$form->{selectvendor} </select>|
-    : qq|<input name=vendor value="$form->{vendor}" size=35>|;
+  $form->{textarea_rows} = $rows;
+
+  $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
 
   my @old_project_ids = ();
-  map({ push(@old_project_ids, $form->{"project_id_$_"})
-          if ($form->{"project_id_$_"}); } (1..$form->{"rowcount"}));
+  map(
+    {
+      if ($form->{"project_id_$_"}) {
+        push(@old_project_ids, $form->{"project_id_$_"});
+      }
+    }
+    (1..$form->{"rowcount"})
+  );
 
   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
                                     "all"       => 0,
@@ -314,374 +298,106 @@ sub form_header {
                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
                                     "module"    => "AP" },);
 
-  map({ $_->{link_split} = [ split(/:/, $_->{link}) ]; }
-      @{ $form->{ALL_CHARTS} });
+  map(
+    { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
+    @{ $form->{ALL_CHARTS} }
+  );
+
+  $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
 
   my %project_labels = ();
-  my @project_values = ("");
   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
-    push(@project_values, $item->{"id"});
-    $project_labels{$item->{"id"}} = $item->{"projectnumber"};
+    $project_labels{$item->{id}} = $item->{projectnumber};
   }
 
-  my (%AP_amount_labels, @AP_amount_values);
-  my (%AP_labels, @AP_values);
-  my (%AP_paid_labels, @AP_paid_values);
   my %charts;
-  my $taxchart_init;
+  my $default_ap_amount_chart_id;
 
   foreach my $item (@{ $form->{ALL_CHARTS} }) {
-    if (grep({ $_ eq "AP_amount" } @{ $item->{link_split} })) {
-      $taxchart_init = $item->{tax_id} if ($taxchart_init eq "");
-      my $key = "$item->{accno}--$item->{tax_id}";
-      push(@AP_amount_values, $key);
-      $AP_amount_labels{$key} =
-        "$item->{accno}--$item->{description}";
-
-    } elsif (grep({ $_ eq "AP" } @{ $item->{link_split} })) {
-      push(@AP_values, $item->{accno});
-      $AP_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
-
-    } elsif (grep({ $_ eq "AP_paid" } @{ $item->{link_split} })) {
-      push(@AP_paid_values, $item->{accno});
-      $AP_paid_labels{$item->{accno}} =
-        "$item->{accno}--$item->{description}";
+    if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
+      $default_ap_amount_chart_id //= $item->{id};
+
+    } elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
+      push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
     }
 
     $charts{$item->{accno}} = $item;
   }
 
-  my %taxchart_labels = ();
-  my @taxchart_values = ();
   my %taxcharts = ();
   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
-    my $key = "$item->{id}--$item->{rate}";
-    $taxchart_init = $key if ($taxchart_init eq $item->{id});
-    push(@taxchart_values, $key);
-    $taxchart_labels{$key} =
-      "$item->{taxdescription} " . ($item->{rate} * 100) . ' %';
     $taxcharts{$item->{id}} = $item;
   }
 
-  # use JavaScript Calendar or not
-  $form->{jsscript} = 1;
-  my $jsscript = "";
-  my ($button1, $button2);
-  if ($form->{jsscript}) {
-
-    # with JavaScript Calendar
-    $button1 = qq|
-       <td><input name=transdate onchange="set_duedate()" id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\" $readonly></td>
-       <td><input type=button name=transdate id="trigger1" value=|
-      . $locale->text('button') . qq|></td>
-       |;
-    $button2 = qq|
-       <td><input name=duedate id=duedate size=11 title="$myconfig{dateformat}" value="$form->{duedate}" onBlur=\"check_right_date_format(this)\" $readonly></td>
-       <td><input type=button name=duedate id="trigger2" value=|
-      . $locale->text('button') . qq|></td></td>
-     |;
-
-    #write Trigger
-    $jsscript =
-      Form->write_trigger(\%myconfig, "2", "transdate", "BL", "trigger1",
-                          "duedate", "BL", "trigger2");
-  } else {
-
-    # without JavaScript Calendar
-    $button1 =
-      qq|<td><input name=transdate onchange="set_duedate()" id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\" $readonly></td>|;
-    $button2 =
-      qq|<td><input name=duedate id=duedate size=11 title="$myconfig{dateformat}" value="$form->{duedate}" onBlur=\"check_right_date_format(this)\" $readonly></td>|;
-  }
-
   my $follow_up_vc         =  $form->{vendor};
   $follow_up_vc            =~ s/--.*?//;
   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
 
-  $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
-  $form->{javascript} .= qq|<script type="text/javascript" src="js/show_vc_details.js"></script>|;
-  $form->{javascript} .= qq|<script type="text/javascript" src="js/follow_up.js"></script>|;
-
-  my $globalprojectnumber =
-    NTI($cgi->popup_menu('-name' => "globalproject_id",
-                         '-values' => \@project_values,
-                         '-labels' => \%project_labels,
-                         '-default' => $form->{"globalproject_id"} ));
+  $::request->layout->add_javascripts("autocomplete_chart.js", "show_vc_details.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.GL.js");
+  my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
+  my $first_taxchart;
 
-  $form->header;
-  print qq|
-<form method=post action=$form->{script}>
-
-<input type=hidden name=id value=$form->{id}>
-<input type=hidden name=sort value=$form->{sort}>
-<input type=hidden name=closedto value=$form->{closedto}>
-<input type=hidden name=locked value=$form->{locked}>
-<input type=hidden name=title value="$title">
-
-<input type="hidden" name="follow_up_trans_id_1" value="| . H($form->{id}) . qq|">
-<input type="hidden" name="follow_up_trans_type_1" value="ap_transaction">
-<input type="hidden" name="follow_up_trans_info_1" value="| . H($follow_up_trans_info) . qq|">
-<input type="hidden" name="follow_up_rowcount" value="1">
-
-| . ($form->{saved_message} ? qq|<p>$form->{saved_message}</p>| : "") . qq|
-
-<table width=100%>
-  <tr class=listtop>
-    <th class=listtop>$form->{title}</th>
-  </tr>
-  <tr height="5"></tr>
-  <tr valign=top>
-    <td>
-      <table width=100%>
-        <tr valign=top>
-          <td>
-            <table>
-              <tr>
-                <th align=right nowrap>| . $locale->text('Vendor') . qq|</th>
-                <td colspan=3>$vendor <input type="button" value="D" onclick="show_vc_details('vendor')"></td>
-                <input type=hidden name=selectvendor value="| . H($form->{selectvendor}) . qq|">
-                <input type=hidden name=oldvendor value="| . H($form->{oldvendor}) . qq|">
-                <input type=hidden name=vendor_id value="| . H($form->{vendor_id}) . qq|">
-                <input type=hidden name=terms value="| . H($form->{terms}) . qq|">
-              </tr>
-              <tr>
-                <td></td>
-                <td colspan=3>
-                  <table width=100%>
-                    <tr>
-                      <th align=left nowrap>| . $locale->text('Credit Limit') . qq|</th>
-                      <td>$form->{creditlimit}</td>
-                      <th align=left nowrap>| . $locale->text('Remaining') . qq|</th>
-                      <td class="plus$n">$form->{creditremaining}</td>
-                      <input type=hidden name=creditlimit value=$form->{creditlimit}>
-                      <input type=hidden name=creditremaining value=$form->{creditremaining}>
-                    </tr>
-                  </table>
-                </td>
-              <tr>
-                <th align=right nowrap>| . $locale->text('Currency') . qq|</th>
-                <td><select name=currency>$form->{selectcurrency}</select></td>
-                <input type=hidden name=selectcurrency value="$form->{selectcurrency}">
-                <input type=hidden name=defaultcurrency value=$form->{defaultcurrency}>
-                <input type=hidden name=fxgain_accno value=$form->{fxgain_accno}>
-                <input type=hidden name=fxloss_accno value=$form->{fxloss_accno}>
-                $exchangerate
-              </tr>
-              $department
-              $taxincluded
-            </table>
-          </td>
-          <td align=right>
-            <table>
-              <tr>
-                <th align=right nowrap>| . $locale->text('Invoice Number') . qq|</th>
-                <td><input name=invnumber size=11 value="$form->{invnumber}" $readonly></td>
-              </tr>
-              <tr>
-                <th align=right nowrap>| . $locale->text('Order Number') . qq|</th>
-                <td><input name=ordnumber size=11 value="$form->{ordnumber}" $readonly></td>
-              </tr>
-              <tr>
-                <th align=right nowrap>| . $locale->text('Invoice Date') . qq|</th>
-                $button1
-              </tr>
-              <tr>
-                <th align=right nowrap>| . $locale->text('Due Date') . qq|</th>
-                $button2
-              </tr>
-              <tr>
-                <th align=right nowrap>| . $locale->text('Project Number') . qq|</th>
-                <td>$globalprojectnumber</td>
-              </tr>
-            </table>
-          </td>
-        </tr>
-      </table>
-    </td>
-  </tr>
-
-
-
-$jsscript
-  <input type=hidden name=rowcount value=$form->{rowcount}>
-  <tr>
-    <td>
-      <table width=100%>
-        <tr class=listheading>
-          <th class=listheading style="width:15%">| . $locale->text('Account') . qq|</th>
-          <th class=listheading style="width:10%">| . $locale->text('Amount') . qq|</th>
-          <th class=listheading style="width:10%">| . $locale->text('Tax') . qq|</th>
-          <th class=listheading style="width:10%">| . $locale->text('Taxkey') . qq|</th>
-          <th class=listheading style="width:10%">| . $locale->text('Project') . qq|</th>
-        </tr>
-|;
-
-  my $amount  = $locale->text('Amount');
-  my $project = $locale->text('Project');
+  $form->header();
 
   for my $i (1 .. $form->{rowcount}) {
 
     # format amounts
-    $form->{"amount_$i"} =
-      $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
+    $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
 
-    my $selected_accno_full;
-    my ($accno_row) = split(/--/, $form->{"AP_amount_$i"});
-    my $item = $charts{$accno_row};
-    $selected_accno_full = "$item->{accno}--$item->{tax_id}";
-
-    my $selected_taxchart = $form->{"taxchart_$i"};
-    my ($selected_accno, $selected_tax_id) = split(/--/, $selected_accno_full);
-    my ($previous_accno, $previous_tax_id) = split(/--/, $form->{"previous_AP_amount_$i"});
+    my ($default_taxchart, $taxchart_to_use);
+    my $amount_chart_id   = $form->{"AP_amount_chart_id_$i"} || $default_ap_amount_chart_id;
+    my $chart_has_changed = $::form->{"previous_AP_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AP_amount_chart_id_$i"});
 
-    if ($previous_accno &&
-        ($previous_accno eq $selected_accno) &&
-        ($previous_tax_id ne $selected_tax_id)) {
-      my $item = $taxcharts{$selected_tax_id};
-      $selected_taxchart = "$item->{id}--$item->{rate}";
+    foreach my $item ( GL->get_active_taxes_for_chart($amount_chart_id, $transdate) ) {
+      my $key             = $item->id . "--" . $item->rate;
+      $first_taxchart   //= $item;
+      $default_taxchart   = $item if $item->{is_default};
+      $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
     }
 
-    $selected_taxchart = $taxchart_init unless ($form->{"taxchart_$i"});
-
-    my $selectAP_amount =
-      NTI($cgi->popup_menu('-name' => "AP_amount_$i",
-                           '-id' => "AP_amount_$i",
-                           '-style' => 'width:400px',
-                           '-onChange' => "setTaxkey(this, $i)",
-                           '-values' => \@AP_amount_values,
-                           '-labels' => \%AP_amount_labels,
-                           '-default' => $selected_accno_full))
-      . $cgi->hidden('-name' => "previous_AP_amount_$i",
-                     '-default' => $selected_accno_full);
-
-    my $tax = qq|<td>| .
-      NTI($cgi->popup_menu('-name' => "taxchart_$i",
-                           '-id' => "taxchart_$i",
-                           '-style' => 'width:200px',
-                           '-values' => \@taxchart_values,
-                           '-labels' => \%taxchart_labels,
-                           '-default' => $selected_taxchart))
-      . qq|</td>|;
-
-    my $projectnumber =
-      NTI($cgi->popup_menu('-name' => "project_id_$i",
-                           '-values' => \@project_values,
-                           '-labels' => \%project_labels,
-                           '-default' => $form->{"project_id_$i"} ));
-
-    print qq|
-        <tr>
-          <td>$selectAP_amount</td>
-          <td><input name="amount_$i" size=10 value=$form->{"amount_$i"}></td>
-          <td><input type="hidden" name="tax_$i" value="$form->{"tax_$i"}">$form->{"tax_$i"}</td>
-          $tax
-          <td>$projectnumber</td>
-        </tr>
-|;
-    $amount  = "";
-    $project = "";
+    $taxchart_to_use                 = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
+    my $selected_taxchart            = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
+    $form->{"selected_taxchart_$i"}  = $selected_taxchart;
+    $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
   }
 
-  my $taxlabel =
-    ($form->{taxincluded})
-    ? $locale->text('Tax Included')
-    : $locale->text('Tax');
+  $form->{taxchart_value_title_sub} = sub {
+    my $item = shift;
+    return [
+      $item->{id} .'--'. $item->{rate},
+      $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
+    ];
+  };
+
+  $form->{AP_paid_value_title_sub} = sub {
+    my $item = shift;
+    return [
+      $item->{accno},
+      $item->{accno} .'--'. $item->{description}
+    ];
+  };
 
   $form->{invtotal_unformatted} = $form->{invtotal};
   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
 
-  my $APselected =
-    NTI($cgi->popup_menu('-name' => "APselected", '-id' => "APselected",
-                         '-style' => 'width:400px',
-                         '-values' => \@AP_values, '-labels' => \%AP_labels,
-                         '-default' => $form->{APselected}));
-  print qq|
-        <tr>
-          <td colspan=6>
-            <hr noshade>
-          </td>
-        </tr>
-        <tr>
-          <td>${APselected}</td>
-          <th align=left>$form->{invtotal}</th>
-
-          <input type=hidden name=oldinvtotal value=$form->{oldinvtotal}>
-          <input type=hidden name=oldtotalpaid value=$form->{oldtotalpaid}>
-
-          <input type=hidden name=taxaccounts value="$form->{taxaccounts}">
-
-          <td colspan=4></td>
-
-
-        </tr>
-      </table>
-     </td>
-    </tr>
-    <tr>
-      <td>
-        <table width=100%>
-        <tr>
-          <th align=left width=1%>| . $locale->text('Notes') . qq|</th>
-          <td align=left>$notes</td>
-        </tr>
-      </table>
-    </td>
-  </tr>
-  <tr>
-    <td>
-      <table width=100%>
-        <tr class=listheading>
-          <th class=listheading colspan=7>| . $locale->text('Payments') . qq|</th>
-        </tr>
-|;
+  $form->{totalpaid} = 0;
 
-  my @column_index;
-  if ($form->{defaultcurrency} && ($form->{currency} eq $form->{defaultcurrency})) {
-    @column_index = qw(datepaid source memo paid AP_paid paid_project_id);
-  } else {
-    @column_index = qw(datepaid source memo paid exchangerate AP_paid paid_project_id);
+  _sort_payments();
+
+  if ( $form->{'paid_'. $form->{paidaccounts}} ) {
+    $form->{paidaccounts}++;
   }
 
-  my %column_data;
-  $column_data{datepaid}     = "<th>" . $locale->text('Date') . "</th>";
-  $column_data{paid}         = "<th>" . $locale->text('Amount') . "</th>";
-  $column_data{exchangerate} = "<th>" . $locale->text('Exch') . "</th>";
-  $column_data{AP_paid}      = "<th>" . $locale->text('Account') . "</th>";
-  $column_data{source}       = "<th>" . $locale->text('Source') . "</th>";
-  $column_data{memo}         = "<th>" . $locale->text('Memo') . "</th>";
-  $column_data{paid_project_id} = "<th>" . $locale->text('Project Number') . "</th>";
-
-  print "
-        <tr>
-";
-  map { print "$column_data{$_}\n" } @column_index;
-  print "
-        </tr>
-";
-
-  my @triggers  = ();
-  $form->{totalpaid} = 0;
+  # default account for current assets (i.e. 1801 - SKR04)
+  $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
-  $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
   for my $i (1 .. $form->{paidaccounts}) {
-    print "
-        <tr>
-";
-
-    my $selectAP_paid =
-      NTI($cgi->popup_menu('-name' => "AP_paid_$i",
-                           '-id' => "AP_paid_$i",
-                           '-values' => \@AP_paid_values,
-                           '-labels' => \%AP_paid_labels,
-                           '-default' => $form->{"AP_paid_$i"}));
-
     $form->{totalpaid} += $form->{"paid_$i"};
 
     # format amounts
     if ($form->{"paid_$i"}) {
-      $form->{"paid_$i"} =
-        $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
+      $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
     }
     if ($form->{"exchangerate_$i"} == 0) {
       $form->{"exchangerate_$i"} = "";
@@ -690,151 +406,43 @@ $jsscript
         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
     }
 
-    print qq|<input type=hidden name="acc_trans_id_$i" value=$form->{"acc_trans_id_$i"}>\n|;
-    print qq|<input type=hidden name="gldate_$i" value=$form->{"gldate_$i"}>\n|;
     my $changeable = 1;
-    if ($::lx_office_conf{features}->{payments_changeable} == 0) {
+    if (SL::DB::Default->get->payments_changeable == 0) {
       # never
       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
     }
-    if ($::lx_office_conf{features}->{payments_changeable} == 2) {
+    if (SL::DB::Default->get->payments_changeable == 2) {
       # on the same day
       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
     }
 
-    $exchangerate = qq|&nbsp;|;
-    if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
-      if ($form->{"forex_$i"}) {
-        $exchangerate =
-          qq|<input type=hidden name="exchangerate_$i" value=$form->{"exchangerate_$i"}>$form->{"exchangerate_$i"}|;
-      } else {
-        if ($changeable) {
-          $exchangerate =
-            qq|<input name="exchangerate_$i" size=10 value=$form->{"exchangerate_$i"}>|;
-        } else {
-          $exchangerate =
-            qq|<input type=hidden name="exchangerate_$i" value=$form->{"exchangerate_$i"}>$form->{"exchangerate_$i"}|;
-        }
-      }
-    }
-
-    $exchangerate .= qq|
-<input type=hidden name="forex_$i" value=$form->{"forex_$i"}>
-|;
-
-    my $datepaid;
-    if ($changeable) {
-      $datepaid = qq|<td align=center><input name="datepaid_$i" id="datepaid_$i" size=11 title="($myconfig{'dateformat'})" value="$form->{"datepaid_$i"}" onBlur=\"check_right_date_format(this)\">
-         <input type="button" name="datepaid_$i" id="trigger_datepaid_$i" value="| . $locale->text('Details (one letter abbreviation)') . qq|"></td>|;
-    } else {
-      $datepaid = qq|<td align=center>$form->{"datepaid_$i"}</td>|.
-        qq|<input type=hidden name="datepaid_$i" value=$form->{"datepaid_$i"}>|;
-    }
-
-    my $paid;
-    if ($changeable) {
-      $paid = qq|<td align=center><input name="paid_$i" size=11 value="$form->{"paid_$i"}" onBlur=\"check_right_number_format(this)\"></td>|;
-    } else {
-      $paid = qq|<td align=center>$form->{"paid_$i"}</td>|.
-        qq|<input type=hidden name="paid_$i" value=$form->{"paid_$i"}>|;
-    }
-
-    my $source;
-    if ($changeable) {
-      $source = qq|<td align=center><input name="source_$i" size=11 value="$form->{"source_$i"}"></td>|;
-    } else {
-      $source = qq|<td align=center>$form->{"source_$i"}</td>|.
-        qq|<input type=hidden name="source_$i" value=$form->{"source_$i"}>|;
-    }
-
-    my $memo;
-    if ($changeable) {
-      $memo = qq|<td align=center><input name="memo_$i" size=11 value="$form->{"memo_$i"}"></td>|;
-    } else {
-      $memo = qq|<td align=center>$form->{"memo_$i"}</td>|.
-        qq|<input type=hidden name="memo_$i" value=$form->{"memo_$i"}>|;
-    }
-
-    my $AP_paid;
-    if ($changeable) {
-      $AP_paid = qq|<td align=center>${selectAP_paid}</td>|;
-    } else {
-      $AP_paid = qq|<td align=center>$form->{"AP_paid_$i"}</td>|.
-        qq|<input type=hidden name="AP_paid_$i" value=$form->{"AP_paid_$i"}>|;
+    #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
+    if ($form->date_closed($form->{"gldate_$i"})) {
+       $changeable = 0;
     }
 
-    my $paid_project_id;
-    if ($changeable) {
-      $paid_project_id =
-      qq|<td>|
-      . NTI($cgi->popup_menu('-name' => "paid_project_id_$i",
-                             '-values' => \@project_values,
-                             '-labels' => \%project_labels,
-                             '-default' => $form->{"paid_project_id_$i"} ))
-      . qq|</td>|;
-    } else {
-      my $projectnumber = $project_labels{$form->{"paid_project_id_$i"}};
-      $paid_project_id = qq|<td>$projectnumber</td>|.
-        qq|<input type=hidden name="paid_project_id_$i" value=$form->{"paid_project_id_$i"}>|;
-    }
+    $form->{'paidaccount_changeable_'. $i} = $changeable;
 
-    $column_data{"paid_$i"}            = $paid;
-    $column_data{"AP_paid_$i"}         = $AP_paid;
-    $column_data{"exchangerate_$i"}    = qq|<td align=center>$exchangerate</td>|;
-    $column_data{"datepaid_$i"}        = $datepaid;
-    $column_data{"source_$i"}          = $source;
-    $column_data{"memo_$i"}            = $memo;
-    $column_data{"paid_project_id_$i"} = $paid_project_id;
-
-    map { print qq|$column_data{"${_}_$i"}\n| } @column_index;
-
-    print "
-        </tr>
-";
-    if ($changeable) {
-      push(@triggers, "datepaid_$i", "BL", "trigger_datepaid_$i");
-    }
+    $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
   }
 
-  my $paid_missing = $form->{invtotal_unformatted} - $form->{totalpaid};
+  $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
 
-  print qq|
-        <tr>
-          <td></td>
-          <td></td>
-          <td align="center">| . $locale->text('Total') . qq|</td>
-          <td align="center">| . H($form->format_amount(\%myconfig, $form->{totalpaid}, 2)) . qq|</td>
-        </tr>
-        <tr>
-          <td></td>
-          <td></td>
-          <td align="center">| . $locale->text('Missing amount') . qq|</td>
-          <td align="center">| . H($form->format_amount(\%myconfig, $paid_missing, 2)) . qq|</td>
-        </tr>
-| . $form->write_trigger(\%myconfig, scalar(@triggers) / 3, @triggers) .
-    qq|
-    <input type=hidden name=paidaccounts value=$form->{paidaccounts}>
-
-      </table>
-    </td>
-  </tr>
-  <tr>
-    <td><hr size=3 noshade></td>
-  </tr>
-</table>
-|;
+  print $form->parse_html_template('ap/form_header', {
+    today => DateTime->today,
+  });
 
   $main::lxdebug->leave_sub();
 }
 
 sub form_footer {
   $::lxdebug->enter_sub;
-  $::auth->assert('general_ledger');
+  $::auth->assert('ap_transactions');
 
   my $num_due;
   my $num_follow_ups;
   if ($::form->{id}) {
-    my $follow_ups = FU->follow_ups('trans_id' => $::form->{id});
+    my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
 
     if (@{ $follow_ups }) {
       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
@@ -852,26 +460,27 @@ sub form_footer {
 
   $::form->header;
   print $::form->parse_html_template('ap/form_footer', {
-    num_due         => $num_due,
-    num_follow_ups  => $num_follow_ups,
-    show_post_draft => ($transdate > $closedto) && !$::form->{id},
-    show_storno     => $storno,
+    num_due           => $num_due,
+    num_follow_ups    => $num_follow_ups,
+    show_post_draft   => ($transdate > $closedto) && !$::form->{id},
+    show_storno       => $storno,
   });
 
   $::lxdebug->leave_sub;
 }
 
 sub mark_as_paid {
-  $main::lxdebug->enter_sub();
+  $::auth->assert('ap_transactions');
 
-  my $form     = $main::form;
-  my %myconfig = %main::myconfig;
+  SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
 
-  $main::auth->assert('general_ledger');
-
-  &mark_as_paid_common(\%myconfig,"ap");
+  $::form->redirect($::locale->text("Marked as paid"));
+}
 
-  $main::lxdebug->leave_sub();
+sub show_draft {
+  $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
+  $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
+  update();
 }
 
 sub update {
@@ -880,7 +489,7 @@ sub update {
   my $form     = $main::form;
   my %myconfig = %main::myconfig;
 
-  $main::auth->assert('general_ledger');
+  $main::auth->assert('ap_transactions');
 
   my $display = shift;
 
@@ -895,23 +504,15 @@ sub update {
   my $count = 0;
   my (@a, $j, $totaltax);
   for my $i (1 .. $form->{rowcount}) {
-    $form->{"amount_$i"} =
-      $form->parse_amount(\%myconfig, $form->{"amount_$i"});
-    $form->{"tax_$i"} = $form->parse_amount(\%myconfig, $form->{"tax_$i"});
+    $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
     if ($form->{"amount_$i"}) {
       push @a, {};
       $j = $#a;
       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
-      if ($taxkey > 1) {
-        if ($form->{taxincluded}) {
-          $form->{"tax_$i"} = $form->{"amount_$i"} / ($rate + 1) * $rate;
-        } else {
-          $form->{"tax_$i"} = $form->{"amount_$i"} * $rate;
-        }
-      } else {
-        $form->{"tax_$i"} = 0;
-      }
-      $form->{"tax_$i"} = $form->round_amount($form->{"tax_$i"}, 2);
+
+      # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
+      my $tmpnetamount;
+      ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
 
       $totaltax += $form->{"tax_$i"};
       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
@@ -926,17 +527,9 @@ sub update {
   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
   $form->{invdate} = $form->{transdate};
-  my %saved_variables = map +( $_ => $form->{$_} ), qw(AP AP_amount_1 taxchart_1);
 
   my $vendor_changed = &check_name("vendor");
 
-  $form->{AP} = $saved_variables{AP};
-  if ($saved_variables{AP_amount_1} =~ m/.--./) {
-    map { $form->{$_} = $saved_variables{$_} } qw(AP_amount_1 taxchart_1);
-  } else {
-    delete $form->{taxchart_1};
-  }
-
   $form->{rowcount} = $count + 1;
 
   $form->{invtotal} =
@@ -963,9 +556,6 @@ sub update {
   $form->{oldinvtotal}  = $form->{invtotal};
   $form->{oldtotalpaid} = $totalpaid;
 
-  # notes
-  $form->{notes} = $form->{intnotes} if $vendor_changed;
-
   &display_form;
 
   $main::lxdebug->leave_sub();
@@ -979,7 +569,8 @@ sub post_payment {
   my %myconfig = %main::myconfig;
   my $locale   = $main::locale;
 
-  $main::auth->assert('general_ledger');
+  $main::auth->assert('ap_transactions');
+  $form->mtime_ischanged('ap');
 
   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
@@ -991,8 +582,13 @@ sub post_payment {
 
       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
+      $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
+        if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
+
+      #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
+      # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
       $form->error($locale->text('Cannot post payment for a closed period!'))
-        if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
+        if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
         $form->{"exchangerate_$i"} = $form->{exchangerate}
@@ -1005,9 +601,15 @@ sub post_payment {
 
   ($form->{AP})      = split /--/, $form->{AP};
   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
-  $form->redirect($locale->text('Payment posted!'))
-      if (AP->post_payment(\%myconfig, \%$form));
+  if (AP->post_payment(\%myconfig, \%$form)) {
+    $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
+    $form->{what_done} = 'invoice';
+    $form->{addition}  = "PAYMENT POSTED";
+    $form->save_history;
+    $form->redirect($locale->text('Payment posted!'))
+  } else {
     $form->error($locale->text('Cannot post payment!'));
+  };
 
 
   $main::lxdebug->leave_sub();
@@ -1021,16 +623,18 @@ sub post {
   my %myconfig = %main::myconfig;
   my $locale   = $main::locale;
 
-  $main::auth->assert('general_ledger');
+  $main::auth->assert('ap_transactions');
+  $form->mtime_ischanged('ap');
 
   my ($inline) = @_;
 
-  # check if there is a vendor, invoice and due date
+  # check if there is a vendor, invoice, due date and invnumber
   $form->isblank("transdate", $locale->text("Invoice Date missing!"));
   $form->isblank("duedate",   $locale->text("Due Date missing!"));
   $form->isblank("vendor",    $locale->text('Vendor missing!'));
+  $form->isblank("invnumber", $locale->text('Invoice Number missing!'));
 
-  if ($myconfig{mandatory_departments} && !$form->{department}) {
+  if ($myconfig{mandatory_departments} && !$form->{department_id}) {
     $form->{saved_message} = $::locale->text('You have to specify a department.');
     update();
     exit;
@@ -1038,6 +642,9 @@ sub post {
 
   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
+
+  $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
+    if ($form->date_max_future($form->{"transdate"}, \%myconfig));
   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
 
   my $zero_amount_posting = 1;
@@ -1060,8 +667,13 @@ sub post {
 
       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
+      $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
+      if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
+
+      #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
+      # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
       $form->error($locale->text('Cannot post payment for a closed period!'))
-        if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
+        if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
         $form->{"exchangerate_$i"} = $form->{exchangerate}
@@ -1077,27 +689,27 @@ sub post {
   my ($vendor) = split /--/, $form->{vendor};
   if ($form->{oldvendor} ne "$vendor--$form->{vendor_id}") {
     &update;
-    ::end_of_request();
+    $::dispatcher->end_request;
   }
-  my ($debitaccno,    $debittaxkey)    = split /--/, $form->{AP_amountselected};
-  my ($taxkey,        $NULL)           = split /--/, $form->{taxchartselected};
-  my ($payablesaccno, $payablestaxkey) = split /--/, $form->{APselected};
-#  $form->{AP_amount_1}  = $debitaccno;
-  $form->{AP_payables}  = $payablesaccno;
-  $form->{taxkey}       = $taxkey;
   $form->{storno}       = 0;
 
   $form->{id} = 0 if $form->{postasnew};
 
   if (AP->post_transaction(\%myconfig, \%$form)) {
+    # create webdav folder
+    if ($::instance_conf->get_webdav) {
+      SL::Webdav->new(type     => 'accounts_payable',
+                      number   => $form->{invnumber},
+                     )->webdav_path;
+    }
     # saving the history
     if(!exists $form->{addition} && $form->{id} ne "") {
-      $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
-      $form->{addition} = "POSTED";
+      $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
+      $form->{addition}  = "POSTED";
+      $form->{what_done} = "invoice";
       $form->save_history;
     }
     # /saving the history
-    remove_draft() if $form->{remove_draft};
     # Dieser Text wird niemals ausgegeben: Probleme beim redirect?
     $form->redirect($locale->text('Transaction posted!')) unless $inline;
   } else {
@@ -1113,13 +725,17 @@ sub post_as_new {
   my $form     = $main::form;
   my %myconfig = %main::myconfig;
 
-  $main::auth->assert('general_ledger');
+  $main::auth->assert('ap_transactions');
 
   $form->{postasnew} = 1;
   # saving the history
   if(!exists $form->{addition} && $form->{id} ne "") {
-    $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
-    $form->{addition} = "POSTED AS NEW";
+    # does this work? post_as_new for ap doesn't immediately save the
+    # invoice, because the invnumber has to be entered by hand.
+    # And the value of $form->{postasnew} isn't checked when calling post
+    $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
+    $form->{addition}  = "POSTED AS NEW";
+    $form->{what_done} = "invoice";
     $form->save_history;
   }
   # /saving the history
@@ -1128,13 +744,13 @@ sub post_as_new {
   $main::lxdebug->leave_sub();
 }
 
-sub use_as_template {
+sub use_as_new {
   $main::lxdebug->enter_sub();
 
   my $form     = $main::form;
   my %myconfig = %main::myconfig;
 
-  $main::auth->assert('general_ledger');
+  $main::auth->assert('ap_transactions');
 
   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);
   $form->{paidaccounts} = 1;
@@ -1151,7 +767,7 @@ sub delete {
   my $form     = $main::form;
   my $locale   = $main::locale;
 
-  $main::auth->assert('general_ledger');
+  $main::auth->assert('ap_transactions');
 
   $form->{title} = $locale->text('Confirm!');
 
@@ -1191,13 +807,14 @@ sub yes {
   my %myconfig = %main::myconfig;
   my $locale   = $main::locale;
 
-  $main::auth->assert('general_ledger');
+  $main::auth->assert('ap_transactions');
 
   if (AP->delete_transaction(\%myconfig, \%$form)) {
     # saving the history
     if(!exists $form->{addition}) {
-      $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
-      $form->{addition} = "DELETED";
+      $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
+      $form->{addition}  = "DELETED";
+      $form->{what_done} = "invoice";
       $form->save_history;
     }
     # /saving the history
@@ -1211,7 +828,7 @@ sub yes {
 sub search {
   $main::lxdebug->enter_sub();
 
-  $main::auth->assert('general_ledger | vendor_invoice_edit');
+  $main::auth->assert('vendor_invoice_edit');
 
   my $form     = $main::form;
   my %myconfig = %main::myconfig;
@@ -1221,15 +838,12 @@ sub search {
   $form->all_vc(\%myconfig, "vendor", "AP");
 
   $form->{title}    = $locale->text('AP Transactions');
-  $form->{fokus}    = "search.vendor";
-  $form->{jsscript} = 1;
 
   $form->get_lists("projects"     => { "key" => "ALL_PROJECTS", "all" => 1 },
-                   "departments"  => "ALL_DEPARTMENTS",
                    "vendors"      => "ALL_VC");
 
+  $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
   # constants and subs for template
-  $form->{jsscript}  = 1;
   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
 
   $form->header;
@@ -1266,7 +880,7 @@ sub ap_transactions {
   my %myconfig = %main::myconfig;
   my $locale   = $main::locale;
 
-  $main::auth->assert('general_ledger | vendor_invoice_edit');
+  $main::auth->assert('vendor_invoice_edit');
 
   ($form->{vendor}, $form->{vendor_id}) = split(/--/, $form->{vendor});
 
@@ -1281,10 +895,11 @@ sub ap_transactions {
   my @columns =
     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
        due duedate transaction_description notes employee globalprojectnumber
-       vendornumber country ustid taxzone payment_terms charts);
+       vendornumber country ustid taxzone payment_terms charts direct_debit);
 
   my @hidden_variables = map { "l_${_}" } @columns;
-  push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto department);
+  push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto
+                                           parts_partnumber parts_description);
 
   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
 
@@ -1309,12 +924,13 @@ sub ap_transactions {
     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
     'country'                 => { 'text' => $locale->text('Country'), },
     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
-    'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
+    'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
+    'direct_debit'            => { 'text' => $locale->text('direct debit'), },
   );
 
-  foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description)) {
+  foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
   }
@@ -1333,11 +949,14 @@ sub ap_transactions {
 
   my @options;
   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
-  push @options, $locale->text('Department')              . " : " . (split /--/, $form->{department})[0] if ($form->{department});
+  push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
+  push @options, $locale->text('Department')              . " : $form->{department}"                     if ($form->{department});
   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
+  push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
+  push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
   push @options, $locale->text('Open')                                                                   if ($form->{open});
@@ -1389,6 +1008,8 @@ sub ap_transactions {
         :                     $locale->text("AP Transaction (abbreviation)");
     }
 
+    $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
+
     my $row = { };
 
     foreach my $column (@columns) {
@@ -1429,7 +1050,7 @@ sub storno {
   my %myconfig = %main::myconfig;
   my $locale   = $main::locale;
 
-  $main::auth->assert('general_ledger');
+  $main::auth->assert('ap_transactions');
 
   if (IS->has_storno(\%myconfig, $form, 'ap')) {
     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
@@ -1443,8 +1064,9 @@ sub storno {
 
   # saving the history
   if(!exists $form->{addition} && $form->{id} ne "") {
-    $form->{snumbers} = "ordnumber_$form->{ordnumber}";
-    $form->{addition} = "STORNO";
+    $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
+    $form->{addition}  = "STORNO";
+    $form->{what_done} = "invoice";
     $form->save_history;
   }
   # /saving the history