Merge branch 'f-chart-picker-in-gl'
authorMoritz Bunkus <m.bunkus@linet-services.de>
Fri, 13 Jan 2017 13:41:53 +0000 (14:41 +0100)
committerMoritz Bunkus <m.bunkus@linet-services.de>
Fri, 13 Jan 2017 13:41:53 +0000 (14:41 +0100)
20 files changed:
SL/AP.pm
SL/AR.pm
SL/DB/Customer.pm
SL/DB/Vendor.pm
SL/Form.pm
SL/GL.pm
SL/IR.pm
SL/IS.pm
bin/mozilla/ap.pl
bin/mozilla/ar.pl
bin/mozilla/gl.pl
js/kivi.GL.js [new file with mode: 0644]
templates/webpages/ap/form_footer.html
templates/webpages/ap/form_header.html
templates/webpages/ar/form_footer.html
templates/webpages/ar/form_header.html
templates/webpages/gl/form_footer.html
templates/webpages/gl/form_header.html
templates/webpages/gl/form_header_chart_balances_js.html [deleted file]
templates/webpages/gl/update_tax_accounts.html

index 46b25ea..4145251 100644 (file)
--- a/SL/AP.pm
+++ b/SL/AP.pm
@@ -73,13 +73,8 @@ sub _post_transaction {
     $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
   }
 
-  for my $i (1 .. $form->{rowcount}) {
-    $form->{AP_amounts}{"amount_$i"} =
-      (split(/--/, $form->{"AP_amount_$i"}))[0];
-  }
-
-  ($form->{AP_amounts}{payables}) = split(/--/, $form->{APselected});
-  ($form->{AP_payables})          = split(/--/, $form->{APselected});
+  # get the charts selected
+  $form->{AP_amounts}{"amount_$_"} = $form->{"AP_amount_chart_id_$_"} for (1 .. $form->{rowcount});
 
   # calculate the totals while calculating and reformatting the $amount_$i and $tax_$i
   ($form->{netamount},$form->{total_tax},$form->{invtotal}) = $form->calculate_arap('buy',$form->{taxincluded}, $form->{exchangerate});
@@ -167,13 +162,11 @@ sub _post_transaction {
         $query =
           qq|INSERT INTO acc_trans | .
           qq|  (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)| .
-          qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
-          qq|  ?, ?, ?, ?, ?,| .
-          qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
-        @values = ($form->{id}, $form->{AP_amounts}{"amount_$i"},
+          qq|VALUES (?, ?,   ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.id = ?))|;
+        @values = ($form->{id}, $form->{"AP_amount_chart_id_$i"},
                    $form->{"amount_$i"}, conv_date($form->{transdate}),
                    $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
-                   $form->{AP_amounts}{"amount_$i"});
+                   $form->{"AP_amount_chart_id_$i"});
         do_query($form, $dbh, $query, @values);
 
         if ($form->{"tax_$i"} != 0) {
@@ -197,19 +190,17 @@ sub _post_transaction {
     # add payables
     $query =
       qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) | .
-      qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, | .
-      qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
+      qq|VALUES (?, ?, ?, ?, | .
+      qq|        (SELECT taxkey_id FROM chart WHERE id = ?),| .
       qq|        (SELECT tax_id| .
       qq|         FROM taxkeys| .
-      qq|         WHERE chart_id= (SELECT id | .
-      qq|                          FROM chart| .
-      qq|                          WHERE accno = ?)| .
+      qq|         WHERE chart_id = ?| .
       qq|         AND startdate <= ?| .
       qq|         ORDER BY startdate DESC LIMIT 1),| .
-      qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
-    @values = ($form->{id}, $form->{AP_amounts}{payables}, $form->{payables},
-               conv_date($form->{transdate}), $form->{AP_amounts}{payables}, $form->{AP_amounts}{payables}, conv_date($form->{transdate}),
-               $form->{AP_amounts}{payables});
+      qq|        (SELECT c.link FROM chart c WHERE c.id = ?))|;
+    @values = ($form->{id}, $form->{AP_chart_id}, $form->{payables},
+               conv_date($form->{transdate}), $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{transdate}),
+               $form->{AP_chart_id});
     do_query($form, $dbh, $query, @values);
   }
 
@@ -254,20 +245,18 @@ sub _post_transaction {
       if ($form->{payables}) {
         $query =
           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link) | .
-          qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, | .
-          qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
+          qq|VALUES (?, ?, ?, ?, ?, | .
+          qq|        (SELECT taxkey_id FROM chart WHERE id = ?),| .
           qq|        (SELECT tax_id| .
           qq|         FROM taxkeys| .
-          qq|         WHERE chart_id= (SELECT id | .
-          qq|                          FROM chart| .
-          qq|                          WHERE accno = ?)| .
+          qq|         WHERE chart_id = ?| .
           qq|         AND startdate <= ?| .
           qq|         ORDER BY startdate DESC LIMIT 1),| .
-          qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
-        @values = ($form->{id}, $form->{AP_payables}, $amount,
+          qq|        (SELECT c.link FROM chart c WHERE c.id = ?))|;
+        @values = ($form->{id}, $form->{AP_chart_id}, $amount,
                    conv_date($form->{"datepaid_$i"}), $project_id,
-                   $form->{AP_payables}, $form->{AP_payables}, conv_date($form->{"datepaid_$i"}),
-                   $form->{AP_payables});
+                   $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{"datepaid_$i"}),
+                   $form->{AP_chart_id});
         do_query($form, $dbh, $query, @values);
       }
       $form->{payables} = $amount;
