Neue Verkaufsberichtvariante mit Umsatz-Sortierung
[kivitendo-erp.git] / bin / mozilla / vk.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
29 #
30 # Sales report
31 #
32 #======================================================================
33
34 # TODO
35 # if qty or weight is shown add unit
36
37 use POSIX qw(strftime);
38 use List::Util qw(sum first);
39
40 use SL::AM;
41 use SL::VK;
42 use SL::IS;
43 use SL::ReportGenerator;
44 use Data::Dumper;
45
46 require "bin/mozilla/arap.pl";
47 require "bin/mozilla/common.pl";
48 require "bin/mozilla/drafts.pl";
49 require "bin/mozilla/reportgenerator.pl";
50
51 use strict;
52
53 sub search_invoice {
54   $main::lxdebug->enter_sub();
55   $main::auth->assert('general_ledger | invoice_edit');
56
57   my $form     = $main::form;
58   my %myconfig = %main::myconfig;
59   my $locale   = $main::locale;
60
61   my ($customer, $department);
62
63   # setup customer selection
64   $form->all_vc(\%myconfig, "customer", "AR");
65
66   $form->{title}    = $locale->text('Sales Report');
67
68   $form->get_lists("projects"        => { "key" => "ALL_PROJECTS", "all" => 1 },
69                    "departments"     => "ALL_DEPARTMENTS",
70                    "business_types"  => "ALL_BUSINESS_TYPES",
71                    "salesmen"        => "ALL_SALESMEN",
72                    'employees'       => 'ALL_EMPLOYEES',
73                    'partsgroup'      => 'ALL_PARTSGROUPS',
74                    "customers"       => "ALL_VC");
75   $form->{CUSTOM_VARIABLES_IC}                  = CVar->get_configs('module' => 'IC');
76   ($form->{CUSTOM_VARIABLES_FILTER_CODE_IC},
77    $form->{CUSTOM_VARIABLES_INCLUSION_CODE_IC}) = CVar->render_search_options('variables'      => $form->{CUSTOM_VARIABLES_IC},
78                                                                            'include_prefix' => 'l_',
79                                                                            'include_value'  => 'Y');
80
81   $form->{CUSTOM_VARIABLES_CT}                  = CVar->get_configs('module' => 'CT');
82   ($form->{CUSTOM_VARIABLES_FILTER_CODE_CT},
83    $form->{CUSTOM_VARIABLES_INCLUSION_CODE_CT}) = CVar->render_search_options('variables'      => $form->{CUSTOM_VARIABLES_CT},
84                                                                            'include_prefix' => 'l_',
85                                                                            'include_value'  => 'Y');
86   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
87   $form->{employee_labels} = sub { $_[0]->{"name"} || $_[0]->{"login"} };
88   $form->{salesman_labels} = $form->{employee_labels};
89
90   $form->header;
91   print $form->parse_html_template('vk/search_invoice', { %myconfig });
92
93   $main::lxdebug->leave_sub();
94 }
95
96 sub search_invoice_top {
97   $main::lxdebug->enter_sub();
98   $main::auth->assert('general_ledger | invoice_edit');
99
100   my $form     = $main::form;
101   my %myconfig = %main::myconfig;
102   my $locale   = $main::locale;
103
104   my ($customer, $department);
105
106   # setup customer selection
107   $form->all_vc(\%myconfig, "customer", "AR");
108
109   $form->{title}    = $locale->text('Sales Report Top');
110
111   $form->get_lists("projects"        => { "key" => "ALL_PROJECTS", "all" => 1 },
112                    "departments"     => "ALL_DEPARTMENTS",
113                    "business_types"  => "ALL_BUSINESS_TYPES",
114                    "salesmen"        => "ALL_SALESMEN",
115                    'employees'       => 'ALL_EMPLOYEES',
116                    'partsgroup'      => 'ALL_PARTSGROUPS',
117                    "customers"       => "ALL_VC");
118   $form->{CUSTOM_VARIABLES_IC}                  = CVar->get_configs('module' => 'IC');
119   ($form->{CUSTOM_VARIABLES_FILTER_CODE_IC},
120    $form->{CUSTOM_VARIABLES_INCLUSION_CODE_IC}) = CVar->render_search_options('variables'      => $form->{CUSTOM_VARIABLES_IC},
121                                                                            'include_prefix' => 'l_',
122                                                                            'include_value'  => 'Y');
123
124   $form->{CUSTOM_VARIABLES_CT}                  = CVar->get_configs('module' => 'CT');
125   ($form->{CUSTOM_VARIABLES_FILTER_CODE_CT},
126    $form->{CUSTOM_VARIABLES_INCLUSION_CODE_CT}) = CVar->render_search_options('variables'      => $form->{CUSTOM_VARIABLES_CT},
127                                                                            'include_prefix' => 'l_',
128                                                                            'include_value'  => 'Y');
129   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
130   $form->{employee_labels} = sub { $_[0]->{"name"} || $_[0]->{"login"} };
131   $form->{salesman_labels} = $form->{employee_labels};
132
133   $form->header;
134   print $form->parse_html_template('vk/search_invoice_top', { %myconfig });
135
136   $main::lxdebug->leave_sub();
137 }
138
139 sub invoice_transactions {
140   $main::lxdebug->enter_sub();
141
142   $main::auth->assert('general_ledger | invoice_edit');
143
144   my $form     = $main::form;
145   my %myconfig = %main::myconfig;
146   my $locale   = $main::locale;
147
148   my @data_to_be_sorted;
149   # debug mode for finding differences in Umsatz as calculated by database and perl
150   # set to "Y" to turn on
151   $form->{"l_sellpricelinetotal"} = "";
152
153   my ($callback, $href, @columns);
154
155   # sort_by_total mode
156   if ( $form->{l_sort_by_total} ) {
157     # uncheck Mainheadings
158     # check both subheadings
159     # set subsort = mainsort
160     $form->{l_headers_mainsort}  = '';
161     $form->{l_subtotal_mainsort} = "Y";
162     $form->{l_headers_subsort} = ''; 
163     $form->{l_subtotal_subsort} = "Y";
164     $form->{mainsort} = $form->{topsortgroup};
165     $form->{subsort} = $form->{mainsort};   # trigger subsort = mainsort
166   };
167
168   # can't currently be configured from report, empty line between main sortings
169   my $addemptylines = 1;
170
171   # don't add empty lines between mainsort subtotals when only subtotal_mainsort is selected
172   if ($form->{l_subtotal_mainsort} eq "Y" and not defined $form->{l_headers_mainsort} and not defined $form->{l_headers_subsort} and not defined $form->{l_subtotal_subsort} ) {
173     $addemptylines = 0
174   };
175
176   if ( $form->{customer} =~ /--/ ) {
177     # Felddaten kommen aus Dropdownbox
178     ($form->{customername}, $form->{customer_id}) = split(/--/, $form->{customer});
179   } elsif ($form->{customer}) {
180     # es wurde ein Wert im Freitextfeld übergeben, auf Eindeutigkeit überprüfen
181
182     # check_name wird mit no_select => 1 ausgeführt, ist die Abfrage nicht eindeutig kommt ein Fehler
183     # und die Abfrage muß erneut ausgeführt werden
184
185     # Ohne no_select kommt bei Auswahl des Kunden ein Aufruf von update der ins
186     # Nichts führt, daher diese Zwischenlösung
187
188     &check_name('customer', no_select => 1);
189
190     # $form->{customer_id} was already set by check_name
191     $form->{customername} = $form->{customer};
192   };
193   # if $form->{customer} is empty nothing further happens here
194
195   # test for decimalplaces or set to default of 2
196   $form->{decimalplaces} = 2 unless $form->{decimalplaces} > 0 && $form->{decimalplaces} < 6;
197
198   my $cvar_configs_ct = CVar->get_configs('module' => 'CT');
199   my $cvar_configs_ic = CVar->get_configs('module' => 'IC');
200
201 #  report_generator_set_default_sort('transdate', 1);
202
203   VK->invoice_transactions(\%myconfig, \%$form);
204
205
206
207
208   if ( $form->{mainsort} eq 'month' or $form->{subsort} eq 'month' ) {
209
210     # Data already comes out of SELECT statement in correct month order, but
211     # remove whitespaces (month names are padded) and translate them as early
212     # as possible
213
214     foreach (@{ $form->{AR} }) {
215       $_->{month} =~ s/\s//g;
216       $_->{month} = $locale->text($_->{month});
217     };
218   };
219
220   $form->{title} = $locale->text('Sales Report');
221
222   @columns =
223     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);
224   push(@columns, "sellpricelinetotal") if $form->{"l_sellpricelinetotal"};
225   
226 # sellpricelinetotal is qty*sellprice as calculated by database
227
228   my @includeable_custom_variables = grep { $_->{includeable} } @{ $cvar_configs_ic }, @{ $cvar_configs_ct };
229   my @searchable_custom_variables  = grep { $_->{searchable} }  @{ $cvar_configs_ic }, @{ $cvar_configs_ct };
230   my %column_defs_cvars            = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @includeable_custom_variables;
231
232   push @columns, map { "cvar_$_->{name}" } @includeable_custom_variables;
233
234
235   # hidden variables für pdf/csv export übergeben
236   # einmal mit l_ um zu bestimmen welche Spalten ausgegeben werden sollen
237   # einmal optionen für die Überschrift (z.B. transdatefrom, partnumber, ...)
238   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),
239       "$form->{db}number",
240       map({ "cvar_$_->{name}" } @searchable_custom_variables),
241       map { "l_$_" } @columns,
242       );
243   push(@hidden_variables, qw(topsortgroup topsorttype l_sort_by_total));  # hidden variables for top
244
245   my @hidden_nondefault = grep({ $form->{$_} } @hidden_variables);
246   # Variablen werden dann als Hidden Variable mitgegeben, z.B.
247   # <input type="hidden" name="report_generator_hidden_transdateto" value="21.05.2010">
248
249   $href = build_std_url('action=invoice_transactions', grep { $form->{$_} } @hidden_variables);
250   # href = vk.pl?action=invoice_transactions&l_headers=Y&l_subtotal=Y&l_total=Y&transdatefrom=04.03.2010 ...
251
252   my %column_defs = (
253     'description'             => { 'text' => $locale->text('Description'), },
254     'partnumber'              => { 'text' => $locale->text('Part Number'), },
255     'partsgroup'              => { 'text' => $locale->text('Group'), },
256     'country'                 => { 'text' => $locale->text('Country'), },
257     'business'                => { 'text' => $locale->text('Customer type'), },
258     'employee'                => { 'text' => $locale->text('Employee'), },
259     'salesman'                => { 'text' => $locale->text('Salesperson'), },
260     'invnumber'               => { 'text' => $locale->text('Invoice Number'), },
261     'transdate'               => { 'text' => $locale->text('Invoice Date'), },
262     'qty'                     => { 'text' => $locale->text('Quantity'), },
263     'parts_unit'              => { 'text' => $locale->text('Base unit'), },
264     'weight'                  => { 'text' => $locale->text('Weight'), },
265     'sellprice'               => { 'text' => $locale->text('Sales price'), },
266     'sellprice_total'         => { 'text' => $locale->text('Sales net amount'), },
267     'lastcost_total'          => { 'text' => $locale->text('Purchase net amount'), },
268     'discount'                => { 'text' => $locale->text('Discount'), },
269     'lastcost'                => { 'text' => $locale->text('Purchase price'), },
270     'marge_total'             => { 'text' => $locale->text('Sales margin'), },
271     'marge_percent'           => { 'text' => $locale->text('Sales margin %'), },
272     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
273     'customername'            => { 'text' => $locale->text('Customer Name'), },
274     'sellpricelinetotal'      => { 'text' => $locale->text('sellpricelinetotal'), }, # debug control
275 # add 3 more column_defs so we have a translation for top_info_text
276     'customer'                => { 'text' => $locale->text('Customer'), },
277     'part'                    => { 'text' => $locale->text('Part'), },
278     'month'                   => { 'text' => $locale->text('Month'), },
279     %column_defs_cvars,
280   );
281
282   if ( not defined $form->{"l_parts"} ) {
283     # the columns for sellprice, lastcost and marge_percent will be averages in subtotal and total lines
284     map { $column_defs{$_}->{text} = $locale->text('Average symbol') . " " . $column_defs{$_}->{text} } qw(sellprice lastcost marge_percent);
285   };
286
287   map { $column_defs{$_}->{visible} = $form->{"l_$_"} eq 'Y' } @columns;
288
289   my %column_alignment = map { $_ => 'right' } qw(lastcost sellprice sellprice_total lastcost_total parts_unit discount marge_total marge_percent qty weight sellpricelinetotal );
290
291   # so now the check-box "Description" is only used as switch for part description in invoice-mode
292   # always fill the column "Description" if we are in Zwischensummenmode
293   $form->{"l_description"} = "Y" if not defined $form->{"l_parts"};
294
295   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
296
297   my @options;
298
299   push @options, $locale->text('Description')             . " : $form->{description}"                                                       if $form->{description};
300   push @options, $locale->text('Customer')                . " : $form->{customername}"                                                      if $form->{customer};
301   push @options, $locale->text('Customer Number')         . " : $form->{customernumber}"                                                    if $form->{customernumber};
302   # TODO: es wird nur id übergeben
303   push @options, $locale->text('Department')              . " : " . (split /--/, $form->{department})[0]                                    if $form->{department};
304   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                                                         if $form->{invnumber};
305   push @options, $locale->text('Invoice Date')            . " : $form->{invdate}"                                                           if $form->{invdate};
306   push @options, $locale->text('Part Number')             . " : $form->{partnumber}"                                                        if $form->{partnumber};
307   push @options, $locale->text('Group')                   . " : " . SL::DB::PartsGroup->new(id => $form->{partsgroup_id})->load->partsgroup if $form->{partsgroup_id};
308   push @options, $locale->text('Country')                 . " : $form->{country}"                                                           if $form->{country};
309   push @options, $locale->text('Employee')                . ' : ' . SL::DB::Employee->new(id => $form->{employee_id})->load->name           if $form->{employee_id};
310   push @options, $locale->text('Salesman')                . ' : ' . SL::DB::Employee->new(id => $form->{salesman_id})->load->name           if $form->{salesman_id};
311   push @options, $locale->text('Customer type')           . ' : ' . SL::DB::Business->new(id => $form->{business_id})->load->description    if $form->{business_id};
312   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                                                         if $form->{ordnumber};
313   push @options, $locale->text('Notes')                   . " : $form->{notes}"                                                             if $form->{notes};
314   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"                                           if $form->{transaction_description};
315   push @options, $locale->text('From')                    . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)                      if $form->{transdatefrom};
316   push @options, $locale->text('Bis')                     . " " . $locale->date(\%myconfig, $form->{transdateto}, 1)                        if $form->{transdateto};
317
318   my $report = SL::ReportGenerator->new(\%myconfig, $form);
319
320   if ( not $form->{l_sort_by_total} ) {
321   $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),
322                        'output_format'        => 'HTML',
323                        'title'                => $form->{title},
324                        'attachment_basename'  => $locale->text('Sales Report') . strftime('_%Y%m%d', localtime time),
325     );
326   } else {
327   $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),
328                        'output_format'        => 'HTML',
329                        'title'                => $form->{title},
330                        'attachment_basename'  => $locale->text('Sales Report') . strftime('_%Y%m%d', localtime time),
331     );
332   };
333
334   $report->set_options_from_form();
335   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
336
337   $report->set_columns(%column_defs);
338   $report->set_column_order(@columns);
339
340   $report->set_export_options('invoice_transactions', @hidden_variables, qw(mainsort sortdir));
341
342   $report->set_sort_indicator($form->{mainsort}, $form->{sortdir}) unless $form->{"l_sort_by_total"};
343   
344
345   CVar->add_custom_variables_to_report('module'         => 'CT',
346       'trans_id_field' => 'customerid',
347       'configs'        => $cvar_configs_ct,
348       'column_defs'    => \%column_defs,
349       'data'           => $form->{AR}
350   );
351
352   CVar->add_custom_variables_to_report('module'         => 'IC',
353       'trans_id_field' => 'parts_id',
354       'configs'        => $cvar_configs_ic,
355       'column_defs'    => \%column_defs,
356       'data'           => $form->{AR}
357   );
358
359   my $num_visible_columns = scalar $report->get_visible_columns;
360   my %empty_row           = (
361     description           => {
362       data                => '',
363       class               => 'listrowempty',
364       colspan             => $num_visible_columns,
365     },
366   );
367
368   # add sort and escape callback, this one we use for the add sub
369   $form->{callback} = $href .= "&sort=$form->{mainsort}";
370
371   # escape callback for href
372   $callback = $form->escape($href);
373
374   my @subtotal_columns = qw(qty weight sellprice sellprice_total lastcost lastcost_total marge_total marge_percent discount sellpricelinetotal);
375   # Total sum:
376   # sum of sellprice_total, lastcost_total and marge_total
377   # average of marge_percent
378 # absolutes: qty, weight, sellprice_total, lastcost_total, marge_total
379 # averages: sellprice, lastcost, marge_percent
380   my @total_columns = qw(sellprice_total lastcost_total marge_total marge_percent sellpricelinetotal);
381
382   my %totals     = map { $_ => 0 } @total_columns;
383   my %subtotals1 = map { $_ => 0 } @subtotal_columns;
384   my %subtotals2 = map { $_ => 0 } @subtotal_columns;
385
386   my $idx = 0;
387
388   my $basefactor;
389   my $all_units = AM->retrieve_all_units();
390
391   foreach my $ar (@{ $form->{AR} }) {
392     $basefactor = $all_units->{$ar->{unit}}->{factor} / $all_units->{$ar->{parts_unit}}->{factor};
393     $basefactor = 1 unless $basefactor;
394
395     $ar->{price_factor} = 1 unless $ar->{price_factor};
396     # calculate individual sellprice
397     # discount was already accounted for in db sellprice
398     $ar->{sellprice}       = $ar->{sellprice}  / $ar->{price_factor} / $basefactor;
399     $ar->{lastcost}        = $ar->{lastcost}   / $ar->{price_factor} / $basefactor;
400     $ar->{sellprice_total} = $form->round_amount( $ar->{qty} * ( $ar->{fxsellprice} * ( 1 - $ar->{discount} ) ) / $ar->{price_factor}, $form->{"decimalplaces"});
401     $ar->{lastcost_total}  = $form->round_amount( $ar->{qty} * $ar->{lastcost} * $basefactor, $form->{"decimalplaces"});
402     # marge_percent wird neu berechnet, da Wert in invoice leer ist (Bug)
403     $ar->{marge_percent} = $ar->{sellprice_total} ? (($ar->{sellprice_total}-$ar->{lastcost_total}) / $ar->{sellprice_total} * 100) : 0;
404     # marge_total neu berechnen
405     $ar->{marge_total} = $ar->{sellprice_total} ? $ar->{sellprice_total}-$ar->{lastcost_total}  : 0;
406     $ar->{discount} *= 100;  # für Ausgabe formatieren, 10% stored as 0.1 in db
407
408     #adapt qty to the chosen unit
409     $ar->{qty} *= $basefactor;
410
411     #weight is the still the weight per part, but here we want the total weight
412     $ar->{weight} *= $ar->{qty};
413
414     # Anfangshauptüberschrift
415     if ( $form->{l_headers_mainsort} eq "Y" && ( $idx == 0 or $ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx - 1]->{ $form->{'mainsort'} } )) {
416       my $headerrow = {
417         # use $emptyname for mainsort header if mainsort is empty
418         data    => $ar->{$form->{'mainsort'}} || $locale->text('empty'),
419         class   => "listmainsortheader",
420         colspan => $num_visible_columns,
421       };
422       $report->add_data([ { description => $headerrow } ]);
423
424       # add empty row after main header
425 #      my $emptyheaderrow->{description}->{data} = "";
426 #      $emptyheaderrow->{description}->{class} = "listmainsortheader";
427 #      my $emptyheaderrow_set = [ $emptyheaderrow ];
428 #      $report->add_data($emptyheaderrow_set) if $form->{l_headers} eq "Y";
429     };
430
431     # subsort überschriften
432     # special case: subsort headers only makes (aesthetical) sense if we show individual parts
433     if ((   $idx == 0
434          or $ar->{ $form->{'subsort'} }  ne $form->{AR}->[$idx - 1]->{ $form->{'subsort'} }
435          or $ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx - 1]->{ $form->{'mainsort'} })
436         && ($form->{l_headers_subsort} eq "Y")
437         && $form->{l_parts}
438     ) {
439       my $headerrow = {
440         # if subsort name is defined, use that name in header, otherwise use $emptyname
441         data    => $ar->{$form->{'subsort'}} || $locale->text('empty'),
442         class   => "listsubsortheader",
443         colspan => $num_visible_columns,
444       };
445       $report->add_data([ { description => $headerrow } ]);
446     };
447
448     map { $subtotals1{$_} += $ar->{$_};
449           $subtotals2{$_} += $ar->{$_};
450         } @subtotal_columns;
451
452     map { $totals{$_}    += $ar->{$_} } @total_columns;
453
454     if ( $subtotals1{qty} != 0 ) {
455       # calculate averages for subtotals1 and subtotals2
456       # credited positions reduce both total and qty and thus don't influence average prices
457       $subtotals1{sellprice} = $subtotals1{sellprice_total} / $subtotals1{qty};
458       $subtotals1{lastcost}  = $subtotals1{lastcost_total}  / $subtotals1{qty};
459     } else {
460       # qty is zero, so we have a special case where each position in subtotal
461       # group has a corresponding credit note so that the total qty is zero in
462       # this case we also want the total amounts to be zero, so overwrite them,
463       # rather than leaving the last value in sellprice/lastcost
464
465       $subtotals1{sellprice} = 0;
466       $subtotals1{lastcost}  = 0;
467     };
468
469     if ( $subtotals2{qty} != 0 ) {
470       $subtotals2{sellprice} = $subtotals2{sellprice_total} / $subtotals2{qty};
471       $subtotals2{lastcost}  = $subtotals2{lastcost_total}  / $subtotals2{qty};
472     } else {
473       $subtotals2{sellprice} = 0;
474       $subtotals2{lastcost}  = 0;
475     };
476
477     # Ertrag prozentual in den Summen: (summe VK - summe Ertrag) / summe VK
478     $subtotals1{marge_percent} = $subtotals1{sellprice_total} ? (($subtotals1{sellprice_total} - $subtotals1{lastcost_total}) / $subtotals1{sellprice_total}) * 100 : 0;
479     $subtotals2{marge_percent} = $subtotals2{sellprice_total} ? (($subtotals2{sellprice_total} - $subtotals2{lastcost_total}) / $subtotals2{sellprice_total}) *100 : 0;
480
481     # Ertrag prozentual:  (Summe VK betrag - Summe EK betrag) / Summe VK betrag
482     # wird laufend bei jeder Position neu berechnet
483     $totals{marge_percent}    = $totals{sellprice_total}    ? ( ($totals{sellprice_total} - $totals{lastcost_total}) / $totals{sellprice_total}   ) * 100 : 0;
484
485     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(marge_percent qty);
486     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 3) } qw(weight);
487     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, $form->{"decimalplaces"} )} qw(lastcost sellprice sellprice_total lastcost_total marge_total);
488     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, $form->{"decimalplaces"} )} qw(sellpricelinetotal) if $form->{"l_sellpricelinetotal"};
489
490     # Einzelzeilen nur zeigen wenn l_parts gesetzt ist, nützlich, wenn man nur
491     # Subtotals und Totals sehen möchte
492     # these lines are only added to report in individual mode
493     
494     if ($form->{l_parts}) {
495       my %row = (
496         map { ($_ => { data => $ar->{$_}, align => $column_alignment{$_} }) } @columns
497       );
498
499       $row{invnumber}->{link} = build_std_url("script=is.pl", 'action=edit') . "&id=" . E($ar->{id}) . "&callback=${callback}";
500
501       # use partdescription according to invoice in article mode
502       $row{description}->{data} = $ar->{invoice_description};
503
504       $report->add_data(\%row);
505     }
506
507     # hier wird bei l_subtotal nicht differenziert zwischen mainsort und subsort
508     # macht man l_subtotal_mainsort aus wird l_subtotal_subsort auch nicht ausgeführt
509     # create a subtotal line if we are at the last element or either the subsort or mainsort element has changed
510     if (   ($form->{l_subtotal_mainsort} eq 'Y')
511         && ($form->{l_subtotal_subsort}  eq 'Y')
512         && (($idx == (scalar @{ $form->{AR} } - 1))   # last element always has a subtotal
513           || ($ar->{ $form->{'subsort'} } ne $form->{AR}->[$idx + 1]->{ $form->{'subsort'}   })
514           || ($ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx + 1]->{ $form->{'mainsort'} })
515           )) {   # if value that is sorted by changes, print subtotal
516
517
518       # stick subtotal_row_invoice in temporary variable
519       # if TOP mode store it in @data_to_be_sorted so we can sort the lines after all lines have been added
520       # otherwise just add to $report to be shown in defualt
521       my $tmpobject = create_subtotal_row_invoice(\%subtotals2, \@columns, \%column_alignment, \@subtotal_columns, $form->{l_parts} ? 'listsubtotal' : undef, $ar->{ $form->{'subsort'} }); 
522       if ( $form->{l_sort_by_total} and not $form->{l_parts} ) {
523         # add subtotal data to temporary array that can later be sorted
524         push(@data_to_be_sorted, $tmpobject);
525       } else {
526         $report->add_data( $tmpobject);
527       };
528      $report->add_data({ %empty_row }) if $form->{l_parts} and $addemptylines;
529    
530     };
531
532     # if last mainsort is reached or mainsort has changed, add mainsort subtotal and empty row
533     if (   ($form->{l_subtotal_mainsort} eq 'Y')
534         && ($form->{l_subtotal_mainsort} eq 'Y')
535         && ($form->{mainsort}            ne $form->{subsort})
536         && (($idx == (scalar @{ $form->{AR} } - 1))   # last element always has a subtotal
537             || ($ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx + 1]->{ $form->{'mainsort'} })
538             )) {   # if value that is sorted by changes, print subtotal
539         # subtotal is overriden if mainsort and subsort are equal, don't print
540         # subtotal line even if it is selected
541       $report->add_data(create_subtotal_row_invoice(\%subtotals1, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal', $ar->{$form->{mainsort}}));
542       $report->add_data({ %empty_row }) if $addemptylines; # insert empty row after mainsort
543     }
544
545     $idx++;
546   }
547
548
549   if ( $form->{l_sort_by_total} ) {
550     # filter allowed parameters for sorttype
551     my @allowed_fields = qw(sellprice_total marge_total qty weight);
552     my ($sorttype) = grep { /^$form->{topsorttype}$/ } @allowed_fields;
553     die "illegal parameter for topsorttype" unless $sorttype;
554   
555     # add marker to column being sorted
556     $report->set_sort_indicator($sorttype);
557   
558     # add subtotal lines to report in numerical order of sorttype
559     @data_to_be_sorted = reverse sort { $a->{$sorttype}{unformatted} <=> $b->{$sorttype}{unformatted} } @data_to_be_sorted;
560     foreach( @data_to_be_sorted ) {
561       # to limit output, e.g. top 100, one could add a counter here
562       # that only adds a certain number of entries
563       # the total at the end would still be over all entries though 
564       $report->add_data( $_ );
565     };
566   };
567
568   if ( $form->{l_total} eq "Y" ) {
569     $report->add_separator();
570     $report->add_data(create_subtotal_row_invoice(\%totals, \@columns, \%column_alignment, \@total_columns, 'listtotal', 'l_total'))
571   };
572   
573   $report->generate_with_headers();
574
575   $main::lxdebug->leave_sub();
576 }
577
578 sub create_subtotal_row_invoice {
579   $main::lxdebug->enter_sub();
580
581   my ($totals, $columns, $column_alignment, $subtotal_columns, $class, $name) = @_;
582
583   my $form     = $main::form;
584   my %myconfig = %main::myconfig;
585   my $locale   = $main::locale;
586
587   my $row = { map { $_ => { data => '', class => $class, align => $column_alignment->{$_}, } } @{ $columns } };
588
589   # set name as "empty" if no value is given, except if we are dealing with the
590   # absolute total, then just write "Total sum"
591   # here we assume that no name will be called 'l_total'
592   $name = $locale->text('empty') unless $name;
593   if ( $name eq 'l_total' ) {
594     $row->{description}->{data} = $locale->text('Total sum');
595   } else {
596     $row->{description}->{data} = $locale->text('Total') . ' ' . $name;
597   };
598
599   map { $row->{$_}->{unformatted} = $totals->{$_} } qw(sellprice_total lastcost_total marge_total qty weight);
600   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } qw(marge_total marge_percent qty);
601   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 3) } qw(weight);
602   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, $form->{decimalplaces}) } qw(lastcost sellprice sellprice_total lastcost_total sellpricelinetotal);
603
604   map { $totals->{$_} = 0 } @{ $subtotal_columns };
605
606   $main::lxdebug->leave_sub();
607
608   return $row;
609 }
610
611 1;