X-Git-Url: http://wagnertech.de/git?a=blobdiff_plain;f=SL%2FForm.pm;h=56e46f798d12f7aadc6f311bd1cf4626822ba00c;hb=b364553bd1c69d15999e3269649fa9a8b55eb8c3;hp=f893c63aabf5ac5a1ea975276b8402bb276a6a3e;hpb=777bf75cfcfc81a87479a508ea900de4a64c483e;p=kivitendo-erp.git diff --git a/SL/Form.pm b/SL/Form.pm index f893c63aa..56e46f798 100644 --- a/SL/Form.pm +++ b/SL/Form.pm @@ -36,27 +36,40 @@ #====================================================================== package Form; + use Data::Dumper; -use Cwd; -use Template; -use SL::Template; +use CGI; use CGI::Ajax; +use Cwd; +use IO::File; +use SL::Auth; +use SL::Auth::DB; +use SL::Auth::LDAP; +use SL::AM; +use SL::Common; use SL::DBUtils; use SL::Mailer; use SL::Menu; +use SL::Template; use SL::User; -use SL::Common; -use CGI; -use List::Util qw(max min sum); +use Template; +use URI; +use List::Util qw(first max min sum); +use List::MoreUtils qw(any); + +use strict; my $standard_dbh; -sub DESTROY { - if ($standard_dbh) { - $standard_dbh->disconnect(); - undef $standard_dbh; - } +END { + disconnect_standard_dbh(); +} + +sub disconnect_standard_dbh { + return unless $standard_dbh; + $standard_dbh->disconnect(); + undef $standard_dbh; } sub _store_value { @@ -66,30 +79,29 @@ sub _store_value { my $key = shift; my $value = shift; - my $curr = $self; + my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key; - while ($key =~ /\[\+?\]\.|\./) { - substr($key, 0, $+[0]) = ''; + my $curr; - if ($& eq '.') { - $curr->{$`} ||= { }; - $curr = $curr->{$`}; + if (scalar @tokens) { + $curr = \ $self->{ shift @tokens }; + } - } else { - $curr->{$`} ||= [ ]; - if (!scalar @{ $curr->{$`} } || $& eq '[+].') { - push @{ $curr->{$`} }, { }; - } + while (@tokens) { + my $sep = shift @tokens; + my $key = shift @tokens; - $curr = $curr->{$`}->[-1]; - } + $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]'; + $curr = \ $$curr->[max 0, $#$$curr] if $sep eq '[].'; + $curr = \ $$curr->[++$#$$curr] if $sep eq '[+].'; + $curr = \ $$curr->{$key} } - $curr->{$key} = $value; + $$curr = $value; $main::lxdebug->leave_sub(2); - return \$curr->{$key}; + return $curr; } sub _input_to_hash { @@ -102,7 +114,7 @@ sub _input_to_hash { foreach (@pairs) { my ($key, $value) = split(/=/, $_, 2); - $self->_store_value($self->unescape($key), $self->unescape($value)); + $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key); } $main::lxdebug->leave_sub(2); @@ -165,7 +177,7 @@ sub _request_to_hash { substr $line, $-[0], $+[0] - $-[0], ""; } - $previous = $self->_store_value($name, ''); + $previous = $self->_store_value($name, '') if ($name); $self->{FILENAME} = $filename if ($filename); next; @@ -188,6 +200,37 @@ sub _request_to_hash { $main::lxdebug->leave_sub(2); } +sub _recode_recursively { + $main::lxdebug->enter_sub(); + my ($iconv, $param) = @_; + + if (any { ref $param eq $_ } qw(Form HASH)) { + foreach my $key (keys %{ $param }) { + if (!ref $param->{$key}) { + # Workaround for a bug: converting $param->{$key} directly + # leads to 'undef'. I don't know why. Converting a copy works, + # though. + $param->{$key} = $iconv->convert("" . $param->{$key}); + } else { + _recode_recursively($iconv, $param->{$key}); + } + } + + } elsif (ref $param eq 'ARRAY') { + foreach my $idx (0 .. scalar(@{ $param }) - 1) { + if (!ref $param->[$idx]) { + # Workaround for a bug: converting $param->[$idx] directly + # leads to 'undef'. I don't know why. Converting a copy works, + # though. + $param->[$idx] = $iconv->convert("" . $param->[$idx]); + } else { + _recode_recursively($iconv, $param->[$idx]); + } + } + } + $main::lxdebug->leave_sub(); +} + sub new { $main::lxdebug->enter_sub(); @@ -200,24 +243,33 @@ sub new { tie %{ $self }, 'SL::Watchdog'; } - read(STDIN, $_, $ENV{CONTENT_LENGTH}); + bless $self, $type; - if ($ENV{QUERY_STRING}) { - $_ = $ENV{QUERY_STRING}; - } + $self->_input_to_hash($ENV{QUERY_STRING}) if $ENV{QUERY_STRING}; + $self->_input_to_hash($ARGV[0]) if @ARGV && $ARGV[0]; - if ($ARGV[0]) { - $_ = $ARGV[0]; + if ($ENV{CONTENT_LENGTH}) { + my $content; + read STDIN, $content, $ENV{CONTENT_LENGTH}; + $self->_request_to_hash($content); } - bless $self, $type; + my $db_charset = $main::dbcharset; + $db_charset ||= Common::DEFAULT_CHARSET; + + my $encoding = $self->{INPUT_ENCODING} || $db_charset; + delete $self->{INPUT_ENCODING}; - $self->_request_to_hash($_); + _recode_recursively(SL::Iconv->new($encoding, $db_charset), $self); $self->{action} = lc $self->{action}; $self->{action} =~ s/( |-|,|\#)/_/g; - $self->{version} = "2.4.3"; + #$self->{version} = "2.6.1"; # Old hardcoded but secure style + open VERSION_FILE, "VERSION"; # New but flexible code reads version from VERSION-file + $self->{version} = ; + close VERSION_FILE; + $self->{version} =~ s/[^0-9A-Za-z\.\_\-]//g; # only allow numbers, letters, points, underscores and dashes. Prevents injecting of malicious code. $main::lxdebug->leave_sub(); @@ -275,6 +327,22 @@ sub flatten_variables { return @variables; } +sub flatten_standard_variables { + $main::lxdebug->enter_sub(2); + + my $self = shift; + my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_); + + my @variables; + + foreach (grep { ! $skip_keys{$_} } keys %{ $self }) { + push @variables, $self->_flatten_variables_rec($self, '', $_); + } + + $main::lxdebug->leave_sub(2); + + return @variables; +} sub debug { $main::lxdebug->enter_sub(); @@ -288,6 +356,24 @@ sub debug { $main::lxdebug->leave_sub(); } +sub dumper { + $main::lxdebug->enter_sub(2); + + my $self = shift; + my $password = $self->{password}; + + $self->{password} = 'X' x 8; + + local $Data::Dumper::Sortkeys = 1; + my $output = Dumper($self); + + $self->{password} = $password; + + $main::lxdebug->leave_sub(2); + + return $output; +} + sub escape { $main::lxdebug->enter_sub(2); @@ -316,47 +402,33 @@ sub unescape { } sub quote { + $main::lxdebug->enter_sub(); my ($self, $str) = @_; if ($str && !ref($str)) { $str =~ s/\"/"/g; } - $str; + $main::lxdebug->leave_sub(); + return $str; } sub unquote { + $main::lxdebug->enter_sub(); my ($self, $str) = @_; if ($str && !ref($str)) { $str =~ s/"/\"/g; } - $str; - -} - -sub quote_html { - $main::lxdebug->enter_sub(2); - - my ($self, $str) = @_; - - my %replace = - ('order' => ['"', '<', '>'], - '<' => '<', - '>' => '>', - '"' => '"', - ); - - map({ $str =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} }); - - $main::lxdebug->leave_sub(2); + $main::lxdebug->leave_sub(); return $str; } sub hide_form { + $main::lxdebug->enter_sub(); my $self = shift; if (@_) { @@ -367,7 +439,7 @@ sub hide_form { print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } } - + $main::lxdebug->leave_sub(); } sub error { @@ -381,8 +453,8 @@ sub error { $self->show_generic_error($msg); } else { - - die "Error: $msg\n"; + print STDERR "Error: $msg\n"; + ::end_of_request(); } $main::lxdebug->leave_sub(); @@ -398,13 +470,22 @@ sub info { if (!$self->{header}) { $self->header; - print qq| - |; + print qq||; } print qq| - -

