Image-Upload neuer Typ für VK-Lieferschein
[kivitendo-erp.git] / bin / mozilla / vk.pl
index b1176f2..8a0dc46 100644 (file)
 # 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.
 #======================================================================
 #
 # Sales report
 #
 #======================================================================
 
-# TODO
-# if qty or weight is shown add unit
-
 use POSIX qw(strftime);
 use List::Util qw(sum first);
 
 use SL::AM;
+use SL::DB::Employee;
 use SL::VK;
 use SL::IS;
 use SL::ReportGenerator;
 use Data::Dumper;
 
-require "bin/mozilla/arap.pl";
 require "bin/mozilla/common.pl";
-require "bin/mozilla/drafts.pl";
 require "bin/mozilla/reportgenerator.pl";
 
 use strict;
 
 sub search_invoice {
   $main::lxdebug->enter_sub();
-  $main::auth->assert('general_ledger | invoice_edit');
+  $main::auth->assert('ar_transactions | ap_transactions | invoice_edit');
 
   my $form     = $main::form;
   my %myconfig = %main::myconfig;
   my $locale   = $main::locale;
 
-  my ($customer, $department);
+  my ($customer);
 
-  # setup customer selection
-  $form->all_vc(\%myconfig, "customer", "AR");
+  $::request->layout->add_javascripts("autocomplete_project.js");
 
   $form->{title}    = $locale->text('Sales Report');
 
-  $form->get_lists("projects"        => { "key" => "ALL_PROJECTS", "all" => 1 },
-                   "departments"     => "ALL_DEPARTMENTS",
+  $form->get_lists("departments"     => "ALL_DEPARTMENTS",
                    "business_types"  => "ALL_BUSINESS_TYPES",
                    "salesmen"        => "ALL_SALESMEN",
-                   'employees'       => 'ALL_EMPLOYEES',
-                   'partsgroup'      => 'ALL_PARTSGROUPS',
-                   "customers"       => "ALL_VC");
-  $form->{CUSTOM_VARIABLES_IC}                  = CVar->get_configs('module' => 'IC');
-  ($form->{CUSTOM_VARIABLES_FILTER_CODE_IC},
-   $form->{CUSTOM_VARIABLES_INCLUSION_CODE_IC}) = CVar->render_search_options('variables'      => $form->{CUSTOM_VARIABLES_IC},
-                                                                           'include_prefix' => 'l_',
-                                                                           'include_value'  => 'Y');
-
-  $form->{CUSTOM_VARIABLES_CT}                  = CVar->get_configs('module' => 'CT');
-  ($form->{CUSTOM_VARIABLES_FILTER_CODE_CT},
-   $form->{CUSTOM_VARIABLES_INCLUSION_CODE_CT}) = CVar->render_search_options('variables'      => $form->{CUSTOM_VARIABLES_CT},
-                                                                           'include_prefix' => 'l_',
-                                                                           'include_value'  => 'Y');
-  $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
-  $form->{employee_labels} = sub { $_[0]->{"name"} || $_[0]->{"login"} };
-  $form->{salesman_labels} = $form->{employee_labels};
+                   'partsgroup'      => 'ALL_PARTSGROUPS');
 
-  $form->header;
-  print $form->parse_html_template('vk/search_invoice', { %myconfig });
+  $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted;
 
-  $main::lxdebug->leave_sub();
-}
-
-sub search_invoice_top {
-  $main::lxdebug->enter_sub();
-  $main::auth->assert('general_ledger | invoice_edit');
-
-  my $form     = $main::form;
-  my %myconfig = %main::myconfig;
-  my $locale   = $main::locale;
-
-  my ($customer, $department);
-
-  # setup customer selection
-  $form->all_vc(\%myconfig, "customer", "AR");
-
-  $form->{title}    = $locale->text('Sales Report Top');
-
-  $form->get_lists("projects"        => { "key" => "ALL_PROJECTS", "all" => 1 },
-                   "departments"     => "ALL_DEPARTMENTS",
-                   "business_types"  => "ALL_BUSINESS_TYPES",
-                   "salesmen"        => "ALL_SALESMEN",
-                   'employees'       => 'ALL_EMPLOYEES',
-                   'partsgroup'      => 'ALL_PARTSGROUPS',
-                   "customers"       => "ALL_VC");
   $form->{CUSTOM_VARIABLES_IC}                  = CVar->get_configs('module' => 'IC');
   ($form->{CUSTOM_VARIABLES_FILTER_CODE_IC},
    $form->{CUSTOM_VARIABLES_INCLUSION_CODE_IC}) = CVar->render_search_options('variables'      => $form->{CUSTOM_VARIABLES_IC},
@@ -126,12 +79,8 @@ sub search_invoice_top {
    $form->{CUSTOM_VARIABLES_INCLUSION_CODE_CT}) = CVar->render_search_options('variables'      => $form->{CUSTOM_VARIABLES_CT},
                                                                            'include_prefix' => 'l_',
                                                                            'include_value'  => 'Y');
-  $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
-  $form->{employee_labels} = sub { $_[0]->{"name"} || $_[0]->{"login"} };
-  $form->{salesman_labels} = $form->{employee_labels};
-
   $form->header;
-  print $form->parse_html_template('vk/search_invoice_top', { %myconfig });
+  print $form->parse_html_template('vk/search_invoice', { %myconfig });
 
   $main::lxdebug->leave_sub();
 }
@@ -139,32 +88,14 @@ sub search_invoice_top {
 sub invoice_transactions {
   $main::lxdebug->enter_sub();
 
-  $main::auth->assert('general_ledger | invoice_edit');
+  $main::auth->assert('ar_transactions | ap_transactions | invoice_edit');
 
   my $form     = $main::form;
   my %myconfig = %main::myconfig;
   my $locale   = $main::locale;
 
-  my @data_to_be_sorted;
-  # debug mode for finding differences in Umsatz as calculated by database and perl
-  # set to "Y" to turn on
-  $form->{"l_sellpricelinetotal"} = "";
-
   my ($callback, $href, @columns);
 
-  # sort_by_total mode
-  if ( $form->{l_sort_by_total} ) {
-    # uncheck Mainheadings
-    # check both subheadings
-    # set subsort = mainsort
-    $form->{l_headers_mainsort}  = '';
-    $form->{l_subtotal_mainsort} = "Y";
-    $form->{l_headers_subsort} = ''; 
-    $form->{l_subtotal_subsort} = "Y";
-    $form->{mainsort} = $form->{topsortgroup};
-    $form->{subsort} = $form->{mainsort};   # trigger subsort = mainsort
-  };
-
   # can't currently be configured from report, empty line between main sortings
   my $addemptylines = 1;
 
@@ -175,21 +106,9 @@ sub invoice_transactions {
 
   if ( $form->{customer} =~ /--/ ) {
     # Felddaten kommen aus Dropdownbox
-    ($form->{customername}, $form->{customer_id}) = split(/--/, $form->{customer});
-  } elsif ($form->{customer}) {
-    # es wurde ein Wert im Freitextfeld übergeben, auf Eindeutigkeit überprüfen
-
-    # check_name wird mit no_select => 1 ausgeführt, ist die Abfrage nicht eindeutig kommt ein Fehler
-    # und die Abfrage muß erneut ausgeführt werden
-
-    # Ohne no_select kommt bei Auswahl des Kunden ein Aufruf von update der ins
-    # Nichts führt, daher diese Zwischenlösung
-
-    &check_name('customer', no_select => 1);
-
-    # $form->{customer_id} was already set by check_name
-    $form->{customername} = $form->{customer};
-  };
+    my $dummy;
+    ($dummy, $form->{customer_id}) = split(/--/, $form->{customer});
+  }
   # if $form->{customer} is empty nothing further happens here
 
   # test for decimalplaces or set to default of 2
@@ -203,8 +122,6 @@ sub invoice_transactions {
   VK->invoice_transactions(\%myconfig, \%$form);
 
 
-
-
   if ( $form->{mainsort} eq 'month' or $form->{subsort} eq 'month' ) {
 
     # Data already comes out of SELECT statement in correct month order, but
@@ -220,10 +137,7 @@ sub invoice_transactions {
   $form->{title} = $locale->text('Sales Report');
 
   @columns =
-    qw(description invnumber transdate customernumber customername partnumber partsgroup country business transdate qty parts_unit weight sellprice sellprice_total discount lastcost lastcost_total marge_total marge_percent employee salesman);
-  push(@columns, "sellpricelinetotal") if $form->{"l_sellpricelinetotal"};
-  
-# sellpricelinetotal is qty*sellprice as calculated by database
+    qw(description invnumber transdate shipvia customernumber customername partnumber partsgroup country business transdate qty parts_unit weight sellprice sellprice_total discount lastcost lastcost_total marge_total marge_percent employee salesman);
 
   my @includeable_custom_variables = grep { $_->{includeable} } @{ $cvar_configs_ic }, @{ $cvar_configs_ct };
   my @searchable_custom_variables  = grep { $_->{searchable} }  @{ $cvar_configs_ic }, @{ $cvar_configs_ct };
@@ -232,18 +146,16 @@ sub invoice_transactions {
   push @columns, map { "cvar_$_->{name}" } @includeable_custom_variables;
 
 
-  # hidden variables für pdf/csv export übergeben
-  # einmal mit l_ um zu bestimmen welche Spalten ausgegeben werden sollen
-  # einmal optionen für die Überschrift (z.B. transdatefrom, partnumber, ...)
-  my @hidden_variables  = (qw(l_headers_mainsort l_headers_subsort l_subtotal_mainsort l_subtotal_subsort l_total l_parts l_customername l_customernumber transdatefrom transdateto decimalplaces customer customername customer_id department partnumber partsgroup country business description project_id customernumber salesman employee salesman_id employee_id business_id partsgroup_id mainsort subsort),
+  # pass hidden variables for pdf/csv export
+  # first with l_ to determine which columns to show
+  # then with the options for headings (such as transdatefrom, partnumber, ...)
+  my @hidden_variables  = (qw(l_headers_mainsort l_headers_subsort l_subtotal_mainsort l_subtotal_subsort l_total l_parts l_customername l_customernumber transdatefrom transdateto decimalplaces customer customer_id department_id partnumber partsgroup country business description project_id customernumber salesman employee salesman_id employee_id business_id partsgroup_id mainsort subsort),
       "$form->{db}number",
       map({ "cvar_$_->{name}" } @searchable_custom_variables),
-      map { "l_$_" } @columns,
+      map { "l_$_" } @columns
       );
-  push(@hidden_variables, qw(topsortgroup topsorttype l_sort_by_total));  # hidden variables for top
-
   my @hidden_nondefault = grep({ $form->{$_} } @hidden_variables);
-  # Variablen werden dann als Hidden Variable mitgegeben, z.B.
+  # variables are passed as hiddens, e.g.
   # <input type="hidden" name="report_generator_hidden_transdateto" value="21.05.2010">
 
   $href = build_std_url('action=invoice_transactions', grep { $form->{$_} } @hidden_variables);
@@ -252,13 +164,14 @@ sub invoice_transactions {
   my %column_defs = (
     'description'             => { 'text' => $locale->text('Description'), },
     'partnumber'              => { 'text' => $locale->text('Part Number'), },
-    'partsgroup'              => { 'text' => $locale->text('Group'), },
+    'partsgroup'              => { 'text' => $locale->text('Partsgroup'), },
     'country'                 => { 'text' => $locale->text('Country'), },
     'business'                => { 'text' => $locale->text('Customer type'), },
     'employee'                => { 'text' => $locale->text('Employee'), },
     'salesman'                => { 'text' => $locale->text('Salesperson'), },
     'invnumber'               => { 'text' => $locale->text('Invoice Number'), },
     'transdate'               => { 'text' => $locale->text('Invoice Date'), },
+    'shipvia'                 => { 'text' => $locale->text('Ship via'), },
     'qty'                     => { 'text' => $locale->text('Quantity'), },
     'parts_unit'              => { 'text' => $locale->text('Base unit'), },
     'weight'                  => { 'text' => $locale->text('Weight'), },
@@ -271,7 +184,6 @@ sub invoice_transactions {
     'marge_percent'           => { 'text' => $locale->text('Sales margin %'), },
     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
     'customername'            => { 'text' => $locale->text('Customer Name'), },
-    'sellpricelinetotal'      => { 'text' => $locale->text('sellpricelinetotal'), }, # debug control
 # add 3 more column_defs so we have a translation for top_info_text
     'customer'                => { 'text' => $locale->text('Customer'), },
     'part'                    => { 'text' => $locale->text('Part'), },
@@ -279,32 +191,28 @@ sub invoice_transactions {
     %column_defs_cvars,
   );
 
-  if ( not defined $form->{"l_parts"} ) {
-    # the columns for sellprice, lastcost and marge_percent will be averages in subtotal and total lines
-    map { $column_defs{$_}->{text} = $locale->text('Average symbol') . " " . $column_defs{$_}->{text} } qw(sellprice lastcost marge_percent);
-  };
-
   map { $column_defs{$_}->{visible} = $form->{"l_$_"} eq 'Y' } @columns;
 
-  my %column_alignment = map { $_ => 'right' } qw(lastcost sellprice sellprice_total lastcost_total parts_unit discount marge_total marge_percent qty weight sellpricelinetotal );
+  my %column_alignment = map { $_ => 'right' } qw(lastcost sellprice sellprice_total lastcost_total parts_unit discount marge_total marge_percent qty weight);
+
 
   # so now the check-box "Description" is only used as switch for part description in invoice-mode
   # always fill the column "Description" if we are in Zwischensummenmode
-  $form->{"l_description"} = "Y" if not defined $form->{"l_parts"};
-
+  $form->{"l_description"} = "Y" if not defined $form->{"l_parts"};;
   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
 
   my @options;
 
   push @options, $locale->text('Description')             . " : $form->{description}"                                                       if $form->{description};
-  push @options, $locale->text('Customer')                . " : $form->{customername}"                                                      if $form->{customer};
+  push @options, $locale->text('Customer')                . " : $form->{customer}"                                                          if $form->{customer};
   push @options, $locale->text('Customer Number')         . " : $form->{customernumber}"                                                    if $form->{customernumber};
-  # TODO: es wird nur id übergeben
-  push @options, $locale->text('Department')              . " : " . (split /--/, $form->{department})[0]                                    if $form->{department};
+  # TODO: only customer id is passed
+  push @options, $locale->text('Department')              . " : " . SL::DB::Department->new(id => $form->{department_id})->load->description if $form->{department_id};
   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                                                         if $form->{invnumber};
   push @options, $locale->text('Invoice Date')            . " : $form->{invdate}"                                                           if $form->{invdate};
+  push @options, $locale->text('Ship via')                . " : $form->{shipvia}"                                                         if $form->{shipvia};
   push @options, $locale->text('Part Number')             . " : $form->{partnumber}"                                                        if $form->{partnumber};
-  push @options, $locale->text('Group')                   . " : " . SL::DB::PartsGroup->new(id => $form->{partsgroup_id})->load->partsgroup if $form->{partsgroup_id};
+  push @options, $locale->text('Partsgroup')              . " : " . SL::DB::PartsGroup->new(id => $form->{partsgroup_id})->load->partsgroup if $form->{partsgroup_id};
   push @options, $locale->text('Country')                 . " : $form->{country}"                                                           if $form->{country};
   push @options, $locale->text('Employee')                . ' : ' . SL::DB::Employee->new(id => $form->{employee_id})->load->name           if $form->{employee_id};
   push @options, $locale->text('Salesman')                . ' : ' . SL::DB::Employee->new(id => $form->{salesman_id})->load->name           if $form->{salesman_id};
@@ -317,20 +225,11 @@ sub invoice_transactions {
 
   my $report = SL::ReportGenerator->new(\%myconfig, $form);
 
-  if ( not $form->{l_sort_by_total} ) {
   $report->set_options('top_info_text'        => join("\n", $locale->text('Main sorting') . ' : ' . $column_defs{$form->{mainsort}}->{text} , $locale->text('Secondary sorting') . ' : ' . $column_defs{$form->{'subsort'}}->{text}, @options),
                        'output_format'        => 'HTML',
                        'title'                => $form->{title},
                        'attachment_basename'  => $locale->text('Sales Report') . strftime('_%Y%m%d', localtime time),
     );
-  } else {
-  $report->set_options('top_info_text'        => join("\n", $locale->text('Grouping') . ' : ' . $column_defs{$form->{topsortgroup}}->{text} , $locale->text('Sort By') . ' : ' . $column_defs{$form->{'topsorttype'}}->{text}, @options),
-                       'output_format'        => 'HTML',
-                       'title'                => $form->{title},
-                       'attachment_basename'  => $locale->text('Sales Report') . strftime('_%Y%m%d', localtime time),
-    );
-  };
-
   $report->set_options_from_form();
   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
@@ -339,8 +238,7 @@ sub invoice_transactions {
 
   $report->set_export_options('invoice_transactions', @hidden_variables, qw(mainsort sortdir));
 
-  $report->set_sort_indicator($form->{mainsort}, $form->{sortdir}) unless $form->{"l_sort_by_total"};
-  
+  $report->set_sort_indicator($form->{mainsort}, $form->{sortdir});
 
   CVar->add_custom_variables_to_report('module'         => 'CT',
       'trans_id_field' => 'customerid',
@@ -371,13 +269,11 @@ sub invoice_transactions {
   # escape callback for href
   $callback = $form->escape($href);
 
-  my @subtotal_columns = qw(qty weight sellprice sellprice_total lastcost lastcost_total marge_total marge_percent discount sellpricelinetotal);
+  my @subtotal_columns = qw(qty weight sellprice sellprice_total lastcost lastcost_total marge_total marge_percent discount);
   # Total sum:
   # sum of sellprice_total, lastcost_total and marge_total
   # average of marge_percent
-# absolutes: qty, weight, sellprice_total, lastcost_total, marge_total
-# averages: sellprice, lastcost, marge_percent
-  my @total_columns = qw(sellprice_total lastcost_total marge_total marge_percent sellpricelinetotal);
+  my @total_columns = qw(sellprice_total lastcost_total marge_total marge_percent );
 
   my %totals     = map { $_ => 0 } @total_columns;
   my %subtotals1 = map { $_ => 0 } @subtotal_columns;
@@ -393,26 +289,56 @@ sub invoice_transactions {
     $basefactor = 1 unless $basefactor;
 
     $ar->{price_factor} = 1 unless $ar->{price_factor};
-    # calculate individual sellprice
-    # discount was already accounted for in db sellprice
+
+    # calculate individual sellprice, discount is already accounted for in column sellprice in db
+
+    # The sellprice total can be calculated from sellprice or fxsellprice (the
+    # value that was actually entered in the sellprice field and is always
+    # stored separately).  However, for fxsellprice this method only works when
+    # the tax is not included, because otherwise fxsellprice includes the tax
+    # and there is no simple way to extract the tax rate of the article from
+    # the big query.
+    #
+    # Using fxsellprice is potentially more accurate (certainly for tax
+    # included), because we can use the same method as is used while the
+    # invoice is generated.
+    #
+    # sellprice however has already been converted to the net value (but
+    # rounded in the process, which leads to rounding errors when calculating
+    # the linetotal from the rounded sellprice in the report.  These rounding
+    # errors can quickly amount to several cents when qty is large)
+    #
+    # For calculating sellprice_total from fxsellprice, you would use:
+    # sellprice_total_including_tax = qty * fxsellprice * (1-discount) /  price_factor * exchangerate
+    # $ar->{sellprice_total_including_tax} =  $form->round_amount( $ar->{qty} * ( $ar->{fxsellprice} * ( 1 - $ar->{discount} ) ) / $ar->{price_factor}, $form->{"decimalplaces"});
+
+    my $sellprice_orig     = $ar->{sellprice};
+    my $qty_orig           = $ar->{qty};
+    # adjust sellprice so it reflects the unit sellprice according to price_factor and basefactor
     $ar->{sellprice}       = $ar->{sellprice}  / $ar->{price_factor} / $basefactor;
+    # for sellprice_total use the original amounts
+    $ar->{sellprice_total} = $form->round_amount( $qty_orig * $sellprice_orig / $ar->{price_factor}, $form->{"decimalplaces"});
+
+    my $lastcost_orig      = $ar->{lastcost};
     $ar->{lastcost}        = $ar->{lastcost}   / $ar->{price_factor} / $basefactor;
-    $ar->{sellprice_total} = $form->round_amount( $ar->{qty} * ( $ar->{fxsellprice} * ( 1 - $ar->{discount} ) ) / $ar->{price_factor}, $form->{"decimalplaces"});
-    $ar->{lastcost_total}  = $form->round_amount( $ar->{qty} * $ar->{lastcost} * $basefactor, $form->{"decimalplaces"});
-    # marge_percent wird neu berechnet, da Wert in invoice leer ist (Bug)
+    $ar->{lastcost_total}  = $form->round_amount( $qty_orig * $lastcost_orig / $ar->{price_factor}, $form->{"decimalplaces"});
+
+    # marge_percent is recalculated, because the value in invoice used to be empty
     $ar->{marge_percent} = $ar->{sellprice_total} ? (($ar->{sellprice_total}-$ar->{lastcost_total}) / $ar->{sellprice_total} * 100) : 0;
-    # marge_total neu berechnen
+    # also recalculate marge_total
     $ar->{marge_total} = $ar->{sellprice_total} ? $ar->{sellprice_total}-$ar->{lastcost_total}  : 0;
-    $ar->{discount} *= 100;  # für Ausgabe formatieren, 10% stored as 0.1 in db
+    $ar->{discount} *= 100;  # format discount value for output, 10% is stored as 0.1 in db
 
-    #adapt qty to the chosen unit
+    # adjust qty to reflect the qty of the base unit
     $ar->{qty} *= $basefactor;
 
-    #weight is the still the weight per part, but here we want the total weight
+    # now $ar->{sellprice} * $ar->{qty} should be the same as $qty_orig * $ar->{qty}
+
+    # weight is the still the weight per part, but here we want the total weight
     $ar->{weight} *= $ar->{qty};
 
-    # Anfangshauptüberschrift
-    if ( $form->{l_headers_mainsort} eq "Y" && ( $idx == 0 or $ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx - 1]->{ $form->{'mainsort'} } )) {
+    # Main header
+    if ( $form->{l_headers_mainsort} eq "Y" && ( $idx == 1 or $ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx - 1]->{ $form->{'mainsort'} } )) {
       my $headerrow = {
         # use $emptyname for mainsort header if mainsort is empty
         data    => $ar->{$form->{'mainsort'}} || $locale->text('empty'),
@@ -428,7 +354,7 @@ sub invoice_transactions {
 #      $report->add_data($emptyheaderrow_set) if $form->{l_headers} eq "Y";
     };
 
-    # subsort überschriften
+    # subsort headers
     # special case: subsort headers only makes (aesthetical) sense if we show individual parts
     if ((   $idx == 0
          or $ar->{ $form->{'subsort'} }  ne $form->{AR}->[$idx - 1]->{ $form->{'subsort'} }
@@ -474,23 +400,21 @@ sub invoice_transactions {
       $subtotals2{lastcost}  = 0;
     };
 
-    # Ertrag prozentual in den Summen: (summe VK - summe Ertrag) / summe VK
+    # marge percent as sums: (sum VK - sum Ertrag) / sum VK
     $subtotals1{marge_percent} = $subtotals1{sellprice_total} ? (($subtotals1{sellprice_total} - $subtotals1{lastcost_total}) / $subtotals1{sellprice_total}) * 100 : 0;
     $subtotals2{marge_percent} = $subtotals2{sellprice_total} ? (($subtotals2{sellprice_total} - $subtotals2{lastcost_total}) / $subtotals2{sellprice_total}) *100 : 0;
 
-    # Ertrag prozentual:  (Summe VK betrag - Summe EK betrag) / Summe VK betrag
-    # wird laufend bei jeder Position neu berechnet
+    # total marge percent:  (sum VK betrag - sum EK betrag) / sum VK betrag
+    # is recalculated after each position
     $totals{marge_percent}    = $totals{sellprice_total}    ? ( ($totals{sellprice_total} - $totals{lastcost_total}) / $totals{sellprice_total}   ) * 100 : 0;
 
     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(marge_percent qty);
     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 3) } qw(weight);
     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, $form->{"decimalplaces"} )} qw(lastcost sellprice sellprice_total lastcost_total marge_total);
-    map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, $form->{"decimalplaces"} )} qw(sellpricelinetotal) if $form->{"l_sellpricelinetotal"};
 
-    # Einzelzeilen nur zeigen wenn l_parts gesetzt ist, nützlich, wenn man nur
-    # Subtotals und Totals sehen möchte
-    # these lines are only added to report in individual mode
-    
+    # only show individual lines when l_parts is set, this is useful, if you
+    # only want to see subtotals and totals
+
     if ($form->{l_parts}) {
       my %row = (
         map { ($_ => { data => $ar->{$_}, align => $column_alignment{$_} }) } @columns
@@ -504,9 +428,8 @@ sub invoice_transactions {
       $report->add_data(\%row);
     }
 
-    # hier wird bei l_subtotal nicht differenziert zwischen mainsort und subsort
-    # macht man l_subtotal_mainsort aus wird l_subtotal_subsort auch nicht ausgeführt
-    # create a subtotal line if we are at the last element or either the subsort or mainsort element has changed
+    # choosing l_subtotal doesn't make a distinction between mainsort and subsort
+    # if l_subtotal_mainsort is not selected l_subtotal_subsort isn't run either
     if (   ($form->{l_subtotal_mainsort} eq 'Y')
         && ($form->{l_subtotal_subsort}  eq 'Y')
         && (($idx == (scalar @{ $form->{AR} } - 1))   # last element always has a subtotal
@@ -514,20 +437,9 @@ sub invoice_transactions {
           || ($ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx + 1]->{ $form->{'mainsort'} })
           )) {   # if value that is sorted by changes, print subtotal
 
-
-      # stick subtotal_row_invoice in temporary variable
-      # if TOP mode store it in @data_to_be_sorted so we can sort the lines after all lines have been added
-      # otherwise just add to $report to be shown in defualt
-      my $tmpobject = create_subtotal_row_invoice(\%subtotals2, \@columns, \%column_alignment, \@subtotal_columns, $form->{l_parts} ? 'listsubtotal' : undef, $ar->{ $form->{'subsort'} }); 
-      if ( $form->{l_sort_by_total} and not $form->{l_parts} ) {
-        # add subtotal data to temporary array that can later be sorted
-        push(@data_to_be_sorted, $tmpobject);
-      } else {
-        $report->add_data( $tmpobject);
-      };
-     $report->add_data({ %empty_row }) if $form->{l_parts} and $addemptylines;
-   
-    };
+      $report->add_data(create_subtotal_row_invoice(\%subtotals2, \@columns, \%column_alignment, \@subtotal_columns, $form->{l_parts} ? 'listsubtotal' : undef, $ar->{ $form->{'subsort'} }));
+      $report->add_data({ %empty_row }) if $form->{l_parts} and $addemptylines;
+    }
 
     # if last mainsort is reached or mainsort has changed, add mainsort subtotal and empty row
     if (   ($form->{l_subtotal_mainsort} eq 'Y')
@@ -536,7 +448,7 @@ sub invoice_transactions {
         && (($idx == (scalar @{ $form->{AR} } - 1))   # last element always has a subtotal
             || ($ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx + 1]->{ $form->{'mainsort'} })
             )) {   # if value that is sorted by changes, print subtotal
-        # subtotal is overriden if mainsort and subsort are equal, don't print
+        # subtotal is overridden if mainsort and subsort are equal, don't print
         # subtotal line even if it is selected
       $report->add_data(create_subtotal_row_invoice(\%subtotals1, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal', $ar->{$form->{mainsort}}));
       $report->add_data({ %empty_row }) if $addemptylines; # insert empty row after mainsort
@@ -544,34 +456,12 @@ sub invoice_transactions {
 
     $idx++;
   }
-
-
-  if ( $form->{l_sort_by_total} ) {
-    # filter allowed parameters for sorttype
-    my @allowed_fields = qw(sellprice_total marge_total qty weight);
-    my ($sorttype) = grep { /^$form->{topsorttype}$/ } @allowed_fields;
-    die "illegal parameter for topsorttype" unless $sorttype;
-  
-    # add marker to column being sorted
-    $report->set_sort_indicator($sorttype);
-  
-    # add subtotal lines to report in numerical order of sorttype
-    @data_to_be_sorted = reverse sort { $a->{$sorttype}{unformatted} <=> $b->{$sorttype}{unformatted} } @data_to_be_sorted;
-    foreach( @data_to_be_sorted ) {
-      # to limit output, e.g. top 100, one could add a counter here
-      # that only adds a certain number of entries
-      # the total at the end would still be over all entries though 
-      $report->add_data( $_ );
-    };
-  };
-
   if ( $form->{l_total} eq "Y" ) {
     $report->add_separator();
     $report->add_data(create_subtotal_row_invoice(\%totals, \@columns, \%column_alignment, \@total_columns, 'listtotal', 'l_total'))
   };
-  
-  $report->generate_with_headers();
 
+  $report->generate_with_headers();
   $main::lxdebug->leave_sub();
 }
 
@@ -596,10 +486,10 @@ sub create_subtotal_row_invoice {
     $row->{description}->{data} = $locale->text('Total') . ' ' . $name;
   };
 
-  map { $row->{$_}->{unformatted} = $totals->{$_} } qw(sellprice_total lastcost_total marge_total qty weight);
   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } qw(marge_total marge_percent qty);
   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 3) } qw(weight);
-  map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, $form->{decimalplaces}) } qw(lastcost sellprice sellprice_total lastcost_total sellpricelinetotal);
+  map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, $form->{decimalplaces}) } qw(lastcost sellprice sellprice_total lastcost_total);
+
 
   map { $totals->{$_} = 0 } @{ $subtotal_columns };