@@ -759,26 +748,7 @@ sub setup_form {
             $form->{"projectnumber_$k"}    = "$form->{acc_trans}{$key}->[$i-1]->{projectnumber}";
             $form->{"oldprojectnumber_$k"} = $form->{"projectnumber_$k"};
             $form->{"project_id_$k"}       = "$form->{acc_trans}{$key}->[$i-1]->{project_id}";
-          }
-
-          $form->{"${key}_$k"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
-
-          my $q_description    = quotemeta($form->{acc_trans}{$key}->[$i-1]->{description});
-          $form->{"select${key}"} =~
-            m/<option value=\"
-                ($form->{acc_trans}{$key}->[$i-1]->{accno}--[^\"]*)
-              \">
-              $form->{acc_trans}{$key}->[$i-1]->{accno}
-              --
-              ${q_description}
-              <\/option>\n/x;
-          $form->{"${key}_$k"} = $1;
-
-          if ($akey eq "AP") {
-            $form->{APselected} = $form->{acc_trans}{$key}->[$i-1]->{accno};
-
-          } elsif ($akey eq 'amount') {
-            $form->{"${key}_$k"}   = $form->{acc_trans}{$key}->[$i-1]->{accno} . "--" . $form->{acc_trans}{$key}->[$i-1]->{id};
+            $form->{"${key}_chart_id_$k"}  = $form->{acc_trans}{$key}->[$i-1]->{chart_id};
             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
           }
         }
index 5f7fadd..4fea4af 100644 (file)
--- a/SL/AR.pm
+++ b/SL/AR.pm
@@ -75,10 +75,7 @@ sub _post_transaction {
         $form->parse_amount($myconfig, $form->{exchangerate}) );
 
   # get the charts selected
-  map { ($form->{AR_amounts}{"amount_$_"}) = split /--/, $form->{"AR_amount_$_"} } 1 .. $form->{rowcount};
-
-  $form->{AR_amounts}{receivables} = $form->{ARselected};
-  $form->{AR}{receivables}         = $form->{ARselected};
+  $form->{AR_amounts}{"amount_$_"} = $form->{"AR_amount_chart_id_$_"} for (1 .. $form->{rowcount});
 
   $form->{tax}       = 0; # is this still needed?
 
@@ -157,7 +154,7 @@ sub _post_transaction {
 
         # insert detail records in acc_trans
         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
-                     VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.accno = ?))|;
+                     VALUES (?, ?, ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.id = ?))|;
         @values = (conv_i($form->{id}), $form->{AR_amounts}{"amount_$i"}, conv_i($form->{"amount_$i"}), conv_date($form->{transdate}), $project_id,
                    conv_i($form->{"taxkey_$i"}), conv_i($form->{"tax_id_$i"}), $form->{AR_amounts}{"amount_$i"});
         do_query($form, $dbh, $query, @values);
@@ -175,17 +172,15 @@ sub _post_transaction {
 
     # add recievables
     $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link)
-                 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
+                 VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?),
                  (SELECT tax_id
                   FROM taxkeys
-                  WHERE chart_id= (SELECT id
-                                   FROM chart
-                                   WHERE accno = ?)
+                  WHERE chart_id = ?
                   AND startdate <= ?
                   ORDER BY startdate DESC LIMIT 1),
-                 (SELECT c.link FROM chart c WHERE c.accno = ?))|;
-    @values = (conv_i($form->{id}), $form->{AR_amounts}{receivables}, conv_i($form->{receivables}), conv_date($form->{transdate}),
-                $form->{AR_amounts}{receivables}, $form->{AR_amounts}{receivables}, conv_date($form->{transdate}), $form->{AR_amounts}{receivables});
+                 (SELECT c.link FROM chart c WHERE c.id = ?))|;
+    @values = (conv_i($form->{id}), $form->{AR_chart_id}, conv_i($form->{receivables}), conv_date($form->{transdate}),
+                $form->{AR_chart_id}, $form->{AR_chart_id}, conv_date($form->{transdate}), $form->{AR_chart_id});
     do_query($form, $dbh, $query, @values);
 
   } else {
@@ -225,17 +220,14 @@ sub _post_transaction {
       if ($amount != 0) {
         # add receivable
         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
-                     VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
+                     VALUES (?, ?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?),
                      (SELECT tax_id
                       FROM taxkeys
-                      WHERE chart_id= (SELECT id
-                                       FROM chart
-                                       WHERE accno = ?)
+                      WHERE chart_id = ?
                       AND startdate <= ?
                       ORDER BY startdate DESC LIMIT 1),
-                     (SELECT c.link FROM chart c WHERE c.accno = ?))|;
-        @values = (conv_i($form->{id}), $form->{AR}{receivables}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR}{receivables}, $form->{AR}{receivables}, conv_date($form->{"datepaid_$i"}),
-        $form->{AR}{receivables});
+                     (SELECT c.link FROM chart c WHERE c.id = ?))|;
+        @values = (conv_i($form->{id}), $form->{AR_chart_id}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR_chart_id}, $form->{AR_chart_id}, conv_date($form->{"datepaid_$i"}), $form->{AR_chart_id});
 
         do_query($form, $dbh, $query, @values);
       }
