Drafts: Ausgelagert in Controller
[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 use POSIX qw(strftime);
35 use List::Util qw(sum first);
36
37 use SL::AM;
38 use SL::VK;
39 use SL::IS;
40 use SL::ReportGenerator;
41 use Data::Dumper;
42
43 require "bin/mozilla/arap.pl";
44 require "bin/mozilla/common.pl";
45 require "bin/mozilla/reportgenerator.pl";
46
47 use strict;
48
49 sub search_invoice {
50   $main::lxdebug->enter_sub();
51   $main::auth->assert('general_ledger | invoice_edit');
52
53   my $form     = $main::form;
54   my %myconfig = %main::myconfig;
55   my $locale   = $main::locale;
56
57   my ($customer, $department);
58
59   # setup customer selection
60   $form->all_vc(\%myconfig, "customer", "AR");
61
62   $form->{title}    = $locale->text('Sales Report');
63
64   $form->get_lists("projects"        => { "key" => "ALL_PROJECTS", "all" => 1 },
65                    "departments"     => "ALL_DEPARTMENTS",
66                    "business_types"  => "ALL_BUSINESS_TYPES",
67                    "salesmen"        => "ALL_SALESMEN",
68                    'employees'       => 'ALL_EMPLOYEES',
69                    'partsgroup'      => 'ALL_PARTSGROUPS',
70                    "customers"       => "ALL_VC");
71   $form->{CUSTOM_VARIABLES_IC}                  = CVar->get_configs('module' => 'IC');
72   ($form->{CUSTOM_VARIABLES_FILTER_CODE_IC},
73    $form->{CUSTOM_VARIABLES_INCLUSION_CODE_IC}) = CVar->render_search_options('variables'      => $form->{CUSTOM_VARIABLES_IC},
74                                                                            'include_prefix' => 'l_',
75                                                                            'include_value'  => 'Y');
76
77   $form->{CUSTOM_VARIABLES_CT}                  = CVar->get_configs('module' => 'CT');
78   ($form->{CUSTOM_VARIABLES_FILTER_CODE_CT},
79    $form->{CUSTOM_VARIABLES_INCLUSION_CODE_CT}) = CVar->render_search_options('variables'      => $form->{CUSTOM_VARIABLES_CT},
80                                                                            'include_prefix' => 'l_',
81                                                                            'include_value'  => 'Y');
82   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
83   $form->{employee_labels} = sub { $_[0]->{"name"} || $_[0]->{"login"} };
84   $form->{salesman_labels} = $form->{employee_labels};
85
86   $form->header;
87   print $form->parse_html_template('vk/search_invoice', { %myconfig });
88
89   $main::lxdebug->leave_sub();
90 }
91
92 sub invoice_transactions {
93   $main::lxdebug->enter_sub();
94
95   $main::auth->assert('general_ledger | invoice_edit');
96
97   my $form     = $main::form;
98   my %myconfig = %main::myconfig;
99   my $locale   = $main::locale;
100
101   my ($callback, $href, @columns);
102
103   # can't currently be configured from report, empty line between main sortings
104   my $addemptylines = 1;
105
106   # don't add empty lines between mainsort subtotals when only subtotal_mainsort is selected
107   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} ) {
108     $addemptylines = 0
109   };
110
111   if ( $form->{customer} =~ /--/ ) {
112     # Felddaten kommen aus Dropdownbox
113     my $dummy;
114     ($dummy, $form->{customer_id}) = split(/--/, $form->{customer});
115   }
116   # if $form->{customer} is empty nothing further happens here
117
118   # test for decimalplaces or set to default of 2
119   $form->{decimalplaces} = 2 unless $form->{decimalplaces} > 0 && $form->{decimalplaces} < 6;
120
121   my $cvar_configs_ct = CVar->get_configs('module' => 'CT');
122   my $cvar_configs_ic = CVar->get_configs('module' => 'IC');
123
124 #  report_generator_set_default_sort('transdate', 1);
125
126   VK->invoice_transactions(\%myconfig, \%$form);
127
128
129   if ( $form->{mainsort} eq 'month' or $form->{subsort} eq 'month' ) {
130
131     # Data already comes out of SELECT statement in correct month order, but
132     # remove whitespaces (month names are padded) and translate them as early
133     # as possible
134
135     foreach (@{ $form->{AR} }) {
136       $_->{month} =~ s/\s//g;
137       $_->{month} = $locale->text($_->{month});
138     };
139   };
140
141   $form->{title} = $locale->text('Sales Report');
142
143   @columns =
144     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);
145
146   my @includeable_custom_variables = grep { $_->{includeable} } @{ $cvar_configs_ic }, @{ $cvar_configs_ct };
147   my @searchable_custom_variables  = grep { $_->{searchable} }  @{ $cvar_configs_ic }, @{ $cvar_configs_ct };
148   my %column_defs_cvars            = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @includeable_custom_variables;
149
150   push @columns, map { "cvar_$_->{name}" } @includeable_custom_variables;
151
152
153   # pass hidden variables for pdf/csv export
154   # first with l_ to determine which columns to show
155   # then with the options for headings (such as transdatefrom, partnumber, ...)
156   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 partnumber partsgroup country business description project_id customernumber salesman employee salesman_id employee_id business_id partsgroup_id mainsort subsort),
157       "$form->{db}number",
158       map({ "cvar_$_->{name}" } @searchable_custom_variables),
159       map { "l_$_" } @columns
160       );
161   my @hidden_nondefault = grep({ $form->{$_} } @hidden_variables);
162   # variables are passed as hiddens, e.g.
163   # <input type="hidden" name="report_generator_hidden_transdateto" value="21.05.2010">
164
165   $href = build_std_url('action=invoice_transactions', grep { $form->{$_} } @hidden_variables);
166   # href = vk.pl?action=invoice_transactions&l_headers=Y&l_subtotal=Y&l_total=Y&transdatefrom=04.03.2010 ...
167
168   my %column_defs = (
169     'description'             => { 'text' => $locale->text('Description'), },
170     'partnumber'              => { 'text' => $locale->text('Part Number'), },
171     'partsgroup'              => { 'text' => $locale->text('Group'), },
172     'country'                 => { 'text' => $locale->text('Country'), },
173     'business'                => { 'text' => $locale->text('Customer type'), },
174     'employee'                => { 'text' => $locale->text('Employee'), },
175     'salesman'                => { 'text' => $locale->text('Salesperson'), },
176     'invnumber'               => { 'text' => $locale->text('Invoice Number'), },
177     'transdate'               => { 'text' => $locale->text('Invoice Date'), },
178     'qty'                     => { 'text' => $locale->text('Quantity'), },
179     'parts_unit'              => { 'text' => $locale->text('Base unit'), },
180     'weight'                  => { 'text' => $locale->text('Weight'), },
181     'sellprice'               => { 'text' => $locale->text('Sales price'), },
182     'sellprice_total'         => { 'text' => $locale->text('Sales net amount'), },
183     'lastcost_total'          => { 'text' => $locale->text('Purchase net amount'), },
184     'discount'                => { 'text' => $locale->text('Discount'), },
185     'lastcost'                => { 'text' => $locale->text('Purchase price'), },
186     'marge_total'             => { 'text' => $locale->text('Sales margin'), },
187     'marge_percent'           => { 'text' => $locale->text('Sales margin %'), },
188     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
189     'customername'            => { 'text' => $locale->text('Customer Name'), },
190 # add 3 more column_defs so we have a translation for top_info_text
191     'customer'                => { 'text' => $locale->text('Customer'), },
192     'part'                    => { 'text' => $locale->text('Part'), },
193     'month'                   => { 'text' => $locale->text('Month'), },
194     %column_defs_cvars,
195   );
196
197   map { $column_defs{$_}->{visible} = $form->{"l_$_"} eq 'Y' } @columns;
198
199   my %column_alignment = map { $_ => 'right' } qw(lastcost sellprice sellprice_total lastcost_total parts_unit discount marge_total marge_percent qty weight);
200
201
202   # so now the check-box "Description" is only used as switch for part description in invoice-mode
203   # always fill the column "Description" if we are in Zwischensummenmode
204   $form->{"l_description"} = "Y" if not defined $form->{"l_parts"};;
205   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
206
207   my @options;
208
209   push @options, $locale->text('Description')             . " : $form->{description}"                                                       if $form->{description};
210   push @options, $locale->text('Customer')                . " : $form->{customer}"                                                          if $form->{customer};
211   push @options, $locale->text('Customer Number')         . " : $form->{customernumber}"                                                    if $form->{customernumber};
212   # TODO: only customer id is passed
213   push @options, $locale->text('Department')              . " : " . (split /--/, $form->{department})[0]                                    if $form->{department};
214   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                                                         if $form->{invnumber};
215   push @options, $locale->text('Invoice Date')            . " : $form->{invdate}"                                                           if $form->{invdate};
216   push @options, $locale->text('Part Number')             . " : $form->{partnumber}"                                                        if $form->{partnumber};
217   push @options, $locale->text('Group')                   . " : " . SL::DB::PartsGroup->new(id => $form->{partsgroup_id})->load->partsgroup if $form->{partsgroup_id};
218   push @options, $locale->text('Country')                 . " : $form->{country}"                                                           if $form->{country};
219   push @options, $locale->text('Employee')                . ' : ' . SL::DB::Employee->new(id => $form->{employee_id})->load->name           if $form->{employee_id};
220   push @options, $locale->text('Salesman')                . ' : ' . SL::DB::Employee->new(id => $form->{salesman_id})->load->name           if $form->{salesman_id};
221   push @options, $locale->text('Customer type')           . ' : ' . SL::DB::Business->new(id => $form->{business_id})->load->description    if $form->{business_id};
222   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                                                         if $form->{ordnumber};
223   push @options, $locale->text('Notes')                   . " : $form->{notes}"                                                             if $form->{notes};
224   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"                                           if $form->{transaction_description};
225   push @options, $locale->text('From')                    . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)                      if $form->{transdatefrom};
226   push @options, $locale->text('Bis')                     . " " . $locale->date(\%myconfig, $form->{transdateto}, 1)                        if $form->{transdateto};
227
228   my $report = SL::ReportGenerator->new(\%myconfig, $form);
229
230   $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),
231                        'output_format'        => 'HTML',
232                        'title'                => $form->{title},
233                        'attachment_basename'  => $locale->text('Sales Report') . strftime('_%Y%m%d', localtime time),
234     );
235   $report->set_options_from_form();
236   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
237
238   $report->set_columns(%column_defs);
239   $report->set_column_order(@columns);
240
241   $report->set_export_options('invoice_transactions', @hidden_variables, qw(mainsort sortdir));
242
243   $report->set_sort_indicator($form->{mainsort}, $form->{sortdir});
244
245   CVar->add_custom_variables_to_report('module'         => 'CT',
246       'trans_id_field' => 'customerid',
247       'configs'        => $cvar_configs_ct,
248       'column_defs'    => \%column_defs,
249       'data'           => $form->{AR}
250   );
251
252   CVar->add_custom_variables_to_report('module'         => 'IC',
253       'trans_id_field' => 'parts_id',
254       'configs'        => $cvar_configs_ic,
255       'column_defs'    => \%column_defs,
256       'data'           => $form->{AR}
257   );
258
259   my $num_visible_columns = scalar $report->get_visible_columns;
260   my %empty_row           = (
261     description           => {
262       data                => '',
263       class               => 'listrowempty',
264       colspan             => $num_visible_columns,
265     },
266   );
267
268   # add sort and escape callback, this one we use for the add sub
269   $form->{callback} = $href .= "&sort=$form->{mainsort}";
270
271   # escape callback for href
272   $callback = $form->escape($href);
273
274   my @subtotal_columns = qw(qty weight sellprice sellprice_total lastcost lastcost_total marge_total marge_percent discount);
275   # Total sum:
276   # sum of sellprice_total, lastcost_total and marge_total
277   # average of marge_percent
278   my @total_columns = qw(sellprice_total lastcost_total marge_total marge_percent );
279
280   my %totals     = map { $_ => 0 } @total_columns;
281   my %subtotals1 = map { $_ => 0 } @subtotal_columns;
282   my %subtotals2 = map { $_ => 0 } @subtotal_columns;
283
284   my $idx = 0;
285
286   my $basefactor;
287   my $all_units = AM->retrieve_all_units();
288
289   foreach my $ar (@{ $form->{AR} }) {
290     $basefactor = $all_units->{$ar->{unit}}->{factor} / $all_units->{$ar->{parts_unit}}->{factor};
291     $basefactor = 1 unless $basefactor;
292
293     $ar->{price_factor} = 1 unless $ar->{price_factor};
294
295     # calculate individual sellprice, discount is already accounted for in column sellprice in db
296
297     # The sellprice total can be calculated from sellprice or fxsellprice (the
298     # value that was actually entered in the sellprice field and is always
299     # stored seperately).  However, for fxsellprice this method only works when
300     # the tax is not included, because otherwise fxsellprice includes the tax
301     # and there is no simple way to extract the tax rate of the article from
302     # the big query.
303     #
304     # Using fxsellprice is potentially more accurate (certainly for tax
305     # included), because we can use the same method as is used while the
306     # invoice is generated.
307     #
308     # sellprice however has already been converted to the net value (but
309     # rounded in the process, which leads to rounding errors when calculating
310     # the linetotal from the rounded sellprice in the report.  These rounding
311     # errors can quickly amount to several cents when qty is large)
312     #
313     # For calculating sellprice_total from fxsellprice, you would use:
314     # sellprice_total_including_tax = qty * fxsellprice * (1-discount) /  price_factor * exchangerate
315     # $ar->{sellprice_total_including_tax} =  $form->round_amount( $ar->{qty} * ( $ar->{fxsellprice} * ( 1 - $ar->{discount} ) ) / $ar->{price_factor}, $form->{"decimalplaces"});
316
317     my $sellprice_orig     = $ar->{sellprice};
318     my $qty_orig           = $ar->{qty};
319     # adjust sellprice so it reflects the unit sellprice according to price_factor and basefactor
320     $ar->{sellprice}       = $ar->{sellprice}  / $ar->{price_factor} / $basefactor;
321     # for sellprice_total use the original amounts
322     $ar->{sellprice_total} = $form->round_amount( $qty_orig * $sellprice_orig / $ar->{price_factor}, $form->{"decimalplaces"});
323
324     my $lastcost_orig      = $ar->{lastcost};
325     $ar->{lastcost}        = $ar->{lastcost}   / $ar->{price_factor} / $basefactor;
326     $ar->{lastcost_total}  = $form->round_amount( $qty_orig * $lastcost_orig / $ar->{price_factor}, $form->{"decimalplaces"});
327
328     # marge_percent is recalculated, because the value in invoice used to be empty
329     $ar->{marge_percent} = $ar->{sellprice_total} ? (($ar->{sellprice_total}-$ar->{lastcost_total}) / $ar->{sellprice_total} * 100) : 0;
330     # also recalculate marge_total
331     $ar->{marge_total} = $ar->{sellprice_total} ? $ar->{sellprice_total}-$ar->{lastcost_total}  : 0;
332     $ar->{discount} *= 100;  # format discount value for output, 10% is stored as 0.1 in db
333
334     # adjust qty to reflect the qty of the base unit
335     $ar->{qty} *= $basefactor;
336
337     # now $ar->{sellprice} * $ar->{qty} should be the same as $qty_orig * $ar->{qty}
338
339     # weight is the still the weight per part, but here we want the total weight
340     $ar->{weight} *= $ar->{qty};
341
342     # Main header
343     if ( $form->{l_headers_mainsort} eq "Y" && ( $idx == 1 or $ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx - 1]->{ $form->{'mainsort'} } )) {
344       my $headerrow = {
345         # use $emptyname for mainsort header if mainsort is empty
346         data    => $ar->{$form->{'mainsort'}} || $locale->text('empty'),
347         class   => "listmainsortheader",
348         colspan => $num_visible_columns,
349       };
350       $report->add_data([ { description => $headerrow } ]);
351
352       # add empty row after main header
353 #      my $emptyheaderrow->{description}->{data} = "";
354 #      $emptyheaderrow->{description}->{class} = "listmainsortheader";
355 #      my $emptyheaderrow_set = [ $emptyheaderrow ];
356 #      $report->add_data($emptyheaderrow_set) if $form->{l_headers} eq "Y";
357     };
358
359     # subsort headers
360     # special case: subsort headers only makes (aesthetical) sense if we show individual parts
361     if ((   $idx == 0
362          or $ar->{ $form->{'subsort'} }  ne $form->{AR}->[$idx - 1]->{ $form->{'subsort'} }
363          or $ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx - 1]->{ $form->{'mainsort'} })
364         && ($form->{l_headers_subsort} eq "Y")
365         && $form->{l_parts}
366     ) {
367       my $headerrow = {
368         # if subsort name is defined, use that name in header, otherwise use $emptyname
369         data    => $ar->{$form->{'subsort'}} || $locale->text('empty'),
370         class   => "listsubsortheader",
371         colspan => $num_visible_columns,
372       };
373       $report->add_data([ { description => $headerrow } ]);
374     };
375
376     map { $subtotals1{$_} += $ar->{$_};
377           $subtotals2{$_} += $ar->{$_};
378         } @subtotal_columns;
379
380     map { $totals{$_}    += $ar->{$_} } @total_columns;
381
382     if ( $subtotals1{qty} != 0 ) {
383       # calculate averages for subtotals1 and subtotals2
384       # credited positions reduce both total and qty and thus don't influence average prices
385       $subtotals1{sellprice} = $subtotals1{sellprice_total} / $subtotals1{qty};
386       $subtotals1{lastcost}  = $subtotals1{lastcost_total}  / $subtotals1{qty};
387     } else {
388       # qty is zero, so we have a special case where each position in subtotal
389       # group has a corresponding credit note so that the total qty is zero in
390       # this case we also want the total amounts to be zero, so overwrite them,
391       # rather than leaving the last value in sellprice/lastcost
392
393       $subtotals1{sellprice} = 0;
394       $subtotals1{lastcost}  = 0;
395     };
396
397     if ( $subtotals2{qty} != 0 ) {
398       $subtotals2{sellprice} = $subtotals2{sellprice_total} / $subtotals2{qty};
399       $subtotals2{lastcost}  = $subtotals2{lastcost_total}  / $subtotals2{qty};
400     } else {
401       $subtotals2{sellprice} = 0;
402       $subtotals2{lastcost}  = 0;
403     };
404
405     # marge percent as sums: (sum VK - sum Ertrag) / sum VK
406     $subtotals1{marge_percent} = $subtotals1{sellprice_total} ? (($subtotals1{sellprice_total} - $subtotals1{lastcost_total}) / $subtotals1{sellprice_total}) * 100 : 0;
407     $subtotals2{marge_percent} = $subtotals2{sellprice_total} ? (($subtotals2{sellprice_total} - $subtotals2{lastcost_total}) / $subtotals2{sellprice_total}) *100 : 0;
408
409     # total marge percent:  (sum VK betrag - sum EK betrag) / sum VK betrag
410     # is recalculated after each position
411     $totals{marge_percent}    = $totals{sellprice_total}    ? ( ($totals{sellprice_total} - $totals{lastcost_total}) / $totals{sellprice_total}   ) * 100 : 0;
412
413     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(marge_percent qty);
414     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 3) } qw(weight);
415     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, $form->{"decimalplaces"} )} qw(lastcost sellprice sellprice_total lastcost_total marge_total);
416
417     # only show individual lines when l_parts is set, this is useful, if you
418     # only want to see subtotals and totals
419
420     if ($form->{l_parts}) {
421       my %row = (
422         map { ($_ => { data => $ar->{$_}, align => $column_alignment{$_} }) } @columns
423       );
424
425       $row{invnumber}->{link} = build_std_url("script=is.pl", 'action=edit') . "&id=" . E($ar->{id}) . "&callback=${callback}";
426
427       # use partdescription according to invoice in article mode
428       $row{description}->{data} = $ar->{invoice_description};
429
430       $report->add_data(\%row);
431     }
432
433     # choosing l_subtotal doesn't make a distinction between mainsort and subsort
434     # if l_subtotal_mainsort is not selected l_subtotal_subsort isn't run either
435     if (   ($form->{l_subtotal_mainsort} eq 'Y')
436         && ($form->{l_subtotal_subsort}  eq 'Y')
437         && (($idx == (scalar @{ $form->{AR} } - 1))   # last element always has a subtotal
438           || ($ar->{ $form->{'subsort'} } ne $form->{AR}->[$idx + 1]->{ $form->{'subsort'}   })
439           || ($ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx + 1]->{ $form->{'mainsort'} })
440           )) {   # if value that is sorted by changes, print subtotal
441
442       $report->add_data(create_subtotal_row_invoice(\%subtotals2, \@columns, \%column_alignment, \@subtotal_columns, $form->{l_parts} ? 'listsubtotal' : undef, $ar->{ $form->{'subsort'} }));
443       $report->add_data({ %empty_row }) if $form->{l_parts} and $addemptylines;
444     }
445
446     # if last mainsort is reached or mainsort has changed, add mainsort subtotal and empty row
447     if (   ($form->{l_subtotal_mainsort} eq 'Y')
448         && ($form->{l_subtotal_mainsort} eq 'Y')
449         && ($form->{mainsort}            ne $form->{subsort})
450         && (($idx == (scalar @{ $form->{AR} } - 1))   # last element always has a subtotal
451             || ($ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx + 1]->{ $form->{'mainsort'} })
452             )) {   # if value that is sorted by changes, print subtotal
453         # subtotal is overridden if mainsort and subsort are equal, don't print
454         # subtotal line even if it is selected
455       $report->add_data(create_subtotal_row_invoice(\%subtotals1, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal', $ar->{$form->{mainsort}}));
456       $report->add_data({ %empty_row }) if $addemptylines; # insert empty row after mainsort
457     }
458
459     $idx++;
460   }
461   if ( $form->{l_total} eq "Y" ) {
462     $report->add_separator();
463     $report->add_data(create_subtotal_row_invoice(\%totals, \@columns, \%column_alignment, \@total_columns, 'listtotal', 'l_total'))
464   };
465
466   $report->generate_with_headers();
467   $main::lxdebug->leave_sub();
468 }
469
470 sub create_subtotal_row_invoice {
471   $main::lxdebug->enter_sub();
472
473   my ($totals, $columns, $column_alignment, $subtotal_columns, $class, $name) = @_;
474
475   my $form     = $main::form;
476   my %myconfig = %main::myconfig;
477   my $locale   = $main::locale;
478
479   my $row = { map { $_ => { data => '', class => $class, align => $column_alignment->{$_}, } } @{ $columns } };
480
481   # set name as "empty" if no value is given, except if we are dealing with the
482   # absolute total, then just write "Total sum"
483   # here we assume that no name will be called 'l_total'
484   $name = $locale->text('empty') unless $name;
485   if ( $name eq 'l_total' ) {
486     $row->{description}->{data} = $locale->text('Total sum');
487   } else {
488     $row->{description}->{data} = $locale->text('Total') . ' ' . $name;
489   };
490
491   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } qw(marge_total marge_percent qty);
492   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 3) } qw(weight);
493   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, $form->{decimalplaces}) } qw(lastcost sellprice sellprice_total lastcost_total);
494
495
496   map { $totals->{$_} = 0 } @{ $subtotal_columns };
497
498   $main::lxdebug->leave_sub();
499
500   return $row;
501 }
502
503 1;