1 #====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
15 # Contributors: Thomas Bayen <bayen@gmx.de>
16 # Antti Kaihola <akaihola@siba.fi>
17 # Moritz Bunkus (tex code)
19 # This program is free software; you can redistribute it and/or modify
20 # it under the terms of the GNU General Public License as published by
21 # the Free Software Foundation; either version 2 of the License, or
22 # (at your option) any later version.
24 # This program is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 # GNU General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, write to the Free Software
30 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #======================================================================
32 # Utilities for parsing forms
33 # and supporting routines for linking account numbers
34 # used in AR, AP and IS, IR modules
36 #======================================================================
67 use List::Util qw(first max min sum);
68 use List::MoreUtils qw(all any apply);
75 disconnect_standard_dbh();
78 sub disconnect_standard_dbh {
79 return unless $standard_dbh;
80 $standard_dbh->disconnect();
85 $main::lxdebug->enter_sub(2);
91 my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key;
96 $curr = \ $self->{ shift @tokens };
100 my $sep = shift @tokens;
101 my $key = shift @tokens;
103 $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]';
104 $curr = \ $$curr->[max 0, $#$$curr] if $sep eq '[].';
105 $curr = \ $$curr->[++$#$$curr] if $sep eq '[+].';
106 $curr = \ $$curr->{$key}
111 $main::lxdebug->leave_sub(2);
117 $main::lxdebug->enter_sub(2);
122 my @pairs = split(/&/, $input);
125 my ($key, $value) = split(/=/, $_, 2);
126 $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key);
129 $main::lxdebug->leave_sub(2);
132 sub _request_to_hash {
133 $main::lxdebug->enter_sub(2);
139 if (!$ENV{'CONTENT_TYPE'}
140 || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
142 $self->_input_to_hash($input);
144 $main::lxdebug->leave_sub(2);
148 my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
150 my $boundary = '--' . $1;
152 foreach my $line (split m/\n/, $input) {
153 last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
155 if (($line eq $boundary) || ($line eq "$boundary\r")) {
156 ${ $previous } =~ s|\r?\n$|| if $previous;
162 $content_type = "text/plain";
169 next unless $boundary_found;
171 if (!$headers_done) {
172 $line =~ s/[\r\n]*$//;
179 if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
180 if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
182 substr $line, $-[0], $+[0] - $-[0], "";
185 if ($line =~ m|name\s*=\s*"(.*?)"|i) {
187 substr $line, $-[0], $+[0] - $-[0], "";
190 $previous = _store_value($uploads, $name, '') if ($name);
191 $self->{FILENAME} = $filename if ($filename);
196 if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
203 next unless $previous;
205 ${ $previous } .= "${line}\n";
208 ${ $previous } =~ s|\r?\n$|| if $previous;
210 $main::lxdebug->leave_sub(2);
215 sub _recode_recursively {
216 $main::lxdebug->enter_sub();
217 my ($iconv, $param) = @_;
219 if (any { ref $param eq $_ } qw(Form HASH)) {
220 foreach my $key (keys %{ $param }) {
221 if (!ref $param->{$key}) {
222 # Workaround for a bug: converting $param->{$key} directly
223 # leads to 'undef'. I don't know why. Converting a copy works,
225 $param->{$key} = $iconv->convert("" . $param->{$key});
227 _recode_recursively($iconv, $param->{$key});
231 } elsif (ref $param eq 'ARRAY') {
232 foreach my $idx (0 .. scalar(@{ $param }) - 1) {
233 if (!ref $param->[$idx]) {
234 # Workaround for a bug: converting $param->[$idx] directly
235 # leads to 'undef'. I don't know why. Converting a copy works,
237 $param->[$idx] = $iconv->convert("" . $param->[$idx]);
239 _recode_recursively($iconv, $param->[$idx]);
243 $main::lxdebug->leave_sub();
247 $main::lxdebug->enter_sub();
254 if ($LXDebug::watch_form) {
255 require SL::Watchdog;
256 tie %{ $self }, 'SL::Watchdog';
261 $main::lxdebug->leave_sub();
267 $main::lxdebug->enter_sub();
271 $self->_input_to_hash($ENV{QUERY_STRING}) if $ENV{QUERY_STRING};
272 $self->_input_to_hash($ARGV[0]) if @ARGV && $ARGV[0];
275 if ($ENV{CONTENT_LENGTH}) {
277 read STDIN, $content, $ENV{CONTENT_LENGTH};
278 $uploads = $self->_request_to_hash($content);
281 if ($self->{RESTORE_FORM_FROM_SESSION_ID}) {
283 $::auth->restore_form_from_session(delete $self->{RESTORE_FORM_FROM_SESSION_ID}, form => \%temp_form);
284 $self->_input_to_hash(join '&', map { $self->escape($_) . '=' . $self->escape($temp_form{$_}) } keys %temp_form);
287 my $db_charset = $::lx_office_conf{system}->{dbcharset};
288 $db_charset ||= Common::DEFAULT_CHARSET;
290 my $encoding = $self->{INPUT_ENCODING} || $db_charset;
291 delete $self->{INPUT_ENCODING};
293 _recode_recursively(SL::Iconv->new($encoding, $db_charset), $self);
295 map { $self->{$_} = $uploads->{$_} } keys %{ $uploads } if $uploads;
297 #$self->{version} = "2.6.1"; # Old hardcoded but secure style
298 open VERSION_FILE, "VERSION"; # New but flexible code reads version from VERSION-file
299 $self->{version} = <VERSION_FILE>;
301 $self->{version} =~ s/[^0-9A-Za-z\.\_\-]//g; # only allow numbers, letters, points, underscores and dashes. Prevents injecting of malicious code.
303 $main::lxdebug->leave_sub();
308 sub _flatten_variables_rec {
309 $main::lxdebug->enter_sub(2);
318 if ('' eq ref $curr->{$key}) {
319 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
321 } elsif ('HASH' eq ref $curr->{$key}) {
322 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
323 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
327 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
328 my $first_array_entry = 1;
330 foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
331 push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
332 $first_array_entry = 0;
337 $main::lxdebug->leave_sub(2);
342 sub flatten_variables {
343 $main::lxdebug->enter_sub(2);
351 push @variables, $self->_flatten_variables_rec($self, '', $_);
354 $main::lxdebug->leave_sub(2);
359 sub flatten_standard_variables {
360 $main::lxdebug->enter_sub(2);
363 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
367 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
368 push @variables, $self->_flatten_variables_rec($self, '', $_);
371 $main::lxdebug->leave_sub(2);
377 $main::lxdebug->enter_sub();
383 map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
385 $main::lxdebug->leave_sub();
389 $main::lxdebug->enter_sub(2);
392 my $password = $self->{password};
394 $self->{password} = 'X' x 8;
396 local $Data::Dumper::Sortkeys = 1;
397 my $output = Dumper($self);
399 $self->{password} = $password;
401 $main::lxdebug->leave_sub(2);
407 $main::lxdebug->enter_sub(2);
409 my ($self, $str) = @_;
411 $str = Encode::encode('utf-8-strict', $str) if $::locale->is_utf8;
412 $str =~ s/([^a-zA-Z0-9_.:-])/sprintf("%%%02x", ord($1))/ge;
414 $main::lxdebug->leave_sub(2);
420 $main::lxdebug->enter_sub(2);
422 my ($self, $str) = @_;
427 $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
428 $str = Encode::decode('utf-8-strict', $str) if $::locale->is_utf8;
430 $main::lxdebug->leave_sub(2);
436 $main::lxdebug->enter_sub();
437 my ($self, $str) = @_;
439 if ($str && !ref($str)) {
440 $str =~ s/\"/"/g;
443 $main::lxdebug->leave_sub();
449 $main::lxdebug->enter_sub();
450 my ($self, $str) = @_;
452 if ($str && !ref($str)) {
453 $str =~ s/"/\"/g;
456 $main::lxdebug->leave_sub();
462 $main::lxdebug->enter_sub();
466 map({ print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
468 for (sort keys %$self) {
469 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
470 print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
473 $main::lxdebug->leave_sub();
477 my ($self, $code) = @_;
478 local $self->{__ERROR_HANDLER} = sub { die SL::X::FormError->new($_[0]) };
483 $main::lxdebug->enter_sub();
485 $main::lxdebug->show_backtrace();
487 my ($self, $msg) = @_;
489 if ($self->{__ERROR_HANDLER}) {
490 $self->{__ERROR_HANDLER}->($msg);
492 } elsif ($ENV{HTTP_USER_AGENT}) {
494 $self->show_generic_error($msg);
497 print STDERR "Error: $msg\n";
501 $main::lxdebug->leave_sub();
505 $main::lxdebug->enter_sub();
507 my ($self, $msg) = @_;
509 if ($ENV{HTTP_USER_AGENT}) {
512 if (!$self->{header}) {
518 <p class="message_ok"><b>$msg</b></p>
520 <script type="text/javascript">
522 // If JavaScript is enabled, the whole thing will be reloaded.
523 // The reason is: When one changes his menu setup (HTML / XUL / CSS ...)
524 // it now loads the correct code into the browser instead of do nothing.
525 setTimeout("top.frames.location.href='login.pl'",500);
534 if ($self->{info_function}) {
535 &{ $self->{info_function} }($msg);
541 $main::lxdebug->leave_sub();
544 # calculates the number of rows in a textarea based on the content and column number
545 # can be capped with maxrows
547 $main::lxdebug->enter_sub();
548 my ($self, $str, $cols, $maxrows, $minrows) = @_;
552 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
555 $main::lxdebug->leave_sub();
557 return max(min($rows, $maxrows), $minrows);
561 $main::lxdebug->enter_sub();
563 my ($self, $msg) = @_;
565 $self->error("$msg\n" . $DBI::errstr);
567 $main::lxdebug->leave_sub();
571 $main::lxdebug->enter_sub();
573 my ($self, $name, $msg) = @_;
576 foreach my $part (split m/\./, $name) {
577 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
580 $curr = $curr->{$part};
583 $main::lxdebug->leave_sub();
586 sub _get_request_uri {
589 return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
591 my $scheme = $ENV{HTTPS} && (lc $ENV{HTTPS} eq 'on') ? 'https' : 'http';
592 my $port = $ENV{SERVER_PORT} || '';
593 $port = undef if (($scheme eq 'http' ) && ($port == 80))
594 || (($scheme eq 'https') && ($port == 443));
596 my $uri = URI->new("${scheme}://");
597 $uri->scheme($scheme);
599 $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
600 $uri->path_query($ENV{REQUEST_URI});
606 sub _add_to_request_uri {
609 my $relative_new_path = shift;
610 my $request_uri = shift || $self->_get_request_uri;
611 my $relative_new_uri = URI->new($relative_new_path);
612 my @request_segments = $request_uri->path_segments;
614 my $new_uri = $request_uri->clone;
615 $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
620 sub create_http_response {
621 $main::lxdebug->enter_sub();
626 my $cgi = $::request->{cgi};
629 if (defined $main::auth) {
630 my $uri = $self->_get_request_uri;
631 my @segments = $uri->path_segments;
633 $uri->path_segments(@segments);
635 my $session_cookie_value = $main::auth->get_session_id();
637 if ($session_cookie_value) {
638 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
639 '-value' => $session_cookie_value,
640 '-path' => $uri->path,
641 '-secure' => $ENV{HTTPS});
645 my %cgi_params = ('-type' => $params{content_type});
646 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
647 $cgi_params{'-cookie'} = $session_cookie if ($session_cookie);
649 map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length);
651 my $output = $cgi->header(%cgi_params);
653 $main::lxdebug->leave_sub();
661 $self->{stylesheet} = [ $self->{stylesheet} ] unless ref $self->{stylesheet} eq 'ARRAY';
662 $self->{stylesheet} = [ grep { -f }
663 map { m:^css/: ? $_ : "css/$_" }
665 (@{ $self->{stylesheet} }, @_)
668 return @{ $self->{stylesheet} };
672 $::lxdebug->enter_sub;
674 # extra code is currently only used by menuv3 and menuv4 to set their css.
675 # it is strongly deprecated, and will be changed in a future version.
676 my ($self, %params) = @_;
677 my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
680 $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
682 $self->{favicon} ||= "favicon.ico";
683 $self->{titlebar} = "$self->{title} - $self->{titlebar}" if $self->{title};
686 if ($self->{refresh_url} || $self->{refresh_time}) {
687 my $refresh_time = $self->{refresh_time} || 3;
688 my $refresh_url = $self->{refresh_url} || $ENV{REFERER};
689 push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
692 push @header, map { qq|<link rel="stylesheet" href="$_" type="text/css" title="Lx-Office stylesheet">| } $self->use_stylesheet;
694 push @header, "<style type='text/css'>\@page { size:landscape; }</style>" if $self->{landscape};
695 push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
696 push @header, '<script type="text/javascript" src="js/jquery.js"></script>',
697 '<script type="text/javascript" src="js/common.js"></script>',
698 '<link rel="stylesheet" type="text/css" href="js/jscalendar/calendar-win2k-1.css">',
699 '<script type="text/javascript" src="js/jscalendar/calendar.js"></script>',
700 '<script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>',
701 '<script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>',
702 '<script type="text/javascript" src="js/part_selection.js"></script>',
703 '<script type="text/javascript" src="js/jquery-ui.js"></script>',
704 '<link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.8.12.custom.css">';
705 push @header, $self->{javascript} if $self->{javascript};
706 push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
707 push @header, "<script type='text/javascript'>function fokus(){ document.$self->{fokus}.focus(); }</script>" if $self->{fokus};
708 push @header, sprintf "<script type='text/javascript'>top.document.title='%s';</script>",
709 join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->{version} if $self->{title};
711 # if there is a title, we put some JavaScript in to the page, wich writes a
712 # meaningful title-tag for our frameset.
714 if ($self->{title}) {
716 <script type="text/javascript">
718 // Write a meaningful title-tag for our frameset.
719 top.document.title="| . $self->{"title"} . qq| - | . $self->{"login"} . qq| - | . $::myconfig{dbname} . qq| - V| . $self->{"version"} . qq|";
725 strict => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
726 transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
727 frameset => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
731 print $self->create_http_response(content_type => 'text/html', charset => $db_charset);
732 print $doctypes{$params{doctype} || 'transitional'}, $/;
736 <meta http-equiv="Content-Type" content="text/html; charset=$db_charset">
737 <title>$self->{titlebar}</title>
739 print " $_\n" for @header;
741 <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css">
742 <meta name="robots" content="noindex,nofollow">
743 <link rel="stylesheet" type="text/css" href="css/tabcontent.css">
744 <script type="text/javascript" src="js/tabcontent.js">
746 /***********************************************
747 * Tab Content script v2.2- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
748 * This notice MUST stay intact for legal use
749 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
750 ***********************************************/
759 $::lxdebug->leave_sub;
762 sub ajax_response_header {
763 $main::lxdebug->enter_sub();
767 my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
768 my $output = $::request->{cgi}->header('-charset' => $db_charset);
770 $main::lxdebug->leave_sub();
775 sub redirect_header {
779 my $base_uri = $self->_get_request_uri;
780 my $new_uri = URI->new_abs($new_url, $base_uri);
782 die "Headers already sent" if $self->{header};
785 return $::request->{cgi}->redirect($new_uri);
788 sub set_standard_title {
789 $::lxdebug->enter_sub;
792 $self->{titlebar} = "Lx-Office " . $::locale->text('Version') . " $self->{version}";
793 $self->{titlebar} .= "- $::myconfig{name}" if $::myconfig{name};
794 $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
796 $::lxdebug->leave_sub;
799 sub _prepare_html_template {
800 $main::lxdebug->enter_sub();
802 my ($self, $file, $additional_params) = @_;
805 if (!%::myconfig || !$::myconfig{"countrycode"}) {
806 $language = $::lx_office_conf{system}->{language};
808 $language = $main::myconfig{"countrycode"};
810 $language = "de" unless ($language);
812 if (-f "templates/webpages/${file}.html") {
813 $file = "templates/webpages/${file}.html";
816 my $info = "Web page template '${file}' not found.\n";
817 print qq|<pre>$info</pre>|;
821 if ($self->{"DEBUG"}) {
822 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
825 if ($additional_params->{"DEBUG"}) {
826 $additional_params->{"DEBUG"} =
827 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
830 if (%main::myconfig) {
831 $::myconfig{jsc_dateformat} = apply {
835 } $::myconfig{"dateformat"};
836 $additional_params->{"myconfig"} ||= \%::myconfig;
837 map { $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys %::myconfig;
840 $additional_params->{"conf_dbcharset"} = $::lx_office_conf{system}->{dbcharset};
841 $additional_params->{"conf_webdav"} = $::lx_office_conf{features}->{webdav};
842 $additional_params->{"conf_latex_templates"} = $::lx_office_conf{print_templates}->{latex};
843 $additional_params->{"conf_opendocument_templates"} = $::lx_office_conf{print_templates}->{opendocument};
844 $additional_params->{"conf_vertreter"} = $::lx_office_conf{features}->{vertreter};
845 $additional_params->{"conf_show_best_before"} = $::lx_office_conf{features}->{show_best_before};
846 $additional_params->{"conf_parts_image_css"} = $::lx_office_conf{features}->{parts_image_css};
847 $additional_params->{"conf_parts_listing_images"} = $::lx_office_conf{features}->{parts_listing_images};
848 $additional_params->{"conf_parts_show_image"} = $::lx_office_conf{features}->{parts_show_image};
849 $additional_params->{"conf_payments_changeable"} = $::lx_office_conf{features}->{payments_changeable};
850 $additional_params->{"INSTANCE_CONF"} = $::instance_conf;
852 if (my $debug_options = $::lx_office_conf{debug}{options}) {
853 map { $additional_params->{'DEBUG_' . uc($_)} = $debug_options->{$_} } keys %$debug_options;
856 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
857 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
858 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
862 $main::lxdebug->leave_sub();
867 sub parse_html_template {
868 $main::lxdebug->enter_sub();
870 my ($self, $file, $additional_params) = @_;
872 $additional_params ||= { };
874 my $real_file = $self->_prepare_html_template($file, $additional_params);
875 my $template = $self->template || $self->init_template;
877 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
880 $template->process($real_file, $additional_params, \$output) || die $template->error;
882 $main::lxdebug->leave_sub();
890 return $self->template if $self->template;
892 return $self->template(Template->new({
897 'PLUGIN_BASE' => 'SL::Template::Plugin',
898 'INCLUDE_PATH' => '.:templates/webpages',
899 'COMPILE_EXT' => '.tcc',
900 'COMPILE_DIR' => $::lx_office_conf{paths}->{userspath} . '/templates-cache',
906 $self->{template_object} = shift if @_;
907 return $self->{template_object};
910 sub show_generic_error {
911 $main::lxdebug->enter_sub();
913 my ($self, $error, %params) = @_;
915 if ($self->{__ERROR_HANDLER}) {
916 $self->{__ERROR_HANDLER}->($error);
917 $main::lxdebug->leave_sub();
922 'title_error' => $params{title},
923 'label_error' => $error,
926 if ($params{action}) {
929 map { delete($self->{$_}); } qw(action);
930 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
932 $add_params->{SHOW_BUTTON} = 1;
933 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
934 $add_params->{VARIABLES} = \@vars;
936 } elsif ($params{back_button}) {
937 $add_params->{SHOW_BACK_BUTTON} = 1;
940 $self->{title} = $params{title} if $params{title};
943 print $self->parse_html_template("generic/error", $add_params);
945 print STDERR "Error: $error\n";
947 $main::lxdebug->leave_sub();
952 sub show_generic_information {
953 $main::lxdebug->enter_sub();
955 my ($self, $text, $title) = @_;
958 'title_information' => $title,
959 'label_information' => $text,
962 $self->{title} = $title if ($title);
965 print $self->parse_html_template("generic/information", $add_params);
967 $main::lxdebug->leave_sub();
972 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
973 # changed it to accept an arbitrary number of triggers - sschoeling
975 $main::lxdebug->enter_sub();
978 my $myconfig = shift;
981 # set dateform for jsscript
984 "dd.mm.yy" => "%d.%m.%Y",
985 "dd-mm-yy" => "%d-%m-%Y",
986 "dd/mm/yy" => "%d/%m/%Y",
987 "mm/dd/yy" => "%m/%d/%Y",
988 "mm-dd-yy" => "%m-%d-%Y",
989 "yyyy-mm-dd" => "%Y-%m-%d",
992 my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
993 $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
1000 inputField : "| . (shift) . qq|",
1001 ifFormat :"$ifFormat",
1002 align : "| . (shift) . qq|",
1003 button : "| . (shift) . qq|"
1009 <script type="text/javascript">
1010 <!--| . join("", @triggers) . qq|//-->
1014 $main::lxdebug->leave_sub();
1017 } #end sub write_trigger
1019 sub _store_redirect_info_in_session {
1022 return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
1024 my ($controller, $params) = ($1, $2);
1025 my $form = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
1026 $self->{callback} = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
1030 $main::lxdebug->enter_sub();
1032 my ($self, $msg) = @_;
1034 if (!$self->{callback}) {
1038 $self->_store_redirect_info_in_session;
1039 print $::form->redirect_header($self->{callback});
1044 $main::lxdebug->leave_sub();
1047 # sort of columns removed - empty sub
1049 $main::lxdebug->enter_sub();
1051 my ($self, @columns) = @_;
1053 $main::lxdebug->leave_sub();
1059 $main::lxdebug->enter_sub(2);
1061 my ($self, $myconfig, $amount, $places, $dash) = @_;
1063 if ($amount eq "") {
1067 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
1069 my $neg = ($amount =~ s/^-//);
1070 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
1072 if (defined($places) && ($places ne '')) {
1078 my ($actual_places) = ($amount =~ /\.(\d+)/);
1079 $actual_places = length($actual_places);
1080 $places = $actual_places > $places ? $actual_places : $places;
1083 $amount = $self->round_amount($amount, $places);
1086 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
1087 my @p = split(/\./, $amount); # split amount at decimal point
1089 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
1092 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
1095 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
1096 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1097 ($neg ? "-$amount" : "$amount" ) ;
1101 $main::lxdebug->leave_sub(2);
1105 sub format_amount_units {
1106 $main::lxdebug->enter_sub();
1111 my $myconfig = \%main::myconfig;
1112 my $amount = $params{amount} * 1;
1113 my $places = $params{places};
1114 my $part_unit_name = $params{part_unit};
1115 my $amount_unit_name = $params{amount_unit};
1116 my $conv_units = $params{conv_units};
1117 my $max_places = $params{max_places};
1119 if (!$part_unit_name) {
1120 $main::lxdebug->leave_sub();
1124 my $all_units = AM->retrieve_all_units;
1126 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1127 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1130 if (!scalar @{ $conv_units }) {
1131 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1132 $main::lxdebug->leave_sub();
1136 my $part_unit = $all_units->{$part_unit_name};
1137 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1139 $amount *= $conv_unit->{factor};
1144 foreach my $unit (@$conv_units) {
1145 my $last = $unit->{name} eq $part_unit->{name};
1147 $num = int($amount / $unit->{factor});
1148 $amount -= $num * $unit->{factor};
1151 if ($last ? $amount : $num) {
1152 push @values, { "unit" => $unit->{name},
1153 "amount" => $last ? $amount / $unit->{factor} : $num,
1154 "places" => $last ? $places : 0 };
1161 push @values, { "unit" => $part_unit_name,
1166 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1168 $main::lxdebug->leave_sub();
1174 $main::lxdebug->enter_sub(2);
1179 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1180 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1181 $input =~ s/\#\#/\#/g;
1183 $main::lxdebug->leave_sub(2);
1191 $main::lxdebug->enter_sub(2);
1193 my ($self, $myconfig, $amount) = @_;
1195 if ( ($myconfig->{numberformat} eq '1.000,00')
1196 || ($myconfig->{numberformat} eq '1000,00')) {
1198 $amount =~ s/,/\./g;
1201 if ($myconfig->{numberformat} eq "1'000.00") {
1207 $main::lxdebug->leave_sub(2);
1209 # Make sure no code wich is not a math expression ends up in eval().
1210 return 0 unless $amount =~ /^ [\s \d \( \) \- \+ \* \/ \. ]* $/x;
1211 return scalar(eval($amount)) * 1 ;
1215 $main::lxdebug->enter_sub(2);
1217 my ($self, $amount, $places) = @_;
1220 # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
1222 # Round amounts to eight places before rounding to the requested
1223 # number of places. This gets rid of errors due to internal floating
1224 # point representation.
1225 $amount = $self->round_amount($amount, 8) if $places < 8;
1226 $amount = $amount * (10**($places));
1227 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1229 $main::lxdebug->leave_sub(2);
1231 return $round_amount;
1235 sub parse_template {
1236 $main::lxdebug->enter_sub();
1238 my ($self, $myconfig) = @_;
1243 my $userspath = $::lx_office_conf{paths}->{userspath};
1245 $self->{"cwd"} = getcwd();
1246 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1251 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1252 $template_type = 'OpenDocument';
1253 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
1255 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1256 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1257 $template_type = 'LaTeX';
1258 $ext_for_format = 'pdf';
1260 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1261 $template_type = 'HTML';
1262 $ext_for_format = 'html';
1264 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1265 $template_type = 'XML';
1266 $ext_for_format = 'xml';
1268 } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
1269 $template_type = 'XML';
1271 } elsif ( $self->{"format"} =~ /excel/i ) {
1272 $template_type = 'Excel';
1273 $ext_for_format = 'xls';
1275 } elsif ( defined $self->{'format'}) {
1276 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1278 } elsif ( $self->{'format'} eq '' ) {
1279 $self->error("No Outputformat given: $self->{'format'}");
1281 } else { #Catch the rest
1282 $self->error("Outputformat not defined: $self->{'format'}");
1285 my $template = SL::Template::create(type => $template_type,
1286 file_name => $self->{IN},
1288 myconfig => $myconfig,
1289 userspath => $userspath);
1291 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1292 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1294 if (!$self->{employee_id}) {
1295 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1298 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1299 map { $self->{"myconfig_${_}"} = $myconfig->{$_} } grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
1301 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1303 # OUT is used for the media, screen, printer, email
1304 # for postscript we store a copy in a temporary file
1306 my $prepend_userspath;
1308 if (!$self->{tmpfile}) {
1309 $self->{tmpfile} = "${fileid}.$self->{IN}";
1310 $prepend_userspath = 1;
1313 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1315 $self->{tmpfile} =~ s|.*/||;
1316 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1317 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1319 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1320 $out = $self->{OUT};
1321 $self->{OUT} = "$self->{tmpfile}";
1327 open(OUT, ">", $self->{OUT}) or $self->error("$self->{OUT} : $!");
1329 *OUT = ($::dispatcher->get_standard_filehandles)[1];
1333 if (!$template->parse(*OUT)) {
1335 $self->error("$self->{IN} : " . $template->get_error());
1338 close OUT if $self->{OUT};
1340 if ($self->{media} eq 'file') {
1341 copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
1343 chdir("$self->{cwd}");
1345 $::lxdebug->leave_sub();
1350 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1352 if ($self->{media} eq 'email') {
1354 my $mail = new Mailer;
1356 map { $mail->{$_} = $self->{$_} }
1357 qw(cc bcc subject message version format);
1358 $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
1359 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1360 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1361 $mail->{fileid} = "$fileid.";
1362 $myconfig->{signature} =~ s/\r//g;
1364 # if we send html or plain text inline
1365 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1366 $mail->{contenttype} = "text/html";
1368 $mail->{message} =~ s/\r//g;
1369 $mail->{message} =~ s/\n/<br>\n/g;
1370 $myconfig->{signature} =~ s/\n/<br>\n/g;
1371 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1373 open(IN, "<", $self->{tmpfile})
1374 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1376 $mail->{message} .= $_;
1383 if (!$self->{"do_not_attach"}) {
1384 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1385 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1386 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1387 "name" => $attachment_name }];
1390 $mail->{message} =~ s/\r//g;
1391 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1395 my $err = $mail->send();
1396 $self->error($self->cleanup . "$err") if ($err);
1400 $self->{OUT} = $out;
1402 my $numbytes = (-s $self->{tmpfile});
1403 open(IN, "<", $self->{tmpfile})
1404 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1407 $self->{copies} = 1 unless $self->{media} eq 'printer';
1409 chdir("$self->{cwd}");
1410 #print(STDERR "Kopien $self->{copies}\n");
1411 #print(STDERR "OUT $self->{OUT}\n");
1412 for my $i (1 .. $self->{copies}) {
1414 open OUT, '>', $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1415 print OUT $_ while <IN>;
1420 $self->{attachment_filename} = ($self->{attachment_filename})
1421 ? $self->{attachment_filename}
1422 : $self->generate_attachment_filename();
1424 # launch application
1425 print qq|Content-Type: | . $template->get_mime_type() . qq|
1426 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1427 Content-Length: $numbytes
1431 $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1442 chdir("$self->{cwd}");
1443 $main::lxdebug->leave_sub();
1446 sub get_formname_translation {
1447 $main::lxdebug->enter_sub();
1448 my ($self, $formname) = @_;
1450 $formname ||= $self->{formname};
1452 my %formname_translations = (
1453 bin_list => $main::locale->text('Bin List'),
1454 credit_note => $main::locale->text('Credit Note'),
1455 invoice => $main::locale->text('Invoice'),
1456 pick_list => $main::locale->text('Pick List'),
1457 proforma => $main::locale->text('Proforma Invoice'),
1458 purchase_order => $main::locale->text('Purchase Order'),
1459 request_quotation => $main::locale->text('RFQ'),
1460 sales_order => $main::locale->text('Confirmation'),
1461 sales_quotation => $main::locale->text('Quotation'),
1462 storno_invoice => $main::locale->text('Storno Invoice'),
1463 sales_delivery_order => $main::locale->text('Delivery Order'),
1464 purchase_delivery_order => $main::locale->text('Delivery Order'),
1465 dunning => $main::locale->text('Dunning'),
1468 $main::lxdebug->leave_sub();
1469 return $formname_translations{$formname}
1472 sub get_number_prefix_for_type {
1473 $main::lxdebug->enter_sub();
1477 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1478 : ($self->{type} =~ /_quotation$/) ? 'quo'
1479 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1482 $main::lxdebug->leave_sub();
1486 sub get_extension_for_format {
1487 $main::lxdebug->enter_sub();
1490 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1491 : $self->{format} =~ /postscript/i ? ".ps"
1492 : $self->{format} =~ /opendocument/i ? ".odt"
1493 : $self->{format} =~ /excel/i ? ".xls"
1494 : $self->{format} =~ /html/i ? ".html"
1497 $main::lxdebug->leave_sub();
1501 sub generate_attachment_filename {
1502 $main::lxdebug->enter_sub();
1505 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1506 my $prefix = $self->get_number_prefix_for_type();
1508 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1509 $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1511 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1512 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1515 $attachment_filename = "";
1518 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1519 $attachment_filename =~ s|[\s/\\]+|_|g;
1521 $main::lxdebug->leave_sub();
1522 return $attachment_filename;
1525 sub generate_email_subject {
1526 $main::lxdebug->enter_sub();
1529 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1530 my $prefix = $self->get_number_prefix_for_type();
1532 if ($subject && $self->{"${prefix}number"}) {
1533 $subject .= " " . $self->{"${prefix}number"}
1536 $main::lxdebug->leave_sub();
1541 $main::lxdebug->enter_sub();
1543 my ($self, $application) = @_;
1545 my $error_code = $?;
1547 chdir("$self->{tmpdir}");
1550 if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1551 push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1553 } elsif (-f "$self->{tmpfile}.err") {
1554 open(FH, "$self->{tmpfile}.err");
1559 if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1560 $self->{tmpfile} =~ s|.*/||g;
1562 $self->{tmpfile} =~ s/\.\w+$//g;
1563 my $tmpfile = $self->{tmpfile};
1564 unlink(<$tmpfile.*>);
1567 chdir("$self->{cwd}");
1569 $main::lxdebug->leave_sub();
1575 $main::lxdebug->enter_sub();
1577 my ($self, $date, $myconfig) = @_;
1580 if ($date && $date =~ /\D/) {
1582 if ($myconfig->{dateformat} =~ /^yy/) {
1583 ($yy, $mm, $dd) = split /\D/, $date;
1585 if ($myconfig->{dateformat} =~ /^mm/) {
1586 ($mm, $dd, $yy) = split /\D/, $date;
1588 if ($myconfig->{dateformat} =~ /^dd/) {
1589 ($dd, $mm, $yy) = split /\D/, $date;
1594 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1595 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1597 $dd = "0$dd" if ($dd < 10);
1598 $mm = "0$mm" if ($mm < 10);
1600 $date = "$yy$mm$dd";
1603 $main::lxdebug->leave_sub();
1608 # Database routines used throughout
1610 sub _dbconnect_options {
1612 my $options = { pg_enable_utf8 => $::locale->is_utf8,
1619 $main::lxdebug->enter_sub(2);
1621 my ($self, $myconfig) = @_;
1623 # connect to database
1624 my $dbh = SL::DBConnect->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options)
1628 if ($myconfig->{dboptions}) {
1629 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1632 $main::lxdebug->leave_sub(2);
1637 sub dbconnect_noauto {
1638 $main::lxdebug->enter_sub();
1640 my ($self, $myconfig) = @_;
1642 # connect to database
1643 my $dbh = SL::DBConnect->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options(AutoCommit => 0))
1647 if ($myconfig->{dboptions}) {
1648 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1651 $main::lxdebug->leave_sub();
1656 sub get_standard_dbh {
1657 $main::lxdebug->enter_sub(2);
1660 my $myconfig = shift || \%::myconfig;
1662 if ($standard_dbh && !$standard_dbh->{Active}) {
1663 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1664 undef $standard_dbh;
1667 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1669 $main::lxdebug->leave_sub(2);
1671 return $standard_dbh;
1675 $main::lxdebug->enter_sub();
1677 my ($self, $date, $myconfig) = @_;
1678 my $dbh = $self->dbconnect($myconfig);
1680 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1681 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1683 # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1684 # es ist sicher ein conv_date vorher IMMER auszuführen.
1685 # Testfälle ohne definiertes closedto:
1686 # Leere Datumseingabe i.O.
1687 # SELECT 1 FROM defaults WHERE '' < closedto
1688 # normale Zahlungsbuchung über Rechnungsmaske i.O.
1689 # SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1690 # Testfälle mit definiertem closedto (30.04.2011):
1691 # Leere Datumseingabe i.O.
1692 # SELECT 1 FROM defaults WHERE '' < closedto
1693 # normale Buchung im geschloßenem Zeitraum i.O.
1694 # SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1695 # Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1696 # normale Buchung in aktiver Buchungsperiode i.O.
1697 # SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1699 my ($closed) = $sth->fetchrow_array;
1701 $main::lxdebug->leave_sub();
1706 sub update_balance {
1707 $main::lxdebug->enter_sub();
1709 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1711 # if we have a value, go do it
1714 # retrieve balance from table
1715 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1716 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1717 my ($balance) = $sth->fetchrow_array;
1723 $query = "UPDATE $table SET $field = $balance WHERE $where";
1724 do_query($self, $dbh, $query, @values);
1726 $main::lxdebug->leave_sub();
1729 sub update_exchangerate {
1730 $main::lxdebug->enter_sub();
1732 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1734 # some sanity check for currency
1736 $main::lxdebug->leave_sub();
1739 $query = qq|SELECT curr FROM defaults|;
1741 my ($currency) = selectrow_query($self, $dbh, $query);
1742 my ($defaultcurrency) = split m/:/, $currency;
1745 if ($curr eq $defaultcurrency) {
1746 $main::lxdebug->leave_sub();
1750 $query = qq|SELECT e.curr FROM exchangerate e
1751 WHERE e.curr = ? AND e.transdate = ?
1753 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1762 $buy = conv_i($buy, "NULL");
1763 $sell = conv_i($sell, "NULL");
1766 if ($buy != 0 && $sell != 0) {
1767 $set = "buy = $buy, sell = $sell";
1768 } elsif ($buy != 0) {
1769 $set = "buy = $buy";
1770 } elsif ($sell != 0) {
1771 $set = "sell = $sell";
1774 if ($sth->fetchrow_array) {
1775 $query = qq|UPDATE exchangerate
1781 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1782 VALUES (?, $buy, $sell, ?)|;
1785 do_query($self, $dbh, $query, $curr, $transdate);
1787 $main::lxdebug->leave_sub();
1790 sub save_exchangerate {
1791 $main::lxdebug->enter_sub();
1793 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1795 my $dbh = $self->dbconnect($myconfig);
1799 $buy = $rate if $fld eq 'buy';
1800 $sell = $rate if $fld eq 'sell';
1803 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1808 $main::lxdebug->leave_sub();
1811 sub get_exchangerate {
1812 $main::lxdebug->enter_sub();
1814 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1817 unless ($transdate) {
1818 $main::lxdebug->leave_sub();
1822 $query = qq|SELECT curr FROM defaults|;
1824 my ($currency) = selectrow_query($self, $dbh, $query);
1825 my ($defaultcurrency) = split m/:/, $currency;
1827 if ($currency eq $defaultcurrency) {
1828 $main::lxdebug->leave_sub();
1832 $query = qq|SELECT e.$fld FROM exchangerate e
1833 WHERE e.curr = ? AND e.transdate = ?|;
1834 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1838 $main::lxdebug->leave_sub();
1840 return $exchangerate;
1843 sub check_exchangerate {
1844 $main::lxdebug->enter_sub();
1846 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1848 if ($fld !~/^buy|sell$/) {
1849 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1852 unless ($transdate) {
1853 $main::lxdebug->leave_sub();
1857 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1859 if ($currency eq $defaultcurrency) {
1860 $main::lxdebug->leave_sub();
1864 my $dbh = $self->get_standard_dbh($myconfig);
1865 my $query = qq|SELECT e.$fld FROM exchangerate e
1866 WHERE e.curr = ? AND e.transdate = ?|;
1868 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1870 $main::lxdebug->leave_sub();
1872 return $exchangerate;
1875 sub get_all_currencies {
1876 $main::lxdebug->enter_sub();
1879 my $myconfig = shift || \%::myconfig;
1880 my $dbh = $self->get_standard_dbh($myconfig);
1882 my $query = qq|SELECT curr FROM defaults|;
1884 my ($curr) = selectrow_query($self, $dbh, $query);
1885 my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
1887 $main::lxdebug->leave_sub();
1892 sub get_default_currency {
1893 $main::lxdebug->enter_sub();
1895 my ($self, $myconfig) = @_;
1896 my @currencies = $self->get_all_currencies($myconfig);
1898 $main::lxdebug->leave_sub();
1900 return $currencies[0];
1903 sub set_payment_options {
1904 $main::lxdebug->enter_sub();
1906 my ($self, $myconfig, $transdate) = @_;
1908 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1910 my $dbh = $self->get_standard_dbh($myconfig);
1913 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long , p.description | .
1914 qq|FROM payment_terms p | .
1917 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1918 $self->{payment_terms}, $self->{payment_description}) =
1919 selectrow_query($self, $dbh, $query, $self->{payment_id});
1921 if ($transdate eq "") {
1922 if ($self->{invdate}) {
1923 $transdate = $self->{invdate};
1925 $transdate = $self->{transdate};
1930 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1931 qq|FROM payment_terms|;
1932 ($self->{netto_date}, $self->{skonto_date}) =
1933 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1935 my ($invtotal, $total);
1936 my (%amounts, %formatted_amounts);
1938 if ($self->{type} =~ /_order$/) {
1939 $amounts{invtotal} = $self->{ordtotal};
1940 $amounts{total} = $self->{ordtotal};
1942 } elsif ($self->{type} =~ /_quotation$/) {
1943 $amounts{invtotal} = $self->{quototal};
1944 $amounts{total} = $self->{quototal};
1947 $amounts{invtotal} = $self->{invtotal};
1948 $amounts{total} = $self->{total};
1950 $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1952 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1954 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1955 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1956 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1958 foreach (keys %amounts) {
1959 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1960 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1963 if ($self->{"language_id"}) {
1965 qq|SELECT t.translation, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1966 qq|FROM generic_translations t | .
1967 qq|LEFT JOIN language l ON t.language_id = l.id | .
1968 qq|WHERE (t.language_id = ?)
1969 AND (t.translation_id = ?)
1970 AND (t.translation_type = 'SL::DB::PaymentTerm/description_long')|;
1971 my ($description_long, $output_numberformat, $output_dateformat,
1972 $output_longdates) =
1973 selectrow_query($self, $dbh, $query,
1974 $self->{"language_id"}, $self->{"payment_id"});
1976 $self->{payment_terms} = $description_long if ($description_long);
1978 if ($output_dateformat) {
1979 foreach my $key (qw(netto_date skonto_date)) {
1981 $main::locale->reformat_date($myconfig, $self->{$key},
1987 if ($output_numberformat &&
1988 ($output_numberformat ne $myconfig->{"numberformat"})) {
1989 my $saved_numberformat = $myconfig->{"numberformat"};
1990 $myconfig->{"numberformat"} = $output_numberformat;
1991 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1992 $myconfig->{"numberformat"} = $saved_numberformat;
1996 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1997 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1998 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1999 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
2000 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
2001 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
2002 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
2004 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
2006 $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
2008 $main::lxdebug->leave_sub();
2012 sub get_template_language {
2013 $main::lxdebug->enter_sub();
2015 my ($self, $myconfig) = @_;
2017 my $template_code = "";
2019 if ($self->{language_id}) {
2020 my $dbh = $self->get_standard_dbh($myconfig);
2021 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
2022 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
2025 $main::lxdebug->leave_sub();
2027 return $template_code;
2030 sub get_printer_code {
2031 $main::lxdebug->enter_sub();
2033 my ($self, $myconfig) = @_;
2035 my $template_code = "";
2037 if ($self->{printer_id}) {
2038 my $dbh = $self->get_standard_dbh($myconfig);
2039 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
2040 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
2043 $main::lxdebug->leave_sub();
2045 return $template_code;
2049 $main::lxdebug->enter_sub();
2051 my ($self, $myconfig) = @_;
2053 my $template_code = "";
2055 if ($self->{shipto_id}) {
2056 my $dbh = $self->get_standard_dbh($myconfig);
2057 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
2058 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
2059 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
2062 $main::lxdebug->leave_sub();
2066 $main::lxdebug->enter_sub();
2068 my ($self, $dbh, $id, $module) = @_;
2073 foreach my $item (qw(name department_1 department_2 street zipcode city country
2074 contact cp_gender phone fax email)) {
2075 if ($self->{"shipto$item"}) {
2076 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
2078 push(@values, $self->{"shipto${item}"});
2082 if ($self->{shipto_id}) {
2083 my $query = qq|UPDATE shipto set
2085 shiptodepartment_1 = ?,
2086 shiptodepartment_2 = ?,
2092 shiptocp_gender = ?,
2096 WHERE shipto_id = ?|;
2097 do_query($self, $dbh, $query, @values, $self->{shipto_id});
2099 my $query = qq|SELECT * FROM shipto
2100 WHERE shiptoname = ? AND
2101 shiptodepartment_1 = ? AND
2102 shiptodepartment_2 = ? AND
2103 shiptostreet = ? AND
2104 shiptozipcode = ? AND
2106 shiptocountry = ? AND
2107 shiptocontact = ? AND
2108 shiptocp_gender = ? AND
2114 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
2117 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
2118 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
2119 shiptocontact, shiptocp_gender, shiptophone, shiptofax, shiptoemail, module)
2120 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
2121 do_query($self, $dbh, $query, $id, @values, $module);
2126 $main::lxdebug->leave_sub();
2130 $main::lxdebug->enter_sub();
2132 my ($self, $dbh) = @_;
2134 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
2136 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2137 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2138 $self->{"employee_id"} *= 1;
2140 $main::lxdebug->leave_sub();
2143 sub get_employee_data {
2144 $main::lxdebug->enter_sub();
2149 Common::check_params(\%params, qw(prefix));
2150 Common::check_params_x(\%params, qw(id));
2153 $main::lxdebug->leave_sub();
2157 my $myconfig = \%main::myconfig;
2158 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
2160 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2163 my $user = User->new($login);
2164 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2166 $self->{$params{prefix} . '_login'} = $login;
2167 $self->{$params{prefix} . '_name'} ||= $login;
2170 $main::lxdebug->leave_sub();
2174 $main::lxdebug->enter_sub();
2176 my ($self, $myconfig, $reference_date) = @_;
2178 $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2180 my $dbh = $self->get_standard_dbh($myconfig);
2181 my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2182 my ($duedate) = selectrow_query($self, $dbh, $query, $self->{payment_id});
2184 $main::lxdebug->leave_sub();
2190 $main::lxdebug->enter_sub();
2192 my ($self, $dbh, $id, $key) = @_;
2194 $key = "all_contacts" unless ($key);
2198 $main::lxdebug->leave_sub();
2203 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2204 qq|FROM contacts | .
2205 qq|WHERE cp_cv_id = ? | .
2206 qq|ORDER BY lower(cp_name)|;
2208 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2210 $main::lxdebug->leave_sub();
2214 $main::lxdebug->enter_sub();
2216 my ($self, $dbh, $key) = @_;
2218 my ($all, $old_id, $where, @values);
2220 if (ref($key) eq "HASH") {
2223 $key = "ALL_PROJECTS";
2225 foreach my $p (keys(%{$params})) {
2227 $all = $params->{$p};
2228 } elsif ($p eq "old_id") {
2229 $old_id = $params->{$p};
2230 } elsif ($p eq "key") {
2231 $key = $params->{$p};
2237 $where = "WHERE active ";
2239 if (ref($old_id) eq "ARRAY") {
2240 my @ids = grep({ $_ } @{$old_id});
2242 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2243 push(@values, @ids);
2246 $where .= " OR (id = ?) ";
2247 push(@values, $old_id);
2253 qq|SELECT id, projectnumber, description, active | .
2256 qq|ORDER BY lower(projectnumber)|;
2258 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2260 $main::lxdebug->leave_sub();
2264 $main::lxdebug->enter_sub();
2266 my ($self, $dbh, $vc_id, $key) = @_;
2268 $key = "all_shipto" unless ($key);
2271 # get shipping addresses
2272 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2274 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2280 $main::lxdebug->leave_sub();
2284 $main::lxdebug->enter_sub();
2286 my ($self, $dbh, $key) = @_;
2288 $key = "all_printers" unless ($key);
2290 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2292 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2294 $main::lxdebug->leave_sub();
2298 $main::lxdebug->enter_sub();
2300 my ($self, $dbh, $params) = @_;
2303 $key = $params->{key};
2304 $key = "all_charts" unless ($key);
2306 my $transdate = quote_db_date($params->{transdate});
2309 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2311 qq|LEFT JOIN taxkeys tk ON | .
2312 qq|(tk.id = (SELECT id FROM taxkeys | .
2313 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2314 qq| ORDER BY startdate DESC LIMIT 1)) | .
2315 qq|ORDER BY c.accno|;
2317 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2319 $main::lxdebug->leave_sub();
2322 sub _get_taxcharts {
2323 $main::lxdebug->enter_sub();
2325 my ($self, $dbh, $params) = @_;
2327 my $key = "all_taxcharts";
2330 if (ref $params eq 'HASH') {
2331 $key = $params->{key} if ($params->{key});
2332 if ($params->{module} eq 'AR') {
2333 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2335 } elsif ($params->{module} eq 'AP') {
2336 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2343 my $where = @where ? ' WHERE ' . join(' AND ', map { "($_)" } @where) : '';
2345 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2347 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2349 $main::lxdebug->leave_sub();
2353 $main::lxdebug->enter_sub();
2355 my ($self, $dbh, $key) = @_;
2357 $key = "all_taxzones" unless ($key);
2359 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2361 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2363 $main::lxdebug->leave_sub();
2366 sub _get_employees {
2367 $main::lxdebug->enter_sub();
2369 my ($self, $dbh, $default_key, $key) = @_;
2371 $key = $default_key unless ($key);
2372 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2374 $main::lxdebug->leave_sub();
2377 sub _get_business_types {
2378 $main::lxdebug->enter_sub();
2380 my ($self, $dbh, $key) = @_;
2382 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2383 $options->{key} ||= "all_business_types";
2386 if (exists $options->{salesman}) {
2387 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2390 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2392 $main::lxdebug->leave_sub();
2395 sub _get_languages {
2396 $main::lxdebug->enter_sub();
2398 my ($self, $dbh, $key) = @_;
2400 $key = "all_languages" unless ($key);
2402 my $query = qq|SELECT * FROM language ORDER BY id|;
2404 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2406 $main::lxdebug->leave_sub();
2409 sub _get_dunning_configs {
2410 $main::lxdebug->enter_sub();
2412 my ($self, $dbh, $key) = @_;
2414 $key = "all_dunning_configs" unless ($key);
2416 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2418 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2420 $main::lxdebug->leave_sub();
2423 sub _get_currencies {
2424 $main::lxdebug->enter_sub();
2426 my ($self, $dbh, $key) = @_;
2428 $key = "all_currencies" unless ($key);
2430 my $query = qq|SELECT curr AS currency FROM defaults|;
2432 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2434 $main::lxdebug->leave_sub();
2438 $main::lxdebug->enter_sub();
2440 my ($self, $dbh, $key) = @_;
2442 $key = "all_payments" unless ($key);
2444 my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2446 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2448 $main::lxdebug->leave_sub();
2451 sub _get_customers {
2452 $main::lxdebug->enter_sub();
2454 my ($self, $dbh, $key) = @_;
2456 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2457 $options->{key} ||= "all_customers";
2458 my $limit_clause = $options->{limit} ? "LIMIT $options->{limit}" : '';
2461 push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman};
2462 push @where, qq|NOT obsolete| if !$options->{with_obsolete};
2463 my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2465 my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2466 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2468 $main::lxdebug->leave_sub();
2472 $main::lxdebug->enter_sub();
2474 my ($self, $dbh, $key) = @_;
2476 $key = "all_vendors" unless ($key);
2478 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2480 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2482 $main::lxdebug->leave_sub();
2485 sub _get_departments {
2486 $main::lxdebug->enter_sub();
2488 my ($self, $dbh, $key) = @_;
2490 $key = "all_departments" unless ($key);
2492 my $query = qq|SELECT * FROM department ORDER BY description|;
2494 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2496 $main::lxdebug->leave_sub();
2499 sub _get_warehouses {
2500 $main::lxdebug->enter_sub();
2502 my ($self, $dbh, $param) = @_;
2504 my ($key, $bins_key);
2506 if ('' eq ref $param) {
2510 $key = $param->{key};
2511 $bins_key = $param->{bins};
2514 my $query = qq|SELECT w.* FROM warehouse w
2515 WHERE (NOT w.invalid) AND
2516 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2517 ORDER BY w.sortkey|;
2519 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2522 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2523 ORDER BY description|;
2524 my $sth = prepare_query($self, $dbh, $query);
2526 foreach my $warehouse (@{ $self->{$key} }) {
2527 do_statement($self, $sth, $query, $warehouse->{id});
2528 $warehouse->{$bins_key} = [];
2530 while (my $ref = $sth->fetchrow_hashref()) {
2531 push @{ $warehouse->{$bins_key} }, $ref;
2537 $main::lxdebug->leave_sub();
2541 $main::lxdebug->enter_sub();
2543 my ($self, $dbh, $table, $key, $sortkey) = @_;
2545 my $query = qq|SELECT * FROM $table|;
2546 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2548 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2550 $main::lxdebug->leave_sub();
2554 # $main::lxdebug->enter_sub();
2556 # my ($self, $dbh, $key) = @_;
2558 # $key ||= "all_groups";
2560 # my $groups = $main::auth->read_groups();
2562 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2564 # $main::lxdebug->leave_sub();
2568 $main::lxdebug->enter_sub();
2573 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2574 my ($sth, $query, $ref);
2576 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2577 my $vc_id = $self->{"${vc}_id"};
2579 if ($params{"contacts"}) {
2580 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2583 if ($params{"shipto"}) {
2584 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2587 if ($params{"projects"} || $params{"all_projects"}) {
2588 $self->_get_projects($dbh, $params{"all_projects"} ?
2589 $params{"all_projects"} : $params{"projects"},
2590 $params{"all_projects"} ? 1 : 0);
2593 if ($params{"printers"}) {
2594 $self->_get_printers($dbh, $params{"printers"});
2597 if ($params{"languages"}) {
2598 $self->_get_languages($dbh, $params{"languages"});
2601 if ($params{"charts"}) {
2602 $self->_get_charts($dbh, $params{"charts"});
2605 if ($params{"taxcharts"}) {
2606 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2609 if ($params{"taxzones"}) {
2610 $self->_get_taxzones($dbh, $params{"taxzones"});
2613 if ($params{"employees"}) {
2614 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2617 if ($params{"salesmen"}) {
2618 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2621 if ($params{"business_types"}) {
2622 $self->_get_business_types($dbh, $params{"business_types"});
2625 if ($params{"dunning_configs"}) {
2626 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2629 if($params{"currencies"}) {
2630 $self->_get_currencies($dbh, $params{"currencies"});
2633 if($params{"customers"}) {
2634 $self->_get_customers($dbh, $params{"customers"});
2637 if($params{"vendors"}) {
2638 if (ref $params{"vendors"} eq 'HASH') {
2639 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2641 $self->_get_vendors($dbh, $params{"vendors"});
2645 if($params{"payments"}) {
2646 $self->_get_payments($dbh, $params{"payments"});
2649 if($params{"departments"}) {
2650 $self->_get_departments($dbh, $params{"departments"});
2653 if ($params{price_factors}) {
2654 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2657 if ($params{warehouses}) {
2658 $self->_get_warehouses($dbh, $params{warehouses});
2661 # if ($params{groups}) {
2662 # $self->_get_groups($dbh, $params{groups});
2665 if ($params{partsgroup}) {
2666 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2669 $main::lxdebug->leave_sub();
2672 # this sub gets the id and name from $table
2674 $main::lxdebug->enter_sub();
2676 my ($self, $myconfig, $table) = @_;
2678 # connect to database
2679 my $dbh = $self->get_standard_dbh($myconfig);
2681 $table = $table eq "customer" ? "customer" : "vendor";
2682 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2684 my ($query, @values);
2686 if (!$self->{openinvoices}) {
2688 if ($self->{customernumber} ne "") {
2689 $where = qq|(vc.customernumber ILIKE ?)|;
2690 push(@values, '%' . $self->{customernumber} . '%');
2692 $where = qq|(vc.name ILIKE ?)|;
2693 push(@values, '%' . $self->{$table} . '%');
2697 qq~SELECT vc.id, vc.name,
2698 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2700 WHERE $where AND (NOT vc.obsolete)
2704 qq~SELECT DISTINCT vc.id, vc.name,
2705 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2707 JOIN $table vc ON (a.${table}_id = vc.id)
2708 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2710 push(@values, '%' . $self->{$table} . '%');
2713 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2715 $main::lxdebug->leave_sub();
2717 return scalar(@{ $self->{name_list} });
2720 # the selection sub is used in the AR, AP, IS, IR and OE module
2723 $main::lxdebug->enter_sub();
2725 my ($self, $myconfig, $table, $module) = @_;
2728 my $dbh = $self->get_standard_dbh;
2730 $table = $table eq "customer" ? "customer" : "vendor";
2732 my $query = qq|SELECT count(*) FROM $table|;
2733 my ($count) = selectrow_query($self, $dbh, $query);
2735 # build selection list
2736 if ($count <= $myconfig->{vclimit}) {
2737 $query = qq|SELECT id, name, salesman_id
2738 FROM $table WHERE NOT obsolete
2740 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2744 $self->get_employee($dbh);
2746 # setup sales contacts
2747 $query = qq|SELECT e.id, e.name
2749 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2750 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2753 push(@{ $self->{all_employees} },
2754 { id => $self->{employee_id},
2755 name => $self->{employee} });
2757 # sort the whole thing
2758 @{ $self->{all_employees} } =
2759 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2762 # prepare query for departments
2763 $query = qq|SELECT id, description
2765 ORDER BY description|;
2767 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2770 $query = qq|SELECT id, description
2774 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2777 $query = qq|SELECT printer_description, id
2779 ORDER BY printer_description|;
2781 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2784 $query = qq|SELECT id, description
2788 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2790 $main::lxdebug->leave_sub();
2793 sub language_payment {
2794 $main::lxdebug->enter_sub();
2796 my ($self, $myconfig) = @_;
2798 my $dbh = $self->get_standard_dbh($myconfig);
2800 my $query = qq|SELECT id, description
2804 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2807 $query = qq|SELECT printer_description, id
2809 ORDER BY printer_description|;
2811 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2814 $query = qq|SELECT id, description
2818 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2820 # get buchungsgruppen
2821 $query = qq|SELECT id, description
2822 FROM buchungsgruppen|;
2824 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2826 $main::lxdebug->leave_sub();
2829 # this is only used for reports
2830 sub all_departments {
2831 $main::lxdebug->enter_sub();
2833 my ($self, $myconfig, $table) = @_;
2835 my $dbh = $self->get_standard_dbh($myconfig);
2837 my $query = qq|SELECT id, description
2839 ORDER BY description|;
2840 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2842 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2844 $main::lxdebug->leave_sub();
2848 $main::lxdebug->enter_sub();
2850 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2853 if ($table eq "customer") {
2862 $self->all_vc($myconfig, $table, $module);
2864 # get last customers or vendors
2865 my ($query, $sth, $ref);
2867 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2872 my $transdate = "current_date";
2873 if ($self->{transdate}) {
2874 $transdate = $dbh->quote($self->{transdate});
2877 # now get the account numbers
2878 # $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2879 # FROM chart c, taxkeys tk
2880 # WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2881 # (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2882 # ORDER BY c.accno|;
2884 # same query as above, but without expensive subquery for each row. about 80% faster
2886 SELECT c.accno, c.description, c.link, c.taxkey_id, tk2.tax_id
2888 -- find newest entries in taxkeys
2890 SELECT chart_id, MAX(startdate) AS startdate
2892 WHERE (startdate <= $transdate)
2894 ) tk ON (c.id = tk.chart_id)
2895 -- and load all of those entries
2896 INNER JOIN taxkeys tk2
2897 ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
2898 WHERE (c.link LIKE ?)
2901 $sth = $dbh->prepare($query);
2903 do_statement($self, $sth, $query, '%' . $module . '%');
2905 $self->{accounts} = "";
2906 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2908 foreach my $key (split(/:/, $ref->{link})) {
2909 if ($key =~ /\Q$module\E/) {
2911 # cross reference for keys
2912 $xkeyref{ $ref->{accno} } = $key;
2914 push @{ $self->{"${module}_links"}{$key} },
2915 { accno => $ref->{accno},
2916 description => $ref->{description},
2917 taxkey => $ref->{taxkey_id},
2918 tax_id => $ref->{tax_id} };
2920 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2926 # get taxkeys and description
2927 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2928 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2930 if (($module eq "AP") || ($module eq "AR")) {
2931 # get tax rates and description
2932 $query = qq|SELECT * FROM tax|;
2933 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2939 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2940 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2941 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2942 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2945 d.description AS department,
2948 JOIN $table c ON (a.${table}_id = c.id)
2949 LEFT JOIN employee e ON (e.id = a.employee_id)
2950 LEFT JOIN department d ON (d.id = a.department_id)
2952 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2954 foreach my $key (keys %$ref) {
2955 $self->{$key} = $ref->{$key};
2958 # remove any trailing whitespace
2959 $self->{currency} =~ s/\s*$//;
2961 my $transdate = "current_date";
2962 if ($self->{transdate}) {
2963 $transdate = $dbh->quote($self->{transdate});
2966 # now get the account numbers
2967 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2969 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2971 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2972 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2975 $sth = $dbh->prepare($query);
2976 do_statement($self, $sth, $query, "%$module%");
2978 $self->{accounts} = "";
2979 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2981 foreach my $key (split(/:/, $ref->{link})) {
2982 if ($key =~ /\Q$module\E/) {
2984 # cross reference for keys
2985 $xkeyref{ $ref->{accno} } = $key;
2987 push @{ $self->{"${module}_links"}{$key} },
2988 { accno => $ref->{accno},
2989 description => $ref->{description},
2990 taxkey => $ref->{taxkey_id},
2991 tax_id => $ref->{tax_id} };
2993 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2999 # get amounts from individual entries
3002 c.accno, c.description,
3003 a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey,
3007 LEFT JOIN chart c ON (c.id = a.chart_id)
3008 LEFT JOIN project p ON (p.id = a.project_id)
3009 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
3010 WHERE (tk.taxkey_id=a.taxkey) AND
3011 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
3012 THEN tk.chart_id = a.chart_id
3015 OR (c.link='%tax%')) AND
3016 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
3017 WHERE a.trans_id = ?
3018 AND a.fx_transaction = '0'
3019 ORDER BY a.acc_trans_id, a.transdate|;
3020 $sth = $dbh->prepare($query);
3021 do_statement($self, $sth, $query, $self->{id});
3023 # get exchangerate for currency
3024 $self->{exchangerate} =
3025 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
3028 # store amounts in {acc_trans}{$key} for multiple accounts
3029 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
3030 $ref->{exchangerate} =
3031 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
3032 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
3035 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
3036 $ref->{amount} *= -1;
3038 $ref->{index} = $index;
3040 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
3046 d.curr AS currencies, d.closedto, d.revtrans,
3047 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
3048 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
3050 $ref = selectfirst_hashref_query($self, $dbh, $query);
3051 map { $self->{$_} = $ref->{$_} } keys %$ref;
3058 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
3059 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
3060 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
3062 $ref = selectfirst_hashref_query($self, $dbh, $query);
3063 map { $self->{$_} = $ref->{$_} } keys %$ref;
3065 if ($self->{"$self->{vc}_id"}) {
3067 # only setup currency
3068 ($self->{currency}) = split(/:/, $self->{currencies});
3072 $self->lastname_used($dbh, $myconfig, $table, $module);
3074 # get exchangerate for currency
3075 $self->{exchangerate} =
3076 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
3082 $main::lxdebug->leave_sub();
3086 $main::lxdebug->enter_sub();
3088 my ($self, $dbh, $myconfig, $table, $module) = @_;
3092 $table = $table eq "customer" ? "customer" : "vendor";
3093 my %column_map = ("a.curr" => "currency",
3094 "a.${table}_id" => "${table}_id",
3095 "a.department_id" => "department_id",
3096 "d.description" => "department",
3097 "ct.name" => $table,
3098 "current_date + ct.terms" => "duedate",
3101 if ($self->{type} =~ /delivery_order/) {
3102 $arap = 'delivery_orders';
3103 delete $column_map{"a.curr"};
3105 } elsif ($self->{type} =~ /_order/) {
3107 $where = "quotation = '0'";
3109 } elsif ($self->{type} =~ /_quotation/) {
3111 $where = "quotation = '1'";
3113 } elsif ($table eq 'customer') {
3121 $where = "($where) AND" if ($where);
3122 my $query = qq|SELECT MAX(id) FROM $arap
3123 WHERE $where ${table}_id > 0|;
3124 my ($trans_id) = selectrow_query($self, $dbh, $query);
3127 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
3128 $query = qq|SELECT $column_spec
3130 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
3131 LEFT JOIN department d ON (a.department_id = d.id)
3133 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3135 map { $self->{$_} = $ref->{$_} } values %column_map;
3137 # remove any trailing whitespace
3138 $self->{currency} =~ s/\s*$// if $self->{currency};
3140 $main::lxdebug->leave_sub();
3144 $main::lxdebug->enter_sub();
3147 my $myconfig = shift || \%::myconfig;
3148 my ($thisdate, $days) = @_;
3150 my $dbh = $self->get_standard_dbh($myconfig);
3155 my $dateformat = $myconfig->{dateformat};
3156 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3157 $thisdate = $dbh->quote($thisdate);
3158 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3160 $query = qq|SELECT current_date AS thisdate|;
3163 ($thisdate) = selectrow_query($self, $dbh, $query);
3165 $main::lxdebug->leave_sub();
3171 $main::lxdebug->enter_sub();
3173 my ($self, $string) = @_;
3175 if ($string !~ /%/) {
3176 $string = "%$string%";
3179 $string =~ s/\'/\'\'/g;
3181 $main::lxdebug->leave_sub();
3187 $main::lxdebug->enter_sub();
3189 my ($self, $flds, $new, $count, $numrows) = @_;
3193 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3198 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3200 my $j = $item->{ndx} - 1;
3201 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3205 for $i ($count + 1 .. $numrows) {
3206 map { delete $self->{"${_}_$i"} } @{$flds};
3209 $main::lxdebug->leave_sub();
3213 $main::lxdebug->enter_sub();
3215 my ($self, $myconfig) = @_;
3219 my $dbh = $self->dbconnect_noauto($myconfig);
3221 my $query = qq|DELETE FROM status
3222 WHERE (formname = ?) AND (trans_id = ?)|;
3223 my $sth = prepare_query($self, $dbh, $query);
3225 if ($self->{formname} =~ /(check|receipt)/) {
3226 for $i (1 .. $self->{rowcount}) {
3227 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3230 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3234 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3235 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3237 my %queued = split / /, $self->{queued};
3240 if ($self->{formname} =~ /(check|receipt)/) {
3242 # this is a check or receipt, add one entry for each lineitem
3243 my ($accno) = split /--/, $self->{account};
3244 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3245 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3246 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3247 $sth = prepare_query($self, $dbh, $query);
3249 for $i (1 .. $self->{rowcount}) {
3250 if ($self->{"checked_$i"}) {
3251 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3257 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3258 VALUES (?, ?, ?, ?, ?)|;
3259 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3260 $queued{$self->{formname}}, $self->{formname});
3266 $main::lxdebug->leave_sub();
3270 $main::lxdebug->enter_sub();
3272 my ($self, $dbh) = @_;
3274 my ($query, $printed, $emailed);
3276 my $formnames = $self->{printed};
3277 my $emailforms = $self->{emailed};
3279 $query = qq|DELETE FROM status
3280 WHERE (formname = ?) AND (trans_id = ?)|;
3281 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3283 # this only applies to the forms
3284 # checks and receipts are posted when printed or queued
3286 if ($self->{queued}) {
3287 my %queued = split / /, $self->{queued};
3289 foreach my $formname (keys %queued) {
3290 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3291 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3293 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3294 VALUES (?, ?, ?, ?, ?)|;
3295 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3297 $formnames =~ s/\Q$self->{formname}\E//;
3298 $emailforms =~ s/\Q$self->{formname}\E//;
3303 # save printed, emailed info
3304 $formnames =~ s/^ +//g;
3305 $emailforms =~ s/^ +//g;
3308 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3309 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3311 foreach my $formname (keys %status) {
3312 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3313 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3315 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3316 VALUES (?, ?, ?, ?)|;
3317 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3320 $main::lxdebug->leave_sub();
3324 # $main::locale->text('SAVED')
3325 # $main::locale->text('DELETED')
3326 # $main::locale->text('ADDED')
3327 # $main::locale->text('PAYMENT POSTED')
3328 # $main::locale->text('POSTED')
3329 # $main::locale->text('POSTED AS NEW')
3330 # $main::locale->text('ELSE')
3331 # $main::locale->text('SAVED FOR DUNNING')
3332 # $main::locale->text('DUNNING STARTED')
3333 # $main::locale->text('PRINTED')
3334 # $main::locale->text('MAILED')
3335 # $main::locale->text('SCREENED')
3336 # $main::locale->text('CANCELED')
3337 # $main::locale->text('invoice')
3338 # $main::locale->text('proforma')
3339 # $main::locale->text('sales_order')
3340 # $main::locale->text('pick_list')
3341 # $main::locale->text('purchase_order')
3342 # $main::locale->text('bin_list')
3343 # $main::locale->text('sales_quotation')
3344 # $main::locale->text('request_quotation')
3347 $main::lxdebug->enter_sub();
3350 my $dbh = shift || $self->get_standard_dbh;
3352 if(!exists $self->{employee_id}) {
3353 &get_employee($self, $dbh);
3357 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3358 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3359 my @values = (conv_i($self->{id}), $self->{login},
3360 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3361 do_query($self, $dbh, $query, @values);
3365 $main::lxdebug->leave_sub();
3369 $main::lxdebug->enter_sub();
3371 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3372 my ($orderBy, $desc) = split(/\-\-/, $order);
3373 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3376 if ($trans_id ne "") {
3378 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 | .
3379 qq|FROM history_erp h | .
3380 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3381 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3384 my $sth = $dbh->prepare($query) || $self->dberror($query);
3386 $sth->execute() || $self->dberror("$query");
3388 while(my $hash_ref = $sth->fetchrow_hashref()) {
3389 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3390 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3391 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3392 $tempArray[$i++] = $hash_ref;
3394 $main::lxdebug->leave_sub() and return \@tempArray
3395 if ($i > 0 && $tempArray[0] ne "");
3397 $main::lxdebug->leave_sub();
3401 sub update_defaults {
3402 $main::lxdebug->enter_sub();
3404 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3407 if ($provided_dbh) {
3408 $dbh = $provided_dbh;
3410 $dbh = $self->dbconnect_noauto($myconfig);
3412 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3413 my $sth = $dbh->prepare($query);
3415 $sth->execute || $self->dberror($query);
3416 my ($var) = $sth->fetchrow_array;
3419 if ($var =~ m/\d+$/) {
3420 my $new_var = (substr $var, $-[0]) * 1 + 1;
3421 my $len_diff = length($var) - $-[0] - length($new_var);
3422 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3428 $query = qq|UPDATE defaults SET $fld = ?|;
3429 do_query($self, $dbh, $query, $var);
3431 if (!$provided_dbh) {
3436 $main::lxdebug->leave_sub();
3441 sub update_business {
3442 $main::lxdebug->enter_sub();
3444 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3447 if ($provided_dbh) {
3448 $dbh = $provided_dbh;
3450 $dbh = $self->dbconnect_noauto($myconfig);
3453 qq|SELECT customernumberinit FROM business
3454 WHERE id = ? FOR UPDATE|;
3455 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3457 return undef unless $var;
3459 if ($var =~ m/\d+$/) {
3460 my $new_var = (substr $var, $-[0]) * 1 + 1;
3461 my $len_diff = length($var) - $-[0] - length($new_var);
3462 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3468 $query = qq|UPDATE business
3469 SET customernumberinit = ?
3471 do_query($self, $dbh, $query, $var, $business_id);
3473 if (!$provided_dbh) {
3478 $main::lxdebug->leave_sub();
3483 sub get_partsgroup {
3484 $main::lxdebug->enter_sub();
3486 my ($self, $myconfig, $p) = @_;
3487 my $target = $p->{target} || 'all_partsgroup';
3489 my $dbh = $self->get_standard_dbh($myconfig);
3491 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3493 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3496 if ($p->{searchitems} eq 'part') {
3497 $query .= qq|WHERE p.inventory_accno_id > 0|;
3499 if ($p->{searchitems} eq 'service') {
3500 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3502 if ($p->{searchitems} eq 'assembly') {
3503 $query .= qq|WHERE p.assembly = '1'|;
3505 if ($p->{searchitems} eq 'labor') {
3506 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3509 $query .= qq|ORDER BY partsgroup|;
3512 $query = qq|SELECT id, partsgroup FROM partsgroup
3513 ORDER BY partsgroup|;
3516 if ($p->{language_code}) {
3517 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3518 t.description AS translation
3520 JOIN parts p ON (p.partsgroup_id = pg.id)
3521 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3522 ORDER BY translation|;
3523 @values = ($p->{language_code});
3526 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3528 $main::lxdebug->leave_sub();
3531 sub get_pricegroup {
3532 $main::lxdebug->enter_sub();
3534 my ($self, $myconfig, $p) = @_;
3536 my $dbh = $self->get_standard_dbh($myconfig);
3538 my $query = qq|SELECT p.id, p.pricegroup
3541 $query .= qq| ORDER BY pricegroup|;
3544 $query = qq|SELECT id, pricegroup FROM pricegroup
3545 ORDER BY pricegroup|;
3548 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3550 $main::lxdebug->leave_sub();
3554 # usage $form->all_years($myconfig, [$dbh])
3555 # return list of all years where bookings found
3558 $main::lxdebug->enter_sub();
3560 my ($self, $myconfig, $dbh) = @_;
3562 $dbh ||= $self->get_standard_dbh($myconfig);
3565 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3566 (SELECT MAX(transdate) FROM acc_trans)|;
3567 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3569 if ($myconfig->{dateformat} =~ /^yy/) {
3570 ($startdate) = split /\W/, $startdate;
3571 ($enddate) = split /\W/, $enddate;
3573 (@_) = split /\W/, $startdate;
3575 (@_) = split /\W/, $enddate;
3580 $startdate = substr($startdate,0,4);
3581 $enddate = substr($enddate,0,4);
3583 while ($enddate >= $startdate) {
3584 push @all_years, $enddate--;
3589 $main::lxdebug->leave_sub();
3593 $main::lxdebug->enter_sub();
3597 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3599 $main::lxdebug->leave_sub();
3603 $main::lxdebug->enter_sub();
3608 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3610 $main::lxdebug->leave_sub();
3613 sub prepare_for_printing {
3616 $self->{templates} ||= $::myconfig{templates};
3617 $self->{formname} ||= $self->{type};
3618 $self->{media} ||= 'email';
3620 die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3622 # set shipto from billto unless set
3623 my $has_shipto = any { $self->{"shipto$_"} } qw(name street zipcode city country contact);
3624 if (!$has_shipto && ($self->{type} =~ m/^(?:purchase_order|request_quotation)$/)) {
3625 $self->{shiptoname} = $::myconfig{company};
3626 $self->{shiptostreet} = $::myconfig{address};
3629 my $language = $self->{language} ? '_' . $self->{language} : '';
3631 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3632 if ($self->{language_id}) {
3633 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3635 $output_dateformat = $::myconfig{dateformat};
3636 $output_numberformat = $::myconfig{numberformat};
3637 $output_longdates = 1;
3640 # Retrieve accounts for tax calculation.
3641 IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3643 if ($self->{type} =~ /_delivery_order$/) {
3644 DO->order_details();
3645 } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3646 OE->order_details(\%::myconfig, $self);
3648 IS->invoice_details(\%::myconfig, $self, $::locale);
3651 # Chose extension & set source file name
3652 my $extension = 'html';
3653 if ($self->{format} eq 'postscript') {
3654 $self->{postscript} = 1;
3656 } elsif ($self->{"format"} =~ /pdf/) {
3658 $extension = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3659 } elsif ($self->{"format"} =~ /opendocument/) {
3660 $self->{opendocument} = 1;
3662 } elsif ($self->{"format"} =~ /excel/) {
3667 my $printer_code = $self->{printer_code} ? '_' . $self->{printer_code} : '';
3668 my $email_extension = -f "$::myconfig{templates}/$self->{formname}_email${language}.${extension}" ? '_email' : '';
3669 $self->{IN} = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3672 $self->format_dates($output_dateformat, $output_longdates,
3673 qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate datepaid
3674 transdate_oe deliverydate_oe employee_startdate employee_enddate),
3675 grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3677 $self->reformat_numbers($output_numberformat, 2,
3678 qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3679 grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3681 $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3683 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3685 if (scalar @{ $cvar_date_fields }) {
3686 $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3689 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3690 $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3697 my ($self, $dateformat, $longformat, @indices) = @_;
3699 $dateformat ||= $::myconfig{dateformat};
3701 foreach my $idx (@indices) {
3702 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3703 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3704 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3708 next unless defined $self->{$idx};
3710 if (!ref($self->{$idx})) {
3711 $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3713 } elsif (ref($self->{$idx}) eq "ARRAY") {
3714 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3715 $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3721 sub reformat_numbers {
3722 my ($self, $numberformat, $places, @indices) = @_;
3724 return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3726 foreach my $idx (@indices) {
3727 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3728 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3729 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3733 next unless defined $self->{$idx};
3735 if (!ref($self->{$idx})) {
3736 $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3738 } elsif (ref($self->{$idx}) eq "ARRAY") {
3739 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3740 $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3745 my $saved_numberformat = $::myconfig{numberformat};
3746 $::myconfig{numberformat} = $numberformat;
3748 foreach my $idx (@indices) {
3749 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3750 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3751 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3755 next unless defined $self->{$idx};
3757 if (!ref($self->{$idx})) {
3758 $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3760 } elsif (ref($self->{$idx}) eq "ARRAY") {
3761 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3762 $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3767 $::myconfig{numberformat} = $saved_numberformat;
3776 SL::Form.pm - main data object.
3780 This is the main data object of Lx-Office.
3781 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3782 Points of interest for a beginner are:
3784 - $form->error - renders a generic error in html. accepts an error message
3785 - $form->get_standard_dbh - returns a database connection for the
3787 =head1 SPECIAL FUNCTIONS
3789 =head2 C<_store_value()>
3791 parses a complex var name, and stores it in the form.
3794 $form->_store_value($key, $value);
3796 keys must start with a string, and can contain various tokens.
3797 supported key structures are:
3800 simple key strings work as expected
3805 separating two keys by a dot (.) will result in a hash lookup for the inner value
3806 this is similar to the behaviour of java and templating mechanisms.
3808 filter.description => $form->{filter}->{description}
3810 3. array+hashref access
3812 adding brackets ([]) before the dot will cause the next hash to be put into an array.
3813 using [+] instead of [] will force a new array index. this is useful for recurring
3814 data structures like part lists. put a [+] into the first varname, and use [] on the
3817 repeating these names in your template:
3820 invoice.items[].parts_id
3824 $form->{invoice}->{items}->[
3838 using brackets at the end of a name will result in a pure array to be created.
3839 note that you mustn't use [+], which is reserved for array+hash access and will
3840 result in undefined behaviour in array context.
3842 filter.status[] => $form->{status}->[ val1, val2, ... ]
3844 =head2 C<update_business> PARAMS
3847 \%config, - config hashref
3848 $business_id, - business id
3849 $dbh - optional database handle
3851 handles business (thats customer/vendor types) sequences.
3853 special behaviour for empty strings in customerinitnumber field:
3854 will in this case not increase the value, and return undef.
3856 =head2 C<redirect_header> $url
3858 Generates a HTTP redirection header for the new C<$url>. Constructs an
3859 absolute URL including scheme, host name and port. If C<$url> is a
3860 relative URL then it is considered relative to Lx-Office base URL.
3862 This function C<die>s if headers have already been created with
3863 C<$::form-E<gt>header>.
3867 print $::form->redirect_header('oe.pl?action=edit&id=1234');
3868 print $::form->redirect_header('http://www.lx-office.org/');
3872 Generates a general purpose http/html header and includes most of the scripts
3873 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3875 Only one header will be generated. If the method was already called in this
3876 request it will not output anything and return undef. Also if no
3877 HTTP_USER_AGENT is found, no header is generated.
3879 Although header does not accept parameters itself, it will honor special
3880 hashkeys of its Form instance:
3888 If one of these is set, a http-equiv refresh is generated. Missing parameters
3889 default to 3 seconds and the refering url.
3893 Either a scalar or an array ref. Will be inlined into the header. Add
3894 stylesheets with the L<use_stylesheet> function.
3898 If true, a css snippet will be generated that sets the page in landscape mode.
3902 Used to override the default favicon.
3906 A html page title will be generated from this