1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
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.
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 #======================================================================
32 #======================================================================
34 use POSIX qw(strftime);
35 use List::Util qw(sum first);
40 use SL::ReportGenerator;
43 require "bin/mozilla/arap.pl";
44 require "bin/mozilla/common.pl";
45 require "bin/mozilla/drafts.pl";
46 require "bin/mozilla/reportgenerator.pl";
51 $main::lxdebug->enter_sub();
52 $main::auth->assert('general_ledger | invoice_edit');
54 my $form = $main::form;
55 my %myconfig = %main::myconfig;
56 my $locale = $main::locale;
58 my ($customer, $department);
60 # setup customer selection
61 $form->all_vc(\%myconfig, "customer", "AR");
63 $form->{title} = $locale->text('Sales Report');
65 $form->get_lists("projects" => { "key" => "ALL_PROJECTS", "all" => 1 },
66 "departments" => "ALL_DEPARTMENTS",
67 "business_types" => "ALL_BUSINESS_TYPES",
68 "salesmen" => "ALL_SALESMEN",
69 'employees' => 'ALL_EMPLOYEES',
70 'partsgroup' => 'ALL_PARTSGROUPS',
71 "customers" => "ALL_VC");
72 $form->{CUSTOM_VARIABLES_IC} = CVar->get_configs('module' => 'IC');
73 ($form->{CUSTOM_VARIABLES_FILTER_CODE_IC},
74 $form->{CUSTOM_VARIABLES_INCLUSION_CODE_IC}) = CVar->render_search_options('variables' => $form->{CUSTOM_VARIABLES_IC},
75 'include_prefix' => 'l_',
76 'include_value' => 'Y');
78 $form->{CUSTOM_VARIABLES_CT} = CVar->get_configs('module' => 'CT');
79 ($form->{CUSTOM_VARIABLES_FILTER_CODE_CT},
80 $form->{CUSTOM_VARIABLES_INCLUSION_CODE_CT}) = CVar->render_search_options('variables' => $form->{CUSTOM_VARIABLES_CT},
81 'include_prefix' => 'l_',
82 'include_value' => 'Y');
83 $form->{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
84 $form->{employee_labels} = sub { $_[0]->{"name"} || $_[0]->{"login"} };
85 $form->{salesman_labels} = $form->{employee_labels};
88 print $form->parse_html_template('vk/search_invoice', { %myconfig });
90 $main::lxdebug->leave_sub();
93 sub invoice_transactions {
94 $main::lxdebug->enter_sub();
96 $main::auth->assert('general_ledger | invoice_edit');
98 my $form = $main::form;
99 my %myconfig = %main::myconfig;
100 my $locale = $main::locale;
102 my ($callback, $href, @columns);
104 # can't currently be configured from report, empty line between main sortings
105 my $addemptylines = 1;
107 # don't add empty lines between mainsort subtotals when only subtotal_mainsort is selected
108 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} ) {
112 if ( $form->{customer} =~ /--/ ) {
113 # field data comes from dropdown box
114 ($form->{customername}, $form->{customer_id}) = split(/--/, $form->{customer});
115 } elsif ($form->{customer}) {
117 # a value was added in the input box, we only want to filter for one
118 # customer, so check that a unique customer can be found
120 # check_name is executed with no_select => 1, if the result isn't unique
121 # quit with an error message, the user has to enter a new name
123 # Without no_select selecting a customer causes an update which doesn't
124 # return anything, which is the reason for this workaround
126 &check_name('customer', no_select => 1);
128 # $form->{customer_id} was already set by check_name
129 $form->{customername} = $form->{customer};
131 # if $form->{customer} is empty nothing further happens here
133 # test for decimalplaces or set to default of 2
134 $form->{decimalplaces} = 2 unless $form->{decimalplaces} > 0 && $form->{decimalplaces} < 6;
136 my $cvar_configs_ct = CVar->get_configs('module' => 'CT');
137 my $cvar_configs_ic = CVar->get_configs('module' => 'IC');
139 # report_generator_set_default_sort('transdate', 1);
141 VK->invoice_transactions(\%myconfig, \%$form);
144 if ( $form->{mainsort} eq 'month' or $form->{subsort} eq 'month' ) {
146 # Data already comes out of SELECT statement in correct month order, but
147 # remove whitespaces (month names are padded) and translate them as early
150 foreach (@{ $form->{AR} }) {
151 $_->{month} =~ s/\s//g;
152 $_->{month} = $locale->text($_->{month});
156 $form->{title} = $locale->text('Sales Report');
159 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);
161 my @includeable_custom_variables = grep { $_->{includeable} } @{ $cvar_configs_ic }, @{ $cvar_configs_ct };
162 my @searchable_custom_variables = grep { $_->{searchable} } @{ $cvar_configs_ic }, @{ $cvar_configs_ct };
163 my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @includeable_custom_variables;
165 push @columns, map { "cvar_$_->{name}" } @includeable_custom_variables;
168 # pass hidden variables for pdf/csv export
169 # first with l_ to determine which columns to show
170 # then with the options for headings (such as transdatefrom, partnumber, ...)
171 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),
173 map({ "cvar_$_->{name}" } @searchable_custom_variables),
174 map { "l_$_" } @columns
176 my @hidden_nondefault = grep({ $form->{$_} } @hidden_variables);
177 # variables are passed as hiddens, e.g.
178 # <input type="hidden" name="report_generator_hidden_transdateto" value="21.05.2010">
180 $href = build_std_url('action=invoice_transactions', grep { $form->{$_} } @hidden_variables);
181 # href = vk.pl?action=invoice_transactions&l_headers=Y&l_subtotal=Y&l_total=Y&transdatefrom=04.03.2010 ...
184 'description' => { 'text' => $locale->text('Description'), },
185 'partnumber' => { 'text' => $locale->text('Part Number'), },
186 'partsgroup' => { 'text' => $locale->text('Group'), },
187 'country' => { 'text' => $locale->text('Country'), },
188 'business' => { 'text' => $locale->text('Customer type'), },
189 'employee' => { 'text' => $locale->text('Employee'), },
190 'salesman' => { 'text' => $locale->text('Salesperson'), },
191 'invnumber' => { 'text' => $locale->text('Invoice Number'), },
192 'transdate' => { 'text' => $locale->text('Invoice Date'), },
193 'qty' => { 'text' => $locale->text('Quantity'), },
194 'parts_unit' => { 'text' => $locale->text('Base unit'), },
195 'weight' => { 'text' => $locale->text('Weight'), },
196 'sellprice' => { 'text' => $locale->text('Sales price'), },
197 'sellprice_total' => { 'text' => $locale->text('Sales net amount'), },
198 'lastcost_total' => { 'text' => $locale->text('Purchase net amount'), },
199 'discount' => { 'text' => $locale->text('Discount'), },
200 'lastcost' => { 'text' => $locale->text('Purchase price'), },
201 'marge_total' => { 'text' => $locale->text('Sales margin'), },
202 'marge_percent' => { 'text' => $locale->text('Sales margin %'), },
203 'customernumber' => { 'text' => $locale->text('Customer Number'), },
204 'customername' => { 'text' => $locale->text('Customer Name'), },
205 # add 3 more column_defs so we have a translation for top_info_text
206 'customer' => { 'text' => $locale->text('Customer'), },
207 'part' => { 'text' => $locale->text('Part'), },
208 'month' => { 'text' => $locale->text('Month'), },
212 map { $column_defs{$_}->{visible} = $form->{"l_$_"} eq 'Y' } @columns;
214 my %column_alignment = map { $_ => 'right' } qw(lastcost sellprice sellprice_total lastcost_total parts_unit discount marge_total marge_percent qty weight);
217 # so now the check-box "Description" is only used as switch for part description in invoice-mode
218 # always fill the column "Description" if we are in Zwischensummenmode
219 $form->{"l_description"} = "Y" if not defined $form->{"l_parts"};;
220 map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
224 push @options, $locale->text('Description') . " : $form->{description}" if $form->{description};
225 push @options, $locale->text('Customer') . " : $form->{customername}" if $form->{customer};
226 push @options, $locale->text('Customer Number') . " : $form->{customernumber}" if $form->{customernumber};
227 # TODO: only customer id is passed
228 push @options, $locale->text('Department') . " : " . (split /--/, $form->{department})[0] if $form->{department};
229 push @options, $locale->text('Invoice Number') . " : $form->{invnumber}" if $form->{invnumber};
230 push @options, $locale->text('Invoice Date') . " : $form->{invdate}" if $form->{invdate};
231 push @options, $locale->text('Part Number') . " : $form->{partnumber}" if $form->{partnumber};
232 push @options, $locale->text('Group') . " : " . SL::DB::PartsGroup->new(id => $form->{partsgroup_id})->load->partsgroup if $form->{partsgroup_id};
233 push @options, $locale->text('Country') . " : $form->{country}" if $form->{country};
234 push @options, $locale->text('Employee') . ' : ' . SL::DB::Employee->new(id => $form->{employee_id})->load->name if $form->{employee_id};
235 push @options, $locale->text('Salesman') . ' : ' . SL::DB::Employee->new(id => $form->{salesman_id})->load->name if $form->{salesman_id};
236 push @options, $locale->text('Customer type') . ' : ' . SL::DB::Business->new(id => $form->{business_id})->load->description if $form->{business_id};
237 push @options, $locale->text('Order Number') . " : $form->{ordnumber}" if $form->{ordnumber};
238 push @options, $locale->text('Notes') . " : $form->{notes}" if $form->{notes};
239 push @options, $locale->text('Transaction description') . " : $form->{transaction_description}" if $form->{transaction_description};
240 push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1) if $form->{transdatefrom};
241 push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1) if $form->{transdateto};
243 my $report = SL::ReportGenerator->new(\%myconfig, $form);
245 $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),
246 'output_format' => 'HTML',
247 'title' => $form->{title},
248 'attachment_basename' => $locale->text('Sales Report') . strftime('_%Y%m%d', localtime time),
250 $report->set_options_from_form();
251 $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
253 $report->set_columns(%column_defs);
254 $report->set_column_order(@columns);
256 $report->set_export_options('invoice_transactions', @hidden_variables, qw(mainsort sortdir));
258 $report->set_sort_indicator($form->{mainsort}, $form->{sortdir});
260 CVar->add_custom_variables_to_report('module' => 'CT',
261 'trans_id_field' => 'customerid',
262 'configs' => $cvar_configs_ct,
263 'column_defs' => \%column_defs,
264 'data' => $form->{AR}
267 CVar->add_custom_variables_to_report('module' => 'IC',
268 'trans_id_field' => 'parts_id',
269 'configs' => $cvar_configs_ic,
270 'column_defs' => \%column_defs,
271 'data' => $form->{AR}
274 my $num_visible_columns = scalar $report->get_visible_columns;
278 class => 'listrowempty',
279 colspan => $num_visible_columns,
283 # add sort and escape callback, this one we use for the add sub
284 $form->{callback} = $href .= "&sort=$form->{mainsort}";
286 # escape callback for href
287 $callback = $form->escape($href);
289 my @subtotal_columns = qw(qty weight sellprice sellprice_total lastcost lastcost_total marge_total marge_percent discount);
291 # sum of sellprice_total, lastcost_total and marge_total
292 # average of marge_percent
293 my @total_columns = qw(sellprice_total lastcost_total marge_total marge_percent );
295 my %totals = map { $_ => 0 } @total_columns;
296 my %subtotals1 = map { $_ => 0 } @subtotal_columns;
297 my %subtotals2 = map { $_ => 0 } @subtotal_columns;
302 my $all_units = AM->retrieve_all_units();
304 foreach my $ar (@{ $form->{AR} }) {
305 $basefactor = $all_units->{$ar->{unit}}->{factor} / $all_units->{$ar->{parts_unit}}->{factor};
306 $basefactor = 1 unless $basefactor;
308 $ar->{price_factor} = 1 unless $ar->{price_factor};
310 # calculate individual sellprice, discount is already accounted for in column sellprice in db
312 # The sellprice total can be calculated from sellprice or fxsellprice (the
313 # value that was actually entered in the sellprice field and is always
314 # stored seperately). However, for fxsellprice this method only works when
315 # the tax is not included, because otherwise fxsellprice includes the tax
316 # and there is no simple way to extract the tax rate of the article from
319 # Using fxsellprice is potentially more accurate (certainly for tax
320 # included), because we can use the same method as is used while the
321 # invoice is generated.
323 # sellprice however has already been converted to the net value (but
324 # rounded in the process, which leads to rounding errors when calculating
325 # the linetotal from the rounded sellprice in the report. These rounding
326 # errors can quickly amount to several cents when qty is large)
328 # For calculating sellprice_total from fxsellprice, you would use:
329 # sellprice_total_including_tax = qty * fxsellprice * (1-discount) / price_factor * exchangerate
330 # $ar->{sellprice_total_including_tax} = $form->round_amount( $ar->{qty} * ( $ar->{fxsellprice} * ( 1 - $ar->{discount} ) ) / $ar->{price_factor}, $form->{"decimalplaces"});
332 $ar->{sellprice} = $ar->{sellprice} / $ar->{price_factor} / $basefactor;
333 $ar->{sellprice_total} = $form->round_amount( $ar->{qty} * $ar->{sellprice} / $ar->{price_factor} , $form->{"decimalplaces"});
335 $ar->{lastcost} = $ar->{lastcost} / $ar->{price_factor} / $basefactor;
336 $ar->{lastcost_total} = $form->round_amount( $ar->{qty} * $ar->{lastcost} / $ar->{price_factor}, $form->{"decimalplaces"});
338 # marge_percent is recalculated, because the value in invoice used to be empty
339 $ar->{marge_percent} = $ar->{sellprice_total} ? (($ar->{sellprice_total}-$ar->{lastcost_total}) / $ar->{sellprice_total} * 100) : 0;
340 # also recalculate marge_total
341 $ar->{marge_total} = $ar->{sellprice_total} ? $ar->{sellprice_total}-$ar->{lastcost_total} : 0;
342 $ar->{discount} *= 100; # format discount value for output, 10% is stored as 0.1 in db
344 # adapt qty to the chosen unit
345 $ar->{qty} *= $basefactor;
347 # weight is the still the weight per part, but here we want the total weight
348 $ar->{weight} *= $ar->{qty};
351 if ( $form->{l_headers_mainsort} eq "Y" && ( $idx == 1 or $ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx - 1]->{ $form->{'mainsort'} } )) {
353 # use $emptyname for mainsort header if mainsort is empty
354 data => $ar->{$form->{'mainsort'}} || $locale->text('empty'),
355 class => "listmainsortheader",
356 colspan => $num_visible_columns,
358 $report->add_data([ { description => $headerrow } ]);
360 # add empty row after main header
361 # my $emptyheaderrow->{description}->{data} = "";
362 # $emptyheaderrow->{description}->{class} = "listmainsortheader";
363 # my $emptyheaderrow_set = [ $emptyheaderrow ];
364 # $report->add_data($emptyheaderrow_set) if $form->{l_headers} eq "Y";
368 # special case: subsort headers only makes (aesthetical) sense if we show individual parts
370 or $ar->{ $form->{'subsort'} } ne $form->{AR}->[$idx - 1]->{ $form->{'subsort'} }
371 or $ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx - 1]->{ $form->{'mainsort'} })
372 && ($form->{l_headers_subsort} eq "Y")
376 # if subsort name is defined, use that name in header, otherwise use $emptyname
377 data => $ar->{$form->{'subsort'}} || $locale->text('empty'),
378 class => "listsubsortheader",
379 colspan => $num_visible_columns,
381 $report->add_data([ { description => $headerrow } ]);
384 map { $subtotals1{$_} += $ar->{$_};
385 $subtotals2{$_} += $ar->{$_};
388 map { $totals{$_} += $ar->{$_} } @total_columns;
390 if ( $subtotals1{qty} != 0 ) {
391 # calculate averages for subtotals1 and subtotals2
392 # credited positions reduce both total and qty and thus don't influence average prices
393 $subtotals1{sellprice} = $subtotals1{sellprice_total} / $subtotals1{qty};
394 $subtotals1{lastcost} = $subtotals1{lastcost_total} / $subtotals1{qty};
396 # qty is zero, so we have a special case where each position in subtotal
397 # group has a corresponding credit note so that the total qty is zero in
398 # this case we also want the total amounts to be zero, so overwrite them,
399 # rather than leaving the last value in sellprice/lastcost
401 $subtotals1{sellprice} = 0;
402 $subtotals1{lastcost} = 0;
405 if ( $subtotals2{qty} != 0 ) {
406 $subtotals2{sellprice} = $subtotals2{sellprice_total} / $subtotals2{qty};
407 $subtotals2{lastcost} = $subtotals2{lastcost_total} / $subtotals2{qty};
409 $subtotals2{sellprice} = 0;
410 $subtotals2{lastcost} = 0;
413 # marge percent as sums: (sum VK - sum Ertrag) / sum VK
414 $subtotals1{marge_percent} = $subtotals1{sellprice_total} ? (($subtotals1{sellprice_total} - $subtotals1{lastcost_total}) / $subtotals1{sellprice_total}) * 100 : 0;
415 $subtotals2{marge_percent} = $subtotals2{sellprice_total} ? (($subtotals2{sellprice_total} - $subtotals2{lastcost_total}) / $subtotals2{sellprice_total}) *100 : 0;
417 # total marge percent: (sum VK betrag - sum EK betrag) / sum VK betrag
418 # is recalculated after each position
419 $totals{marge_percent} = $totals{sellprice_total} ? ( ($totals{sellprice_total} - $totals{lastcost_total}) / $totals{sellprice_total} ) * 100 : 0;
421 map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(marge_percent qty);
422 map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 3) } qw(weight);
423 map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, $form->{"decimalplaces"} )} qw(lastcost sellprice sellprice_total lastcost_total marge_total);
425 # only show individual lines when l_parts is set, this is useful, if you
426 # only want to see subtotals and totals
428 if ($form->{l_parts}) {
430 map { ($_ => { data => $ar->{$_}, align => $column_alignment{$_} }) } @columns
433 $row{invnumber}->{link} = build_std_url("script=is.pl", 'action=edit') . "&id=" . E($ar->{id}) . "&callback=${callback}";
435 # use partdescription according to invoice in article mode
436 $row{description}->{data} = $ar->{invoice_description};
438 $report->add_data(\%row);
441 # choosing l_subtotal doesn't make a distinction between mainsort and subsort
442 # if l_subtotal_mainsort is not selected l_subtotal_subsort isn't run either
443 if ( ($form->{l_subtotal_mainsort} eq 'Y')
444 && ($form->{l_subtotal_subsort} eq 'Y')
445 && (($idx == (scalar @{ $form->{AR} } - 1)) # last element always has a subtotal
446 || ($ar->{ $form->{'subsort'} } ne $form->{AR}->[$idx + 1]->{ $form->{'subsort'} })
447 || ($ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx + 1]->{ $form->{'mainsort'} })
448 )) { # if value that is sorted by changes, print subtotal
450 $report->add_data(create_subtotal_row_invoice(\%subtotals2, \@columns, \%column_alignment, \@subtotal_columns, $form->{l_parts} ? 'listsubtotal' : undef, $ar->{ $form->{'subsort'} }));
451 $report->add_data({ %empty_row }) if $form->{l_parts} and $addemptylines;
454 # if last mainsort is reached or mainsort has changed, add mainsort subtotal and empty row
455 if ( ($form->{l_subtotal_mainsort} eq 'Y')
456 && ($form->{l_subtotal_mainsort} eq 'Y')
457 && ($form->{mainsort} ne $form->{subsort})
458 && (($idx == (scalar @{ $form->{AR} } - 1)) # last element always has a subtotal
459 || ($ar->{ $form->{'mainsort'} } ne $form->{AR}->[$idx + 1]->{ $form->{'mainsort'} })
460 )) { # if value that is sorted by changes, print subtotal
461 # subtotal is overridden if mainsort and subsort are equal, don't print
462 # subtotal line even if it is selected
463 $report->add_data(create_subtotal_row_invoice(\%subtotals1, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal', $ar->{$form->{mainsort}}));
464 $report->add_data({ %empty_row }) if $addemptylines; # insert empty row after mainsort
469 if ( $form->{l_total} eq "Y" ) {
470 $report->add_separator();
471 $report->add_data(create_subtotal_row_invoice(\%totals, \@columns, \%column_alignment, \@total_columns, 'listtotal', 'l_total'))
474 $report->generate_with_headers();
475 $main::lxdebug->leave_sub();
478 sub create_subtotal_row_invoice {
479 $main::lxdebug->enter_sub();
481 my ($totals, $columns, $column_alignment, $subtotal_columns, $class, $name) = @_;
483 my $form = $main::form;
484 my %myconfig = %main::myconfig;
485 my $locale = $main::locale;
487 my $row = { map { $_ => { data => '', class => $class, align => $column_alignment->{$_}, } } @{ $columns } };
489 # set name as "empty" if no value is given, except if we are dealing with the
490 # absolute total, then just write "Total sum"
491 # here we assume that no name will be called 'l_total'
492 $name = $locale->text('empty') unless $name;
493 if ( $name eq 'l_total' ) {
494 $row->{description}->{data} = $locale->text('Total sum');
496 $row->{description}->{data} = $locale->text('Total') . ' ' . $name;
499 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } qw(marge_total marge_percent qty);
500 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 3) } qw(weight);
501 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, $form->{decimalplaces}) } qw(lastcost sellprice sellprice_total lastcost_total);
504 map { $totals->{$_} = 0 } @{ $subtotal_columns };
506 $main::lxdebug->leave_sub();