@@ -421,9 +413,9 @@ sub _post_payment {
   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
-  # Get the AR accno (which is normally done by Form::create_links()).
+  # Get the AR chart ID (which is normally done by Form::create_links()).
   $query =
-    qq|SELECT c.accno
+    qq|SELECT c.id
        FROM acc_trans at
        LEFT JOIN chart c ON (at.chart_id = c.id)
        WHERE (trans_id = ?)
@@ -431,7 +423,7 @@ sub _post_payment {
        ORDER BY at.acc_trans_id
        LIMIT 1|;
 
-  ($form->{ARselected}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
+  ($form->{AR_chart_id}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
 
   # Post the new payments.
   $self->post_transaction($myconfig, $form, $dbh, 1);
@@ -739,15 +731,8 @@ sub setup_form {
             $form->{"projectnumber_$k"}    = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
             $form->{taxrate}               = $form->{acc_trans}{$key}->[$i - 1]->{rate};
             $form->{"project_id_$k"}       = $form->{acc_trans}{$key}->[$i-1]->{project_id};
-          }
-
-          $form->{"${key}_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
-
-          if ($akey eq "AR") {
-            $form->{ARselected} = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
-          } elsif ($akey eq "amount") {
-            $form->{"${key}_$k"}   = $form->{acc_trans}{$key}->[$i-1]->{accno} . "--" . $form->{acc_trans}{$key}->[$i-1]->{id};
+            $form->{"${key}_chart_id_$k"} = $form->{acc_trans}{$key}->[$i-1]->{chart_id};
             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
           }
         }
index 8dd2a31..d15f5ec 100644 (file)
@@ -4,6 +4,7 @@ use strict;
 
 use Rose::DB::Object::Helpers qw(as_tree);
 
+use SL::DBUtils ();
 use SL::DB::MetaSetup::Customer;
 use SL::DB::Manager::Customer;
 use SL::DB::Helper::IBANValidation;
@@ -64,6 +65,28 @@ sub displayable_name {
   return join ' ', grep $_, $self->customernumber, $self->name;
 }
 
+sub last_used_ar_chart {
+  my ($self) = @_;
+
+  my $query = <<EOSQL;
+    SELECT c.id
+    FROM chart c
+    JOIN acc_trans ac ON (ac.chart_id = c.id)
+    JOIN ar a ON (a.id = ac.trans_id)
+    WHERE (a.customer_id = ?)
+      AND (c.category = 'I')
+      AND (c.link !~ '_(paid|tax)')
+      AND (a.id IN (SELECT max(a2.id) FROM ar a2 WHERE a2.customer_id = ?))
+    ORDER BY ac.acc_trans_id ASC
+    LIMIT 1
+EOSQL
+
+  my ($chart_id) = SL::DBUtils::selectfirst_array_query($::form, $self->db->dbh, $query, ($self->id) x 2);
+
+  return if !$chart_id;
+  return SL::DB::Chart->load_cached($chart_id);
+}
+
 sub is_customer { 1 };
 sub is_vendor   { 0 };
 sub payment_terms { goto &payment }
index 0779826..b174014 100644 (file)
@@ -4,6 +4,7 @@ use strict;
 
 use Rose::DB::Object::Helpers qw(as_tree);
 
+use SL::DBUtils ();
 use SL::DB::MetaSetup::Vendor;
 use SL::DB::Manager::Vendor;
 use SL::DB::Helper::IBANValidation;
@@ -63,4 +64,26 @@ sub is_vendor   { 1 };
 sub payment_terms { goto &payment }
 sub number { goto &vendornumber }
 
+sub last_used_ap_chart {
+  my ($self) = @_;
+
+  my $query = <<EOSQL;
+    SELECT c.id
+    FROM chart c
+    JOIN acc_trans ac ON (ac.chart_id = c.id)
+    JOIN ap a         ON (a.id        = ac.trans_id)
+    WHERE (a.vendor_id = ?)
+      AND (c.category = 'E')
+      AND (c.link !~ '_(paid|tax)')
+      AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))
+    ORDER BY ac.acc_trans_id ASC
+    LIMIT 1
+EOSQL
+
+  my ($chart_id) = SL::DBUtils::selectfirst_array_query($::form, $self->db->dbh, $query, ($self->id) x 2);
+
+  return if !$chart_id;
+  return SL::DB::Chart->load_cached($chart_id);
+}
+
 1;
index 4c8f3d7..00880f1 100644 (file)
@@ -2663,15 +2663,8 @@ sub create_links {
     }
 
     # now get the account numbers
-#    $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
-#                FROM chart c, taxkeys tk
-#                WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
-#                  (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
-#                ORDER BY c.accno|;
-
-#  same query as above, but without expensive subquery for each row. about 80% faster
     $query = qq|
-      SELECT c.accno, c.description, c.link, c.taxkey_id, tk2.tax_id
+      SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
         FROM chart c
         -- find newest entries in taxkeys
         INNER JOIN (
@@ -2701,6 +2694,7 @@ sub create_links {
 
           push @{ $self->{"${module}_links"}{$key} },
             { accno       => $ref->{accno},
+              chart_id    => $ref->{chart_id},
               description => $ref->{description},
               taxkey      => $ref->{taxkey_id},
               tax_id      => $ref->{tax_id} };
@@ -2754,7 +2748,7 @@ sub create_links {
     }
 
     # now get the account numbers
-    $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
+    $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
                 FROM chart c
                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
                 WHERE c.link LIKE ?
@@ -2776,6 +2770,7 @@ sub create_links {
 
           push @{ $self->{"${module}_links"}{$key} },
             { accno       => $ref->{accno},
+              chart_id    => $ref->{chart_id},
               description => $ref->{description},
               taxkey      => $ref->{taxkey_id},
               tax_id      => $ref->{tax_id} };
@@ -2790,7 +2785,7 @@ sub create_links {
     $query =
       qq|SELECT
            c.accno, c.description,
-           a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey,
+           a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
            p.projectnumber,
            t.rate, t.id
          FROM acc_trans a
index 09fc2f0..f46a954 100644 (file)
--- a/SL/GL.pm
+++ b/SL/GL.pm
 
 package GL;
 
+use List::Util qw(first);
+
 use Data::Dumper;
 use SL::DATEV qw(:CONSTANTS);
 use SL::DBUtils;
+use SL::DB::Chart;
 use SL::Util qw(trim);
 use SL::DB;
 
@@ -131,8 +134,6 @@ sub _post_transaction {
 
   # insert acc_trans transactions
   for $i (1 .. $form->{rowcount}) {
-    # extract accno
-    my ($accno) = split(/--/, $form->{"accno_$i"});
     ($form->{"tax_id_$i"}) = split(/--/, $form->{"taxchart_$i"});
     if ($form->{"tax_id_$i"} ne "") {
       $query = qq|SELECT taxkey, rate FROM tax WHERE id = ?|;
@@ -161,10 +162,9 @@ sub _post_transaction {
       $query =
         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
                                   source, memo, project_id, taxkey, ob_transaction, cb_transaction, tax_id, chart_link)
-           VALUES (?, (SELECT id FROM chart WHERE accno = ?),
-                   ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT link FROM chart WHERE accno = ?))|;
-      @values = (conv_i($form->{id}), $accno, $amount, conv_date($form->{transdate}),
-                 $form->{"source_$i"}, $form->{"memo_$i"}, $project_id, $taxkey, $form->{ob_transaction} ? 't' : 'f', $form->{cb_transaction} ? 't' : 'f', conv_i($form->{"tax_id_$i"}), $accno);
+           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT link FROM chart WHERE id = ?))|;
+      @values = (conv_i($form->{id}), $form->{"accno_id_$i"}, $amount, conv_date($form->{transdate}),
+                 $form->{"source_$i"}, $form->{"memo_$i"}, $project_id, $taxkey, $form->{ob_transaction} ? 't' : 'f', $form->{cb_transaction} ? 't' : 'f', conv_i($form->{"tax_id_$i"}), $form->{"accno_id_$i"});
       do_query($form, $dbh, $query, @values);
     }
 
@@ -650,7 +650,7 @@ sub transaction {
     $query =
       qq|SELECT c.accno, t.taxkey AS accnotaxkey, a.amount, a.memo, a.source,
            a.transdate, a.cleared, a.project_id, p.projectnumber,
-           a.taxkey, t.rate AS taxrate, t.id,
+           a.taxkey, t.rate AS taxrate, t.id, a.chart_id,
            (SELECT c1.accno
             FROM chart c1, tax t1
             WHERE (t1.id = t.id) AND (c1.id = t.chart_id)) AS taxaccno,
@@ -754,60 +754,35 @@ sub _storno {
 }
 
 sub get_chart_balances {
-  $main::lxdebug->enter_sub();
-
-  my $self     = shift;
-  my %params   = @_;
-
-  Common::check_params(\%params, qw(charts));
+  my ($self, @chart_ids) = @_;
 
-  my $myconfig = \%main::myconfig;
-  my $form     = $main::form;
-
-  my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
-
-  my @ids      = map { $_->{id} } @{ $params{charts} };
-
-  if (!@ids) {
-    $main::lxdebug->leave_sub();
-    return;
-  }
+  return () unless @chart_ids;
 
+  my $placeholders = join ', ', ('?') x scalar(@chart_ids);
   my $query = qq|SELECT chart_id, SUM(amount) AS sum
                  FROM acc_trans
-                 WHERE chart_id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)
+                 WHERE chart_id IN (${placeholders})
                  GROUP BY chart_id|;
 
-  my %balances = selectall_as_map($form, $dbh, $query, 'chart_id', 'sum', @ids);
+  my %balances = selectall_as_map($::form, $::form->get_standard_dbh(\%::myconfig), $query, 'chart_id', 'sum', @chart_ids);
 
-  foreach my $chart (@{ $params{charts} }) {
-    $chart->{balance} = $balances{ $chart->{id} } || 0;
-  }
-
-  $main::lxdebug->leave_sub();
+  return %balances;
 }
 
-sub get_tax_dropdown {
-  my ($self, $accno) = @_;
-
-  my $myconfig = \%main::myconfig;
-  my $form = $main::form;
+sub get_active_taxes_for_chart {
+  my ($self, $chart_id, $transdate) = @_;
 
-  my $dbh = $form->get_standard_dbh($myconfig);
+  my $chart         = SL::DB::Chart->new(id => $chart_id)->load;
+  my $active_taxkey = $chart->get_active_taxkey($transdate);
+  my $taxes         = SL::DB::Manager::Tax->get_all(
+    where   => [ chart_categories => { like => '%' . $chart->category . '%' }],
+    sort_by => 'taxkey, rate',
+  );
 
-  my $query = qq|SELECT category FROM chart WHERE accno = ?|;
-  my ($category) = selectrow_query($form, $dbh, $query, $accno);
-
-  $query = qq|SELECT * FROM tax WHERE chart_categories like '%$category%' order by taxkey, rate|;
-
-  my $sth = prepare_execute_query($form, $dbh, $query);
-
-  my @tax_accounts = ();
-  while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
-    push(@tax_accounts, $ref);
-  }
+  my $default_tax            = first { $active_taxkey->tax_id == $_->id } @{ $taxes };
+  $default_tax->{is_default} = 1 if $default_tax;
 
-  return @tax_accounts;
+  return @{ $taxes };
 }
 
 1;
index f25aa92..a2688ba 100644 (file)
--- a/SL/IR.pm
+++ b/SL/IR.pm
@@ -1172,43 +1172,6 @@ sub get_vendor {
   }
   $sth->finish();
 
-  if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
-    # setup last accounts used
-    $query =
-      qq|SELECT c.id, c.accno, c.description, c.link, c.category
-         FROM chart c
-         JOIN acc_trans ac ON (ac.chart_id = c.id)
-         JOIN ap a         ON (a.id = ac.trans_id)
-         WHERE (a.vendor_id = ?)
-           AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
-           AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
-    my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
-
-    my $i = 0;
-    for $ref (@$refs) {
-      if ($ref->{category} eq 'E') {
-        $i++;
-        my ($tax_id, $rate);
-        if ($params->{initial_transdate}) {
-          my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
-                             LEFT JOIN tax t ON (tk.tax_id = t.id)
-                             WHERE (tk.chart_id = ?) AND (startdate <= ?)
-                             ORDER BY tk.startdate DESC
-                             LIMIT 1|;
-          ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
-          $params->{"taxchart_$i"} = "${tax_id}--${rate}";
-        }
-
-        $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
-      }
-
-      if ($ref->{category} eq 'L') {
-        $params->{APselected} = $params->{AP_1} = $ref->{accno};
-      }
-    }
-    $params->{rowcount} = $i if ($i && !$params->{type});
-  }
-
   $main::lxdebug->leave_sub();
 }
 
index 3759e57..6d1e843 100644 (file)
--- a/SL/IS.pm
+++ b/SL/IS.pm
@@ -2203,46 +2203,6 @@ sub get_customer {
   }
   $sth->finish;
 
-  # setup last accounts used for this customer
-  if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
-    $query =
-      qq|SELECT c.id, c.accno, c.description, c.link, c.category
-         FROM chart c
-         JOIN acc_trans ac ON (ac.chart_id = c.id)
-         JOIN ar a ON (a.id = ac.trans_id)
-         WHERE a.customer_id = ?
-           AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
-           AND a.id IN (SELECT max(a2.id) FROM ar a2 WHERE a2.customer_id = ?)|;
-    $sth = prepare_execute_query($form, $dbh, $query, $cid, $cid);
-
-    my $i = 0;
-    while ($ref = $sth->fetchrow_hashref('NAME_lc')) {
-      if ($ref->{category} eq 'I') {
-        $i++;
-        $form->{"AR_amount_$i"} = "$ref->{accno}--$ref->{description}";
-
-        if ($form->{initial_transdate}) {
-          my $tax_query =
-            qq|SELECT tk.tax_id, t.rate
-               FROM taxkeys tk
-               LEFT JOIN tax t ON tk.tax_id = t.id
-               WHERE (tk.chart_id = ?) AND (startdate <= date(?))
-               ORDER BY tk.startdate DESC
-               LIMIT 1|;
-          my ($tax_id, $rate) =
-            selectrow_query($form, $dbh, $tax_query, $ref->{id},
-                            $form->{initial_transdate});
-          $form->{"taxchart_$i"} = "${tax_id}--${rate}";
-        }
-      }
-      if ($ref->{category} eq 'A') {
-        $form->{ARselected} = $form->{AR_1} = $ref->{accno};
-      }
-    }
-    $sth->finish;
-    $form->{rowcount} = $i if ($i && !$form->{type});
-  }
-
   $main::lxdebug->leave_sub();
 }
 
index 3440f93..765c2c0 100644 (file)
@@ -38,6 +38,7 @@ use List::UtilsBy qw(sort_by);
 
 use SL::AP;
 use SL::FU;
+use SL::GL;
 use SL::IR;
 use SL::IS;
 use SL::ReportGenerator;
@@ -101,6 +102,11 @@ sub add {
   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();
@@ -171,6 +177,7 @@ sub create_links {
   $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";
@@ -232,6 +239,8 @@ sub form_header {
 
   $::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
 
+  $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');
 
@@ -302,20 +311,13 @@ sub form_header {
   }
 
   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} }) ) {
-      if ( $taxchart_init eq '' ) {
-        $taxchart_init = $item->{tax_id};
-      }
+      $default_ap_amount_chart_id //= $item->{id};
 
-      push(@{ $form->{ALL_CHARTS_AP_amount} }, $item);
-    }
-    elsif ( grep({ $_ eq 'AP' } @{ $item->{link_split} }) ) {
-      push(@{ $form->{ALL_CHARTS_AP} }, $item);
-    }
-    elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
+    } elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
       push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
     }
 