$msg +

$msg

+ + + + |; } else { @@ -423,13 +504,16 @@ sub info { # can be capped with maxrows sub numtextrows { $main::lxdebug->enter_sub(); - my ($self, $str, $cols, $maxrows) = @_; + my ($self, $str, $cols, $maxrows, $minrows) = @_; + + $minrows ||= 1; my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str; $maxrows ||= $rows; $main::lxdebug->leave_sub(); - return min $rows, $maxrows; + + return max(min($rows, $maxrows), $minrows); } sub dberror { @@ -448,7 +532,7 @@ sub isblank { my ($self, $name, $msg) = @_; my $curr = $self; - foreach my $part (split '.', $name) { + foreach my $part (split m/\./, $name) { if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) { $self->error($msg); } @@ -458,9 +542,82 @@ sub isblank { $main::lxdebug->leave_sub(); } +sub _get_request_uri { + my $self = shift; + + return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR}; + + my $scheme = $ENV{HTTPS} && (lc $ENV{HTTPS} eq 'on') ? 'https' : 'http'; + my $port = $ENV{SERVER_PORT} || ''; + $port = undef if (($scheme eq 'http' ) && ($port == 80)) + || (($scheme eq 'https') && ($port == 443)); + + my $uri = URI->new("${scheme}://"); + $uri->scheme($scheme); + $uri->port($port); + $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR}); + $uri->path_query($ENV{REQUEST_URI}); + $uri->query(''); + + return $uri; +} + +sub _add_to_request_uri { + my $self = shift; + + my $relative_new_path = shift; + my $request_uri = shift || $self->_get_request_uri; + my $relative_new_uri = URI->new($relative_new_path); + my @request_segments = $request_uri->path_segments; + + my $new_uri = $request_uri->clone; + $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments); + + return $new_uri; +} + +sub create_http_response { + $main::lxdebug->enter_sub(); + + my $self = shift; + my %params = @_; + + my $cgi = $main::cgi; + $cgi ||= CGI->new(''); + + my $session_cookie; + if (defined $main::auth) { + my $uri = $self->_get_request_uri; + my @segments = $uri->path_segments; + pop @segments; + $uri->path_segments(@segments); + + my $session_cookie_value = $main::auth->get_session_id(); + $session_cookie_value ||= 'NO_SESSION'; + + $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(), + '-value' => $session_cookie_value, + '-path' => $uri->path, + '-secure' => $ENV{HTTPS}); + } + + my %cgi_params = ('-type' => $params{content_type}); + $cgi_params{'-charset'} = $params{charset} if ($params{charset}); + + my $output = $cgi->header('-cookie' => $session_cookie, + %cgi_params); + + $main::lxdebug->leave_sub(); + + return $output; +} + + sub header { $main::lxdebug->enter_sub(); + # extra code ist currently only used by menuv3 and menuv4 to set their css. + # it is strongly deprecated, and will be changed in a future version. my ($self, $extra_code) = @_; if ($self->{header}) { @@ -468,7 +625,7 @@ sub header { return; } - my ($stylesheet, $favicon); + my ($stylesheet, $favicon, $pagelayout); if ($ENV{HTTP_USER_AGENT}) { my $doctype; @@ -505,13 +662,37 @@ sub header { |; } - my $fokus = qq| document.$self->{fokus}.focus();| if ($self->{"fokus"}); + my $fokus = qq| + + | if $self->{"fokus"}; + + # if there is a title, we put some JavaScript in to the page, wich writes a + # meaningful title-tag for our frameset. + my $title_hack; + if ($self->{"title"}){ + $title_hack = qq| + + |; + } #Set Calendar my $jsscript = ""; if ($self->{jsscript} == 1) { $jsscript = qq| + + @@ -525,40 +706,36 @@ sub header { ? "$self->{title} - $self->{titlebar}" : $self->{titlebar}; my $ajax = ""; - foreach $item (@ { $self->{AJAX} }) { + for my $item (@ { $self->{AJAX} || [] }) { $ajax .= $item->show_javascript(); } - print qq|Content-Type: text/html; charset=${db_charset}; -${doctype} + print $self->create_http_response('content_type' => 'text/html', + 'charset' => $db_charset,); + print qq|${doctype} + $self->{titlebar} $stylesheet $pagelayout $favicon - $jsscript $ajax + $fokus + $title_hack - + - - + @@ -572,38 +749,73 @@ ${doctype} $main::lxdebug->leave_sub(); } +sub ajax_response_header { + $main::lxdebug->enter_sub(); + + my ($self) = @_; + + my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET; + my $cgi = $main::cgi || CGI->new(''); + my $output = $cgi->header('-charset' => $db_charset); + + $main::lxdebug->leave_sub(); + + return $output; +} + +sub redirect_header { + my $self = shift; + my $new_url = shift; + + my $base_uri = $self->_get_request_uri; + my $new_uri = URI->new_abs($new_url, $base_uri); + + die "Headers already sent" if $::self->{header}; + $self->{header} = 1; + + my $cgi = $main::cgi || CGI->new(''); + return $cgi->redirect($new_uri); +} + +sub set_standard_title { + $::lxdebug->enter_sub; + my $self = shift; + + $self->{titlebar} = "Lx-Office " . $::locale->text('Version') . " $self->{version}"; + $self->{titlebar} .= "- $::myconfig{name}" if $::myconfig{name}; + $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name}; + + $::lxdebug->leave_sub; +} + sub _prepare_html_template { $main::lxdebug->enter_sub(); my ($self, $file, $additional_params) = @_; my $language; - if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) { + if (!%::myconfig || !$::myconfig{"countrycode"}) { $language = $main::language; } else { $language = $main::myconfig{"countrycode"}; } $language = "de" unless ($language); - if (-f "templates/webpages/${file}_${language}.html") { - if ((-f ".developer") && - (-f "templates/webpages/${file}_master.html") && - ((stat("templates/webpages/${file}_master.html"))[9] > - (stat("templates/webpages/${file}_${language}.html"))[9])) { - my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" . + if (-f "templates/webpages/${file}.html") { + if ((-f ".developer") && ((stat("templates/webpages/${file}.html"))[9] > (stat("locale/${language}/all"))[9])) { + my $info = "Developer information: templates/webpages/${file}.html is newer than the translation file locale/${language}/all.\n" . "Please re-run 'locales.pl' in 'locale/${language}'."; print(qq|
$info
|); - die($info); + ::end_of_request(); } - $file = "templates/webpages/${file}_${language}.html"; - } elsif (-f "templates/webpages/${file}.html") { $file = "templates/webpages/${file}.html"; + } else { my $info = "Web page template '${file}' not found.\n" . "Please re-run 'locales.pl' in 'locale/${language}'."; print(qq|
$info
|); - die($info); + ::end_of_request(); } if ($self->{"DEBUG"}) { @@ -622,17 +834,27 @@ sub _prepare_html_template { $jsc_dateformat =~ s/m+/\%m/gi; $jsc_dateformat =~ s/y+/\%Y/gi; $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat; + $additional_params->{"myconfig"} ||= \%::myconfig; } + $additional_params->{"conf_dbcharset"} = $main::dbcharset; $additional_params->{"conf_webdav"} = $main::webdav; $additional_params->{"conf_lizenzen"} = $main::lizenzen; $additional_params->{"conf_latex_templates"} = $main::latex; $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates; + $additional_params->{"conf_vertreter"} = $main::vertreter; + $additional_params->{"conf_show_best_before"} = $main::show_best_before; if (%main::debug_options) { map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options; } + if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) { + while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) { + $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value; + } + } + $main::lxdebug->leave_sub(); return $file; @@ -645,58 +867,81 @@ sub parse_html_template { $additional_params ||= { }; - $file = $self->_prepare_html_template($file, $additional_params); - - my $template = Template->new({ 'INTERPOLATE' => 0, - 'EVAL_PERL' => 0, - 'ABSOLUTE' => 1, - 'CACHE_SIZE' => 0, - 'PLUGIN_BASE' => 'SL::Template::Plugin', - 'INCLUDE_PATH' => '.:templates/webpages', - }) || die; + my $real_file = $self->_prepare_html_template($file, $additional_params); + my $template = $self->template || $self->init_template; map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self }; my $output; - if (!$template->process($file, $additional_params, \$output)) { - print STDERR $template->error(); - } - - $output = $main::locale->{iconv}->convert($output) if ($main::locale); + $template->process($real_file, $additional_params, \$output) || die $template->error; $main::lxdebug->leave_sub(); return $output; } +sub init_template { + my $self = shift; + + return if $self->template; + + return $self->template(Template->new({ + 'INTERPOLATE' => 0, + 'EVAL_PERL' => 0, + 'ABSOLUTE' => 1, + 'CACHE_SIZE' => 0, + 'PLUGIN_BASE' => 'SL::Template::Plugin', + 'INCLUDE_PATH' => '.:templates/webpages', + 'COMPILE_EXT' => '.tcc', + 'COMPILE_DIR' => $::userspath . '/templates-cache', + })) || die; +} + +sub template { + my $self = shift; + $self->{template_object} = shift if @_; + return $self->{template_object}; +} + sub show_generic_error { - my ($self, $error, $title, $action) = @_; + $main::lxdebug->enter_sub(); + + my ($self, $error, %params) = @_; my $add_params = { - 'title_error' => $title, + 'title_error' => $params{title}, 'label_error' => $error, }; - my @vars; - if ($action) { - map({ delete($self->{$_}); } qw(action)); - map({ push(@vars, { "name" => $_, "value" => $self->{$_} }) - if (!ref($self->{$_})); } - keys(%{$self})); - $add_params->{"SHOW_BUTTON"} = 1; - $add_params->{"BUTTON_LABEL"} = $action; + if ($params{action}) { + my @vars; + + map { delete($self->{$_}); } qw(action); + map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self }; + + $add_params->{SHOW_BUTTON} = 1; + $add_params->{BUTTON_LABEL} = $params{label} || $params{action}; + $add_params->{VARIABLES} = \@vars; + + } elsif ($params{back_button}) { + $add_params->{SHOW_BACK_BUTTON} = 1; } - $add_params->{"VARIABLES"} = \@vars; - $self->{title} = $title if ($title); + $self->{title} = $params{title} if $params{title}; $self->header(); print $self->parse_html_template("generic/error", $add_params); - die("Error: $error\n"); + print STDERR "Error: $error\n"; + + $main::lxdebug->leave_sub(); + + ::end_of_request(); } sub show_generic_information { + $main::lxdebug->enter_sub(); + my ($self, $text, $title) = @_; my $add_params = { @@ -709,7 +954,9 @@ sub show_generic_information { $self->header(); print $self->parse_html_template("generic/information", $add_params); - die("Information: $error\n"); + $main::lxdebug->leave_sub(); + + ::end_of_request(); } # write Trigger JavaScript-Code ($qty = quantity of Triggers) @@ -732,8 +979,8 @@ sub write_trigger { "yyyy-mm-dd" => "%Y-%m-%d", ); - my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ? - $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y"; + my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ? + $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y"; my @triggers; while ($#_ >= 2) { @@ -764,19 +1011,19 @@ sub redirect { my ($self, $msg) = @_; - if ($self->{callback}) { - - ($script, $argv) = split(/\?/, $self->{callback}, 2); - $script =~ s|.*/||; - $script =~ s|[^a-zA-Z0-9_\.]||g; - exec("perl", "$script", $argv); - - } else { + if (!$self->{callback}) { $self->info($msg); - exit; + ::end_of_request(); } +# my ($script, $argv) = split(/\?/, $self->{callback}, 2); +# $script =~ s|.*/||; +# $script =~ s|[^a-zA-Z0-9_\.]||g; +# exec("perl", "$script", $argv); + + print $::form->redirect_header($self->{callback}); + $main::lxdebug->leave_sub(); } @@ -799,12 +1046,12 @@ sub format_amount { if ($amount eq "") { $amount = 0; } - + # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13 - + my $neg = ($amount =~ s/^-//); my $exp = ($amount =~ m/[e]/) ? 1 : 0; - + if (defined($places) && ($places ne '')) { if (not $exp) { if ($places < 0) { @@ -828,16 +1075,84 @@ sub format_amount { $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne ''); $amount = do { - ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) : - ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) : - ($neg ? "-$amount" : "$amount" ) ; + ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) : + ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) : + ($neg ? "-$amount" : "$amount" ) ; }; $main::lxdebug->leave_sub(2); return $amount; } -# + +sub format_amount_units { + $main::lxdebug->enter_sub(); + + my $self = shift; + my %params = @_; + + my $myconfig = \%main::myconfig; + my $amount = $params{amount} * 1; + my $places = $params{places}; + my $part_unit_name = $params{part_unit}; + my $amount_unit_name = $params{amount_unit}; + my $conv_units = $params{conv_units}; + my $max_places = $params{max_places}; + + if (!$part_unit_name) { + $main::lxdebug->leave_sub(); + return ''; + } + + AM->retrieve_all_units(); + my $all_units = $main::all_units; + + if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) { + $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller'); + } + + if (!scalar @{ $conv_units }) { + my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name; + $main::lxdebug->leave_sub(); + return $result; + } + + my $part_unit = $all_units->{$part_unit_name}; + my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit; + + $amount *= $conv_unit->{factor}; + + my @values; + my $num; + + foreach my $unit (@$conv_units) { + my $last = $unit->{name} eq $part_unit->{name}; + if (!$last) { + $num = int($amount / $unit->{factor}); + $amount -= $num * $unit->{factor}; + } + + if ($last ? $amount : $num) { + push @values, { "unit" => $unit->{name}, + "amount" => $last ? $amount / $unit->{factor} : $num, + "places" => $last ? $places : 0 }; + } + + last if $last; + } + + if (!@values) { + push @values, { "unit" => $part_unit_name, + "amount" => 0, + "places" => 0 }; + } + + my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values; + + $main::lxdebug->leave_sub(); + + return $result; +} sub format_string { $main::lxdebug->enter_sub(2); @@ -854,6 +1169,8 @@ sub format_string { return $input; } +# + sub parse_amount { $main::lxdebug->enter_sub(2); @@ -882,13 +1199,13 @@ sub round_amount { my ($self, $amount, $places) = @_; my $round_amount; - # Rounding like "Kaufmannsrunden" - # Descr. http://de.wikipedia.org/wiki/Rundung - # Inspired by - # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html - # Solves Bug: 189 - # Udo Spallek - $amount = $amount * (10**($places)); + # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung ) + + # Round amounts to eight places before rounding to the requested + # number of places. This gets rid of errors due to internal floating + # point representation. + $amount = $self->round_amount($amount, 8) if $places < 8; + $amount = $amount * (10**($places)); $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places)); $main::lxdebug->leave_sub(2); @@ -901,49 +1218,64 @@ sub parse_template { $main::lxdebug->enter_sub(); my ($self, $myconfig, $userspath) = @_; - my ($template, $out); + my $out; local (*IN, *OUT); $self->{"cwd"} = getcwd(); $self->{"tmpdir"} = $self->{cwd} . "/${userspath}"; + my $ext_for_format; + + my $template_type; if ($self->{"format"} =~ /(opendocument|oasis)/i) { - $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath); + $template_type = 'OpenDocument'; + $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt'; + } elsif ($self->{"format"} =~ /(postscript|pdf)/i) { $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"}; - $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath); - } elsif (($self->{"format"} =~ /html/i) || - (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) { - $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath); - } elsif (($self->{"format"} =~ /xml/i) || - (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) { - $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath); - } elsif ( $self->{"format"} =~ /elsterwinston/i ) { - $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath); - } elsif ( $self->{"format"} =~ /elstertaxbird/i ) { - $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath); + $template_type = 'LaTeX'; + $ext_for_format = 'pdf'; + + } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) { + $template_type = 'HTML'; + $ext_for_format = 'html'; + + } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) { + $template_type = 'XML'; + $ext_for_format = 'xml'; + + } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) { + $template_type = 'xml'; + + } elsif ( $self->{"format"} =~ /excel/i ) { + $template_type = 'Excel'; + $ext_for_format = 'xls'; + } elsif ( defined $self->{'format'}) { $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}"); + } elsif ( $self->{'format'} eq '' ) { $self->error("No Outputformat given: $self->{'format'}"); + } else { #Catch the rest $self->error("Outputformat not defined: $self->{'format'}"); } + my $template = SL::Template::create(type => $template_type, + file_name => $self->{IN}, + form => $self, + myconfig => $myconfig, + userspath => $userspath); + # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be. $self->{"notes"} = $self->{ $self->{"formname"} . "notes" }; - map({ $self->{"employee_${_}"} = $myconfig->{$_}; } - qw(email tel fax name signature company address businessnumber - co_ustid taxnumber duns)); - map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; } - qw(company address signature)); - map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature)); + if (!$self->{employee_id}) { + map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns); + } - map({ $self->{"${_}"} = $myconfig->{$_}; } - qw(co_ustid)); - + map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid); $self->{copies} = 1 if (($self->{copies} *= 1) <= 0); @@ -968,20 +1300,23 @@ sub parse_template { $self->{OUT} = ">$self->{tmpfile}"; } + my $result; + if ($self->{OUT}) { - open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!"); + open OUT, "$self->{OUT}" or $self->error("$self->{OUT} : $!"); + $result = $template->parse(*OUT); + close OUT; + } else { - open(OUT, ">-") or $self->error("STDOUT : $!"); $self->header; + $result = $template->parse(*STDOUT); } - if (!$template->parse(*OUT)) { + if (!$result) { $self->cleanup(); $self->error("$self->{IN} : " . $template->get_error()); } - close(OUT); - if ($template->uses_temp_file() || $self->{media} eq 'email') { if ($self->{media} eq 'email') { @@ -994,14 +1329,15 @@ sub parse_template { $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email}; $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|; $mail->{fileid} = "$fileid."; - $myconfig->{signature} =~ s/\\r\\n/\\n/g; + $myconfig->{signature} =~ s/\r//g; # if we send html or plain text inline if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) { $mail->{contenttype} = "text/html"; - $mail->{message} =~ s/\r\n/
\n/g; - $myconfig->{signature} =~ s/\\n/
\n/g; + $mail->{message} =~ s/\r//g; + $mail->{message} =~ s/\n/
\n/g; + $myconfig->{signature} =~ s/\n/
\n/g; $mail->{message} .= "
\n--
\n$myconfig->{signature}\n
"; open(IN, $self->{tmpfile}) @@ -1015,15 +1351,14 @@ sub parse_template { } else { if (!$self->{"do_not_attach"}) { - @{ $mail->{attachments} } = - ({ "filename" => $self->{"tmpfile"}, - "name" => $self->{"attachment_filename"} ? - $self->{"attachment_filename"} : $self->{"tmpfile"} }); + my $attachment_name = $self->{attachment_filename} || $self->{tmpfile}; + $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format); + $mail->{attachments} = [{ "filename" => $self->{tmpfile}, + "name" => $attachment_name }]; } - $mail->{message} =~ s/\r\n/\n/g; - $myconfig->{signature} =~ s/\\n/\n/g; - $mail->{message} .= "\n-- \n$myconfig->{signature}"; + $mail->{message} =~ s/\r//g; + $mail->{message} .= "\n-- \n$myconfig->{signature}"; } @@ -1045,10 +1380,13 @@ sub parse_template { #print(STDERR "OUT $self->{OUT}\n"); for my $i (1 .. $self->{copies}) { if ($self->{OUT}) { - open(OUT, $self->{OUT}) - or $self->error($self->cleanup . "$self->{OUT} : $!"); + open OUT, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!"); + print OUT while ; + close OUT; + seek IN, 0, 0; + } else { - $self->{attachment_filename} = ($self->{attachment_filename}) + $self->{attachment_filename} = ($self->{attachment_filename}) ? $self->{attachment_filename} : $self->generate_attachment_filename(); @@ -1059,17 +1397,8 @@ Content-Length: $numbytes |; - open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT"); - - } - - while () { - print OUT $_; + $::locale->with_raw_io(\*STDOUT, sub { print while }); } - - close(OUT); - - seek IN, 0, 0; } close(IN); @@ -1084,55 +1413,101 @@ Content-Length: $numbytes } sub get_formname_translation { + $main::lxdebug->enter_sub(); my ($self, $formname) = @_; $formname ||= $self->{formname}; my %formname_translations = ( - bin_list => $main::locale->text('Bin List'), - credit_note => $main::locale->text('Credit Note'), - invoice => $main::locale->text('Invoice'), - packing_list => $main::locale->text('Packing List'), - pick_list => $main::locale->text('Pick List'), - proforma => $main::locale->text('Proforma Invoice'), - purchase_order => $main::locale->text('Purchase Order'), - request_quotation => $main::locale->text('RFQ'), - sales_order => $main::locale->text('Confirmation'), - sales_quotation => $main::locale->text('Quotation'), - storno_invoice => $main::locale->text('Storno Invoice'), - storno_packing_list => $main::locale->text('Storno Packing List'), + bin_list => $main::locale->text('Bin List'), + credit_note => $main::locale->text('Credit Note'), + invoice => $main::locale->text('Invoice'), + packing_list => $main::locale->text('Packing List'), + pick_list => $main::locale->text('Pick List'), + proforma => $main::locale->text('Proforma Invoice'), + purchase_order => $main::locale->text('Purchase Order'), + request_quotation => $main::locale->text('RFQ'), + sales_order => $main::locale->text('Confirmation'), + sales_quotation => $main::locale->text('Quotation'), + storno_invoice => $main::locale->text('Storno Invoice'), + storno_packing_list => $main::locale->text('Storno Packing List'), + sales_delivery_order => $main::locale->text('Delivery Order'), + purchase_delivery_order => $main::locale->text('Delivery Order'), + dunning => $main::locale->text('Dunning'), ); + $main::lxdebug->leave_sub(); return $formname_translations{$formname} } +sub get_number_prefix_for_type { + $main::lxdebug->enter_sub(); + my ($self) = @_; + + my $prefix = + (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv' + : ($self->{type} =~ /_quotation$/) ? 'quo' + : ($self->{type} =~ /_delivery_order$/) ? 'do' + : 'ord'; + + $main::lxdebug->leave_sub(); + return $prefix; +} + +sub get_extension_for_format { + $main::lxdebug->enter_sub(); + my ($self) = @_; + + my $extension = $self->{format} =~ /pdf/i ? ".pdf" + : $self->{format} =~ /postscript/i ? ".ps" + : $self->{format} =~ /opendocument/i ? ".odt" + : $self->{format} =~ /excel/i ? ".xls" + : $self->{format} =~ /html/i ? ".html" + : ""; + + $main::lxdebug->leave_sub(); + return $extension; +} + sub generate_attachment_filename { + $main::lxdebug->enter_sub(); my ($self) = @_; - my $attachment_filename = $self->get_formname_translation(); - my $prefix = - (grep { $self->{"type"} eq $_ } qw(invoice credit_note)) ? "inv" - : ($self->{"type"} =~ /_quotation$/) ? "quo" - : "ord"; - - if ($attachment_filename && $self->{"${prefix}number"}) { - $attachment_filename .= "_" . $self->{"${prefix}number"} - . ( $self->{format} =~ /pdf/i ? ".pdf" - : $self->{format} =~ /postscript/i ? ".ps" - : $self->{format} =~ /opendocument/i ? ".odt" - : $self->{format} =~ /html/i ? ".html" - : ""); - $attachment_filename =~ s/ /_/g; - my %umlaute = ( "ä" => "ae", "ö" => "oe", "ü" => "ue", - "Ä" => "Ae", "Ö" => "Oe", "Ü" => "Ue", "ß" => "ss"); - map { $attachment_filename =~ s/$_/$umlaute{$_}/g } keys %umlaute; + my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation()); + my $prefix = $self->get_number_prefix_for_type(); + + if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) { + $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format(); + + } elsif ($attachment_filename && $self->{"${prefix}number"}) { + $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format(); + } else { $attachment_filename = ""; } + $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename); + $attachment_filename =~ s|[\s/\\]+|_|g; + + $main::lxdebug->leave_sub(); return $attachment_filename; } +sub generate_email_subject { + $main::lxdebug->enter_sub(); + my ($self) = @_; + + my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation()); + my $prefix = $self->get_number_prefix_for_type(); + + if ($subject && $self->{"${prefix}number"}) { + $subject .= " " . $self->{"${prefix}number"} + } + + $main::lxdebug->leave_sub(); + return $subject; +} + sub cleanup { $main::lxdebug->enter_sub(); @@ -1147,7 +1522,7 @@ sub cleanup { close(FH); } - if ($self->{tmpfile}) { + if ($self->{tmpfile} && ! $::keep_temp_files) { $self->{tmpfile} =~ s|.*/||g; # strip extension $self->{tmpfile} =~ s/\.\w+$//g; @@ -1166,6 +1541,7 @@ sub datetonum { $main::lxdebug->enter_sub(); my ($self, $date, $myconfig) = @_; + my ($yy, $mm, $dd); if ($date && $date =~ /\D/) { @@ -1197,15 +1573,21 @@ sub datetonum { # Database routines used throughout +sub _dbconnect_options { + my $self = shift; + my $options = { pg_enable_utf8 => $::locale->is_utf8, + @_ }; + + return $options; +} + sub dbconnect { $main::lxdebug->enter_sub(2); my ($self, $myconfig) = @_; # connect to database - my $dbh = - DBI->connect($myconfig->{dbconnect}, - $myconfig->{dbuser}, $myconfig->{dbpasswd}) + my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options) or $self->dberror; # set db options @@ -1222,11 +1604,9 @@ sub dbconnect_noauto { $main::lxdebug->enter_sub(); my ($self, $myconfig) = @_; - + # connect to database - $dbh = - DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, - $myconfig->{dbpasswd}, { AutoCommit => 0 }) + my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options(AutoCommit => 0)) or $self->dberror; # set db options @@ -1242,7 +1622,13 @@ sub dbconnect_noauto { sub get_standard_dbh { $main::lxdebug->enter_sub(2); - my ($self, $myconfig) = @_; + my $self = shift; + my $myconfig = shift || \%::myconfig; + + if ($standard_dbh && !$standard_dbh->{Active}) { + $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore"); + undef $standard_dbh; + } $standard_dbh ||= $self->dbconnect_noauto($myconfig); @@ -1251,6 +1637,21 @@ sub get_standard_dbh { return $standard_dbh; } +sub date_closed { + $main::lxdebug->enter_sub(); + + my ($self, $date, $myconfig) = @_; + my $dbh = $self->dbconnect($myconfig); + + my $query = "SELECT 1 FROM defaults WHERE ? < closedto"; + my $sth = prepare_execute_query($self, $dbh, $query, $date); + my ($closed) = $sth->fetchrow_array; + + $main::lxdebug->leave_sub(); + + return $closed; +} + sub update_balance { $main::lxdebug->enter_sub(); @@ -1283,7 +1684,7 @@ sub update_exchangerate { if ($curr eq '') { $main::lxdebug->leave_sub(); return; - } + } $query = qq|SELECT curr FROM defaults|; my ($currency) = selectrow_query($self, $dbh, $query); @@ -1324,7 +1725,7 @@ sub update_exchangerate { SET $set WHERE curr = ? AND transdate = ?|; - + } else { $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate) VALUES (?, $buy, $sell, ?)|; @@ -1393,6 +1794,10 @@ sub check_exchangerate { my ($self, $myconfig, $currency, $transdate, $fld) = @_; + if ($fld !~/^buy|sell$/) { + $self->error('Fatal: check_exchangerate called with invalid buy/sell argument'); + } + unless ($transdate) { $main::lxdebug->leave_sub(); return ""; @@ -1411,29 +1816,38 @@ sub check_exchangerate { my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate); - $exchangerate = 1 if ($exchangerate eq ""); - $main::lxdebug->leave_sub(); return $exchangerate; } -sub get_default_currency { +sub get_all_currencies { $main::lxdebug->enter_sub(); - my ($self, $myconfig) = @_; - my $dbh = $self->get_standard_dbh($myconfig); + my $self = shift; + my $myconfig = shift || \%::myconfig; + my $dbh = $self->get_standard_dbh($myconfig); my $query = qq|SELECT curr FROM defaults|; - my ($curr) = selectrow_query($self, $dbh, $query); - my ($defaultcurrency) = split m/:/, $curr; + my ($curr) = selectrow_query($self, $dbh, $query); + my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr; $main::lxdebug->leave_sub(); - return $defaultcurrency; + return @currencies; } +sub get_default_currency { + $main::lxdebug->enter_sub(); + + my ($self, $myconfig) = @_; + my @currencies = $self->get_all_currencies($myconfig); + + $main::lxdebug->leave_sub(); + + return $currencies[0]; +} sub set_payment_options { $main::lxdebug->enter_sub(); @@ -1482,6 +1896,7 @@ sub set_payment_options { $amounts{invtotal} = $self->{invtotal}; $amounts{total} = $self->{total}; } + $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto}; map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts; @@ -1535,6 +1950,8 @@ sub set_payment_options { map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts; + $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent}; + $main::lxdebug->leave_sub(); } @@ -1637,7 +2054,7 @@ sub add_shipto { shiptophone = ? AND shiptofax = ? AND shiptoemail = ? AND - module = ? AND + module = ? AND trans_id = ?|; my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id); if(!$insert_check){ @@ -1659,6 +2076,8 @@ sub get_employee { my ($self, $dbh) = @_; + $dbh ||= $self->get_standard_dbh(\%main::myconfig); + my $query = qq|SELECT id, name FROM employee WHERE login = ?|; ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login}); $self->{"employee_id"} *= 1; @@ -1666,30 +2085,31 @@ sub get_employee { $main::lxdebug->leave_sub(); } -sub get_salesman { +sub get_employee_data { $main::lxdebug->enter_sub(); - my ($self, $myconfig, $salesman_id) = @_; + my $self = shift; + my %params = @_; - $main::lxdebug->leave_sub() and return unless $salesman_id; + Common::check_params(\%params, qw(prefix)); + Common::check_params_x(\%params, qw(id)); - my $dbh = $self->get_standard_dbh($myconfig); + if (!$params{id}) { + $main::lxdebug->leave_sub(); + return; + } - my ($login) = - selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, - $salesman_id); + my $myconfig = \%main::myconfig; + my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig); - if ($login) { - my $user = new User($main::memberfile, $login); - map({ $self->{"salesman_$_"} = $user->{$_}; } - qw(address businessnumber co_ustid company duns email fax name - taxnumber tel)); - $self->{salesman_login} = $login; + my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id})); - $self->{salesman_name} = $login - if ($self->{salesman_name} eq ""); + if ($login) { + my $user = User->new($login); + map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel); - map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company)); + $self->{$params{prefix} . '_login'} = $login; + $self->{$params{prefix} . '_name'} ||= $login; } $main::lxdebug->leave_sub(); @@ -1698,13 +2118,17 @@ sub get_salesman { sub get_duedate { $main::lxdebug->enter_sub(); - my ($self, $myconfig) = @_; + my ($self, $myconfig, $reference_date) = @_; - my $dbh = $self->get_standard_dbh($myconfig); - my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|; - ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id}); + $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date'; + + my $dbh = $self->get_standard_dbh($myconfig); + my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|; + my ($duedate) = selectrow_query($self, $dbh, $query, $self->{payment_id}); $main::lxdebug->leave_sub(); + + return $duedate; } sub _get_contacts { @@ -1714,6 +2138,12 @@ sub _get_contacts { $key = "all_contacts" unless ($key); + if (!$id) { + $self->{$key} = []; + $main::lxdebug->leave_sub(); + return; + } + my $query = qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | . qq|FROM contacts | . @@ -1782,10 +2212,15 @@ sub _get_shipto { $key = "all_shipto" unless ($key); - # get shipping addresses - my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|; + if ($vc_id) { + # get shipping addresses + my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|; + + $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id); - $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id); + } else { + $self->{$key} = []; + } $main::lxdebug->leave_sub(); } @@ -1808,6 +2243,7 @@ sub _get_charts { $main::lxdebug->enter_sub(); my ($self, $dbh, $params) = @_; + my ($key); $key = $params->{key}; $key = "all_charts" unless ($key); @@ -1815,7 +2251,7 @@ sub _get_charts { my $transdate = quote_db_date($params->{transdate}); my $query = - qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | . + qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | . qq|FROM chart c | . qq|LEFT JOIN taxkeys tk ON | . qq|(tk.id = (SELECT id FROM taxkeys | . @@ -1831,11 +2267,27 @@ sub _get_charts { sub _get_taxcharts { $main::lxdebug->enter_sub(); - my ($self, $dbh, $key) = @_; + my ($self, $dbh, $params) = @_; - $key = "all_taxcharts" unless ($key); + my $key = "all_taxcharts"; + my @where; - my $query = qq|SELECT * FROM tax ORDER BY taxkey|; + if (ref $params eq 'HASH') { + $key = $params->{key} if ($params->{key}); + if ($params->{module} eq 'AR') { + push @where, 'taxkey NOT IN (8, 9, 18, 19)'; + + } elsif ($params->{module} eq 'AP') { + push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)'; + } + + } elsif ($params) { + $key = $params; + } + + my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where); + + my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|; $self->{$key} = selectall_hashref_query($self, $dbh, $query); @@ -1862,7 +2314,7 @@ sub _get_employees { my ($self, $dbh, $default_key, $key) = @_; $key = $default_key unless ($key); - $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|); + $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|); $main::lxdebug->leave_sub(); } @@ -1872,9 +2324,15 @@ sub _get_business_types { my ($self, $dbh, $key) = @_; - $key = "all_business_types" unless ($key); - $self->{$key} = - selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|); + my $options = ref $key eq 'HASH' ? $key : { key => $key }; + $options->{key} ||= "all_business_types"; + my $where = ''; + + if (exists $options->{salesman}) { + $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)'; + } + + $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|); $main::lxdebug->leave_sub(); } @@ -1915,7 +2373,7 @@ $main::lxdebug->enter_sub(); $key = "all_currencies" unless ($key); my $query = qq|SELECT curr AS currency FROM defaults|; - + $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})]; $main::lxdebug->leave_sub(); @@ -1929,7 +2387,7 @@ $main::lxdebug->enter_sub(); $key = "all_payments" unless ($key); my $query = qq|SELECT * FROM payment_terms ORDER BY id|; - + $self->{$key} = selectall_hashref_query($self, $dbh, $query); $main::lxdebug->leave_sub(); @@ -1938,14 +2396,19 @@ $main::lxdebug->enter_sub(); sub _get_customers { $main::lxdebug->enter_sub(); - my ($self, $dbh, $key, $limit) = @_; + my ($self, $dbh, $key) = @_; - $key = "all_customers" unless ($key); - $limit_clause = "LIMIT $limit" if $limit; + my $options = ref $key eq 'HASH' ? $key : { key => $key }; + $options->{key} ||= "all_customers"; + my $limit_clause = "LIMIT $options->{limit}" if $options->{limit}; - my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|; + my @where; + push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman}; + push @where, qq|NOT obsolete| if !$options->{with_obsolete}; + my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : ''; - $self->{$key} = selectall_hashref_query($self, $dbh, $query); + my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|; + $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query); $main::lxdebug->leave_sub(); } @@ -1978,20 +2441,73 @@ sub _get_departments { $main::lxdebug->leave_sub(); } -sub _get_price_factors { +sub _get_warehouses { $main::lxdebug->enter_sub(); - my ($self, $dbh, $key) = @_; + my ($self, $dbh, $param) = @_; - $key ||= "all_price_factors"; + my ($key, $bins_key); - my $query = qq|SELECT * FROM price_factors ORDER BY sortkey|; + if ('' eq ref $param) { + $key = $param; + + } else { + $key = $param->{key}; + $bins_key = $param->{bins}; + } + + my $query = qq|SELECT w.* FROM warehouse w + WHERE (NOT w.invalid) AND + ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0) + ORDER BY w.sortkey|; + + $self->{$key} = selectall_hashref_query($self, $dbh, $query); + + if ($bins_key) { + $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|; + my $sth = prepare_query($self, $dbh, $query); + + foreach my $warehouse (@{ $self->{$key} }) { + do_statement($self, $sth, $query, $warehouse->{id}); + $warehouse->{$bins_key} = []; + + while (my $ref = $sth->fetchrow_hashref()) { + push @{ $warehouse->{$bins_key} }, $ref; + } + } + $sth->finish(); + } + + $main::lxdebug->leave_sub(); +} + +sub _get_simple { + $main::lxdebug->enter_sub(); + + my ($self, $dbh, $table, $key, $sortkey) = @_; + + my $query = qq|SELECT * FROM $table|; + $query .= qq| ORDER BY $sortkey| if ($sortkey); $self->{$key} = selectall_hashref_query($self, $dbh, $query); $main::lxdebug->leave_sub(); } +#sub _get_groups { +# $main::lxdebug->enter_sub(); +# +# my ($self, $dbh, $key) = @_; +# +# $key ||= "all_groups"; +# +# my $groups = $main::auth->read_groups(); +# +# $self->{$key} = selectall_hashref_query($self, $dbh, $query); +# +# $main::lxdebug->leave_sub(); +#} + sub get_lists { $main::lxdebug->enter_sub(); @@ -2041,7 +2557,7 @@ sub get_lists { if ($params{"employees"}) { $self->_get_employees($dbh, "all_employees", $params{"employees"}); } - + if ($params{"salesmen"}) { $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"}); } @@ -2053,19 +2569,15 @@ sub get_lists { if ($params{"dunning_configs"}) { $self->_get_dunning_configs($dbh, $params{"dunning_configs"}); } - + if($params{"currencies"}) { $self->_get_currencies($dbh, $params{"currencies"}); } - + if($params{"customers"}) { - if (ref $params{"customers"} eq 'HASH') { - $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit}); - } else { - $self->_get_customers($dbh, $params{"customers"}); - } + $self->_get_customers($dbh, $params{"customers"}); } - + if($params{"vendors"}) { if (ref $params{"vendors"} eq 'HASH') { $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit}); @@ -2073,7 +2585,7 @@ sub get_lists { $self->_get_vendors($dbh, $params{"vendors"}); } } - + if($params{"payments"}) { $self->_get_payments($dbh, $params{"payments"}); } @@ -2083,7 +2595,19 @@ sub get_lists { } if ($params{price_factors}) { - $self->_get_price_factors($dbh, $params{price_factors}); + $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey'); + } + + if ($params{warehouses}) { + $self->_get_warehouses($dbh, $params{warehouses}); + } + +# if ($params{groups}) { +# $self->_get_groups($dbh, $params{groups}); +# } + + if ($params{partsgroup}) { + $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} }); } $main::lxdebug->leave_sub(); @@ -2145,7 +2669,7 @@ sub all_vc { my ($self, $myconfig, $table, $module) = @_; my $ref; - my $dbh = $self->get_standard_dbh($myconfig); + my $dbh = $self->get_standard_dbh; $table = $table eq "customer" ? "customer" : "vendor"; @@ -2153,7 +2677,7 @@ sub all_vc { my ($count) = selectrow_query($self, $dbh, $query); # build selection list - if ($count < $myconfig->{vclimit}) { + if ($count <= $myconfig->{vclimit}) { $query = qq|SELECT id, name, salesman_id FROM $table WHERE NOT obsolete ORDER BY name|; @@ -2273,7 +2797,7 @@ sub all_departments { ORDER BY description|; $self->{all_departments} = selectall_hashref_query($self, $dbh, $query); - delete($self->{all_departments}) unless (@{ $self->{all_departments} }); + delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] }); $main::lxdebug->leave_sub(); } @@ -2320,7 +2844,7 @@ sub create_links { do_statement($self, $sth, $query, '%' . $module . '%'); $self->{accounts} = ""; - while ($ref = $sth->fetchrow_hashref(NAME_lc)) { + while ($ref = $sth->fetchrow_hashref("NAME_lc")) { foreach my $key (split(/:/, $ref->{link})) { if ($key =~ /\Q$module\E/) { @@ -2367,7 +2891,7 @@ sub create_links { WHERE a.id = ?|; $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id}); - foreach $key (keys %$ref) { + foreach my $key (keys %$ref) { $self->{$key} = $ref->{$key}; } @@ -2389,7 +2913,7 @@ sub create_links { do_statement($self, $sth, $query, "%$module%"); $self->{accounts} = ""; - while ($ref = $sth->fetchrow_hashref(NAME_lc)) { + while ($ref = $sth->fetchrow_hashref("NAME_lc")) { foreach my $key (split(/:/, $ref->{link})) { if ($key =~ /\Q$module\E/) { @@ -2429,7 +2953,7 @@ sub create_links { (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1)) WHERE a.trans_id = ? AND a.fx_transaction = '0' - ORDER BY a.oid, a.transdate|; + ORDER BY a.acc_trans_id, a.transdate|; $sth = $dbh->prepare($query); do_statement($self, $sth, $query, $self->{id}); @@ -2439,7 +2963,7 @@ sub create_links { my $index = 0; # store amounts in {acc_trans}{$key} for multiple accounts - while (my $ref = $sth->fetchrow_hashref(NAME_lc)) { + while (my $ref = $sth->fetchrow_hashref("NAME_lc")) { $ref->{exchangerate} = $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld); if (!($xkeyref{ $ref->{accno} } =~ /tax/)) { @@ -2500,36 +3024,52 @@ sub lastname_used { my ($self, $dbh, $myconfig, $table, $module) = @_; - my $arap = ($table eq 'customer') ? "ar" : "ap"; - $table = $table eq "customer" ? "customer" : "vendor"; - my $where = "1 = 1"; + my ($arap, $where); + + $table = $table eq "customer" ? "customer" : "vendor"; + my %column_map = ("a.curr" => "currency", + "a.${table}_id" => "${table}_id", + "a.department_id" => "department_id", + "d.description" => "department", + "ct.name" => $table, + "current_date + ct.terms" => "duedate", + ); - if ($self->{type} =~ /_order/) { + if ($self->{type} =~ /delivery_order/) { + $arap = 'delivery_orders'; + delete $column_map{"a.curr"}; + + } elsif ($self->{type} =~ /_order/) { $arap = 'oe'; $where = "quotation = '0'"; - } - if ($self->{type} =~ /_quotation/) { + + } elsif ($self->{type} =~ /_quotation/) { $arap = 'oe'; $where = "quotation = '1'"; + + } elsif ($table eq 'customer') { + $arap = 'ar'; + + } else { + $arap = 'ap'; + } - my $query = qq|SELECT MAX(id) FROM $arap - WHERE $where AND ${table}_id > 0|; - my ($trans_id) = selectrow_query($self, $dbh, $query); + $where = "($where) AND" if ($where); + my $query = qq|SELECT MAX(id) FROM $arap + WHERE $where ${table}_id > 0|; + my ($trans_id) = selectrow_query($self, $dbh, $query); + $trans_id *= 1; - $trans_id *= 1; - $query = - qq|SELECT - a.curr, a.${table}_id, a.department_id, - d.description AS department, - ct.name, current_date + ct.terms AS duedate - FROM $arap a - LEFT JOIN $table ct ON (a.${table}_id = ct.id) - LEFT JOIN department d ON (a.department_id = d.id) - WHERE a.id = ?|; - ($self->{currency}, $self->{"${table}_id"}, $self->{department_id}, - $self->{department}, $self->{$table}, $self->{duedate}) - = selectrow_query($self, $dbh, $query, $trans_id); + my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map); + $query = qq|SELECT $column_spec + FROM $arap a + LEFT JOIN $table ct ON (a.${table}_id = ct.id) + LEFT JOIN department d ON (a.department_id = d.id) + WHERE a.id = ?|; + my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id); + + map { $self->{$_} = $ref->{$_} } values %column_map; $main::lxdebug->leave_sub(); } @@ -2537,7 +3077,9 @@ sub lastname_used { sub current_date { $main::lxdebug->enter_sub(); - my ($self, $myconfig, $thisdate, $days) = @_; + my $self = shift; + my $myconfig = shift || \%::myconfig; + my ($thisdate, $days) = @_; my $dbh = $self->get_standard_dbh($myconfig); my $query; @@ -2589,7 +3131,7 @@ sub redo_rows { # fill rows foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) { $i++; - $j = $item->{ndx} - 1; + my $j = $item->{ndx} - 1; map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds}; } @@ -2739,8 +3281,8 @@ sub save_status { sub save_history { $main::lxdebug->enter_sub(); - my $self = shift(); - my $dbh = shift(); + my $self = shift; + my $dbh = shift || $self->get_standard_dbh; if(!exists $self->{employee_id}) { &get_employee($self, $dbh); @@ -2753,6 +3295,8 @@ sub save_history { $self->{addition}, $self->{what_done}, "$self->{snumbers}"); do_query($self, $dbh, $query, @values); + $dbh->commit; + $main::lxdebug->leave_sub(); } @@ -2769,10 +3313,9 @@ sub get_history { qq|SELECT h.employee_id, h.itime::timestamp(0) AS itime, h.addition, h.what_done, emp.name, h.snumbers, h.trans_id AS id | . qq|FROM history_erp h | . qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | . - qq|WHERE trans_id = | . $trans_id - . $restriction . qq| | - . $order; - + qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | . + $order; + my $sth = $dbh->prepare($query) || $self->dberror($query); $sth->execute() || $self->dberror("$query"); @@ -2783,7 +3326,7 @@ sub get_history { $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g; $tempArray[$i++] = $hash_ref; } - $main::lxdebug->leave_sub() and return \@tempArray + $main::lxdebug->leave_sub() and return \@tempArray if ($i > 0 && $tempArray[0] ne ""); } $main::lxdebug->leave_sub(); @@ -2846,6 +3389,8 @@ sub update_business { WHERE id = ? FOR UPDATE|; my ($var) = selectrow_query($self, $dbh, $query, $business_id); + return undef unless $var; + if ($var =~ m/\d+$/) { my $new_var = (substr $var, $-[0]) * 1 + 1; my $len_diff = length($var) - $-[0] - length($new_var); @@ -2874,6 +3419,7 @@ sub get_partsgroup { $main::lxdebug->enter_sub(); my ($self, $myconfig, $p) = @_; + my $target = $p->{target} || 'all_partsgroup'; my $dbh = $self->get_standard_dbh($myconfig); @@ -2912,7 +3458,7 @@ sub get_partsgroup { @values = ($p->{language_code}); } - $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values); + $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values); $main::lxdebug->leave_sub(); } @@ -2978,4 +3524,129 @@ sub all_years { $main::lxdebug->leave_sub(); } +sub backup_vars { + $main::lxdebug->enter_sub(); + my $self = shift; + my @vars = @_; + + map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars; + + $main::lxdebug->leave_sub(); +} + +sub restore_vars { + $main::lxdebug->enter_sub(); + + my $self = shift; + my @vars = @_; + + map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars; + + $main::lxdebug->leave_sub(); +} + 1; + +__END__ + +=head1 NAME + +SL::Form.pm - main data object. + +=head1 SYNOPSIS + +This is the main data object of Lx-Office. +Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points. +Points of interest for a beginner are: + + - $form->error - renders a generic error in html. accepts an error message + - $form->get_standard_dbh - returns a database connection for the + +=head1 SPECIAL FUNCTIONS + +=over 4 + +=item _store_value() + +parses a complex var name, and stores it in the form. + +syntax: + $form->_store_value($key, $value); + +keys must start with a string, and can contain various tokens. +supported key structures are: + +1. simple access + simple key strings work as expected + + id => $form->{id} + +2. hash access. + separating two keys by a dot (.) will result in a hash lookup for the inner value + this is similar to the behaviour of java and templating mechanisms. + + filter.description => $form->{filter}->{description} + +3. array+hashref access + + adding brackets ([]) before the dot will cause the next hash to be put into an array. + using [+] instead of [] will force a new array index. this is useful for recurring + data structures like part lists. put a [+] into the first varname, and use [] on the + following ones. + + repeating these names in your template: + + invoice.items[+].id + invoice.items[].parts_id + + will result in: + + $form->{invoice}->{items}->[ + { + id => ... + parts_id => ... + }, + { + id => ... + parts_id => ... + } + ... + ] + +4. arrays + + using brackets at the end of a name will result in a pure array to be created. + note that you mustn't use [+], which is reserved for array+hash access and will + result in undefined behaviour in array context. + + filter.status[] => $form->{status}->[ val1, val2, ... ] + +=item update_business PARAMS + +PARAMS (not named): + \%config, - config hashref + $business_id, - business id + $dbh - optional database handle + +handles business (thats customer/vendor types) sequences. + +special behaviour for empty strings in customerinitnumber field: +will in this case not increase the value, and return undef. + +=item redirect_header $url + +Generates a HTTP redirection header for the new C<$url>. Constructs an +absolute URL including scheme, host name and port. If C<$url> is a +relative URL then it is considered relative to Lx-Office base URL. + +This function Cs if headers have already been created with +C<$::form-Eheader>. + +Examples: + + print $::form->redirect_header('oe.pl?action=edit&id=1234'); + print $::form->redirect_header('http://www.lx-office.org/'); + +=back + +=cut