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 #======================================================================
68 use List::Util qw(first max min sum);
69 use List::MoreUtils qw(all any apply);
76 disconnect_standard_dbh();
79 sub disconnect_standard_dbh {
80 return unless $standard_dbh;
81 $standard_dbh->disconnect();
86 $main::lxdebug->enter_sub(2);
92 my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key;
97 $curr = \ $self->{ shift @tokens };
101 my $sep = shift @tokens;
102 my $key = shift @tokens;
104 $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]';
105 $curr = \ $$curr->[max 0, $#$$curr] if $sep eq '[].';
106 $curr = \ $$curr->[++$#$$curr] if $sep eq '[+].';
107 $curr = \ $$curr->{$key}
112 $main::lxdebug->leave_sub(2);
118 $main::lxdebug->enter_sub(2);
123 my @pairs = split(/&/, $input);
126 my ($key, $value) = split(/=/, $_, 2);
127 $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key);
130 $main::lxdebug->leave_sub(2);
133 sub _request_to_hash {
134 $main::lxdebug->enter_sub(2);
140 if (!$ENV{'CONTENT_TYPE'}
141 || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
143 $self->_input_to_hash($input);
145 $main::lxdebug->leave_sub(2);
149 my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
151 my $boundary = '--' . $1;
153 foreach my $line (split m/\n/, $input) {
154 last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
156 if (($line eq $boundary) || ($line eq "$boundary\r")) {
157 ${ $previous } =~ s|\r?\n$|| if $previous;
163 $content_type = "text/plain";
170 next unless $boundary_found;
172 if (!$headers_done) {
173 $line =~ s/[\r\n]*$//;
180 if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
181 if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
183 substr $line, $-[0], $+[0] - $-[0], "";
186 if ($line =~ m|name\s*=\s*"(.*?)"|i) {
188 substr $line, $-[0], $+[0] - $-[0], "";
191 $previous = _store_value($uploads, $name, '') if ($name);
192 $self->{FILENAME} = $filename if ($filename);
197 if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
204 next unless $previous;
206 ${ $previous } .= "${line}\n";
209 ${ $previous } =~ s|\r?\n$|| if $previous;
211 $main::lxdebug->leave_sub(2);
216 sub _recode_recursively {
217 $main::lxdebug->enter_sub();
218 my ($iconv, $param) = @_;
220 if (any { ref $param eq $_ } qw(Form HASH)) {
221 foreach my $key (keys %{ $param }) {
222 if (!ref $param->{$key}) {
223 # Workaround for a bug: converting $param->{$key} directly
224 # leads to 'undef'. I don't know why. Converting a copy works,
226 $param->{$key} = $iconv->convert("" . $param->{$key});
228 _recode_recursively($iconv, $param->{$key});
232 } elsif (ref $param eq 'ARRAY') {
233 foreach my $idx (0 .. scalar(@{ $param }) - 1) {
234 if (!ref $param->[$idx]) {
235 # Workaround for a bug: converting $param->[$idx] directly
236 # leads to 'undef'. I don't know why. Converting a copy works,
238 $param->[$idx] = $iconv->convert("" . $param->[$idx]);
240 _recode_recursively($iconv, $param->[$idx]);
244 $main::lxdebug->leave_sub();
248 $main::lxdebug->enter_sub();
255 if ($LXDebug::watch_form) {
256 require SL::Watchdog;
257 tie %{ $self }, 'SL::Watchdog';
262 $main::lxdebug->leave_sub();
268 $main::lxdebug->enter_sub();
272 $self->_input_to_hash($ENV{QUERY_STRING}) if $ENV{QUERY_STRING};
273 $self->_input_to_hash($ARGV[0]) if @ARGV && $ARGV[0];
276 if ($ENV{CONTENT_LENGTH}) {
278 read STDIN, $content, $ENV{CONTENT_LENGTH};
279 $uploads = $self->_request_to_hash($content);
282 if ($self->{RESTORE_FORM_FROM_SESSION_ID}) {
284 $::auth->restore_form_from_session(delete $self->{RESTORE_FORM_FROM_SESSION_ID}, form => \%temp_form);
285 $self->_input_to_hash(join '&', map { $self->escape($_) . '=' . $self->escape($temp_form{$_}) } keys %temp_form);
288 my $db_charset = $::lx_office_conf{system}->{dbcharset};
289 $db_charset ||= Common::DEFAULT_CHARSET;
291 my $encoding = $self->{INPUT_ENCODING} || $db_charset;
292 delete $self->{INPUT_ENCODING};
294 _recode_recursively(SL::Iconv->new($encoding, $db_charset), $self);
296 map { $self->{$_} = $uploads->{$_} } keys %{ $uploads } if $uploads;
298 #$self->{version} = "2.6.1"; # Old hardcoded but secure style
299 open VERSION_FILE, "VERSION"; # New but flexible code reads version from VERSION-file
300 $self->{version} = <VERSION_FILE>;
302 $self->{version} =~ s/[^0-9A-Za-z\.\_\-]//g; # only allow numbers, letters, points, underscores and dashes. Prevents injecting of malicious code.
304 $main::lxdebug->leave_sub();
309 sub _flatten_variables_rec {
310 $main::lxdebug->enter_sub(2);
319 if ('' eq ref $curr->{$key}) {
320 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
322 } elsif ('HASH' eq ref $curr->{$key}) {
323 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
324 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
328 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
329 my $first_array_entry = 1;
331 foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
332 push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
333 $first_array_entry = 0;
338 $main::lxdebug->leave_sub(2);
343 sub flatten_variables {
344 $main::lxdebug->enter_sub(2);
352 push @variables, $self->_flatten_variables_rec($self, '', $_);
355 $main::lxdebug->leave_sub(2);
360 sub flatten_standard_variables {
361 $main::lxdebug->enter_sub(2);
364 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
368 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
369 push @variables, $self->_flatten_variables_rec($self, '', $_);
372 $main::lxdebug->leave_sub(2);
378 $main::lxdebug->enter_sub();
384 map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
386 $main::lxdebug->leave_sub();
390 $main::lxdebug->enter_sub(2);
393 my $password = $self->{password};
395 $self->{password} = 'X' x 8;
397 local $Data::Dumper::Sortkeys = 1;
398 my $output = Dumper($self);
400 $self->{password} = $password;
402 $main::lxdebug->leave_sub(2);
408 $main::lxdebug->enter_sub(2);
410 my ($self, $str) = @_;
412 $str = Encode::encode('utf-8-strict', $str) if $::locale->is_utf8;
413 $str =~ s/([^a-zA-Z0-9_.:-])/sprintf("%%%02x", ord($1))/ge;
415 $main::lxdebug->leave_sub(2);
421 $main::lxdebug->enter_sub(2);
423 my ($self, $str) = @_;
428 $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
429 $str = Encode::decode('utf-8-strict', $str) if $::locale->is_utf8;
431 $main::lxdebug->leave_sub(2);
437 $main::lxdebug->enter_sub();
438 my ($self, $str) = @_;
440 if ($str && !ref($str)) {
441 $str =~ s/\"/"/g;
444 $main::lxdebug->leave_sub();
450 $main::lxdebug->enter_sub();
451 my ($self, $str) = @_;
453 if ($str && !ref($str)) {
454 $str =~ s/"/\"/g;
457 $main::lxdebug->leave_sub();
463 $main::lxdebug->enter_sub();
467 map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
469 for (sort keys %$self) {
470 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
471 print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
474 $main::lxdebug->leave_sub();
478 my ($self, $code) = @_;
479 local $self->{__ERROR_HANDLER} = sub { die SL::X::FormError->new($_[0]) };
484 $main::lxdebug->enter_sub();
486 $main::lxdebug->show_backtrace();
488 my ($self, $msg) = @_;
490 if ($self->{__ERROR_HANDLER}) {
491 $self->{__ERROR_HANDLER}->($msg);
493 } elsif ($ENV{HTTP_USER_AGENT}) {
495 $self->show_generic_error($msg);
498 print STDERR "Error: $msg\n";
502 $main::lxdebug->leave_sub();
506 $main::lxdebug->enter_sub();
508 my ($self, $msg) = @_;
510 if ($ENV{HTTP_USER_AGENT}) {
513 if (!$self->{header}) {
519 <p class="message_ok"><b>$msg</b></p>
521 <script type="text/javascript">
523 // If JavaScript is enabled, the whole thing will be reloaded.
524 // The reason is: When one changes his menu setup (HTML / XUL / CSS ...)
525 // it now loads the correct code into the browser instead of do nothing.
526 setTimeout("top.frames.location.href='login.pl'",500);
535 if ($self->{info_function}) {
536 &{ $self->{info_function} }($msg);
542 $main::lxdebug->leave_sub();
545 # calculates the number of rows in a textarea based on the content and column number
546 # can be capped with maxrows
548 $main::lxdebug->enter_sub();
549 my ($self, $str, $cols, $maxrows, $minrows) = @_;
553 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
556 $main::lxdebug->leave_sub();
558 return max(min($rows, $maxrows), $minrows);
562 $main::lxdebug->enter_sub();
564 my ($self, $msg) = @_;
566 $self->error("$msg\n" . $DBI::errstr);
568 $main::lxdebug->leave_sub();
572 $main::lxdebug->enter_sub();
574 my ($self, $name, $msg) = @_;
577 foreach my $part (split m/\./, $name) {
578 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
581 $curr = $curr->{$part};
584 $main::lxdebug->leave_sub();
587 sub _get_request_uri {
590 return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
592 my $scheme = $ENV{HTTPS} && (lc $ENV{HTTPS} eq 'on') ? 'https' : 'http';
593 my $port = $ENV{SERVER_PORT} || '';
594 $port = undef if (($scheme eq 'http' ) && ($port == 80))
595 || (($scheme eq 'https') && ($port == 443));
597 my $uri = URI->new("${scheme}://");
598 $uri->scheme($scheme);
600 $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
601 $uri->path_query($ENV{REQUEST_URI});
607 sub _add_to_request_uri {
610 my $relative_new_path = shift;
611 my $request_uri = shift || $self->_get_request_uri;
612 my $relative_new_uri = URI->new($relative_new_path);
613 my @request_segments = $request_uri->path_segments;
615 my $new_uri = $request_uri->clone;
616 $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
621 sub create_http_response {
622 $main::lxdebug->enter_sub();
627 my $cgi = $main::cgi;
628 $cgi ||= CGI->new('');
631 if (defined $main::auth) {
632 my $uri = $self->_get_request_uri;
633 my @segments = $uri->path_segments;
635 $uri->path_segments(@segments);
637 my $session_cookie_value = $main::auth->get_session_id();
639 if ($session_cookie_value) {
640 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
641 '-value' => $session_cookie_value,
642 '-path' => $uri->path,
643 '-secure' => $ENV{HTTPS});
647 my %cgi_params = ('-type' => $params{content_type});
648 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
649 $cgi_params{'-cookie'} = $session_cookie if ($session_cookie);
651 map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length);
653 my $output = $cgi->header(%cgi_params);
655 $main::lxdebug->leave_sub();
663 $self->{stylesheet} = [ $self->{stylesheet} ] unless ref $self->{stylesheet} eq 'ARRAY';
664 $self->{stylesheet} = [ grep { -f }
665 map { m:^css/: ? $_ : "css/$_" }
667 (@{ $self->{stylesheet} }, @_)
670 return @{ $self->{stylesheet} };
674 $::lxdebug->enter_sub;
676 # extra code is currently only used by menuv3 and menuv4 to set their css.
677 # it is strongly deprecated, and will be changed in a future version.
678 my ($self, $extra_code) = @_;
679 my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
682 $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
684 $self->{favicon} ||= "favicon.ico";
685 $self->{titlebar} = "$self->{title} - $self->{titlebar}" if $self->{title};
688 if ($self->{refresh_url} || $self->{refresh_time}) {
689 my $refresh_time = $self->{refresh_time} || 3;
690 my $refresh_url = $self->{refresh_url} || $ENV{REFERER};
691 push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
694 push @header, map { qq|<link rel="stylesheet" href="$_" type="text/css" title="Lx-Office stylesheet">| } $self->use_stylesheet;
696 push @header, "<style type='text/css'>\@page { size:landscape; }</style>" if $self->{landscape};
697 push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
698 push @header, '<script type="text/javascript" src="js/jquery.js"></script>',
699 '<script type="text/javascript" src="js/common.js"></script>',
700 '<style type="text/css">@import url(js/jscalendar/calendar-win2k-1.css);</style>',
701 '<script type="text/javascript" src="js/jscalendar/calendar.js"></script>',
702 '<script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>',
703 '<script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>',
704 '<script type="text/javascript" src="js/part_selection.js"></script>';
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 print $self->create_http_response(content_type => 'text/html', charset => $db_charset);
726 print "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN' 'http://www.w3.org/TR/html4/strict.dtd'>\n"
727 if $ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/; # Other browsers may choke on menu scripts with DOCTYPE.
731 <meta http-equiv="Content-Type" content="text/html; charset=$db_charset">
732 <title>$self->{titlebar}</title>
734 print " $_\n" for @header;
736 <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
737 <meta name="robots" content="noindex,nofollow" />
738 <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
739 <script type="text/javascript" src="js/tabcontent.js">
741 /***********************************************
742 * Tab Content script v2.2- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
743 * This notice MUST stay intact for legal use
744 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
745 ***********************************************/
754 $::lxdebug->leave_sub;
757 sub ajax_response_header {
758 $main::lxdebug->enter_sub();
762 my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
763 my $cgi = $main::cgi || CGI->new('');
764 my $output = $cgi->header('-charset' => $db_charset);
766 $main::lxdebug->leave_sub();
771 sub redirect_header {
775 my $base_uri = $self->_get_request_uri;
776 my $new_uri = URI->new_abs($new_url, $base_uri);
778 die "Headers already sent" if $self->{header};
781 my $cgi = $main::cgi || CGI->new('');
782 return $cgi->redirect($new_uri);
785 sub set_standard_title {
786 $::lxdebug->enter_sub;
789 $self->{titlebar} = "Lx-Office " . $::locale->text('Version') . " $self->{version}";
790 $self->{titlebar} .= "- $::myconfig{name}" if $::myconfig{name};
791 $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
793 $::lxdebug->leave_sub;
796 sub _prepare_html_template {
797 $main::lxdebug->enter_sub();
799 my ($self, $file, $additional_params) = @_;
802 if (!%::myconfig || !$::myconfig{"countrycode"}) {
803 $language = $::lx_office_conf{system}->{language};
805 $language = $main::myconfig{"countrycode"};
807 $language = "de" unless ($language);
809 if (-f "templates/webpages/${file}.html") {
810 $file = "templates/webpages/${file}.html";
813 my $info = "Web page template '${file}' not found.\n";
814 print qq|<pre>$info</pre>|;
818 if ($self->{"DEBUG"}) {
819 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
822 if ($additional_params->{"DEBUG"}) {
823 $additional_params->{"DEBUG"} =
824 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
827 if (%main::myconfig) {
828 $::myconfig{jsc_dateformat} = apply {
832 } $::myconfig{"dateformat"};
833 $additional_params->{"myconfig"} ||= \%::myconfig;
834 map { $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys %::myconfig;
837 $additional_params->{"conf_dbcharset"} = $::lx_office_conf{system}->{dbcharset};
838 $additional_params->{"conf_webdav"} = $::lx_office_conf{features}->{webdav};
839 $additional_params->{"conf_latex_templates"} = $::lx_office_conf{print_templates}->{latex};
840 $additional_params->{"conf_opendocument_templates"} = $::lx_office_conf{print_templates}->{opendocument};
841 $additional_params->{"conf_vertreter"} = $::lx_office_conf{features}->{vertreter};
842 $additional_params->{"conf_show_best_before"} = $::lx_office_conf{features}->{show_best_before};
843 $additional_params->{"conf_parts_image_css"} = $::lx_office_conf{features}->{parts_image_css};
844 $additional_params->{"conf_parts_listing_images"} = $::lx_office_conf{features}->{parts_listing_images};
845 $additional_params->{"conf_parts_show_image"} = $::lx_office_conf{features}->{parts_show_image};
846 $additional_params->{"conf_payments_changeable"} = $::lx_office_conf{features}->{payments_changeable};
847 $additional_params->{"INSTANCE_CONF"} = $::instance_conf;
849 if (my $debug_options = $::lx_office_conf{debug}{options}) {
850 map { $additional_params->{'DEBUG_' . uc($_)} = $debug_options->{$_} } keys %$debug_options;
853 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
854 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
855 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
859 $main::lxdebug->leave_sub();
864 sub parse_html_template {
865 $main::lxdebug->enter_sub();
867 my ($self, $file, $additional_params) = @_;
869 $additional_params ||= { };
871 my $real_file = $self->_prepare_html_template($file, $additional_params);
872 my $template = $self->template || $self->init_template;
874 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
877 $template->process($real_file, $additional_params, \$output) || die $template->error;
879 $main::lxdebug->leave_sub();
887 return $self->template if $self->template;
889 return $self->template(Template->new({
894 'PLUGIN_BASE' => 'SL::Template::Plugin',
895 'INCLUDE_PATH' => '.:templates/webpages',
896 'COMPILE_EXT' => '.tcc',
897 'COMPILE_DIR' => $::lx_office_conf{paths}->{userspath} . '/templates-cache',
903 $self->{template_object} = shift if @_;
904 return $self->{template_object};
907 sub show_generic_error {
908 $main::lxdebug->enter_sub();
910 my ($self, $error, %params) = @_;
912 if ($self->{__ERROR_HANDLER}) {
913 $self->{__ERROR_HANDLER}->($error);
914 $main::lxdebug->leave_sub();
919 'title_error' => $params{title},
920 'label_error' => $error,
923 if ($params{action}) {
926 map { delete($self->{$_}); } qw(action);
927 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
929 $add_params->{SHOW_BUTTON} = 1;
930 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
931 $add_params->{VARIABLES} = \@vars;
933 } elsif ($params{back_button}) {
934 $add_params->{SHOW_BACK_BUTTON} = 1;
937 $self->{title} = $params{title} if $params{title};
940 print $self->parse_html_template("generic/error", $add_params);
942 print STDERR "Error: $error\n";
944 $main::lxdebug->leave_sub();
949 sub show_generic_information {
950 $main::lxdebug->enter_sub();
952 my ($self, $text, $title) = @_;
955 'title_information' => $title,
956 'label_information' => $text,
959 $self->{title} = $title if ($title);
962 print $self->parse_html_template("generic/information", $add_params);
964 $main::lxdebug->leave_sub();
969 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
970 # changed it to accept an arbitrary number of triggers - sschoeling
972 $main::lxdebug->enter_sub();
975 my $myconfig = shift;
978 # set dateform for jsscript
981 "dd.mm.yy" => "%d.%m.%Y",
982 "dd-mm-yy" => "%d-%m-%Y",
983 "dd/mm/yy" => "%d/%m/%Y",
984 "mm/dd/yy" => "%m/%d/%Y",
985 "mm-dd-yy" => "%m-%d-%Y",
986 "yyyy-mm-dd" => "%Y-%m-%d",
989 my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
990 $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
997 inputField : "| . (shift) . qq|",
998 ifFormat :"$ifFormat",
999 align : "| . (shift) . qq|",
1000 button : "| . (shift) . qq|"
1006 <script type="text/javascript">
1007 <!--| . join("", @triggers) . qq|//-->
1011 $main::lxdebug->leave_sub();
1014 } #end sub write_trigger
1016 sub _store_redirect_info_in_session {
1019 return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
1021 my ($controller, $params) = ($1, $2);
1022 my $form = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
1023 $self->{callback} = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
1027 $main::lxdebug->enter_sub();
1029 my ($self, $msg) = @_;
1031 if (!$self->{callback}) {
1035 $self->_store_redirect_info_in_session;
1036 print $::form->redirect_header($self->{callback});
1041 $main::lxdebug->leave_sub();
1044 # sort of columns removed - empty sub
1046 $main::lxdebug->enter_sub();
1048 my ($self, @columns) = @_;
1050 $main::lxdebug->leave_sub();
1056 $main::lxdebug->enter_sub(2);
1058 my ($self, $myconfig, $amount, $places, $dash) = @_;
1060 if ($amount eq "") {
1064 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
1066 my $neg = ($amount =~ s/^-//);
1067 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
1069 if (defined($places) && ($places ne '')) {
1075 my ($actual_places) = ($amount =~ /\.(\d+)/);
1076 $actual_places = length($actual_places);
1077 $places = $actual_places > $places ? $actual_places : $places;
1080 $amount = $self->round_amount($amount, $places);
1083 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
1084 my @p = split(/\./, $amount); # split amount at decimal point
1086 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
1089 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
1092 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
1093 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1094 ($neg ? "-$amount" : "$amount" ) ;
1098 $main::lxdebug->leave_sub(2);
1102 sub format_amount_units {
1103 $main::lxdebug->enter_sub();
1108 my $myconfig = \%main::myconfig;
1109 my $amount = $params{amount} * 1;
1110 my $places = $params{places};
1111 my $part_unit_name = $params{part_unit};
1112 my $amount_unit_name = $params{amount_unit};
1113 my $conv_units = $params{conv_units};
1114 my $max_places = $params{max_places};
1116 if (!$part_unit_name) {
1117 $main::lxdebug->leave_sub();
1121 my $all_units = AM->retrieve_all_units;
1123 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1124 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1127 if (!scalar @{ $conv_units }) {
1128 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1129 $main::lxdebug->leave_sub();
1133 my $part_unit = $all_units->{$part_unit_name};
1134 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1136 $amount *= $conv_unit->{factor};
1141 foreach my $unit (@$conv_units) {
1142 my $last = $unit->{name} eq $part_unit->{name};
1144 $num = int($amount / $unit->{factor});
1145 $amount -= $num * $unit->{factor};
1148 if ($last ? $amount : $num) {
1149 push @values, { "unit" => $unit->{name},
1150 "amount" => $last ? $amount / $unit->{factor} : $num,
1151 "places" => $last ? $places : 0 };
1158 push @values, { "unit" => $part_unit_name,
1163 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1165 $main::lxdebug->leave_sub();
1171 $main::lxdebug->enter_sub(2);
1176 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1177 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1178 $input =~ s/\#\#/\#/g;
1180 $main::lxdebug->leave_sub(2);
1188 $main::lxdebug->enter_sub(2);
1190 my ($self, $myconfig, $amount) = @_;
1192 if ( ($myconfig->{numberformat} eq '1.000,00')
1193 || ($myconfig->{numberformat} eq '1000,00')) {
1195 $amount =~ s/,/\./g;
1198 if ($myconfig->{numberformat} eq "1'000.00") {
1204 $main::lxdebug->leave_sub(2);
1206 # Make sure no code wich is not a math expression ends up in eval().
1207 return 0 unless $amount =~ /^ [\s \d \( \) \- \+ \* \/ \. ]* $/x;
1208 return scalar(eval($amount)) * 1 ;
1212 $main::lxdebug->enter_sub(2);
1214 my ($self, $amount, $places) = @_;
1217 # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
1219 # Round amounts to eight places before rounding to the requested
1220 # number of places. This gets rid of errors due to internal floating
1221 # point representation.
1222 $amount = $self->round_amount($amount, 8) if $places < 8;
1223 $amount = $amount * (10**($places));
1224 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1226 $main::lxdebug->leave_sub(2);
1228 return $round_amount;
1232 sub parse_template {
1233 $main::lxdebug->enter_sub();
1235 my ($self, $myconfig) = @_;
1240 my $userspath = $::lx_office_conf{paths}->{userspath};
1242 $self->{"cwd"} = getcwd();
1243 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1248 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1249 $template_type = 'OpenDocument';
1250 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
1252 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1253 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1254 $template_type = 'LaTeX';
1255 $ext_for_format = 'pdf';
1257 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1258 $template_type = 'HTML';
1259 $ext_for_format = 'html';
1261 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1262 $template_type = 'XML';
1263 $ext_for_format = 'xml';
1265 } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
1266 $template_type = 'XML';
1268 } elsif ( $self->{"format"} =~ /excel/i ) {
1269 $template_type = 'Excel';
1270 $ext_for_format = 'xls';
1272 } elsif ( defined $self->{'format'}) {
1273 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1275 } elsif ( $self->{'format'} eq '' ) {
1276 $self->error("No Outputformat given: $self->{'format'}");
1278 } else { #Catch the rest
1279 $self->error("Outputformat not defined: $self->{'format'}");
1282 my $template = SL::Template::create(type => $template_type,
1283 file_name => $self->{IN},
1285 myconfig => $myconfig,
1286 userspath => $userspath);
1288 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1289 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1291 if (!$self->{employee_id}) {
1292 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1295 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1296 map { $self->{"myconfig_${_}"} = $myconfig->{$_} } grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
1298 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1300 # OUT is used for the media, screen, printer, email
1301 # for postscript we store a copy in a temporary file
1303 my $prepend_userspath;
1305 if (!$self->{tmpfile}) {
1306 $self->{tmpfile} = "${fileid}.$self->{IN}";
1307 $prepend_userspath = 1;
1310 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1312 $self->{tmpfile} =~ s|.*/||;
1313 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1314 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1316 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1317 $out = $self->{OUT};
1318 $self->{OUT} = "$self->{tmpfile}";
1324 open(OUT, ">", $self->{OUT}) or $self->error("$self->{OUT} : $!");
1326 open(OUT, ">&", \*STDOUT) or $self->error("STDOUT : $!");
1330 if (!$template->parse(*OUT)) {
1332 $self->error("$self->{IN} : " . $template->get_error());
1337 if ($self->{media} eq 'file') {
1338 copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
1340 chdir("$self->{cwd}");
1342 $::lxdebug->leave_sub();
1347 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1349 if ($self->{media} eq 'email') {
1351 my $mail = new Mailer;
1353 map { $mail->{$_} = $self->{$_} }
1354 qw(cc bcc subject message version format);
1355 $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
1356 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1357 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1358 $mail->{fileid} = "$fileid.";
1359 $myconfig->{signature} =~ s/\r//g;
1361 # if we send html or plain text inline
1362 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1363 $mail->{contenttype} = "text/html";
1365 $mail->{message} =~ s/\r//g;
1366 $mail->{message} =~ s/\n/<br>\n/g;
1367 $myconfig->{signature} =~ s/\n/<br>\n/g;
1368 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1370 open(IN, "<", $self->{tmpfile})
1371 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1373 $mail->{message} .= $_;
1380 if (!$self->{"do_not_attach"}) {
1381 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1382 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1383 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1384 "name" => $attachment_name }];
1387 $mail->{message} =~ s/\r//g;
1388 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1392 my $err = $mail->send();
1393 $self->error($self->cleanup . "$err") if ($err);
1397 $self->{OUT} = $out;
1399 my $numbytes = (-s $self->{tmpfile});
1400 open(IN, "<", $self->{tmpfile})
1401 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1404 $self->{copies} = 1 unless $self->{media} eq 'printer';
1406 chdir("$self->{cwd}");
1407 #print(STDERR "Kopien $self->{copies}\n");
1408 #print(STDERR "OUT $self->{OUT}\n");
1409 for my $i (1 .. $self->{copies}) {
1411 open OUT, '>', $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1412 print OUT while <IN>;
1417 $self->{attachment_filename} = ($self->{attachment_filename})
1418 ? $self->{attachment_filename}
1419 : $self->generate_attachment_filename();
1421 # launch application
1422 print qq|Content-Type: | . $template->get_mime_type() . qq|
1423 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1424 Content-Length: $numbytes
1428 $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1439 chdir("$self->{cwd}");
1440 $main::lxdebug->leave_sub();
1443 sub get_formname_translation {
1444 $main::lxdebug->enter_sub();
1445 my ($self, $formname) = @_;
1447 $formname ||= $self->{formname};
1449 my %formname_translations = (
1450 bin_list => $main::locale->text('Bin List'),
1451 credit_note => $main::locale->text('Credit Note'),
1452 invoice => $main::locale->text('Invoice'),
1453 pick_list => $main::locale->text('Pick List'),
1454 proforma => $main::locale->text('Proforma Invoice'),
1455 purchase_order => $main::locale->text('Purchase Order'),
1456 request_quotation => $main::locale->text('RFQ'),
1457 sales_order => $main::locale->text('Confirmation'),
1458 sales_quotation => $main::locale->text('Quotation'),
1459 storno_invoice => $main::locale->text('Storno Invoice'),
1460 sales_delivery_order => $main::locale->text('Delivery Order'),
1461 purchase_delivery_order => $main::locale->text('Delivery Order'),
1462 dunning => $main::locale->text('Dunning'),
1465 $main::lxdebug->leave_sub();
1466 return $formname_translations{$formname}
1469 sub get_number_prefix_for_type {
1470 $main::lxdebug->enter_sub();
1474 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1475 : ($self->{type} =~ /_quotation$/) ? 'quo'
1476 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1479 $main::lxdebug->leave_sub();
1483 sub get_extension_for_format {
1484 $main::lxdebug->enter_sub();
1487 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1488 : $self->{format} =~ /postscript/i ? ".ps"
1489 : $self->{format} =~ /opendocument/i ? ".odt"
1490 : $self->{format} =~ /excel/i ? ".xls"
1491 : $self->{format} =~ /html/i ? ".html"
1494 $main::lxdebug->leave_sub();
1498 sub generate_attachment_filename {
1499 $main::lxdebug->enter_sub();
1502 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1503 my $prefix = $self->get_number_prefix_for_type();
1505 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1506 $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1508 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1509 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1512 $attachment_filename = "";
1515 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1516 $attachment_filename =~ s|[\s/\\]+|_|g;
1518 $main::lxdebug->leave_sub();
1519 return $attachment_filename;
1522 sub generate_email_subject {
1523 $main::lxdebug->enter_sub();
1526 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1527 my $prefix = $self->get_number_prefix_for_type();
1529 if ($subject && $self->{"${prefix}number"}) {
1530 $subject .= " " . $self->{"${prefix}number"}
1533 $main::lxdebug->leave_sub();
1538 $main::lxdebug->enter_sub();
1540 my ($self, $application) = @_;
1542 my $error_code = $?;
1544 chdir("$self->{tmpdir}");
1547 if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1548 push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1550 } elsif (-f "$self->{tmpfile}.err") {
1551 open(FH, "$self->{tmpfile}.err");
1556 if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1557 $self->{tmpfile} =~ s|.*/||g;
1559 $self->{tmpfile} =~ s/\.\w+$//g;
1560 my $tmpfile = $self->{tmpfile};
1561 unlink(<$tmpfile.*>);
1564 chdir("$self->{cwd}");
1566 $main::lxdebug->leave_sub();
1572 $main::lxdebug->enter_sub();
1574 my ($self, $date, $myconfig) = @_;
1577 if ($date && $date =~ /\D/) {
1579 if ($myconfig->{dateformat} =~ /^yy/) {
1580 ($yy, $mm, $dd) = split /\D/, $date;
1582 if ($myconfig->{dateformat} =~ /^mm/) {
1583 ($mm, $dd, $yy) = split /\D/, $date;
1585 if ($myconfig->{dateformat} =~ /^dd/) {
1586 ($dd, $mm, $yy) = split /\D/, $date;
1591 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1592 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1594 $dd = "0$dd" if ($dd < 10);
1595 $mm = "0$mm" if ($mm < 10);
1597 $date = "$yy$mm$dd";
1600 $main::lxdebug->leave_sub();
1605 # Database routines used throughout
1607 sub _dbconnect_options {
1609 my $options = { pg_enable_utf8 => $::locale->is_utf8,
1616 $main::lxdebug->enter_sub(2);
1618 my ($self, $myconfig) = @_;
1620 # connect to database
1621 my $dbh = SL::DBConnect->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options)
1625 if ($myconfig->{dboptions}) {
1626 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1629 $main::lxdebug->leave_sub(2);
1634 sub dbconnect_noauto {
1635 $main::lxdebug->enter_sub();
1637 my ($self, $myconfig) = @_;
1639 # connect to database
1640 my $dbh = SL::DBConnect->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options(AutoCommit => 0))
1644 if ($myconfig->{dboptions}) {
1645 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1648 $main::lxdebug->leave_sub();
1653 sub get_standard_dbh {
1654 $main::lxdebug->enter_sub(2);
1657 my $myconfig = shift || \%::myconfig;
1659 if ($standard_dbh && !$standard_dbh->{Active}) {
1660 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1661 undef $standard_dbh;
1664 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1666 $main::lxdebug->leave_sub(2);
1668 return $standard_dbh;
1672 $main::lxdebug->enter_sub();
1674 my ($self, $date, $myconfig) = @_;
1675 my $dbh = $self->dbconnect($myconfig);
1677 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1678 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1680 # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1681 # es ist sicher ein conv_date vorher IMMER auszuführen.
1682 # Testfälle ohne definiertes closedto:
1683 # Leere Datumseingabe i.O.
1684 # SELECT 1 FROM defaults WHERE '' < closedto
1685 # normale Zahlungsbuchung über Rechnungsmaske i.O.
1686 # SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1687 # Testfälle mit definiertem closedto (30.04.2011):
1688 # Leere Datumseingabe i.O.
1689 # SELECT 1 FROM defaults WHERE '' < closedto
1690 # normale Buchung im geschloßenem Zeitraum i.O.
1691 # SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1692 # Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1693 # normale Buchung in aktiver Buchungsperiode i.O.
1694 # SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1696 my ($closed) = $sth->fetchrow_array;
1698 $main::lxdebug->leave_sub();
1703 sub update_balance {
1704 $main::lxdebug->enter_sub();
1706 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1708 # if we have a value, go do it
1711 # retrieve balance from table
1712 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1713 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1714 my ($balance) = $sth->fetchrow_array;
1720 $query = "UPDATE $table SET $field = $balance WHERE $where";
1721 do_query($self, $dbh, $query, @values);
1723 $main::lxdebug->leave_sub();
1726 sub update_exchangerate {
1727 $main::lxdebug->enter_sub();
1729 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1731 # some sanity check for currency
1733 $main::lxdebug->leave_sub();
1736 $query = qq|SELECT curr FROM defaults|;
1738 my ($currency) = selectrow_query($self, $dbh, $query);
1739 my ($defaultcurrency) = split m/:/, $currency;
1742 if ($curr eq $defaultcurrency) {
1743 $main::lxdebug->leave_sub();
1747 $query = qq|SELECT e.curr FROM exchangerate e
1748 WHERE e.curr = ? AND e.transdate = ?
1750 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1759 $buy = conv_i($buy, "NULL");
1760 $sell = conv_i($sell, "NULL");
1763 if ($buy != 0 && $sell != 0) {
1764 $set = "buy = $buy, sell = $sell";
1765 } elsif ($buy != 0) {
1766 $set = "buy = $buy";
1767 } elsif ($sell != 0) {
1768 $set = "sell = $sell";
1771 if ($sth->fetchrow_array) {
1772 $query = qq|UPDATE exchangerate
1778 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1779 VALUES (?, $buy, $sell, ?)|;
1782 do_query($self, $dbh, $query, $curr, $transdate);
1784 $main::lxdebug->leave_sub();
1787 sub save_exchangerate {
1788 $main::lxdebug->enter_sub();
1790 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1792 my $dbh = $self->dbconnect($myconfig);
1796 $buy = $rate if $fld eq 'buy';
1797 $sell = $rate if $fld eq 'sell';
1800 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1805 $main::lxdebug->leave_sub();
1808 sub get_exchangerate {
1809 $main::lxdebug->enter_sub();
1811 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1814 unless ($transdate) {
1815 $main::lxdebug->leave_sub();
1819 $query = qq|SELECT curr FROM defaults|;
1821 my ($currency) = selectrow_query($self, $dbh, $query);
1822 my ($defaultcurrency) = split m/:/, $currency;
1824 if ($currency eq $defaultcurrency) {
1825 $main::lxdebug->leave_sub();
1829 $query = qq|SELECT e.$fld FROM exchangerate e
1830 WHERE e.curr = ? AND e.transdate = ?|;
1831 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1835 $main::lxdebug->leave_sub();
1837 return $exchangerate;
1840 sub check_exchangerate {
1841 $main::lxdebug->enter_sub();
1843 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1845 if ($fld !~/^buy|sell$/) {
1846 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1849 unless ($transdate) {
1850 $main::lxdebug->leave_sub();
1854 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1856 if ($currency eq $defaultcurrency) {
1857 $main::lxdebug->leave_sub();
1861 my $dbh = $self->get_standard_dbh($myconfig);
1862 my $query = qq|SELECT e.$fld FROM exchangerate e
1863 WHERE e.curr = ? AND e.transdate = ?|;
1865 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1867 $main::lxdebug->leave_sub();
1869 return $exchangerate;
1872 sub get_all_currencies {
1873 $main::lxdebug->enter_sub();
1876 my $myconfig = shift || \%::myconfig;
1877 my $dbh = $self->get_standard_dbh($myconfig);
1879 my $query = qq|SELECT curr FROM defaults|;
1881 my ($curr) = selectrow_query($self, $dbh, $query);
1882 my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
1884 $main::lxdebug->leave_sub();
1889 sub get_default_currency {
1890 $main::lxdebug->enter_sub();
1892 my ($self, $myconfig) = @_;
1893 my @currencies = $self->get_all_currencies($myconfig);
1895 $main::lxdebug->leave_sub();
1897 return $currencies[0];
1900 sub set_payment_options {
1901 $main::lxdebug->enter_sub();
1903 my ($self, $myconfig, $transdate) = @_;
1905 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1907 my $dbh = $self->get_standard_dbh($myconfig);
1910 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long , p.description | .
1911 qq|FROM payment_terms p | .
1914 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1915 $self->{payment_terms}, $self->{payment_description}) =
1916 selectrow_query($self, $dbh, $query, $self->{payment_id});
1918 if ($transdate eq "") {
1919 if ($self->{invdate}) {
1920 $transdate = $self->{invdate};
1922 $transdate = $self->{transdate};
1927 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1928 qq|FROM payment_terms|;
1929 ($self->{netto_date}, $self->{skonto_date}) =
1930 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1932 my ($invtotal, $total);
1933 my (%amounts, %formatted_amounts);
1935 if ($self->{type} =~ /_order$/) {
1936 $amounts{invtotal} = $self->{ordtotal};
1937 $amounts{total} = $self->{ordtotal};
1939 } elsif ($self->{type} =~ /_quotation$/) {
1940 $amounts{invtotal} = $self->{quototal};
1941 $amounts{total} = $self->{quototal};
1944 $amounts{invtotal} = $self->{invtotal};
1945 $amounts{total} = $self->{total};
1947 $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1949 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1951 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1952 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1953 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1955 foreach (keys %amounts) {
1956 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1957 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1960 if ($self->{"language_id"}) {
1962 qq|SELECT t.translation, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1963 qq|FROM generic_translations t | .
1964 qq|LEFT JOIN language l ON t.language_id = l.id | .
1965 qq|WHERE (t.language_id = ?)
1966 AND (t.translation_id = ?)
1967 AND (t.translation_type = 'SL::DB::PaymentTerm/description_long')|;
1968 my ($description_long, $output_numberformat, $output_dateformat,
1969 $output_longdates) =
1970 selectrow_query($self, $dbh, $query,
1971 $self->{"language_id"}, $self->{"payment_id"});
1973 $self->{payment_terms} = $description_long if ($description_long);
1975 if ($output_dateformat) {
1976 foreach my $key (qw(netto_date skonto_date)) {
1978 $main::locale->reformat_date($myconfig, $self->{$key},
1984 if ($output_numberformat &&
1985 ($output_numberformat ne $myconfig->{"numberformat"})) {
1986 my $saved_numberformat = $myconfig->{"numberformat"};
1987 $myconfig->{"numberformat"} = $output_numberformat;
1988 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1989 $myconfig->{"numberformat"} = $saved_numberformat;
1993 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1994 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1995 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1996 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1997 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1998 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1999 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
2001 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
2003 $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
2005 $main::lxdebug->leave_sub();
2009 sub get_template_language {
2010 $main::lxdebug->enter_sub();
2012 my ($self, $myconfig) = @_;
2014 my $template_code = "";
2016 if ($self->{language_id}) {
2017 my $dbh = $self->get_standard_dbh($myconfig);
2018 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
2019 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
2022 $main::lxdebug->leave_sub();
2024 return $template_code;
2027 sub get_printer_code {
2028 $main::lxdebug->enter_sub();
2030 my ($self, $myconfig) = @_;
2032 my $template_code = "";
2034 if ($self->{printer_id}) {
2035 my $dbh = $self->get_standard_dbh($myconfig);
2036 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
2037 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
2040 $main::lxdebug->leave_sub();
2042 return $template_code;
2046 $main::lxdebug->enter_sub();
2048 my ($self, $myconfig) = @_;
2050 my $template_code = "";
2052 if ($self->{shipto_id}) {
2053 my $dbh = $self->get_standard_dbh($myconfig);
2054 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
2055 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
2056 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
2059 $main::lxdebug->leave_sub();
2063 $main::lxdebug->enter_sub();
2065 my ($self, $dbh, $id, $module) = @_;
2070 foreach my $item (qw(name department_1 department_2 street zipcode city country
2071 contact cp_gender phone fax email)) {
2072 if ($self->{"shipto$item"}) {
2073 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
2075 push(@values, $self->{"shipto${item}"});
2079 if ($self->{shipto_id}) {
2080 my $query = qq|UPDATE shipto set
2082 shiptodepartment_1 = ?,
2083 shiptodepartment_2 = ?,
2089 shiptocp_gender = ?,
2093 WHERE shipto_id = ?|;
2094 do_query($self, $dbh, $query, @values, $self->{shipto_id});
2096 my $query = qq|SELECT * FROM shipto
2097 WHERE shiptoname = ? AND
2098 shiptodepartment_1 = ? AND
2099 shiptodepartment_2 = ? AND
2100 shiptostreet = ? AND
2101 shiptozipcode = ? AND
2103 shiptocountry = ? AND
2104 shiptocontact = ? AND
2105 shiptocp_gender = ? AND
2111 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
2114 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
2115 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
2116 shiptocontact, shiptocp_gender, shiptophone, shiptofax, shiptoemail, module)
2117 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
2118 do_query($self, $dbh, $query, $id, @values, $module);
2123 $main::lxdebug->leave_sub();
2127 $main::lxdebug->enter_sub();
2129 my ($self, $dbh) = @_;
2131 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
2133 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2134 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2135 $self->{"employee_id"} *= 1;
2137 $main::lxdebug->leave_sub();
2140 sub get_employee_data {
2141 $main::lxdebug->enter_sub();
2146 Common::check_params(\%params, qw(prefix));
2147 Common::check_params_x(\%params, qw(id));
2150 $main::lxdebug->leave_sub();
2154 my $myconfig = \%main::myconfig;
2155 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
2157 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2160 my $user = User->new($login);
2161 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2163 $self->{$params{prefix} . '_login'} = $login;
2164 $self->{$params{prefix} . '_name'} ||= $login;
2167 $main::lxdebug->leave_sub();
2171 $main::lxdebug->enter_sub();
2173 my ($self, $myconfig, $reference_date) = @_;
2175 $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2177 my $dbh = $self->get_standard_dbh($myconfig);
2178 my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2179 my ($duedate) = selectrow_query($self, $dbh, $query, $self->{payment_id});
2181 $main::lxdebug->leave_sub();
2187 $main::lxdebug->enter_sub();
2189 my ($self, $dbh, $id, $key) = @_;
2191 $key = "all_contacts" unless ($key);
2195 $main::lxdebug->leave_sub();
2200 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2201 qq|FROM contacts | .
2202 qq|WHERE cp_cv_id = ? | .
2203 qq|ORDER BY lower(cp_name)|;
2205 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2207 $main::lxdebug->leave_sub();
2211 $main::lxdebug->enter_sub();
2213 my ($self, $dbh, $key) = @_;
2215 my ($all, $old_id, $where, @values);
2217 if (ref($key) eq "HASH") {
2220 $key = "ALL_PROJECTS";
2222 foreach my $p (keys(%{$params})) {
2224 $all = $params->{$p};
2225 } elsif ($p eq "old_id") {
2226 $old_id = $params->{$p};
2227 } elsif ($p eq "key") {
2228 $key = $params->{$p};
2234 $where = "WHERE active ";
2236 if (ref($old_id) eq "ARRAY") {
2237 my @ids = grep({ $_ } @{$old_id});
2239 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2240 push(@values, @ids);
2243 $where .= " OR (id = ?) ";
2244 push(@values, $old_id);
2250 qq|SELECT id, projectnumber, description, active | .
2253 qq|ORDER BY lower(projectnumber)|;
2255 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2257 $main::lxdebug->leave_sub();
2261 $main::lxdebug->enter_sub();
2263 my ($self, $dbh, $vc_id, $key) = @_;
2265 $key = "all_shipto" unless ($key);
2268 # get shipping addresses
2269 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2271 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2277 $main::lxdebug->leave_sub();
2281 $main::lxdebug->enter_sub();
2283 my ($self, $dbh, $key) = @_;
2285 $key = "all_printers" unless ($key);
2287 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2289 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2291 $main::lxdebug->leave_sub();
2295 $main::lxdebug->enter_sub();
2297 my ($self, $dbh, $params) = @_;
2300 $key = $params->{key};
2301 $key = "all_charts" unless ($key);
2303 my $transdate = quote_db_date($params->{transdate});
2306 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2308 qq|LEFT JOIN taxkeys tk ON | .
2309 qq|(tk.id = (SELECT id FROM taxkeys | .
2310 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2311 qq| ORDER BY startdate DESC LIMIT 1)) | .
2312 qq|ORDER BY c.accno|;
2314 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2316 $main::lxdebug->leave_sub();
2319 sub _get_taxcharts {
2320 $main::lxdebug->enter_sub();
2322 my ($self, $dbh, $params) = @_;
2324 my $key = "all_taxcharts";
2327 if (ref $params eq 'HASH') {
2328 $key = $params->{key} if ($params->{key});
2329 if ($params->{module} eq 'AR') {
2330 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2332 } elsif ($params->{module} eq 'AP') {
2333 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2340 my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2342 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2344 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2346 $main::lxdebug->leave_sub();
2350 $main::lxdebug->enter_sub();
2352 my ($self, $dbh, $key) = @_;
2354 $key = "all_taxzones" unless ($key);
2356 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2358 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2360 $main::lxdebug->leave_sub();
2363 sub _get_employees {
2364 $main::lxdebug->enter_sub();
2366 my ($self, $dbh, $default_key, $key) = @_;
2368 $key = $default_key unless ($key);
2369 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2371 $main::lxdebug->leave_sub();
2374 sub _get_business_types {
2375 $main::lxdebug->enter_sub();
2377 my ($self, $dbh, $key) = @_;
2379 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2380 $options->{key} ||= "all_business_types";
2383 if (exists $options->{salesman}) {
2384 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2387 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2389 $main::lxdebug->leave_sub();
2392 sub _get_languages {
2393 $main::lxdebug->enter_sub();
2395 my ($self, $dbh, $key) = @_;
2397 $key = "all_languages" unless ($key);
2399 my $query = qq|SELECT * FROM language ORDER BY id|;
2401 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2403 $main::lxdebug->leave_sub();
2406 sub _get_dunning_configs {
2407 $main::lxdebug->enter_sub();
2409 my ($self, $dbh, $key) = @_;
2411 $key = "all_dunning_configs" unless ($key);
2413 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2415 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2417 $main::lxdebug->leave_sub();
2420 sub _get_currencies {
2421 $main::lxdebug->enter_sub();
2423 my ($self, $dbh, $key) = @_;
2425 $key = "all_currencies" unless ($key);
2427 my $query = qq|SELECT curr AS currency FROM defaults|;
2429 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2431 $main::lxdebug->leave_sub();
2435 $main::lxdebug->enter_sub();
2437 my ($self, $dbh, $key) = @_;
2439 $key = "all_payments" unless ($key);
2441 my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2443 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2445 $main::lxdebug->leave_sub();
2448 sub _get_customers {
2449 $main::lxdebug->enter_sub();
2451 my ($self, $dbh, $key) = @_;
2453 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2454 $options->{key} ||= "all_customers";
2455 my $limit_clause = "LIMIT $options->{limit}" if $options->{limit};
2458 push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman};
2459 push @where, qq|NOT obsolete| if !$options->{with_obsolete};
2460 my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2462 my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2463 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2465 $main::lxdebug->leave_sub();
2469 $main::lxdebug->enter_sub();
2471 my ($self, $dbh, $key) = @_;
2473 $key = "all_vendors" unless ($key);
2475 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2477 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2479 $main::lxdebug->leave_sub();
2482 sub _get_departments {
2483 $main::lxdebug->enter_sub();
2485 my ($self, $dbh, $key) = @_;
2487 $key = "all_departments" unless ($key);
2489 my $query = qq|SELECT * FROM department ORDER BY description|;
2491 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2493 $main::lxdebug->leave_sub();
2496 sub _get_warehouses {
2497 $main::lxdebug->enter_sub();
2499 my ($self, $dbh, $param) = @_;
2501 my ($key, $bins_key);
2503 if ('' eq ref $param) {
2507 $key = $param->{key};
2508 $bins_key = $param->{bins};
2511 my $query = qq|SELECT w.* FROM warehouse w
2512 WHERE (NOT w.invalid) AND
2513 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2514 ORDER BY w.sortkey|;
2516 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2519 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2520 ORDER BY description|;
2521 my $sth = prepare_query($self, $dbh, $query);
2523 foreach my $warehouse (@{ $self->{$key} }) {
2524 do_statement($self, $sth, $query, $warehouse->{id});
2525 $warehouse->{$bins_key} = [];
2527 while (my $ref = $sth->fetchrow_hashref()) {
2528 push @{ $warehouse->{$bins_key} }, $ref;
2534 $main::lxdebug->leave_sub();
2538 $main::lxdebug->enter_sub();
2540 my ($self, $dbh, $table, $key, $sortkey) = @_;
2542 my $query = qq|SELECT * FROM $table|;
2543 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2545 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2547 $main::lxdebug->leave_sub();
2551 # $main::lxdebug->enter_sub();
2553 # my ($self, $dbh, $key) = @_;
2555 # $key ||= "all_groups";
2557 # my $groups = $main::auth->read_groups();
2559 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2561 # $main::lxdebug->leave_sub();
2565 $main::lxdebug->enter_sub();
2570 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2571 my ($sth, $query, $ref);
2573 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2574 my $vc_id = $self->{"${vc}_id"};
2576 if ($params{"contacts"}) {
2577 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2580 if ($params{"shipto"}) {
2581 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2584 if ($params{"projects"} || $params{"all_projects"}) {
2585 $self->_get_projects($dbh, $params{"all_projects"} ?
2586 $params{"all_projects"} : $params{"projects"},
2587 $params{"all_projects"} ? 1 : 0);
2590 if ($params{"printers"}) {
2591 $self->_get_printers($dbh, $params{"printers"});
2594 if ($params{"languages"}) {
2595 $self->_get_languages($dbh, $params{"languages"});
2598 if ($params{"charts"}) {
2599 $self->_get_charts($dbh, $params{"charts"});
2602 if ($params{"taxcharts"}) {
2603 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2606 if ($params{"taxzones"}) {
2607 $self->_get_taxzones($dbh, $params{"taxzones"});
2610 if ($params{"employees"}) {
2611 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2614 if ($params{"salesmen"}) {
2615 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2618 if ($params{"business_types"}) {
2619 $self->_get_business_types($dbh, $params{"business_types"});
2622 if ($params{"dunning_configs"}) {
2623 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2626 if($params{"currencies"}) {
2627 $self->_get_currencies($dbh, $params{"currencies"});
2630 if($params{"customers"}) {
2631 $self->_get_customers($dbh, $params{"customers"});
2634 if($params{"vendors"}) {
2635 if (ref $params{"vendors"} eq 'HASH') {
2636 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2638 $self->_get_vendors($dbh, $params{"vendors"});
2642 if($params{"payments"}) {
2643 $self->_get_payments($dbh, $params{"payments"});
2646 if($params{"departments"}) {
2647 $self->_get_departments($dbh, $params{"departments"});
2650 if ($params{price_factors}) {
2651 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2654 if ($params{warehouses}) {
2655 $self->_get_warehouses($dbh, $params{warehouses});
2658 # if ($params{groups}) {
2659 # $self->_get_groups($dbh, $params{groups});
2662 if ($params{partsgroup}) {
2663 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2666 $main::lxdebug->leave_sub();
2669 # this sub gets the id and name from $table
2671 $main::lxdebug->enter_sub();
2673 my ($self, $myconfig, $table) = @_;
2675 # connect to database
2676 my $dbh = $self->get_standard_dbh($myconfig);
2678 $table = $table eq "customer" ? "customer" : "vendor";
2679 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2681 my ($query, @values);
2683 if (!$self->{openinvoices}) {
2685 if ($self->{customernumber} ne "") {
2686 $where = qq|(vc.customernumber ILIKE ?)|;
2687 push(@values, '%' . $self->{customernumber} . '%');
2689 $where = qq|(vc.name ILIKE ?)|;
2690 push(@values, '%' . $self->{$table} . '%');
2694 qq~SELECT vc.id, vc.name,
2695 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2697 WHERE $where AND (NOT vc.obsolete)
2701 qq~SELECT DISTINCT vc.id, vc.name,
2702 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2704 JOIN $table vc ON (a.${table}_id = vc.id)
2705 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2707 push(@values, '%' . $self->{$table} . '%');
2710 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2712 $main::lxdebug->leave_sub();
2714 return scalar(@{ $self->{name_list} });
2717 # the selection sub is used in the AR, AP, IS, IR and OE module
2720 $main::lxdebug->enter_sub();
2722 my ($self, $myconfig, $table, $module) = @_;
2725 my $dbh = $self->get_standard_dbh;
2727 $table = $table eq "customer" ? "customer" : "vendor";
2729 my $query = qq|SELECT count(*) FROM $table|;
2730 my ($count) = selectrow_query($self, $dbh, $query);
2732 # build selection list
2733 if ($count <= $myconfig->{vclimit}) {
2734 $query = qq|SELECT id, name, salesman_id
2735 FROM $table WHERE NOT obsolete
2737 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2741 $self->get_employee($dbh);
2743 # setup sales contacts
2744 $query = qq|SELECT e.id, e.name
2746 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2747 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2750 push(@{ $self->{all_employees} },
2751 { id => $self->{employee_id},
2752 name => $self->{employee} });
2754 # sort the whole thing
2755 @{ $self->{all_employees} } =
2756 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2758 if ($module eq 'AR') {
2760 # prepare query for departments
2761 $query = qq|SELECT id, description
2764 ORDER BY description|;
2767 $query = qq|SELECT id, description
2769 ORDER BY description|;
2772 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2775 $query = qq|SELECT id, description
2779 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2782 $query = qq|SELECT printer_description, id
2784 ORDER BY printer_description|;
2786 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2789 $query = qq|SELECT id, description
2793 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2795 $main::lxdebug->leave_sub();
2798 sub language_payment {
2799 $main::lxdebug->enter_sub();
2801 my ($self, $myconfig) = @_;
2803 my $dbh = $self->get_standard_dbh($myconfig);
2805 my $query = qq|SELECT id, description
2809 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2812 $query = qq|SELECT printer_description, id
2814 ORDER BY printer_description|;
2816 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2819 $query = qq|SELECT id, description
2823 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2825 # get buchungsgruppen
2826 $query = qq|SELECT id, description
2827 FROM buchungsgruppen|;
2829 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2831 $main::lxdebug->leave_sub();
2834 # this is only used for reports
2835 sub all_departments {
2836 $main::lxdebug->enter_sub();
2838 my ($self, $myconfig, $table) = @_;
2840 my $dbh = $self->get_standard_dbh($myconfig);
2843 if ($table eq 'customer') {
2844 $where = "WHERE role = 'P' ";
2847 my $query = qq|SELECT id, description
2850 ORDER BY description|;
2851 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2853 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2855 $main::lxdebug->leave_sub();
2859 $main::lxdebug->enter_sub();
2861 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2864 if ($table eq "customer") {
2873 $self->all_vc($myconfig, $table, $module);
2875 # get last customers or vendors
2876 my ($query, $sth, $ref);
2878 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2883 my $transdate = "current_date";
2884 if ($self->{transdate}) {
2885 $transdate = $dbh->quote($self->{transdate});
2888 # now get the account numbers
2889 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2890 FROM chart c, taxkeys tk
2891 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2892 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2895 $sth = $dbh->prepare($query);
2897 do_statement($self, $sth, $query, '%' . $module . '%');
2899 $self->{accounts} = "";
2900 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2902 foreach my $key (split(/:/, $ref->{link})) {
2903 if ($key =~ /\Q$module\E/) {
2905 # cross reference for keys
2906 $xkeyref{ $ref->{accno} } = $key;
2908 push @{ $self->{"${module}_links"}{$key} },
2909 { accno => $ref->{accno},
2910 description => $ref->{description},
2911 taxkey => $ref->{taxkey_id},
2912 tax_id => $ref->{tax_id} };
2914 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2920 # get taxkeys and description
2921 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2922 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2924 if (($module eq "AP") || ($module eq "AR")) {
2925 # get tax rates and description
2926 $query = qq|SELECT * FROM tax|;
2927 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2933 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2934 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2935 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2936 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2939 d.description AS department,
2942 JOIN $table c ON (a.${table}_id = c.id)
2943 LEFT JOIN employee e ON (e.id = a.employee_id)
2944 LEFT JOIN department d ON (d.id = a.department_id)
2946 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2948 foreach my $key (keys %$ref) {
2949 $self->{$key} = $ref->{$key};
2952 my $transdate = "current_date";
2953 if ($self->{transdate}) {
2954 $transdate = $dbh->quote($self->{transdate});
2957 # now get the account numbers
2958 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2960 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2962 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2963 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2966 $sth = $dbh->prepare($query);
2967 do_statement($self, $sth, $query, "%$module%");
2969 $self->{accounts} = "";
2970 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2972 foreach my $key (split(/:/, $ref->{link})) {
2973 if ($key =~ /\Q$module\E/) {
2975 # cross reference for keys
2976 $xkeyref{ $ref->{accno} } = $key;
2978 push @{ $self->{"${module}_links"}{$key} },
2979 { accno => $ref->{accno},
2980 description => $ref->{description},
2981 taxkey => $ref->{taxkey_id},
2982 tax_id => $ref->{tax_id} };
2984 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2990 # get amounts from individual entries
2993 c.accno, c.description,
2994 a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey,
2998 LEFT JOIN chart c ON (c.id = a.chart_id)
2999 LEFT JOIN project p ON (p.id = a.project_id)
3000 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
3001 WHERE (tk.taxkey_id=a.taxkey) AND
3002 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
3003 THEN tk.chart_id = a.chart_id
3006 OR (c.link='%tax%')) AND
3007 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
3008 WHERE a.trans_id = ?
3009 AND a.fx_transaction = '0'
3010 ORDER BY a.acc_trans_id, a.transdate|;
3011 $sth = $dbh->prepare($query);
3012 do_statement($self, $sth, $query, $self->{id});
3014 # get exchangerate for currency
3015 $self->{exchangerate} =
3016 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
3019 # store amounts in {acc_trans}{$key} for multiple accounts
3020 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
3021 $ref->{exchangerate} =
3022 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
3023 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
3026 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
3027 $ref->{amount} *= -1;
3029 $ref->{index} = $index;
3031 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
3037 d.curr AS currencies, d.closedto, d.revtrans,
3038 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
3039 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
3041 $ref = selectfirst_hashref_query($self, $dbh, $query);
3042 map { $self->{$_} = $ref->{$_} } keys %$ref;
3049 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
3050 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
3051 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
3053 $ref = selectfirst_hashref_query($self, $dbh, $query);
3054 map { $self->{$_} = $ref->{$_} } keys %$ref;
3056 if ($self->{"$self->{vc}_id"}) {
3058 # only setup currency
3059 ($self->{currency}) = split(/:/, $self->{currencies});
3063 $self->lastname_used($dbh, $myconfig, $table, $module);
3065 # get exchangerate for currency
3066 $self->{exchangerate} =
3067 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
3073 $main::lxdebug->leave_sub();
3077 $main::lxdebug->enter_sub();
3079 my ($self, $dbh, $myconfig, $table, $module) = @_;
3083 $table = $table eq "customer" ? "customer" : "vendor";
3084 my %column_map = ("a.curr" => "currency",
3085 "a.${table}_id" => "${table}_id",
3086 "a.department_id" => "department_id",
3087 "d.description" => "department",
3088 "ct.name" => $table,
3089 "current_date + ct.terms" => "duedate",
3092 if ($self->{type} =~ /delivery_order/) {
3093 $arap = 'delivery_orders';
3094 delete $column_map{"a.curr"};
3096 } elsif ($self->{type} =~ /_order/) {
3098 $where = "quotation = '0'";
3100 } elsif ($self->{type} =~ /_quotation/) {
3102 $where = "quotation = '1'";
3104 } elsif ($table eq 'customer') {
3112 $where = "($where) AND" if ($where);
3113 my $query = qq|SELECT MAX(id) FROM $arap
3114 WHERE $where ${table}_id > 0|;
3115 my ($trans_id) = selectrow_query($self, $dbh, $query);
3118 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
3119 $query = qq|SELECT $column_spec
3121 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
3122 LEFT JOIN department d ON (a.department_id = d.id)
3124 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3126 map { $self->{$_} = $ref->{$_} } values %column_map;
3128 $main::lxdebug->leave_sub();
3132 $main::lxdebug->enter_sub();
3135 my $myconfig = shift || \%::myconfig;
3136 my ($thisdate, $days) = @_;
3138 my $dbh = $self->get_standard_dbh($myconfig);
3143 my $dateformat = $myconfig->{dateformat};
3144 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3145 $thisdate = $dbh->quote($thisdate);
3146 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3148 $query = qq|SELECT current_date AS thisdate|;
3151 ($thisdate) = selectrow_query($self, $dbh, $query);
3153 $main::lxdebug->leave_sub();
3159 $main::lxdebug->enter_sub();
3161 my ($self, $string) = @_;
3163 if ($string !~ /%/) {
3164 $string = "%$string%";
3167 $string =~ s/\'/\'\'/g;
3169 $main::lxdebug->leave_sub();
3175 $main::lxdebug->enter_sub();
3177 my ($self, $flds, $new, $count, $numrows) = @_;
3181 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3186 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3188 my $j = $item->{ndx} - 1;
3189 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3193 for $i ($count + 1 .. $numrows) {
3194 map { delete $self->{"${_}_$i"} } @{$flds};
3197 $main::lxdebug->leave_sub();
3201 $main::lxdebug->enter_sub();
3203 my ($self, $myconfig) = @_;
3207 my $dbh = $self->dbconnect_noauto($myconfig);
3209 my $query = qq|DELETE FROM status
3210 WHERE (formname = ?) AND (trans_id = ?)|;
3211 my $sth = prepare_query($self, $dbh, $query);
3213 if ($self->{formname} =~ /(check|receipt)/) {
3214 for $i (1 .. $self->{rowcount}) {
3215 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3218 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3222 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3223 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3225 my %queued = split / /, $self->{queued};
3228 if ($self->{formname} =~ /(check|receipt)/) {
3230 # this is a check or receipt, add one entry for each lineitem
3231 my ($accno) = split /--/, $self->{account};
3232 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3233 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3234 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3235 $sth = prepare_query($self, $dbh, $query);
3237 for $i (1 .. $self->{rowcount}) {
3238 if ($self->{"checked_$i"}) {
3239 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3245 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3246 VALUES (?, ?, ?, ?, ?)|;
3247 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3248 $queued{$self->{formname}}, $self->{formname});
3254 $main::lxdebug->leave_sub();
3258 $main::lxdebug->enter_sub();
3260 my ($self, $dbh) = @_;
3262 my ($query, $printed, $emailed);
3264 my $formnames = $self->{printed};
3265 my $emailforms = $self->{emailed};
3267 $query = qq|DELETE FROM status
3268 WHERE (formname = ?) AND (trans_id = ?)|;
3269 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3271 # this only applies to the forms
3272 # checks and receipts are posted when printed or queued
3274 if ($self->{queued}) {
3275 my %queued = split / /, $self->{queued};
3277 foreach my $formname (keys %queued) {
3278 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3279 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3281 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3282 VALUES (?, ?, ?, ?, ?)|;
3283 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3285 $formnames =~ s/\Q$self->{formname}\E//;
3286 $emailforms =~ s/\Q$self->{formname}\E//;
3291 # save printed, emailed info
3292 $formnames =~ s/^ +//g;
3293 $emailforms =~ s/^ +//g;
3296 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3297 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3299 foreach my $formname (keys %status) {
3300 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3301 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3303 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3304 VALUES (?, ?, ?, ?)|;
3305 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3308 $main::lxdebug->leave_sub();
3312 # $main::locale->text('SAVED')
3313 # $main::locale->text('DELETED')
3314 # $main::locale->text('ADDED')
3315 # $main::locale->text('PAYMENT POSTED')
3316 # $main::locale->text('POSTED')
3317 # $main::locale->text('POSTED AS NEW')
3318 # $main::locale->text('ELSE')
3319 # $main::locale->text('SAVED FOR DUNNING')
3320 # $main::locale->text('DUNNING STARTED')
3321 # $main::locale->text('PRINTED')
3322 # $main::locale->text('MAILED')
3323 # $main::locale->text('SCREENED')
3324 # $main::locale->text('CANCELED')
3325 # $main::locale->text('invoice')
3326 # $main::locale->text('proforma')
3327 # $main::locale->text('sales_order')
3328 # $main::locale->text('pick_list')
3329 # $main::locale->text('purchase_order')
3330 # $main::locale->text('bin_list')
3331 # $main::locale->text('sales_quotation')
3332 # $main::locale->text('request_quotation')
3335 $main::lxdebug->enter_sub();
3338 my $dbh = shift || $self->get_standard_dbh;
3340 if(!exists $self->{employee_id}) {
3341 &get_employee($self, $dbh);
3345 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3346 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3347 my @values = (conv_i($self->{id}), $self->{login},
3348 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3349 do_query($self, $dbh, $query, @values);
3353 $main::lxdebug->leave_sub();
3357 $main::lxdebug->enter_sub();
3359 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3360 my ($orderBy, $desc) = split(/\-\-/, $order);
3361 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3364 if ($trans_id ne "") {
3366 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 | .
3367 qq|FROM history_erp h | .
3368 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3369 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3372 my $sth = $dbh->prepare($query) || $self->dberror($query);
3374 $sth->execute() || $self->dberror("$query");
3376 while(my $hash_ref = $sth->fetchrow_hashref()) {
3377 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3378 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3379 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3380 $tempArray[$i++] = $hash_ref;
3382 $main::lxdebug->leave_sub() and return \@tempArray
3383 if ($i > 0 && $tempArray[0] ne "");
3385 $main::lxdebug->leave_sub();
3389 sub update_defaults {
3390 $main::lxdebug->enter_sub();
3392 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3395 if ($provided_dbh) {
3396 $dbh = $provided_dbh;
3398 $dbh = $self->dbconnect_noauto($myconfig);
3400 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3401 my $sth = $dbh->prepare($query);
3403 $sth->execute || $self->dberror($query);
3404 my ($var) = $sth->fetchrow_array;
3407 if ($var =~ m/\d+$/) {
3408 my $new_var = (substr $var, $-[0]) * 1 + 1;
3409 my $len_diff = length($var) - $-[0] - length($new_var);
3410 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3416 $query = qq|UPDATE defaults SET $fld = ?|;
3417 do_query($self, $dbh, $query, $var);
3419 if (!$provided_dbh) {
3424 $main::lxdebug->leave_sub();
3429 sub update_business {
3430 $main::lxdebug->enter_sub();
3432 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3435 if ($provided_dbh) {
3436 $dbh = $provided_dbh;
3438 $dbh = $self->dbconnect_noauto($myconfig);
3441 qq|SELECT customernumberinit FROM business
3442 WHERE id = ? FOR UPDATE|;
3443 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3445 return undef unless $var;
3447 if ($var =~ m/\d+$/) {
3448 my $new_var = (substr $var, $-[0]) * 1 + 1;
3449 my $len_diff = length($var) - $-[0] - length($new_var);
3450 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3456 $query = qq|UPDATE business
3457 SET customernumberinit = ?
3459 do_query($self, $dbh, $query, $var, $business_id);
3461 if (!$provided_dbh) {
3466 $main::lxdebug->leave_sub();
3471 sub get_partsgroup {
3472 $main::lxdebug->enter_sub();
3474 my ($self, $myconfig, $p) = @_;
3475 my $target = $p->{target} || 'all_partsgroup';
3477 my $dbh = $self->get_standard_dbh($myconfig);
3479 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3481 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3484 if ($p->{searchitems} eq 'part') {
3485 $query .= qq|WHERE p.inventory_accno_id > 0|;
3487 if ($p->{searchitems} eq 'service') {
3488 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3490 if ($p->{searchitems} eq 'assembly') {
3491 $query .= qq|WHERE p.assembly = '1'|;
3493 if ($p->{searchitems} eq 'labor') {
3494 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3497 $query .= qq|ORDER BY partsgroup|;
3500 $query = qq|SELECT id, partsgroup FROM partsgroup
3501 ORDER BY partsgroup|;
3504 if ($p->{language_code}) {
3505 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3506 t.description AS translation
3508 JOIN parts p ON (p.partsgroup_id = pg.id)
3509 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3510 ORDER BY translation|;
3511 @values = ($p->{language_code});
3514 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3516 $main::lxdebug->leave_sub();
3519 sub get_pricegroup {
3520 $main::lxdebug->enter_sub();
3522 my ($self, $myconfig, $p) = @_;
3524 my $dbh = $self->get_standard_dbh($myconfig);
3526 my $query = qq|SELECT p.id, p.pricegroup
3529 $query .= qq| ORDER BY pricegroup|;
3532 $query = qq|SELECT id, pricegroup FROM pricegroup
3533 ORDER BY pricegroup|;
3536 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3538 $main::lxdebug->leave_sub();
3542 # usage $form->all_years($myconfig, [$dbh])
3543 # return list of all years where bookings found
3546 $main::lxdebug->enter_sub();
3548 my ($self, $myconfig, $dbh) = @_;
3550 $dbh ||= $self->get_standard_dbh($myconfig);
3553 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3554 (SELECT MAX(transdate) FROM acc_trans)|;
3555 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3557 if ($myconfig->{dateformat} =~ /^yy/) {
3558 ($startdate) = split /\W/, $startdate;
3559 ($enddate) = split /\W/, $enddate;
3561 (@_) = split /\W/, $startdate;
3563 (@_) = split /\W/, $enddate;
3568 $startdate = substr($startdate,0,4);
3569 $enddate = substr($enddate,0,4);
3571 while ($enddate >= $startdate) {
3572 push @all_years, $enddate--;
3577 $main::lxdebug->leave_sub();
3581 $main::lxdebug->enter_sub();
3585 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3587 $main::lxdebug->leave_sub();
3591 $main::lxdebug->enter_sub();
3596 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3598 $main::lxdebug->leave_sub();
3601 sub prepare_for_printing {
3604 $self->{templates} ||= $::myconfig{templates};
3605 $self->{formname} ||= $self->{type};
3606 $self->{media} ||= 'email';
3608 die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3610 # set shipto from billto unless set
3611 my $has_shipto = any { $self->{"shipto$_"} } qw(name street zipcode city country contact);
3612 if (!$has_shipto && ($self->{type} =~ m/^(?:purchase_order|request_quotation)$/)) {
3613 $self->{shiptoname} = $::myconfig{company};
3614 $self->{shiptostreet} = $::myconfig{address};
3617 my $language = $self->{language} ? '_' . $self->{language} : '';
3619 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3620 if ($self->{language_id}) {
3621 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3623 $output_dateformat = $::myconfig{dateformat};
3624 $output_numberformat = $::myconfig{numberformat};
3625 $output_longdates = 1;
3628 # Retrieve accounts for tax calculation.
3629 IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3631 if ($self->{type} =~ /_delivery_order$/) {
3632 DO->order_details();
3633 } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3634 OE->order_details(\%::myconfig, $self);
3636 IS->invoice_details(\%::myconfig, $self, $::locale);
3639 # Chose extension & set source file name
3640 my $extension = 'html';
3641 if ($self->{format} eq 'postscript') {
3642 $self->{postscript} = 1;
3644 } elsif ($self->{"format"} =~ /pdf/) {
3646 $extension = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3647 } elsif ($self->{"format"} =~ /opendocument/) {
3648 $self->{opendocument} = 1;
3650 } elsif ($self->{"format"} =~ /excel/) {
3655 my $printer_code = '_' . $self->{printer_code} if $self->{printer_code};
3656 my $email_extension = '_email' if -f "$self->{templates}/$self->{formname}_email${language}${printer_code}.${extension}";
3657 $self->{IN} = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3660 $self->format_dates($output_dateformat, $output_longdates,
3661 qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate datepaid
3662 transdate_oe deliverydate_oe employee_startdate employee_enddate),
3663 grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3665 $self->reformat_numbers($output_numberformat, 2,
3666 qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3667 grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3669 $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3671 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3673 if (scalar @{ $cvar_date_fields }) {
3674 $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3677 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3678 $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3685 my ($self, $dateformat, $longformat, @indices) = @_;
3687 $dateformat ||= $::myconfig{dateformat};
3689 foreach my $idx (@indices) {
3690 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3691 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3692 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3696 next unless defined $self->{$idx};
3698 if (!ref($self->{$idx})) {
3699 $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3701 } elsif (ref($self->{$idx}) eq "ARRAY") {
3702 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3703 $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3709 sub reformat_numbers {
3710 my ($self, $numberformat, $places, @indices) = @_;
3712 return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3714 foreach my $idx (@indices) {
3715 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3716 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3717 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3721 next unless defined $self->{$idx};
3723 if (!ref($self->{$idx})) {
3724 $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3726 } elsif (ref($self->{$idx}) eq "ARRAY") {
3727 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3728 $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3733 my $saved_numberformat = $::myconfig{numberformat};
3734 $::myconfig{numberformat} = $numberformat;
3736 foreach my $idx (@indices) {
3737 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3738 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3739 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3743 next unless defined $self->{$idx};
3745 if (!ref($self->{$idx})) {
3746 $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3748 } elsif (ref($self->{$idx}) eq "ARRAY") {
3749 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3750 $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3755 $::myconfig{numberformat} = $saved_numberformat;
3764 SL::Form.pm - main data object.
3768 This is the main data object of Lx-Office.
3769 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3770 Points of interest for a beginner are:
3772 - $form->error - renders a generic error in html. accepts an error message
3773 - $form->get_standard_dbh - returns a database connection for the
3775 =head1 SPECIAL FUNCTIONS
3777 =head2 C<_store_value()>
3779 parses a complex var name, and stores it in the form.
3782 $form->_store_value($key, $value);
3784 keys must start with a string, and can contain various tokens.
3785 supported key structures are:
3788 simple key strings work as expected
3793 separating two keys by a dot (.) will result in a hash lookup for the inner value
3794 this is similar to the behaviour of java and templating mechanisms.
3796 filter.description => $form->{filter}->{description}
3798 3. array+hashref access
3800 adding brackets ([]) before the dot will cause the next hash to be put into an array.
3801 using [+] instead of [] will force a new array index. this is useful for recurring
3802 data structures like part lists. put a [+] into the first varname, and use [] on the
3805 repeating these names in your template:
3808 invoice.items[].parts_id
3812 $form->{invoice}->{items}->[
3826 using brackets at the end of a name will result in a pure array to be created.
3827 note that you mustn't use [+], which is reserved for array+hash access and will
3828 result in undefined behaviour in array context.
3830 filter.status[] => $form->{status}->[ val1, val2, ... ]
3832 =head2 C<update_business> PARAMS
3835 \%config, - config hashref
3836 $business_id, - business id
3837 $dbh - optional database handle
3839 handles business (thats customer/vendor types) sequences.
3841 special behaviour for empty strings in customerinitnumber field:
3842 will in this case not increase the value, and return undef.
3844 =head2 C<redirect_header> $url
3846 Generates a HTTP redirection header for the new C<$url>. Constructs an
3847 absolute URL including scheme, host name and port. If C<$url> is a
3848 relative URL then it is considered relative to Lx-Office base URL.
3850 This function C<die>s if headers have already been created with
3851 C<$::form-E<gt>header>.
3855 print $::form->redirect_header('oe.pl?action=edit&id=1234');
3856 print $::form->redirect_header('http://www.lx-office.org/');
3860 Generates a general purpose http/html header and includes most of the scripts
3861 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3863 Only one header will be generated. If the method was already called in this
3864 request it will not output anything and return undef. Also if no
3865 HTTP_USER_AGENT is found, no header is generated.
3867 Although header does not accept parameters itself, it will honor special
3868 hashkeys of its Form instance:
3876 If one of these is set, a http-equiv refresh is generated. Missing parameters
3877 default to 3 seconds and the refering url.
3881 Either a scalar or an array ref. Will be inlined into the header. Add
3882 stylesheets with the L<use_stylesheet> function.
3886 If true, a css snippet will be generated that sets the page in landscape mode.
3890 Used to override the default favicon.
3894 A html page title will be generated from this