@@ -324,12 +326,6 @@ sub form_header {
 
   my %taxcharts = ();
   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
-    my $key = $item->{id} .'--'. $item->{rate};
-
-    if ( $taxchart_init eq $item->{id} ) {
-      $taxchart_init = $key;
-    }
-
     $taxcharts{$item->{id}} = $item;
   }
 
@@ -337,10 +333,9 @@ sub form_header {
   $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>|;
-  $form->{javascript} .= qq|<script type="text/javascript" src="js/kivi.Draft.js"></script>|;
+  $::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();
 
@@ -350,37 +345,23 @@ sub form_header {
     $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 ($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"});
 
-    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"});
-
-    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"});
-
-    $form->{'selected_accno_full_'. $i} = $selected_accno_full;
-
-    $form->{'selected_taxchart_'. $i} = $selected_taxchart;
+    $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;
   }
 
-  $form->{AP_amount_value_title_sub} = sub {
-    my $item = shift;
-    return [
-      $item->{accno} .'--'. $item->{tax_id},
-      $item->{accno} .'--'. $item->{description},
-    ];
-  };
-
   $form->{taxchart_value_title_sub} = sub {
     my $item = shift;
     return [
@@ -397,14 +378,6 @@ sub form_header {
     ];
   };
 
-  $form->{APselected_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);
 
@@ -559,17 +532,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 notes);
 
   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} =
@@ -731,12 +696,6 @@ sub post {
     &update;
     $::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};
index 7456cd5..9416ac7 100644 (file)
@@ -38,6 +38,7 @@ use List::UtilsBy qw(sort_by);
 
 use SL::AR;
 use SL::FU;
+use SL::GL;
 use SL::IS;
 use SL::DB::Default;
 use SL::DB::Invoice;
@@ -101,6 +102,12 @@ sub add {
   $form->{initial_transdate} = $form->{transdate};
   create_links(dont_save => 1);
   $form->{transdate} = $form->{initial_transdate};
+
+  if ($form->{customer_id}) {
+    my $last_used_ar_chart = SL::DB::Customer->load_cached($form->{customer_id})->last_used_ar_chart;
+    $form->{"AR_amount_chart_id_1"} = $last_used_ar_chart->id if $last_used_ar_chart;
+  }
+
   &display_form;
   $main::lxdebug->leave_sub();
 }
@@ -167,6 +174,7 @@ sub create_links {
   $form->{$_}          = $saved{$_} for keys %saved;
   $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
   $form->{rowcount}    = 1;
+  $form->{AR_chart_id} = $form->{acc_trans} && $form->{acc_trans}->{AR} ? $form->{acc_trans}->{AR}->[0]->{chart_id} : $form->{AR_links}->{AR}->[0]->{chart_id};
 
   # currencies
   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
@@ -218,36 +226,14 @@ sub form_header {
 
   my ($title, $readonly, $exchangerate, $rows);
   my ($notes, $customer, $employee, $amount, $project);
-  my ($ARselected);
 
+  $form->{initial_focus} = !($form->{amount_1} * 1) ? 'customer' : 'row_' . $form->{rowcount};
 
   $title = $form->{title};
   # $locale->text('Add Accounts Receivables Transaction')
   # $locale->text('Edit Accounts Receivables Transaction')
   $form->{title} = $locale->text("$title Accounts Receivables 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 js
-  $form->{javascript} .= qq|<script type="text/javascript" src="js/show_history.js"></script>|;
-  #/show history button js
   $readonly = ($form->{id}) ? "readonly" : "";
 
   $form->{radier} = ($::instance_conf->get_ar_changeable == 2)
@@ -285,53 +271,27 @@ sub form_header {
 
   my %project_labels = map { $_->{id} => $_->{projectnumber} } @{ $form->{"ALL_PROJECTS"} };
 
-  my (@AR_amount_values);
-  my (@AR_values);
-  my (@AR_paid_values);
-  my %chart_labels;
-  my %charts;
-  my $taxchart_init;
+  my (@AR_paid_values, %AR_paid_labels);
+  my $default_ar_amount_chart_id;
 
   foreach my $item (@{ $form->{ALL_CHARTS} }) {
     if ($item->{link_split}{AR_amount}) {
-      $taxchart_init = $item->{tax_id} if ($taxchart_init eq "");
-      my $key = "$item->{accno}--$item->{tax_id}";
-      push(@AR_amount_values, $key);
-    } elsif ($item->{link_split}{AR}) {
-      push(@AR_values, $item->{accno});
+      $default_ar_amount_chart_id //= $item->{id};
+
     } elsif ($item->{link_split}{AR_paid}) {
       push(@AR_paid_values, $item->{accno});
+      $AR_paid_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
     }
-
-    # weirdness for AR_amount
-    $chart_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
-    $chart_labels{"$item->{accno}--$item->{tax_id}"} = "$item->{accno}--$item->{description}";
-
-    $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;
   }
 
   my $follow_up_vc         =  $form->{customer};
   $follow_up_vc            =~ s/--.*?//;
   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
 
-  $form->{javascript} .=
-    qq|<script type="text/javascript" src="js/show_vc_details.js"></script>| .
-    qq|<script type="text/javascript" src="js/follow_up.js"></script>| .
-    qq|<script type="text/javascript" src="js/kivi.Draft.js"></script>|;
+  $::request->layout->add_javascripts("autocomplete_chart.js", "show_vc_details.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.GL.js");
 
-#  $amount  = $locale->text('Amount');
-#  $project = $locale->text('Project');
+  my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
+  my $first_taxchart;
 
   my @transactions;
   for my $i (1 .. $form->{rowcount}) {
@@ -341,40 +301,26 @@ sub form_header {
       project_id => ($i==$form->{rowcount}) ? $form->{globalproject_id} : $form->{"project_id_$i"},
     };
 
-    my $selected_accno_full;
-    my ($accno_row) = split(/--/, $form->{"AR_amount_$i"});
-    my $item = $charts{$accno_row};
-    $selected_accno_full = "$item->{accno}--$item->{tax_id}";
+    my (%taxchart_labels, @taxchart_values, $default_taxchart, $taxchart_to_use);
+    my $amount_chart_id   = $form->{"AR_amount_chart_id_$i"} // $default_ar_amount_chart_id;
+    my $chart_has_changed = $::form->{"previous_AR_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AR_amount_chart_id_$i"});
 
-    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_AR_amount_$i"});
+    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"};
 
-    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}";
+      push(@taxchart_values, $key);
+      $taxchart_labels{$key} = $item->taxdescription . " " . $item->rate * 100 . ' %';
     }
 
-    if (!$form->{"taxchart_$i"}) {
-      if ($form->{"AR_amount_$i"} =~ m/.--./) {
-        $selected_taxchart = join '--', map { ($_->{id}, $_->{rate}) } first { $_->{id} == $item->{tax_id} } @{ $form->{ALL_TAXCHARTS} };
-      } else {
-        $selected_taxchart = $taxchart_init;
-      }
-    }
+    $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;
 
     $transaction->{selectAR_amount} =
-      NTI($cgi->popup_menu('-name' => "AR_amount_$i",
-                           '-id' => "AR_amount_$i",
-                           '-style' => 'width:400px',
-                           '-onChange' => "setTaxkey(this, $i)",
-                           '-values' => \@AR_amount_values,
-                           '-labels' => \%chart_labels,
-                           '-default' => $selected_accno_full))
-      . $cgi->hidden('-name' => "previous_AR_amount_$i",
-                     '-default' => $selected_accno_full);
+        $::request->presenter->chart_picker("AR_amount_chart_id_$i", $amount_chart_id, style => "width: 400px", type => "AR_amount", class => ($form->{initial_focus} eq "row_$i" ? "initial_focus" : ""))
+      . $::request->presenter->hidden_tag("previous_AR_amount_chart_id_$i", $amount_chart_id);
 
     $transaction->{taxchart} =
       NTI($cgi->popup_menu('-name' => "taxchart_$i",
@@ -389,13 +335,6 @@ sub form_header {
 
   $form->{invtotal_unformatted} = $form->{invtotal};
 
-  $ARselected =
-    NTI($cgi->popup_menu('-name' => "ARselected", '-id' => "ARselected",
-                         '-style' => 'width:400px',
-                         '-values' => \@AR_values, '-labels' => \%chart_labels,
-                         '-default' => $form->{ARselected}));
-
-
   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
 
   my $now = $form->current_date(\%myconfig);
@@ -423,7 +362,7 @@ sub form_header {
       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
                            '-id' => "AR_paid_$i",
                            '-values' => \@AR_paid_values,
-                           '-labels' => \%chart_labels,
+                           '-labels' => \%AR_paid_labels,
                            '-default' => $payment->{AR_paid} || $form->{accno_arap}));
 
 
@@ -457,7 +396,7 @@ sub form_header {
     transactions         => \@transactions,
     project_labels       => \%project_labels,
     rows                 => $rows,
-    ARselected           => $ARselected,
+    AR_chart_id          => $form->{AR_chart_id},
     title_str            => $title,
     follow_up_trans_info => $follow_up_trans_info,
     today                => DateTime->today,
@@ -570,17 +509,8 @@ sub update {
 
   $form->{invdate} = $form->{transdate};
 
-  my %saved_variables = map +( $_ => $form->{$_} ), qw(AR AR_amount_1 taxchart_1 customer_id notes);
-
   &check_name("customer");
 
-  $form->{AR} = $saved_variables{AR};
-  if ($saved_variables{AR_amount_1} =~ m/.--./) {
-    map { $form->{$_} = $saved_variables{$_} } qw(AR_amount_1 taxchart_1);
-  } else {
-    delete $form->{taxchart_1};
-  }
-
   $form->{invtotal} =
     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
 
index 2c203d3..cb2ebb2 100644 (file)
@@ -140,7 +140,7 @@ sub prepare_transaction {
       $form->{"project_id_$j"} = $ref->{project_id};
 
     } else {
-      $form->{"accno_$i"} = "$ref->{accno}--$ref->{tax_id}";
+      $form->{"accno_id_$i"} = $ref->{chart_id};
       for (qw(fx_transaction source memo)) { $form->{"${_}_$i"} = $ref->{$_} }
       if ($ref->{amount} < 0) {
         $form->{totaldebit} -= $ref->{amount};
@@ -650,6 +650,8 @@ sub display_rows {
   my %myconfig = %main::myconfig;
   my $cgi      = $::request->{cgi};
 
+  my %balances = GL->get_chart_balances(map { $_->{id} } @{ $form->{ALL_CHARTS} });
+
   $form->{debit_1}     = 0 if !$form->{"debit_1"};
   $form->{totaldebit}  = 0;
   $form->{totalcredit} = 0;
@@ -661,20 +663,9 @@ sub display_rows {
     $project_labels{$item->{"id"}} = $item->{"projectnumber"};
   }
 
-  my %chart_labels = ();
-  my @chart_values = ();
-  my %charts = ();
-  my $taxchart_init;
-  foreach my $item (@{ $form->{ALL_CHARTS} }) {
-    if ($item->{charttype} eq 'H'){ #falls ÃƒÅ’berschrift
-      next;                         #ÃŒberspringen (Bug 1150)
-    }
-    my $key = $item->{accno} . "--" . $item->{tax_id};
-    $taxchart_init = $item->{tax_id} unless (@chart_values);
-    push(@chart_values, $key);
-    $chart_labels{$key} = $item->{accno} . "--" . $item->{description};
-    $charts{$item->{accno}} = $item;
-  }
+  my %charts_by_id  = map { ($_->{id} => $_) } @{ $::form->{ALL_CHARTS} };
+  my $default_chart = $::form->{ALL_CHARTS}[0];
+  my $transdate     = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
 
   my ($source, $memo, $source_hidden, $memo_hidden);
   for my $i (1 .. $form->{rowcount}) {
@@ -690,49 +681,31 @@ sub display_rows {
       <input type="hidden" name="memo_$i" value="$form->{"memo_$i"}" size="16">|;
     }
 
-    my $selected_accno_full;
-    my ($accno_row) = split(/--/, $form->{"accno_$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_accno_$i"});
-
     my %taxchart_labels = ();
     my @taxchart_values = ();
-    my %taxcharts = ();
-    my $filter_accno;
-    $filter_accno = $::form->{ALL_CHARTS}[0]->{accno};
-    $filter_accno = $selected_accno if (!$init and $i < $form->{rowcount});
-    foreach my $item ( GL->get_tax_dropdown($filter_accno) ) {
-      my $key = $item->{id} . "--" . $item->{rate};
-      $taxchart_init = $key if ($taxchart_init == $item->{id});
-      push(@taxchart_values, $key);
-      $taxchart_labels{$key} = $item->{taxdescription} . " " . $item->{rate} * 100 . ' %';
-      $taxcharts{$item->{id}} = $item;
-    }
 
-    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}";
+    my $accno_id          = $::form->{"accno_id_$i"};
+    my $chart             = $charts_by_id{$accno_id} // $default_chart;
+    $accno_id             = $chart->{id};
+    my $chart_has_changed = $::form->{"previous_accno_id_$i"} && ($accno_id != $::form->{"previous_accno_id_$i"});
+    my ($first_taxchart, $default_taxchart, $taxchart_to_use);
+
+    foreach my $item ( GL->get_active_taxes_for_chart($accno_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"};
+
+      push(@taxchart_values, $key);
+      $taxchart_labels{$key} = $item->taxdescription . " " . $item->rate * 100 . ' %';
     }
 
-    $selected_accno      = '' if ($init);
-    $selected_taxchart ||= $taxchart_init;
+    $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;
 
     my $accno = qq|<td>| .
-      NTI($cgi->popup_menu('-name' => "accno_$i",
-                           '-id' => "accno_$i",
-                           '-onChange' => "updateTaxes($i);",
-                           '-style' => 'width:200px',
-                           '-values' => \@chart_values,
-                           '-labels' => \%chart_labels,
-                           '-default' => $selected_accno_full))
-      . $cgi->hidden('-name' => "previous_accno_$i",
-                     '-default' => $selected_accno_full)
+      $::request->presenter->chart_picker("accno_id_$i", $accno_id, style => "width: 300px") .
+      $::request->presenter->hidden_tag("previous_accno_id_$i", $accno_id)
       . qq|</td>|;
     my $tax_ddbox = qq|<td>| .
       NTI($cgi->popup_menu('-name' => "taxchart_$i",
@@ -808,10 +781,11 @@ sub display_rows {
     <input type="hidden" name="project_id_$i" value="$form->{"project_id_$i"}">|;
 
     my $copy2credit = $i == 1 ? 'onkeyup="copy_debit_to_credit()"' : '';
+    my $balance     = $form->format_amount(\%::myconfig, $balances{$accno_id} // 0, 2, 'DRCR');
 
     print qq|<tr valign=top>
     $accno
-    <td id="chart_balance_$i" align="right">&nbsp;</td>
+    <td id="chart_balance_$i" align="right">${balance}</td>
     $fx_transaction
     <td><input name="debit_$i" size="8" value="$form->{"debit_$i"}" accesskey=$i $copy2credit $debitreadonly></td>
     <td><input name="credit_$i" size=8 value="$form->{"credit_$i"}" $creditreadonly></td>
@@ -852,6 +826,8 @@ sub form_header {
 
   my ($init) = @_;
 
+  $::request->layout->add_javascripts("autocomplete_chart.js", "kivi.GL.js");
+
   my @old_project_ids = grep { $_ } map{ $::form->{"project_id_$_"} } 1..$::form->{rowcount};
 
   $::form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
@@ -863,8 +839,6 @@ sub form_header {
 
   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
 
-  GL->get_chart_balances('charts' => $::form->{ALL_CHARTS});
-
   my $title      = $::form->{title};
   $::form->{title} = $::locale->text("$title General Ledger Transaction");
   # $locale->text('Add General Ledger Transaction')
@@ -877,7 +851,7 @@ sub form_header {
     $::request->{layout}->focus("#reference");
     $::form->{taxincluded} = "1";
   } else {
-    $::request->{layout}->focus("#accno_$::form->{rowcount}");
+    $::request->{layout}->focus("#accno_id_$::form->{rowcount}_name");
   }
 
   $::form->{previous_id}     ||= "--";
@@ -1222,22 +1196,18 @@ sub continue {
 }
 
 sub get_tax_dropdown {
-  $main::lxdebug->enter_sub();
+  my $transdate    = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
+  my @tax_accounts = GL->get_active_taxes_for_chart($::form->{accno_id}, $transdate);
+  my $html         = $::form->parse_html_template("gl/update_tax_accounts", { TAX_ACCOUNTS => \@tax_accounts });
 
-  my $form = $main::form;
-  my @tax_accounts = GL->get_tax_dropdown($form->{accno});
-
-  foreach my $item (@tax_accounts) {
-    $item->{taxdescription} = $::locale->{iconv_utf8}->convert($item->{taxdescription});
-    $item->{taxdescription} .= ' ' . $form->round_amount($item->{rate} * 100);
-  }
-
-  $form->{TAX_ACCOUNTS} = [ @tax_accounts ];
-
-  print $form->ajax_response_header, $form->parse_html_template("gl/update_tax_accounts");
+  print $::form->ajax_response_header, $html;
+}
 
-  $main::lxdebug->leave_sub();
+sub get_chart_balance {
+  my %balances = GL->get_chart_balances($::form->{accno_id});
+  my $balance  = $::form->format_amount(\%::myconfig, $balances{ $::form->{accno_id} }, 2, 'DRCR');
 
+  print $::form->ajax_response_header, $balance;
 }
 
 1;
diff --git a/js/kivi.GL.js b/js/kivi.GL.js
new file mode 100644 (file)
index 0000000..833d928
--- /dev/null
@@ -0,0 +1,30 @@
+namespace('kivi.GL', function(ns) {
+  "use strict";
+
+  this.show_chart_balance = function(obj) {
+    var row = $(obj).attr('name').replace(/.*_/, '');
+
+    $.ajax({
+      url: 'gl.pl?action=get_chart_balance',
+      data: { accno_id:  $(obj).val() },
+      dataType: 'html',
+      success: function (new_html) {
+        $('#chart_balance_' + row).html(new_html);
+      }
+    });
+  };
+
+  this.update_taxes = function(obj) {
+    var row = $(obj).attr('name').replace(/.*_/, '');
+
+    $.ajax({
+      url: 'gl.pl?action=get_tax_dropdown',
+      data: { accno_id:  $(obj).val(),
+              transdate: $('#transdate').val() },
+      dataType: 'html',
+      success: function (new_html) {
+        $("#taxchart_" + row).html(new_html);
+      }
+    });
+  };
+});
index 14d4966..c3611a2 100644 (file)
 [%- END %]
 
 </form>
+
+<script type="text/javascript">
+ <!--
+$(document).ready(function() {
+  [%- SET row=0 %]
+  [%- WHILE row < rowcount %]
+   [%- SET row=row + 1 %]
+   $('#AP_amount_chart_id_[% row %]').on('set_item:ChartPicker', function(e, item) {
+     kivi.GL.update_taxes(this);
+   });
+  [%- END %]
+});
+-->
+</script>
index 169a5e0..8c8a173 100644 (file)
@@ -1,29 +1,7 @@
 [%- USE L %]
 [%- USE HTML %]
 [%- USE T8 %]
-[%- USE LxERP %]
-
-<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>
-
-<script type="text/javascript" src="js/show_history.js"></script>
+[%- USE LxERP %][%- USE P -%]
 
 <form method="post" action="[% script | html %]">
 
                 <th align="right" nowrap>[% 'Vendor' | $T8 %]</th>
                 <td colspan="3">
                   [% IF ( selectvendor ) %]
-                    <select name="vendor" onchange="document.getElementById('update_button').click();">[% selectvendor %]</select>
+                    <select name="vendor" onchange="document.getElementById('update_button').click();"[% IF initial_focus == 'vendor' %] class="initial_focus"[% END %]>[% selectvendor %]</select>
                   [% ELSE %]
-                    <input name=vendor value="[% vendor | html %]" size="35">
+                    <input name=vendor value="[% vendor | html %]" size="35"[% IF initial_focus == 'vendor' %] class="initial_focus"[% END %]>
                   [% END %]
                   <input type="button" value="D" onclick="show_vc_details('vendor')">
                 </td>
         [% FOREACH i IN [1..rowcount] %]
           <tr>
             <td>
-              [% selected_accno_full = "selected_accno_full_"_ i %]
-              [% L.select_tag('AP_amount_'_ i, ALL_CHARTS_AP_amount, value_title_sub = \AP_amount_value_title_sub, onchange = 'setTaxkey(this, '_ i _')', default = $selected_accno_full) %]
-
-              <input type="hidden" name="previous_AP_amount_[% i %]" value="[% $selected_accno_full %]">
+              [% SET selected_chart_id = "AP_amount_chart_id_"_ i %]
+              [% P.chart_picker("AP_amount_chart_id_" _ i, $selected_chart_id, style="width: 400px", type="AP_amount", class=(initial_focus == 'row_' _ i ? "initial_focus" : "")) %]
+              [% L.hidden_tag("previous_AP_amount_chart_id_" _ i, $selected_chart_id) %]
               <input type="hidden" name="tax_[% i %]" value="[% temp = "tax"_ i %][% $temp | html %]">
             </td>
             <td>
         </tr>
         <tr>
           <td>
-            [% L.select_tag('APselected', ALL_CHARTS_AP, value_title_sub = \APselected_value_title_sub, default = APselected) %]
+            [% P.chart_picker('AP_chart_id', AP_chart_id, style="width: 400px", type="AP") %]
           </td>
           <th align="left">[% invtotal | html %]</th>
           <td colspan="4"></td>
index df81ee5..5ce251c 100644 (file)
   [% END %]
 
 </form>
+
+<script type="text/javascript">
+ <!--
+$(document).ready(function() {
+  [%- SET row=0 %]
+  [%- WHILE row < rowcount %]
+   [%- SET row=row + 1 %]
+   $('#AR_amount_chart_id_[% row %]').on('set_item:ChartPicker', function(e, item) {
+     kivi.GL.update_taxes(this);
+   });
+  [%- END %]
+});
+-->
+</script>
index bcae2be..258a40a 100644 (file)
@@ -1,7 +1,7 @@
 [%- USE HTML %]
 [%- USE L %]
 [%- USE T8 %]
-[%- USE LxERP %]
+[%- USE LxERP %][%- USE P -%]
 
 <form method=post name="arledger" action="[% script %]">
 
@@ -43,9 +43,9 @@
                 <th align="right" nowrap>[% 'Customer' | $T8 %]</th>
                 <td colspan=3>
 [%- IF selectcustomer %]
-    <select id='customer' name="customer" onchange="document.getElementById('update_button').click();" class="initial_focus">[% selectcustomer %]</select>
+    <select id='customer' name="customer" onchange="document.getElementById('update_button').click();"[% IF initial_focus == 'customer'%] class="initial_focus"[% END %]>[% selectcustomer %]</select>
 [%- ELSE %]
-    <input id='customer' name=customer value="[% customer | html %]" size=35 class="initial_focus">
+    <input id='customer' name=customer value="[% customer | html %]" size=35[% IF initial_focus == 'customer'%] class="initial_focus"[% END %]>
 [%- END %]
                 <input type="button" value="[% 'Details (one letter abbreviation)' | $T8 %]" onclick="show_vc_details('customer')"></td>
                 [% L.hidden_tag('selectcustomer', selectcustomer) %]
           </td>
         </tr>
         <tr>
-          <td>[% ARselected %]</td>
+          <td>[% P.chart_picker("AR_chart_id", AR_chart_id, style="width: 400px", type="AR") %]</td>
           <th align=left>[% LxERP.format_amount(invtotal, 2) | html %]</th>
 
           <input type=hidden name=oldinvtotal value='[% oldinvtotal %]'>
index 48bbbea..6e78ce1 100644 (file)
 
   </form>
 
+<script type="text/javascript">
+ <!--
+$(document).ready(function() {
+  [%- SET row=0 %]
+  [%- WHILE row < rowcount %]
+   [%- SET row=row + 1 %]
+   $('#accno_id_[% row %]').on('set_item:ChartPicker', function(e, item) {
+     kivi.GL.show_chart_balance(this);
+     kivi.GL.update_taxes(this);
+   });
+  [%- END %]
+});
+-->
+</script>
index 748ff1b..2a34a69 100644 (file)
@@ -6,26 +6,6 @@
 
 <script type="text/javascript">
   <!--
-function updateTaxes(row)
-{
-  var accno  = document.getElementById('accno_' + row);
-  var taxkey = accno.options[accno.selectedIndex].value;
-  var reg = /^(.*?)--(\d*)$/;
-  var found = reg.exec(taxkey);
-  var account = found[1];
-  var default_tax_id = found[2];
-
-  $.ajax({
-    url: 'gl.pl?action=get_tax_dropdown',
-    data: { accno: account,
-            selected_tax_id: default_tax_id},
-    dataType: 'html',
-    success: function (new_html) {
-                                $("#taxchart_" + row).html(new_html);
-                              },
-  });
-};
-
   function copy_debit_to_credit() {
     var txt = document.getElementsByName('debit_1')[0].value;
     document.getElementsByName('credit_2')[0].value = txt;
@@ -162,5 +142,3 @@ function updateTaxes(row)
 [%- END %]
 
         </tr>
-
-[%- PROCESS 'gl/form_header_chart_balances_js.html' %]
diff --git a/templates/webpages/gl/form_header_chart_balances_js.html b/templates/webpages/gl/form_header_chart_balances_js.html
deleted file mode 100644 (file)
index 705d8f6..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-[% USE HTML %]
-[% USE JavaScript %]
-[% USE LxERP %]
-
-<script type="text/javascript">
- <!--
-var chart_balances = new Array();
-
-[% FOREACH chart = ALL_CHARTS %]
-chart_balances[[% loop.count - 1 %]] = '[% JavaScript.escape(LxERP.format_amount(chart.balance, 2, 0, 'DRCR')) %]';
-[%- END %]
-
-function show_chart_balance(obj) {
-  var row = $(obj).attr('name').replace(/.*_/, '');
-  var idx = $('#accno_' + row).prop('selectedIndex');
-  $('#chart_balance_' + row).html(chart_balances[idx]);
-}
-
-$(document).ready(function() {
-  [%- SET row=0 %]
-  [%- WHILE row < rowcount %]
-   [%- SET row=row + 1 %]
-   $('#accno_[% row %]').change(function() { show_chart_balance(this); });
-   show_chart_balance($('#accno_[% row %]'));
-  [%- END %]
-});
--->
-</script>
index d3c9586..88d8668 100644 (file)
@@ -1,4 +1,4 @@
-[% USE L %]
+[% USE L %][%- USE LxERP -%]
 [% FOR row = TAX_ACCOUNTS %]
-<option value='[% row.id %]--[% row.rate %]'[% IF row.id == selected_tax_id%] selected[% END %]>[% row.taxdescription %] %</option>
+<option value='[% row.id %]--[% row.rate %]'[% IF row.is_default %] selected[% END %]>[% row.taxdescription %] [% LxERP.round_amount(row.rate * 100) %] %</option>
 [% END %]