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();
254 if ($LXDebug::watch_form) {
255 require SL::Watchdog;
256 tie %{ $self }, 'SL::Watchdog';
261 $self->_input_to_hash($ENV{QUERY_STRING}) if $ENV{QUERY_STRING};
262 $self->_input_to_hash($ARGV[0]) if @ARGV && $ARGV[0];
265 if ($ENV{CONTENT_LENGTH}) {
267 read STDIN, $content, $ENV{CONTENT_LENGTH};
268 $uploads = $self->_request_to_hash($content);
271 my $db_charset = $::lx_office_conf{system}->{dbcharset};
272 $db_charset ||= Common::DEFAULT_CHARSET;
274 my $encoding = $self->{INPUT_ENCODING} || $db_charset;
275 delete $self->{INPUT_ENCODING};
277 _recode_recursively(SL::Iconv->new($encoding, $db_charset), $self);
279 map { $self->{$_} = $uploads->{$_} } keys %{ $uploads } if $uploads;
281 #$self->{version} = "2.6.1"; # Old hardcoded but secure style
282 open VERSION_FILE, "VERSION"; # New but flexible code reads version from VERSION-file
283 $self->{version} = <VERSION_FILE>;
285 $self->{version} =~ s/[^0-9A-Za-z\.\_\-]//g; # only allow numbers, letters, points, underscores and dashes. Prevents injecting of malicious code.
287 $main::lxdebug->leave_sub();
292 sub _flatten_variables_rec {
293 $main::lxdebug->enter_sub(2);
302 if ('' eq ref $curr->{$key}) {
303 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
305 } elsif ('HASH' eq ref $curr->{$key}) {
306 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
307 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
311 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
312 my $first_array_entry = 1;
314 foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
315 push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
316 $first_array_entry = 0;
321 $main::lxdebug->leave_sub(2);
326 sub flatten_variables {
327 $main::lxdebug->enter_sub(2);
335 push @variables, $self->_flatten_variables_rec($self, '', $_);
338 $main::lxdebug->leave_sub(2);
343 sub flatten_standard_variables {
344 $main::lxdebug->enter_sub(2);
347 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
351 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
352 push @variables, $self->_flatten_variables_rec($self, '', $_);
355 $main::lxdebug->leave_sub(2);
361 $main::lxdebug->enter_sub();
367 map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
369 $main::lxdebug->leave_sub();
373 $main::lxdebug->enter_sub(2);
376 my $password = $self->{password};
378 $self->{password} = 'X' x 8;
380 local $Data::Dumper::Sortkeys = 1;
381 my $output = Dumper($self);
383 $self->{password} = $password;
385 $main::lxdebug->leave_sub(2);
391 $main::lxdebug->enter_sub(2);
393 my ($self, $str) = @_;
395 $str = Encode::encode('utf-8-strict', $str) if $::locale->is_utf8;
396 $str =~ s/([^a-zA-Z0-9_.:-])/sprintf("%%%02x", ord($1))/ge;
398 $main::lxdebug->leave_sub(2);
404 $main::lxdebug->enter_sub(2);
406 my ($self, $str) = @_;
411 $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
412 $str = Encode::decode('utf-8-strict', $str) if $::locale->is_utf8;
414 $main::lxdebug->leave_sub(2);
420 $main::lxdebug->enter_sub();
421 my ($self, $str) = @_;
423 if ($str && !ref($str)) {
424 $str =~ s/\"/"/g;
427 $main::lxdebug->leave_sub();
433 $main::lxdebug->enter_sub();
434 my ($self, $str) = @_;
436 if ($str && !ref($str)) {
437 $str =~ s/"/\"/g;
440 $main::lxdebug->leave_sub();
446 $main::lxdebug->enter_sub();
450 map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
452 for (sort keys %$self) {
453 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
454 print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
457 $main::lxdebug->leave_sub();
461 my ($self, $code) = @_;
462 local $self->{__ERROR_HANDLER} = sub { die SL::X::FormError->new($_[0]) };
467 $main::lxdebug->enter_sub();
469 $main::lxdebug->show_backtrace();
471 my ($self, $msg) = @_;
473 if ($self->{__ERROR_HANDLER}) {
474 $self->{__ERROR_HANDLER}->($msg);
476 } elsif ($ENV{HTTP_USER_AGENT}) {
478 $self->show_generic_error($msg);
481 print STDERR "Error: $msg\n";
485 $main::lxdebug->leave_sub();
489 $main::lxdebug->enter_sub();
491 my ($self, $msg) = @_;
493 if ($ENV{HTTP_USER_AGENT}) {
496 if (!$self->{header}) {
502 <p class="message_ok"><b>$msg</b></p>
504 <script type="text/javascript">
506 // If JavaScript is enabled, the whole thing will be reloaded.
507 // The reason is: When one changes his menu setup (HTML / XUL / CSS ...)
508 // it now loads the correct code into the browser instead of do nothing.
509 setTimeout("top.frames.location.href='login.pl'",500);
518 if ($self->{info_function}) {
519 &{ $self->{info_function} }($msg);
525 $main::lxdebug->leave_sub();
528 # calculates the number of rows in a textarea based on the content and column number
529 # can be capped with maxrows
531 $main::lxdebug->enter_sub();
532 my ($self, $str, $cols, $maxrows, $minrows) = @_;
536 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
539 $main::lxdebug->leave_sub();
541 return max(min($rows, $maxrows), $minrows);
545 $main::lxdebug->enter_sub();
547 my ($self, $msg) = @_;
549 $self->error("$msg\n" . $DBI::errstr);
551 $main::lxdebug->leave_sub();
555 $main::lxdebug->enter_sub();
557 my ($self, $name, $msg) = @_;
560 foreach my $part (split m/\./, $name) {
561 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
564 $curr = $curr->{$part};
567 $main::lxdebug->leave_sub();
570 sub _get_request_uri {
573 return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
575 my $scheme = $ENV{HTTPS} && (lc $ENV{HTTPS} eq 'on') ? 'https' : 'http';
576 my $port = $ENV{SERVER_PORT} || '';
577 $port = undef if (($scheme eq 'http' ) && ($port == 80))
578 || (($scheme eq 'https') && ($port == 443));
580 my $uri = URI->new("${scheme}://");
581 $uri->scheme($scheme);
583 $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
584 $uri->path_query($ENV{REQUEST_URI});
590 sub _add_to_request_uri {
593 my $relative_new_path = shift;
594 my $request_uri = shift || $self->_get_request_uri;
595 my $relative_new_uri = URI->new($relative_new_path);
596 my @request_segments = $request_uri->path_segments;
598 my $new_uri = $request_uri->clone;
599 $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
604 sub create_http_response {
605 $main::lxdebug->enter_sub();
610 my $cgi = $main::cgi;
611 $cgi ||= CGI->new('');
614 if (defined $main::auth) {
615 my $uri = $self->_get_request_uri;
616 my @segments = $uri->path_segments;
618 $uri->path_segments(@segments);
620 my $session_cookie_value = $main::auth->get_session_id();
622 if ($session_cookie_value) {
623 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
624 '-value' => $session_cookie_value,
625 '-path' => $uri->path,
626 '-secure' => $ENV{HTTPS});
630 my %cgi_params = ('-type' => $params{content_type});
631 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
632 $cgi_params{'-cookie'} = $session_cookie if ($session_cookie);
634 map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length);
636 my $output = $cgi->header(%cgi_params);
638 $main::lxdebug->leave_sub();
646 $self->{stylesheet} = [ $self->{stylesheet} ] unless ref $self->{stylesheet} eq 'ARRAY';
647 $self->{stylesheet} = [ grep { -f }
648 map { m:^css/: ? $_ : "css/$_" }
650 (@{ $self->{stylesheet} }, @_)
653 return @{ $self->{stylesheet} };
657 $::lxdebug->enter_sub;
659 # extra code is currently only used by menuv3 and menuv4 to set their css.
660 # it is strongly deprecated, and will be changed in a future version.
661 my ($self, $extra_code) = @_;
662 my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
665 $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
667 $self->{favicon} ||= "favicon.ico";
668 $self->{titlebar} = "$self->{title} - $self->{titlebar}" if $self->{title};
671 if ($self->{refresh_url} || $self->{refresh_time}) {
672 my $refresh_time = $self->{refresh_time} || 3;
673 my $refresh_url = $self->{refresh_url} || $ENV{REFERER};
674 push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
677 push @header, map { qq|<link rel="stylesheet" href="$_" type="text/css" title="Lx-Office stylesheet">| } $self->use_stylesheet;
679 push @header, "<style type='text/css'>\@page { size:landscape; }</style>" if $self->{landscape};
680 push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
681 push @header, '<script type="text/javascript" src="js/jquery.js"></script>',
682 '<script type="text/javascript" src="js/common.js"></script>',
683 '<style type="text/css">@import url(js/jscalendar/calendar-win2k-1.css);</style>',
684 '<script type="text/javascript" src="js/jscalendar/calendar.js"></script>',
685 '<script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>',
686 '<script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>',
687 '<script type="text/javascript" src="js/part_selection.js"></script>';
688 push @header, $self->{javascript} if $self->{javascript};
689 push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
690 push @header, "<script type='text/javascript'>function fokus(){ document.$self->{fokus}.focus(); }</script>" if $self->{fokus};
691 push @header, sprintf "<script type='text/javascript'>top.document.title='%s';</script>",
692 join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->{version} if $self->{title};
694 # if there is a title, we put some JavaScript in to the page, wich writes a
695 # meaningful title-tag for our frameset.
697 if ($self->{title}) {
699 <script type="text/javascript">
701 // Write a meaningful title-tag for our frameset.
702 top.document.title="| . $self->{"title"} . qq| - | . $self->{"login"} . qq| - | . $::myconfig{dbname} . qq| - V| . $self->{"version"} . qq|";
708 print $self->create_http_response(content_type => 'text/html', charset => $db_charset);
709 print "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN' 'http://www.w3.org/TR/html4/strict.dtd'>\n"
710 if $ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/; # Other browsers may choke on menu scripts with DOCTYPE.
714 <meta http-equiv="Content-Type" content="text/html; charset=$db_charset">
715 <title>$self->{titlebar}</title>
717 print " $_\n" for @header;
719 <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
720 <meta name="robots" content="noindex,nofollow" />
721 <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
722 <script type="text/javascript" src="js/tabcontent.js">
724 /***********************************************
725 * Tab Content script v2.2- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
726 * This notice MUST stay intact for legal use
727 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
728 ***********************************************/
737 $::lxdebug->leave_sub;
740 sub ajax_response_header {
741 $main::lxdebug->enter_sub();
745 my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
746 my $cgi = $main::cgi || CGI->new('');
747 my $output = $cgi->header('-charset' => $db_charset);
749 $main::lxdebug->leave_sub();
754 sub redirect_header {
758 my $base_uri = $self->_get_request_uri;
759 my $new_uri = URI->new_abs($new_url, $base_uri);
761 die "Headers already sent" if $self->{header};
764 my $cgi = $main::cgi || CGI->new('');
765 return $cgi->redirect($new_uri);
768 sub set_standard_title {
769 $::lxdebug->enter_sub;
772 $self->{titlebar} = "Lx-Office " . $::locale->text('Version') . " $self->{version}";
773 $self->{titlebar} .= "- $::myconfig{name}" if $::myconfig{name};
774 $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
776 $::lxdebug->leave_sub;
779 sub _prepare_html_template {
780 $main::lxdebug->enter_sub();
782 my ($self, $file, $additional_params) = @_;
785 if (!%::myconfig || !$::myconfig{"countrycode"}) {
786 $language = $::lx_office_conf{system}->{language};
788 $language = $main::myconfig{"countrycode"};
790 $language = "de" unless ($language);
792 if (-f "templates/webpages/${file}.html") {
793 $file = "templates/webpages/${file}.html";
796 my $info = "Web page template '${file}' not found.\n";
797 print qq|<pre>$info</pre>|;
801 if ($self->{"DEBUG"}) {
802 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
805 if ($additional_params->{"DEBUG"}) {
806 $additional_params->{"DEBUG"} =
807 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
810 if (%main::myconfig) {
811 $::myconfig{jsc_dateformat} = apply {
815 } $::myconfig{"dateformat"};
816 $additional_params->{"myconfig"} ||= \%::myconfig;
817 map { $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys %::myconfig;
820 $additional_params->{"conf_dbcharset"} = $::lx_office_conf{system}->{dbcharset};
821 $additional_params->{"conf_webdav"} = $::lx_office_conf{features}->{webdav};
822 $additional_params->{"conf_latex_templates"} = $::lx_office_conf{print_templates}->{latex};
823 $additional_params->{"conf_opendocument_templates"} = $::lx_office_conf{print_templates}->{opendocument};
824 $additional_params->{"conf_vertreter"} = $::lx_office_conf{features}->{vertreter};
825 $additional_params->{"conf_show_best_before"} = $::lx_office_conf{features}->{show_best_before};
826 $additional_params->{"conf_parts_image_css"} = $::lx_office_conf{features}->{parts_image_css};
827 $additional_params->{"conf_parts_listing_images"} = $::lx_office_conf{features}->{parts_listing_images};
828 $additional_params->{"conf_parts_show_image"} = $::lx_office_conf{features}->{parts_show_image};
830 if (%main::debug_options) {
831 map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
834 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
835 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
836 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
840 $main::lxdebug->leave_sub();
845 sub parse_html_template {
846 $main::lxdebug->enter_sub();
848 my ($self, $file, $additional_params) = @_;
850 $additional_params ||= { };
852 my $real_file = $self->_prepare_html_template($file, $additional_params);
853 my $template = $self->template || $self->init_template;
855 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
858 $template->process($real_file, $additional_params, \$output) || die $template->error;
860 $main::lxdebug->leave_sub();
868 return if $self->template;
870 return $self->template(Template->new({
875 'PLUGIN_BASE' => 'SL::Template::Plugin',
876 'INCLUDE_PATH' => '.:templates/webpages',
877 'COMPILE_EXT' => '.tcc',
878 'COMPILE_DIR' => $::lx_office_conf{paths}->{userspath} . '/templates-cache',
884 $self->{template_object} = shift if @_;
885 return $self->{template_object};
888 sub show_generic_error {
889 $main::lxdebug->enter_sub();
891 my ($self, $error, %params) = @_;
893 if ($self->{__ERROR_HANDLER}) {
894 $self->{__ERROR_HANDLER}->($error);
895 $main::lxdebug->leave_sub();
900 'title_error' => $params{title},
901 'label_error' => $error,
904 if ($params{action}) {
907 map { delete($self->{$_}); } qw(action);
908 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
910 $add_params->{SHOW_BUTTON} = 1;
911 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
912 $add_params->{VARIABLES} = \@vars;
914 } elsif ($params{back_button}) {
915 $add_params->{SHOW_BACK_BUTTON} = 1;
918 $self->{title} = $params{title} if $params{title};
921 print $self->parse_html_template("generic/error", $add_params);
923 print STDERR "Error: $error\n";
925 $main::lxdebug->leave_sub();
930 sub show_generic_information {
931 $main::lxdebug->enter_sub();
933 my ($self, $text, $title) = @_;
936 'title_information' => $title,
937 'label_information' => $text,
940 $self->{title} = $title if ($title);
943 print $self->parse_html_template("generic/information", $add_params);
945 $main::lxdebug->leave_sub();
950 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
951 # changed it to accept an arbitrary number of triggers - sschoeling
953 $main::lxdebug->enter_sub();
956 my $myconfig = shift;
959 # set dateform for jsscript
962 "dd.mm.yy" => "%d.%m.%Y",
963 "dd-mm-yy" => "%d-%m-%Y",
964 "dd/mm/yy" => "%d/%m/%Y",
965 "mm/dd/yy" => "%m/%d/%Y",
966 "mm-dd-yy" => "%m-%d-%Y",
967 "yyyy-mm-dd" => "%Y-%m-%d",
970 my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
971 $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
978 inputField : "| . (shift) . qq|",
979 ifFormat :"$ifFormat",
980 align : "| . (shift) . qq|",
981 button : "| . (shift) . qq|"
987 <script type="text/javascript">
988 <!--| . join("", @triggers) . qq|//-->
992 $main::lxdebug->leave_sub();
995 } #end sub write_trigger
998 $main::lxdebug->enter_sub();
1000 my ($self, $msg) = @_;
1002 if (!$self->{callback}) {
1006 print $::form->redirect_header($self->{callback});
1011 $main::lxdebug->leave_sub();
1014 # sort of columns removed - empty sub
1016 $main::lxdebug->enter_sub();
1018 my ($self, @columns) = @_;
1020 $main::lxdebug->leave_sub();
1026 $main::lxdebug->enter_sub(2);
1028 my ($self, $myconfig, $amount, $places, $dash) = @_;
1030 if ($amount eq "") {
1034 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
1036 my $neg = ($amount =~ s/^-//);
1037 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
1039 if (defined($places) && ($places ne '')) {
1045 my ($actual_places) = ($amount =~ /\.(\d+)/);
1046 $actual_places = length($actual_places);
1047 $places = $actual_places > $places ? $actual_places : $places;
1050 $amount = $self->round_amount($amount, $places);
1053 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
1054 my @p = split(/\./, $amount); # split amount at decimal point
1056 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
1059 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
1062 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
1063 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1064 ($neg ? "-$amount" : "$amount" ) ;
1068 $main::lxdebug->leave_sub(2);
1072 sub format_amount_units {
1073 $main::lxdebug->enter_sub();
1078 my $myconfig = \%main::myconfig;
1079 my $amount = $params{amount} * 1;
1080 my $places = $params{places};
1081 my $part_unit_name = $params{part_unit};
1082 my $amount_unit_name = $params{amount_unit};
1083 my $conv_units = $params{conv_units};
1084 my $max_places = $params{max_places};
1086 if (!$part_unit_name) {
1087 $main::lxdebug->leave_sub();
1091 AM->retrieve_all_units();
1092 my $all_units = $main::all_units;
1094 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1095 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1098 if (!scalar @{ $conv_units }) {
1099 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1100 $main::lxdebug->leave_sub();
1104 my $part_unit = $all_units->{$part_unit_name};
1105 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1107 $amount *= $conv_unit->{factor};
1112 foreach my $unit (@$conv_units) {
1113 my $last = $unit->{name} eq $part_unit->{name};
1115 $num = int($amount / $unit->{factor});
1116 $amount -= $num * $unit->{factor};
1119 if ($last ? $amount : $num) {
1120 push @values, { "unit" => $unit->{name},
1121 "amount" => $last ? $amount / $unit->{factor} : $num,
1122 "places" => $last ? $places : 0 };
1129 push @values, { "unit" => $part_unit_name,
1134 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1136 $main::lxdebug->leave_sub();
1142 $main::lxdebug->enter_sub(2);
1147 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1148 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1149 $input =~ s/\#\#/\#/g;
1151 $main::lxdebug->leave_sub(2);
1159 $main::lxdebug->enter_sub(2);
1161 my ($self, $myconfig, $amount) = @_;
1163 if ( ($myconfig->{numberformat} eq '1.000,00')
1164 || ($myconfig->{numberformat} eq '1000,00')) {
1166 $amount =~ s/,/\./g;
1169 if ($myconfig->{numberformat} eq "1'000.00") {
1175 $main::lxdebug->leave_sub(2);
1177 # Make sure no code wich is not a math expression ends up in eval().
1178 return 0 unless $amount =~ /^ [\s \d \( \) \- \+ \* \/ \. ]* $/x;
1179 return scalar(eval($amount)) * 1 ;
1183 $main::lxdebug->enter_sub(2);
1185 my ($self, $amount, $places) = @_;
1188 # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
1190 # Round amounts to eight places before rounding to the requested
1191 # number of places. This gets rid of errors due to internal floating
1192 # point representation.
1193 $amount = $self->round_amount($amount, 8) if $places < 8;
1194 $amount = $amount * (10**($places));
1195 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1197 $main::lxdebug->leave_sub(2);
1199 return $round_amount;
1203 sub parse_template {
1204 $main::lxdebug->enter_sub();
1206 my ($self, $myconfig) = @_;
1211 my $userspath = $::lx_office_conf{paths}->{userspath};
1213 $self->{"cwd"} = getcwd();
1214 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1219 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1220 $template_type = 'OpenDocument';
1221 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
1223 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1224 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1225 $template_type = 'LaTeX';
1226 $ext_for_format = 'pdf';
1228 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1229 $template_type = 'HTML';
1230 $ext_for_format = 'html';
1232 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1233 $template_type = 'XML';
1234 $ext_for_format = 'xml';
1236 } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
1237 $template_type = 'XML';
1239 } elsif ( $self->{"format"} =~ /excel/i ) {
1240 $template_type = 'Excel';
1241 $ext_for_format = 'xls';
1243 } elsif ( defined $self->{'format'}) {
1244 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1246 } elsif ( $self->{'format'} eq '' ) {
1247 $self->error("No Outputformat given: $self->{'format'}");
1249 } else { #Catch the rest
1250 $self->error("Outputformat not defined: $self->{'format'}");
1253 my $template = SL::Template::create(type => $template_type,
1254 file_name => $self->{IN},
1256 myconfig => $myconfig,
1257 userspath => $userspath);
1259 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1260 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1262 if (!$self->{employee_id}) {
1263 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1266 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1267 map { $self->{"myconfig_${_}"} = $myconfig->{$_} } grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
1269 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1271 # OUT is used for the media, screen, printer, email
1272 # for postscript we store a copy in a temporary file
1274 my $prepend_userspath;
1276 if (!$self->{tmpfile}) {
1277 $self->{tmpfile} = "${fileid}.$self->{IN}";
1278 $prepend_userspath = 1;
1281 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1283 $self->{tmpfile} =~ s|.*/||;
1284 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1285 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1287 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1288 $out = $self->{OUT};
1289 $self->{OUT} = ">$self->{tmpfile}";
1295 open OUT, "$self->{OUT}" or $self->error("$self->{OUT} : $!");
1296 $result = $template->parse(*OUT);
1301 $result = $template->parse(*STDOUT);
1306 $self->error("$self->{IN} : " . $template->get_error());
1309 if ($self->{media} eq 'file') {
1310 copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
1312 chdir("$self->{cwd}");
1314 $::lxdebug->leave_sub();
1319 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1321 if ($self->{media} eq 'email') {
1323 my $mail = new Mailer;
1325 map { $mail->{$_} = $self->{$_} }
1326 qw(cc bcc subject message version format);
1327 $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
1328 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1329 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1330 $mail->{fileid} = "$fileid.";
1331 $myconfig->{signature} =~ s/\r//g;
1333 # if we send html or plain text inline
1334 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1335 $mail->{contenttype} = "text/html";
1337 $mail->{message} =~ s/\r//g;
1338 $mail->{message} =~ s/\n/<br>\n/g;
1339 $myconfig->{signature} =~ s/\n/<br>\n/g;
1340 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1342 open(IN, $self->{tmpfile})
1343 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1345 $mail->{message} .= $_;
1352 if (!$self->{"do_not_attach"}) {
1353 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1354 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1355 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1356 "name" => $attachment_name }];
1359 $mail->{message} =~ s/\r//g;
1360 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1364 my $err = $mail->send();
1365 $self->error($self->cleanup . "$err") if ($err);
1369 $self->{OUT} = $out;
1371 my $numbytes = (-s $self->{tmpfile});
1372 open(IN, $self->{tmpfile})
1373 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1376 $self->{copies} = 1 unless $self->{media} eq 'printer';
1378 chdir("$self->{cwd}");
1379 #print(STDERR "Kopien $self->{copies}\n");
1380 #print(STDERR "OUT $self->{OUT}\n");
1381 for my $i (1 .. $self->{copies}) {
1383 open OUT, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1384 print OUT while <IN>;
1389 $self->{attachment_filename} = ($self->{attachment_filename})
1390 ? $self->{attachment_filename}
1391 : $self->generate_attachment_filename();
1393 # launch application
1394 print qq|Content-Type: | . $template->get_mime_type() . qq|
1395 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1396 Content-Length: $numbytes
1400 $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1411 chdir("$self->{cwd}");
1412 $main::lxdebug->leave_sub();
1415 sub get_formname_translation {
1416 $main::lxdebug->enter_sub();
1417 my ($self, $formname) = @_;
1419 $formname ||= $self->{formname};
1421 my %formname_translations = (
1422 bin_list => $main::locale->text('Bin List'),
1423 credit_note => $main::locale->text('Credit Note'),
1424 invoice => $main::locale->text('Invoice'),
1425 pick_list => $main::locale->text('Pick List'),
1426 proforma => $main::locale->text('Proforma Invoice'),
1427 purchase_order => $main::locale->text('Purchase Order'),
1428 request_quotation => $main::locale->text('RFQ'),
1429 sales_order => $main::locale->text('Confirmation'),
1430 sales_quotation => $main::locale->text('Quotation'),
1431 storno_invoice => $main::locale->text('Storno Invoice'),
1432 sales_delivery_order => $main::locale->text('Delivery Order'),
1433 purchase_delivery_order => $main::locale->text('Delivery Order'),
1434 dunning => $main::locale->text('Dunning'),
1437 $main::lxdebug->leave_sub();
1438 return $formname_translations{$formname}
1441 sub get_number_prefix_for_type {
1442 $main::lxdebug->enter_sub();
1446 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1447 : ($self->{type} =~ /_quotation$/) ? 'quo'
1448 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1451 $main::lxdebug->leave_sub();
1455 sub get_extension_for_format {
1456 $main::lxdebug->enter_sub();
1459 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1460 : $self->{format} =~ /postscript/i ? ".ps"
1461 : $self->{format} =~ /opendocument/i ? ".odt"
1462 : $self->{format} =~ /excel/i ? ".xls"
1463 : $self->{format} =~ /html/i ? ".html"
1466 $main::lxdebug->leave_sub();
1470 sub generate_attachment_filename {
1471 $main::lxdebug->enter_sub();
1474 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1475 my $prefix = $self->get_number_prefix_for_type();
1477 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1478 $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1480 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1481 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1484 $attachment_filename = "";
1487 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1488 $attachment_filename =~ s|[\s/\\]+|_|g;
1490 $main::lxdebug->leave_sub();
1491 return $attachment_filename;
1494 sub generate_email_subject {
1495 $main::lxdebug->enter_sub();
1498 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1499 my $prefix = $self->get_number_prefix_for_type();
1501 if ($subject && $self->{"${prefix}number"}) {
1502 $subject .= " " . $self->{"${prefix}number"}
1505 $main::lxdebug->leave_sub();
1510 $main::lxdebug->enter_sub();
1514 chdir("$self->{tmpdir}");
1517 if (-f "$self->{tmpfile}.err") {
1518 open(FH, "$self->{tmpfile}.err");
1523 if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1524 $self->{tmpfile} =~ s|.*/||g;
1526 $self->{tmpfile} =~ s/\.\w+$//g;
1527 my $tmpfile = $self->{tmpfile};
1528 unlink(<$tmpfile.*>);
1531 chdir("$self->{cwd}");
1533 $main::lxdebug->leave_sub();
1539 $main::lxdebug->enter_sub();
1541 my ($self, $date, $myconfig) = @_;
1544 if ($date && $date =~ /\D/) {
1546 if ($myconfig->{dateformat} =~ /^yy/) {
1547 ($yy, $mm, $dd) = split /\D/, $date;
1549 if ($myconfig->{dateformat} =~ /^mm/) {
1550 ($mm, $dd, $yy) = split /\D/, $date;
1552 if ($myconfig->{dateformat} =~ /^dd/) {
1553 ($dd, $mm, $yy) = split /\D/, $date;
1558 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1559 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1561 $dd = "0$dd" if ($dd < 10);
1562 $mm = "0$mm" if ($mm < 10);
1564 $date = "$yy$mm$dd";
1567 $main::lxdebug->leave_sub();
1572 # Database routines used throughout
1574 sub _dbconnect_options {
1576 my $options = { pg_enable_utf8 => $::locale->is_utf8,
1583 $main::lxdebug->enter_sub(2);
1585 my ($self, $myconfig) = @_;
1587 # connect to database
1588 my $dbh = SL::DBConnect->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options)
1592 if ($myconfig->{dboptions}) {
1593 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1596 $main::lxdebug->leave_sub(2);
1601 sub dbconnect_noauto {
1602 $main::lxdebug->enter_sub();
1604 my ($self, $myconfig) = @_;
1606 # connect to database
1607 my $dbh = SL::DBConnect->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options(AutoCommit => 0))
1611 if ($myconfig->{dboptions}) {
1612 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1615 $main::lxdebug->leave_sub();
1620 sub get_standard_dbh {
1621 $main::lxdebug->enter_sub(2);
1624 my $myconfig = shift || \%::myconfig;
1626 if ($standard_dbh && !$standard_dbh->{Active}) {
1627 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1628 undef $standard_dbh;
1631 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1633 $main::lxdebug->leave_sub(2);
1635 return $standard_dbh;
1639 $main::lxdebug->enter_sub();
1641 my ($self, $date, $myconfig) = @_;
1642 my $dbh = $self->dbconnect($myconfig);
1644 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1645 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1647 # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1648 # es ist sicher ein conv_date vorher IMMER auszuführen.
1649 # Testfälle ohne definiertes closedto:
1650 # Leere Datumseingabe i.O.
1651 # SELECT 1 FROM defaults WHERE '' < closedto
1652 # normale Zahlungsbuchung über Rechnungsmaske i.O.
1653 # SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1654 # Testfälle mit definiertem closedto (30.04.2011):
1655 # Leere Datumseingabe i.O.
1656 # SELECT 1 FROM defaults WHERE '' < closedto
1657 # normale Buchung im geschloßenem Zeitraum i.O.
1658 # SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1659 # Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1660 # normale Buchung in aktiver Buchungsperiode i.O.
1661 # SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1663 my ($closed) = $sth->fetchrow_array;
1665 $main::lxdebug->leave_sub();
1670 sub update_balance {
1671 $main::lxdebug->enter_sub();
1673 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1675 # if we have a value, go do it
1678 # retrieve balance from table
1679 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1680 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1681 my ($balance) = $sth->fetchrow_array;
1687 $query = "UPDATE $table SET $field = $balance WHERE $where";
1688 do_query($self, $dbh, $query, @values);
1690 $main::lxdebug->leave_sub();
1693 sub update_exchangerate {
1694 $main::lxdebug->enter_sub();
1696 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1698 # some sanity check for currency
1700 $main::lxdebug->leave_sub();
1703 $query = qq|SELECT curr FROM defaults|;
1705 my ($currency) = selectrow_query($self, $dbh, $query);
1706 my ($defaultcurrency) = split m/:/, $currency;
1709 if ($curr eq $defaultcurrency) {
1710 $main::lxdebug->leave_sub();
1714 $query = qq|SELECT e.curr FROM exchangerate e
1715 WHERE e.curr = ? AND e.transdate = ?
1717 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1726 $buy = conv_i($buy, "NULL");
1727 $sell = conv_i($sell, "NULL");
1730 if ($buy != 0 && $sell != 0) {
1731 $set = "buy = $buy, sell = $sell";
1732 } elsif ($buy != 0) {
1733 $set = "buy = $buy";
1734 } elsif ($sell != 0) {
1735 $set = "sell = $sell";
1738 if ($sth->fetchrow_array) {
1739 $query = qq|UPDATE exchangerate
1745 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1746 VALUES (?, $buy, $sell, ?)|;
1749 do_query($self, $dbh, $query, $curr, $transdate);
1751 $main::lxdebug->leave_sub();
1754 sub save_exchangerate {
1755 $main::lxdebug->enter_sub();
1757 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1759 my $dbh = $self->dbconnect($myconfig);
1763 $buy = $rate if $fld eq 'buy';
1764 $sell = $rate if $fld eq 'sell';
1767 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1772 $main::lxdebug->leave_sub();
1775 sub get_exchangerate {
1776 $main::lxdebug->enter_sub();
1778 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1781 unless ($transdate) {
1782 $main::lxdebug->leave_sub();
1786 $query = qq|SELECT curr FROM defaults|;
1788 my ($currency) = selectrow_query($self, $dbh, $query);
1789 my ($defaultcurrency) = split m/:/, $currency;
1791 if ($currency eq $defaultcurrency) {
1792 $main::lxdebug->leave_sub();
1796 $query = qq|SELECT e.$fld FROM exchangerate e
1797 WHERE e.curr = ? AND e.transdate = ?|;
1798 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1802 $main::lxdebug->leave_sub();
1804 return $exchangerate;
1807 sub check_exchangerate {
1808 $main::lxdebug->enter_sub();
1810 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1812 if ($fld !~/^buy|sell$/) {
1813 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1816 unless ($transdate) {
1817 $main::lxdebug->leave_sub();
1821 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1823 if ($currency eq $defaultcurrency) {
1824 $main::lxdebug->leave_sub();
1828 my $dbh = $self->get_standard_dbh($myconfig);
1829 my $query = qq|SELECT e.$fld FROM exchangerate e
1830 WHERE e.curr = ? AND e.transdate = ?|;
1832 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1834 $main::lxdebug->leave_sub();
1836 return $exchangerate;
1839 sub get_all_currencies {
1840 $main::lxdebug->enter_sub();
1843 my $myconfig = shift || \%::myconfig;
1844 my $dbh = $self->get_standard_dbh($myconfig);
1846 my $query = qq|SELECT curr FROM defaults|;
1848 my ($curr) = selectrow_query($self, $dbh, $query);
1849 my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
1851 $main::lxdebug->leave_sub();
1856 sub get_default_currency {
1857 $main::lxdebug->enter_sub();
1859 my ($self, $myconfig) = @_;
1860 my @currencies = $self->get_all_currencies($myconfig);
1862 $main::lxdebug->leave_sub();
1864 return $currencies[0];
1867 sub set_payment_options {
1868 $main::lxdebug->enter_sub();
1870 my ($self, $myconfig, $transdate) = @_;
1872 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1874 my $dbh = $self->get_standard_dbh($myconfig);
1877 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long , p.description | .
1878 qq|FROM payment_terms p | .
1881 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1882 $self->{payment_terms}, $self->{payment_description}) =
1883 selectrow_query($self, $dbh, $query, $self->{payment_id});
1885 if ($transdate eq "") {
1886 if ($self->{invdate}) {
1887 $transdate = $self->{invdate};
1889 $transdate = $self->{transdate};
1894 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1895 qq|FROM payment_terms|;
1896 ($self->{netto_date}, $self->{skonto_date}) =
1897 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1899 my ($invtotal, $total);
1900 my (%amounts, %formatted_amounts);
1902 if ($self->{type} =~ /_order$/) {
1903 $amounts{invtotal} = $self->{ordtotal};
1904 $amounts{total} = $self->{ordtotal};
1906 } elsif ($self->{type} =~ /_quotation$/) {
1907 $amounts{invtotal} = $self->{quototal};
1908 $amounts{total} = $self->{quototal};
1911 $amounts{invtotal} = $self->{invtotal};
1912 $amounts{total} = $self->{total};
1914 $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1916 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1918 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1919 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1920 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1922 foreach (keys %amounts) {
1923 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1924 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1927 if ($self->{"language_id"}) {
1929 qq|SELECT t.translation, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1930 qq|FROM generic_translations t | .
1931 qq|LEFT JOIN language l ON t.language_id = l.id | .
1932 qq|WHERE (t.language_id = ?)
1933 AND (t.translation_id = ?)
1934 AND (t.translation_type = 'SL::DB::PaymentTerm/description_long')|;
1935 my ($description_long, $output_numberformat, $output_dateformat,
1936 $output_longdates) =
1937 selectrow_query($self, $dbh, $query,
1938 $self->{"language_id"}, $self->{"payment_id"});
1940 $self->{payment_terms} = $description_long if ($description_long);
1942 if ($output_dateformat) {
1943 foreach my $key (qw(netto_date skonto_date)) {
1945 $main::locale->reformat_date($myconfig, $self->{$key},
1951 if ($output_numberformat &&
1952 ($output_numberformat ne $myconfig->{"numberformat"})) {
1953 my $saved_numberformat = $myconfig->{"numberformat"};
1954 $myconfig->{"numberformat"} = $output_numberformat;
1955 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1956 $myconfig->{"numberformat"} = $saved_numberformat;
1960 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1961 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1962 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1963 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1964 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1965 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1966 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1968 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1970 $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1972 $main::lxdebug->leave_sub();
1976 sub get_template_language {
1977 $main::lxdebug->enter_sub();
1979 my ($self, $myconfig) = @_;
1981 my $template_code = "";
1983 if ($self->{language_id}) {
1984 my $dbh = $self->get_standard_dbh($myconfig);
1985 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1986 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1989 $main::lxdebug->leave_sub();
1991 return $template_code;
1994 sub get_printer_code {
1995 $main::lxdebug->enter_sub();
1997 my ($self, $myconfig) = @_;
1999 my $template_code = "";
2001 if ($self->{printer_id}) {
2002 my $dbh = $self->get_standard_dbh($myconfig);
2003 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
2004 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
2007 $main::lxdebug->leave_sub();
2009 return $template_code;
2013 $main::lxdebug->enter_sub();
2015 my ($self, $myconfig) = @_;
2017 my $template_code = "";
2019 if ($self->{shipto_id}) {
2020 my $dbh = $self->get_standard_dbh($myconfig);
2021 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
2022 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
2023 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
2026 $main::lxdebug->leave_sub();
2030 $main::lxdebug->enter_sub();
2032 my ($self, $dbh, $id, $module) = @_;
2037 foreach my $item (qw(name department_1 department_2 street zipcode city country
2038 contact cp_gender phone fax email)) {
2039 if ($self->{"shipto$item"}) {
2040 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
2042 push(@values, $self->{"shipto${item}"});
2046 if ($self->{shipto_id}) {
2047 my $query = qq|UPDATE shipto set
2049 shiptodepartment_1 = ?,
2050 shiptodepartment_2 = ?,
2056 shiptocp_gender = ?,
2060 WHERE shipto_id = ?|;
2061 do_query($self, $dbh, $query, @values, $self->{shipto_id});
2063 my $query = qq|SELECT * FROM shipto
2064 WHERE shiptoname = ? AND
2065 shiptodepartment_1 = ? AND
2066 shiptodepartment_2 = ? AND
2067 shiptostreet = ? AND
2068 shiptozipcode = ? AND
2070 shiptocountry = ? AND
2071 shiptocontact = ? AND
2072 shiptocp_gender = ? AND
2078 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
2081 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
2082 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
2083 shiptocontact, shiptocp_gender, shiptophone, shiptofax, shiptoemail, module)
2084 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
2085 do_query($self, $dbh, $query, $id, @values, $module);
2090 $main::lxdebug->leave_sub();
2094 $main::lxdebug->enter_sub();
2096 my ($self, $dbh) = @_;
2098 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
2100 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2101 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2102 $self->{"employee_id"} *= 1;
2104 $main::lxdebug->leave_sub();
2107 sub get_employee_data {
2108 $main::lxdebug->enter_sub();
2113 Common::check_params(\%params, qw(prefix));
2114 Common::check_params_x(\%params, qw(id));
2117 $main::lxdebug->leave_sub();
2121 my $myconfig = \%main::myconfig;
2122 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
2124 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2127 my $user = User->new($login);
2128 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2130 $self->{$params{prefix} . '_login'} = $login;
2131 $self->{$params{prefix} . '_name'} ||= $login;
2134 $main::lxdebug->leave_sub();
2138 $main::lxdebug->enter_sub();
2140 my ($self, $myconfig, $reference_date) = @_;
2142 $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2144 my $dbh = $self->get_standard_dbh($myconfig);
2145 my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2146 my ($duedate) = selectrow_query($self, $dbh, $query, $self->{payment_id});
2148 $main::lxdebug->leave_sub();
2154 $main::lxdebug->enter_sub();
2156 my ($self, $dbh, $id, $key) = @_;
2158 $key = "all_contacts" unless ($key);
2162 $main::lxdebug->leave_sub();
2167 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2168 qq|FROM contacts | .
2169 qq|WHERE cp_cv_id = ? | .
2170 qq|ORDER BY lower(cp_name)|;
2172 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2174 $main::lxdebug->leave_sub();
2178 $main::lxdebug->enter_sub();
2180 my ($self, $dbh, $key) = @_;
2182 my ($all, $old_id, $where, @values);
2184 if (ref($key) eq "HASH") {
2187 $key = "ALL_PROJECTS";
2189 foreach my $p (keys(%{$params})) {
2191 $all = $params->{$p};
2192 } elsif ($p eq "old_id") {
2193 $old_id = $params->{$p};
2194 } elsif ($p eq "key") {
2195 $key = $params->{$p};
2201 $where = "WHERE active ";
2203 if (ref($old_id) eq "ARRAY") {
2204 my @ids = grep({ $_ } @{$old_id});
2206 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2207 push(@values, @ids);
2210 $where .= " OR (id = ?) ";
2211 push(@values, $old_id);
2217 qq|SELECT id, projectnumber, description, active | .
2220 qq|ORDER BY lower(projectnumber)|;
2222 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2224 $main::lxdebug->leave_sub();
2228 $main::lxdebug->enter_sub();
2230 my ($self, $dbh, $vc_id, $key) = @_;
2232 $key = "all_shipto" unless ($key);
2235 # get shipping addresses
2236 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2238 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2244 $main::lxdebug->leave_sub();
2248 $main::lxdebug->enter_sub();
2250 my ($self, $dbh, $key) = @_;
2252 $key = "all_printers" unless ($key);
2254 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2256 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2258 $main::lxdebug->leave_sub();
2262 $main::lxdebug->enter_sub();
2264 my ($self, $dbh, $params) = @_;
2267 $key = $params->{key};
2268 $key = "all_charts" unless ($key);
2270 my $transdate = quote_db_date($params->{transdate});
2273 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2275 qq|LEFT JOIN taxkeys tk ON | .
2276 qq|(tk.id = (SELECT id FROM taxkeys | .
2277 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2278 qq| ORDER BY startdate DESC LIMIT 1)) | .
2279 qq|ORDER BY c.accno|;
2281 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2283 $main::lxdebug->leave_sub();
2286 sub _get_taxcharts {
2287 $main::lxdebug->enter_sub();
2289 my ($self, $dbh, $params) = @_;
2291 my $key = "all_taxcharts";
2294 if (ref $params eq 'HASH') {
2295 $key = $params->{key} if ($params->{key});
2296 if ($params->{module} eq 'AR') {
2297 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2299 } elsif ($params->{module} eq 'AP') {
2300 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2307 my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2309 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2311 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2313 $main::lxdebug->leave_sub();
2317 $main::lxdebug->enter_sub();
2319 my ($self, $dbh, $key) = @_;
2321 $key = "all_taxzones" unless ($key);
2323 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2325 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2327 $main::lxdebug->leave_sub();
2330 sub _get_employees {
2331 $main::lxdebug->enter_sub();
2333 my ($self, $dbh, $default_key, $key) = @_;
2335 $key = $default_key unless ($key);
2336 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2338 $main::lxdebug->leave_sub();
2341 sub _get_business_types {
2342 $main::lxdebug->enter_sub();
2344 my ($self, $dbh, $key) = @_;
2346 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2347 $options->{key} ||= "all_business_types";
2350 if (exists $options->{salesman}) {
2351 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2354 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2356 $main::lxdebug->leave_sub();
2359 sub _get_languages {
2360 $main::lxdebug->enter_sub();
2362 my ($self, $dbh, $key) = @_;
2364 $key = "all_languages" unless ($key);
2366 my $query = qq|SELECT * FROM language ORDER BY id|;
2368 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2370 $main::lxdebug->leave_sub();
2373 sub _get_dunning_configs {
2374 $main::lxdebug->enter_sub();
2376 my ($self, $dbh, $key) = @_;
2378 $key = "all_dunning_configs" unless ($key);
2380 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2382 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2384 $main::lxdebug->leave_sub();
2387 sub _get_currencies {
2388 $main::lxdebug->enter_sub();
2390 my ($self, $dbh, $key) = @_;
2392 $key = "all_currencies" unless ($key);
2394 my $query = qq|SELECT curr AS currency FROM defaults|;
2396 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2398 $main::lxdebug->leave_sub();
2402 $main::lxdebug->enter_sub();
2404 my ($self, $dbh, $key) = @_;
2406 $key = "all_payments" unless ($key);
2408 my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2410 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2412 $main::lxdebug->leave_sub();
2415 sub _get_customers {
2416 $main::lxdebug->enter_sub();
2418 my ($self, $dbh, $key) = @_;
2420 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2421 $options->{key} ||= "all_customers";
2422 my $limit_clause = "LIMIT $options->{limit}" if $options->{limit};
2425 push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman};
2426 push @where, qq|NOT obsolete| if !$options->{with_obsolete};
2427 my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2429 my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2430 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2432 $main::lxdebug->leave_sub();
2436 $main::lxdebug->enter_sub();
2438 my ($self, $dbh, $key) = @_;
2440 $key = "all_vendors" unless ($key);
2442 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2444 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2446 $main::lxdebug->leave_sub();
2449 sub _get_departments {
2450 $main::lxdebug->enter_sub();
2452 my ($self, $dbh, $key) = @_;
2454 $key = "all_departments" unless ($key);
2456 my $query = qq|SELECT * FROM department ORDER BY description|;
2458 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2460 $main::lxdebug->leave_sub();
2463 sub _get_warehouses {
2464 $main::lxdebug->enter_sub();
2466 my ($self, $dbh, $param) = @_;
2468 my ($key, $bins_key);
2470 if ('' eq ref $param) {
2474 $key = $param->{key};
2475 $bins_key = $param->{bins};
2478 my $query = qq|SELECT w.* FROM warehouse w
2479 WHERE (NOT w.invalid) AND
2480 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2481 ORDER BY w.sortkey|;
2483 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2486 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2487 ORDER BY description|;
2488 my $sth = prepare_query($self, $dbh, $query);
2490 foreach my $warehouse (@{ $self->{$key} }) {
2491 do_statement($self, $sth, $query, $warehouse->{id});
2492 $warehouse->{$bins_key} = [];
2494 while (my $ref = $sth->fetchrow_hashref()) {
2495 push @{ $warehouse->{$bins_key} }, $ref;
2501 $main::lxdebug->leave_sub();
2505 $main::lxdebug->enter_sub();
2507 my ($self, $dbh, $table, $key, $sortkey) = @_;
2509 my $query = qq|SELECT * FROM $table|;
2510 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2512 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2514 $main::lxdebug->leave_sub();
2518 # $main::lxdebug->enter_sub();
2520 # my ($self, $dbh, $key) = @_;
2522 # $key ||= "all_groups";
2524 # my $groups = $main::auth->read_groups();
2526 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2528 # $main::lxdebug->leave_sub();
2532 $main::lxdebug->enter_sub();
2537 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2538 my ($sth, $query, $ref);
2540 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2541 my $vc_id = $self->{"${vc}_id"};
2543 if ($params{"contacts"}) {
2544 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2547 if ($params{"shipto"}) {
2548 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2551 if ($params{"projects"} || $params{"all_projects"}) {
2552 $self->_get_projects($dbh, $params{"all_projects"} ?
2553 $params{"all_projects"} : $params{"projects"},
2554 $params{"all_projects"} ? 1 : 0);
2557 if ($params{"printers"}) {
2558 $self->_get_printers($dbh, $params{"printers"});
2561 if ($params{"languages"}) {
2562 $self->_get_languages($dbh, $params{"languages"});
2565 if ($params{"charts"}) {
2566 $self->_get_charts($dbh, $params{"charts"});
2569 if ($params{"taxcharts"}) {
2570 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2573 if ($params{"taxzones"}) {
2574 $self->_get_taxzones($dbh, $params{"taxzones"});
2577 if ($params{"employees"}) {
2578 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2581 if ($params{"salesmen"}) {
2582 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2585 if ($params{"business_types"}) {
2586 $self->_get_business_types($dbh, $params{"business_types"});
2589 if ($params{"dunning_configs"}) {
2590 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2593 if($params{"currencies"}) {
2594 $self->_get_currencies($dbh, $params{"currencies"});
2597 if($params{"customers"}) {
2598 $self->_get_customers($dbh, $params{"customers"});
2601 if($params{"vendors"}) {
2602 if (ref $params{"vendors"} eq 'HASH') {
2603 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2605 $self->_get_vendors($dbh, $params{"vendors"});
2609 if($params{"payments"}) {
2610 $self->_get_payments($dbh, $params{"payments"});
2613 if($params{"departments"}) {
2614 $self->_get_departments($dbh, $params{"departments"});
2617 if ($params{price_factors}) {
2618 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2621 if ($params{warehouses}) {
2622 $self->_get_warehouses($dbh, $params{warehouses});
2625 # if ($params{groups}) {
2626 # $self->_get_groups($dbh, $params{groups});
2629 if ($params{partsgroup}) {
2630 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2633 $main::lxdebug->leave_sub();
2636 # this sub gets the id and name from $table
2638 $main::lxdebug->enter_sub();
2640 my ($self, $myconfig, $table) = @_;
2642 # connect to database
2643 my $dbh = $self->get_standard_dbh($myconfig);
2645 $table = $table eq "customer" ? "customer" : "vendor";
2646 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2648 my ($query, @values);
2650 if (!$self->{openinvoices}) {
2652 if ($self->{customernumber} ne "") {
2653 $where = qq|(vc.customernumber ILIKE ?)|;
2654 push(@values, '%' . $self->{customernumber} . '%');
2656 $where = qq|(vc.name ILIKE ?)|;
2657 push(@values, '%' . $self->{$table} . '%');
2661 qq~SELECT vc.id, vc.name,
2662 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2664 WHERE $where AND (NOT vc.obsolete)
2668 qq~SELECT DISTINCT vc.id, vc.name,
2669 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2671 JOIN $table vc ON (a.${table}_id = vc.id)
2672 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2674 push(@values, '%' . $self->{$table} . '%');
2677 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2679 $main::lxdebug->leave_sub();
2681 return scalar(@{ $self->{name_list} });
2684 # the selection sub is used in the AR, AP, IS, IR and OE module
2687 $main::lxdebug->enter_sub();
2689 my ($self, $myconfig, $table, $module) = @_;
2692 my $dbh = $self->get_standard_dbh;
2694 $table = $table eq "customer" ? "customer" : "vendor";
2696 my $query = qq|SELECT count(*) FROM $table|;
2697 my ($count) = selectrow_query($self, $dbh, $query);
2699 # build selection list
2700 if ($count <= $myconfig->{vclimit}) {
2701 $query = qq|SELECT id, name, salesman_id
2702 FROM $table WHERE NOT obsolete
2704 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2708 $self->get_employee($dbh);
2710 # setup sales contacts
2711 $query = qq|SELECT e.id, e.name
2713 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2714 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2717 push(@{ $self->{all_employees} },
2718 { id => $self->{employee_id},
2719 name => $self->{employee} });
2721 # sort the whole thing
2722 @{ $self->{all_employees} } =
2723 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2725 if ($module eq 'AR') {
2727 # prepare query for departments
2728 $query = qq|SELECT id, description
2731 ORDER BY description|;
2734 $query = qq|SELECT id, description
2736 ORDER BY description|;
2739 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2742 $query = qq|SELECT id, description
2746 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2749 $query = qq|SELECT printer_description, id
2751 ORDER BY printer_description|;
2753 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2756 $query = qq|SELECT id, description
2760 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2762 $main::lxdebug->leave_sub();
2765 sub language_payment {
2766 $main::lxdebug->enter_sub();
2768 my ($self, $myconfig) = @_;
2770 my $dbh = $self->get_standard_dbh($myconfig);
2772 my $query = qq|SELECT id, description
2776 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2779 $query = qq|SELECT printer_description, id
2781 ORDER BY printer_description|;
2783 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2786 $query = qq|SELECT id, description
2790 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2792 # get buchungsgruppen
2793 $query = qq|SELECT id, description
2794 FROM buchungsgruppen|;
2796 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2798 $main::lxdebug->leave_sub();
2801 # this is only used for reports
2802 sub all_departments {
2803 $main::lxdebug->enter_sub();
2805 my ($self, $myconfig, $table) = @_;
2807 my $dbh = $self->get_standard_dbh($myconfig);
2810 if ($table eq 'customer') {
2811 $where = "WHERE role = 'P' ";
2814 my $query = qq|SELECT id, description
2817 ORDER BY description|;
2818 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2820 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2822 $main::lxdebug->leave_sub();
2826 $main::lxdebug->enter_sub();
2828 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2831 if ($table eq "customer") {
2840 $self->all_vc($myconfig, $table, $module);
2842 # get last customers or vendors
2843 my ($query, $sth, $ref);
2845 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2850 my $transdate = "current_date";
2851 if ($self->{transdate}) {
2852 $transdate = $dbh->quote($self->{transdate});
2855 # now get the account numbers
2856 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2857 FROM chart c, taxkeys tk
2858 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2859 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2862 $sth = $dbh->prepare($query);
2864 do_statement($self, $sth, $query, '%' . $module . '%');
2866 $self->{accounts} = "";
2867 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2869 foreach my $key (split(/:/, $ref->{link})) {
2870 if ($key =~ /\Q$module\E/) {
2872 # cross reference for keys
2873 $xkeyref{ $ref->{accno} } = $key;
2875 push @{ $self->{"${module}_links"}{$key} },
2876 { accno => $ref->{accno},
2877 description => $ref->{description},
2878 taxkey => $ref->{taxkey_id},
2879 tax_id => $ref->{tax_id} };
2881 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2887 # get taxkeys and description
2888 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2889 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2891 if (($module eq "AP") || ($module eq "AR")) {
2892 # get tax rates and description
2893 $query = qq|SELECT * FROM tax|;
2894 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2900 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2901 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2902 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2903 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2905 d.description AS department,
2908 JOIN $table c ON (a.${table}_id = c.id)
2909 LEFT JOIN employee e ON (e.id = a.employee_id)
2910 LEFT JOIN department d ON (d.id = a.department_id)
2912 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2914 foreach my $key (keys %$ref) {
2915 $self->{$key} = $ref->{$key};
2918 my $transdate = "current_date";
2919 if ($self->{transdate}) {
2920 $transdate = $dbh->quote($self->{transdate});
2923 # now get the account numbers
2924 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2926 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2928 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2929 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2932 $sth = $dbh->prepare($query);
2933 do_statement($self, $sth, $query, "%$module%");
2935 $self->{accounts} = "";
2936 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2938 foreach my $key (split(/:/, $ref->{link})) {
2939 if ($key =~ /\Q$module\E/) {
2941 # cross reference for keys
2942 $xkeyref{ $ref->{accno} } = $key;
2944 push @{ $self->{"${module}_links"}{$key} },
2945 { accno => $ref->{accno},
2946 description => $ref->{description},
2947 taxkey => $ref->{taxkey_id},
2948 tax_id => $ref->{tax_id} };
2950 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2956 # get amounts from individual entries
2959 c.accno, c.description,
2960 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2964 LEFT JOIN chart c ON (c.id = a.chart_id)
2965 LEFT JOIN project p ON (p.id = a.project_id)
2966 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2967 WHERE (tk.taxkey_id=a.taxkey) AND
2968 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2969 THEN tk.chart_id = a.chart_id
2972 OR (c.link='%tax%')) AND
2973 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2974 WHERE a.trans_id = ?
2975 AND a.fx_transaction = '0'
2976 ORDER BY a.acc_trans_id, a.transdate|;
2977 $sth = $dbh->prepare($query);
2978 do_statement($self, $sth, $query, $self->{id});
2980 # get exchangerate for currency
2981 $self->{exchangerate} =
2982 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2985 # store amounts in {acc_trans}{$key} for multiple accounts
2986 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2987 $ref->{exchangerate} =
2988 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2989 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2992 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2993 $ref->{amount} *= -1;
2995 $ref->{index} = $index;
2997 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
3003 d.curr AS currencies, d.closedto, d.revtrans,
3004 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
3005 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
3007 $ref = selectfirst_hashref_query($self, $dbh, $query);
3008 map { $self->{$_} = $ref->{$_} } keys %$ref;
3015 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
3016 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
3017 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
3019 $ref = selectfirst_hashref_query($self, $dbh, $query);
3020 map { $self->{$_} = $ref->{$_} } keys %$ref;
3022 if ($self->{"$self->{vc}_id"}) {
3024 # only setup currency
3025 ($self->{currency}) = split(/:/, $self->{currencies});
3029 $self->lastname_used($dbh, $myconfig, $table, $module);
3031 # get exchangerate for currency
3032 $self->{exchangerate} =
3033 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
3039 $main::lxdebug->leave_sub();
3043 $main::lxdebug->enter_sub();
3045 my ($self, $dbh, $myconfig, $table, $module) = @_;
3049 $table = $table eq "customer" ? "customer" : "vendor";
3050 my %column_map = ("a.curr" => "currency",
3051 "a.${table}_id" => "${table}_id",
3052 "a.department_id" => "department_id",
3053 "d.description" => "department",
3054 "ct.name" => $table,
3055 "current_date + ct.terms" => "duedate",
3058 if ($self->{type} =~ /delivery_order/) {
3059 $arap = 'delivery_orders';
3060 delete $column_map{"a.curr"};
3062 } elsif ($self->{type} =~ /_order/) {
3064 $where = "quotation = '0'";
3066 } elsif ($self->{type} =~ /_quotation/) {
3068 $where = "quotation = '1'";
3070 } elsif ($table eq 'customer') {
3078 $where = "($where) AND" if ($where);
3079 my $query = qq|SELECT MAX(id) FROM $arap
3080 WHERE $where ${table}_id > 0|;
3081 my ($trans_id) = selectrow_query($self, $dbh, $query);
3084 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
3085 $query = qq|SELECT $column_spec
3087 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
3088 LEFT JOIN department d ON (a.department_id = d.id)
3090 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3092 map { $self->{$_} = $ref->{$_} } values %column_map;
3094 $main::lxdebug->leave_sub();
3098 $main::lxdebug->enter_sub();
3101 my $myconfig = shift || \%::myconfig;
3102 my ($thisdate, $days) = @_;
3104 my $dbh = $self->get_standard_dbh($myconfig);
3109 my $dateformat = $myconfig->{dateformat};
3110 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3111 $thisdate = $dbh->quote($thisdate);
3112 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3114 $query = qq|SELECT current_date AS thisdate|;
3117 ($thisdate) = selectrow_query($self, $dbh, $query);
3119 $main::lxdebug->leave_sub();
3125 $main::lxdebug->enter_sub();
3127 my ($self, $string) = @_;
3129 if ($string !~ /%/) {
3130 $string = "%$string%";
3133 $string =~ s/\'/\'\'/g;
3135 $main::lxdebug->leave_sub();
3141 $main::lxdebug->enter_sub();
3143 my ($self, $flds, $new, $count, $numrows) = @_;
3147 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3152 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3154 my $j = $item->{ndx} - 1;
3155 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3159 for $i ($count + 1 .. $numrows) {
3160 map { delete $self->{"${_}_$i"} } @{$flds};
3163 $main::lxdebug->leave_sub();
3167 $main::lxdebug->enter_sub();
3169 my ($self, $myconfig) = @_;
3173 my $dbh = $self->dbconnect_noauto($myconfig);
3175 my $query = qq|DELETE FROM status
3176 WHERE (formname = ?) AND (trans_id = ?)|;
3177 my $sth = prepare_query($self, $dbh, $query);
3179 if ($self->{formname} =~ /(check|receipt)/) {
3180 for $i (1 .. $self->{rowcount}) {
3181 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3184 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3188 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3189 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3191 my %queued = split / /, $self->{queued};
3194 if ($self->{formname} =~ /(check|receipt)/) {
3196 # this is a check or receipt, add one entry for each lineitem
3197 my ($accno) = split /--/, $self->{account};
3198 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3199 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3200 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3201 $sth = prepare_query($self, $dbh, $query);
3203 for $i (1 .. $self->{rowcount}) {
3204 if ($self->{"checked_$i"}) {
3205 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3211 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3212 VALUES (?, ?, ?, ?, ?)|;
3213 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3214 $queued{$self->{formname}}, $self->{formname});
3220 $main::lxdebug->leave_sub();
3224 $main::lxdebug->enter_sub();
3226 my ($self, $dbh) = @_;
3228 my ($query, $printed, $emailed);
3230 my $formnames = $self->{printed};
3231 my $emailforms = $self->{emailed};
3233 $query = qq|DELETE FROM status
3234 WHERE (formname = ?) AND (trans_id = ?)|;
3235 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3237 # this only applies to the forms
3238 # checks and receipts are posted when printed or queued
3240 if ($self->{queued}) {
3241 my %queued = split / /, $self->{queued};
3243 foreach my $formname (keys %queued) {
3244 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3245 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3247 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3248 VALUES (?, ?, ?, ?, ?)|;
3249 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3251 $formnames =~ s/\Q$self->{formname}\E//;
3252 $emailforms =~ s/\Q$self->{formname}\E//;
3257 # save printed, emailed info
3258 $formnames =~ s/^ +//g;
3259 $emailforms =~ s/^ +//g;
3262 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3263 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3265 foreach my $formname (keys %status) {
3266 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3267 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3269 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3270 VALUES (?, ?, ?, ?)|;
3271 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3274 $main::lxdebug->leave_sub();
3278 # $main::locale->text('SAVED')
3279 # $main::locale->text('DELETED')
3280 # $main::locale->text('ADDED')
3281 # $main::locale->text('PAYMENT POSTED')
3282 # $main::locale->text('POSTED')
3283 # $main::locale->text('POSTED AS NEW')
3284 # $main::locale->text('ELSE')
3285 # $main::locale->text('SAVED FOR DUNNING')
3286 # $main::locale->text('DUNNING STARTED')
3287 # $main::locale->text('PRINTED')
3288 # $main::locale->text('MAILED')
3289 # $main::locale->text('SCREENED')
3290 # $main::locale->text('CANCELED')
3291 # $main::locale->text('invoice')
3292 # $main::locale->text('proforma')
3293 # $main::locale->text('sales_order')
3294 # $main::locale->text('pick_list')
3295 # $main::locale->text('purchase_order')
3296 # $main::locale->text('bin_list')
3297 # $main::locale->text('sales_quotation')
3298 # $main::locale->text('request_quotation')
3301 $main::lxdebug->enter_sub();
3304 my $dbh = shift || $self->get_standard_dbh;
3306 if(!exists $self->{employee_id}) {
3307 &get_employee($self, $dbh);
3311 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3312 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3313 my @values = (conv_i($self->{id}), $self->{login},
3314 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3315 do_query($self, $dbh, $query, @values);
3319 $main::lxdebug->leave_sub();
3323 $main::lxdebug->enter_sub();
3325 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3326 my ($orderBy, $desc) = split(/\-\-/, $order);
3327 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3330 if ($trans_id ne "") {
3332 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 | .
3333 qq|FROM history_erp h | .
3334 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3335 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3338 my $sth = $dbh->prepare($query) || $self->dberror($query);
3340 $sth->execute() || $self->dberror("$query");
3342 while(my $hash_ref = $sth->fetchrow_hashref()) {
3343 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3344 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3345 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3346 $tempArray[$i++] = $hash_ref;
3348 $main::lxdebug->leave_sub() and return \@tempArray
3349 if ($i > 0 && $tempArray[0] ne "");
3351 $main::lxdebug->leave_sub();
3355 sub update_defaults {
3356 $main::lxdebug->enter_sub();
3358 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3361 if ($provided_dbh) {
3362 $dbh = $provided_dbh;
3364 $dbh = $self->dbconnect_noauto($myconfig);
3366 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3367 my $sth = $dbh->prepare($query);
3369 $sth->execute || $self->dberror($query);
3370 my ($var) = $sth->fetchrow_array;
3373 if ($var =~ m/\d+$/) {
3374 my $new_var = (substr $var, $-[0]) * 1 + 1;
3375 my $len_diff = length($var) - $-[0] - length($new_var);
3376 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3382 $query = qq|UPDATE defaults SET $fld = ?|;
3383 do_query($self, $dbh, $query, $var);
3385 if (!$provided_dbh) {
3390 $main::lxdebug->leave_sub();
3395 sub update_business {
3396 $main::lxdebug->enter_sub();
3398 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3401 if ($provided_dbh) {
3402 $dbh = $provided_dbh;
3404 $dbh = $self->dbconnect_noauto($myconfig);
3407 qq|SELECT customernumberinit FROM business
3408 WHERE id = ? FOR UPDATE|;
3409 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3411 return undef unless $var;
3413 if ($var =~ m/\d+$/) {
3414 my $new_var = (substr $var, $-[0]) * 1 + 1;
3415 my $len_diff = length($var) - $-[0] - length($new_var);
3416 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3422 $query = qq|UPDATE business
3423 SET customernumberinit = ?
3425 do_query($self, $dbh, $query, $var, $business_id);
3427 if (!$provided_dbh) {
3432 $main::lxdebug->leave_sub();
3437 sub get_partsgroup {
3438 $main::lxdebug->enter_sub();
3440 my ($self, $myconfig, $p) = @_;
3441 my $target = $p->{target} || 'all_partsgroup';
3443 my $dbh = $self->get_standard_dbh($myconfig);
3445 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3447 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3450 if ($p->{searchitems} eq 'part') {
3451 $query .= qq|WHERE p.inventory_accno_id > 0|;
3453 if ($p->{searchitems} eq 'service') {
3454 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3456 if ($p->{searchitems} eq 'assembly') {
3457 $query .= qq|WHERE p.assembly = '1'|;
3459 if ($p->{searchitems} eq 'labor') {
3460 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3463 $query .= qq|ORDER BY partsgroup|;
3466 $query = qq|SELECT id, partsgroup FROM partsgroup
3467 ORDER BY partsgroup|;
3470 if ($p->{language_code}) {
3471 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3472 t.description AS translation
3474 JOIN parts p ON (p.partsgroup_id = pg.id)
3475 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3476 ORDER BY translation|;
3477 @values = ($p->{language_code});
3480 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3482 $main::lxdebug->leave_sub();
3485 sub get_pricegroup {
3486 $main::lxdebug->enter_sub();
3488 my ($self, $myconfig, $p) = @_;
3490 my $dbh = $self->get_standard_dbh($myconfig);
3492 my $query = qq|SELECT p.id, p.pricegroup
3495 $query .= qq| ORDER BY pricegroup|;
3498 $query = qq|SELECT id, pricegroup FROM pricegroup
3499 ORDER BY pricegroup|;
3502 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3504 $main::lxdebug->leave_sub();
3508 # usage $form->all_years($myconfig, [$dbh])
3509 # return list of all years where bookings found
3512 $main::lxdebug->enter_sub();
3514 my ($self, $myconfig, $dbh) = @_;
3516 $dbh ||= $self->get_standard_dbh($myconfig);
3519 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3520 (SELECT MAX(transdate) FROM acc_trans)|;
3521 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3523 if ($myconfig->{dateformat} =~ /^yy/) {
3524 ($startdate) = split /\W/, $startdate;
3525 ($enddate) = split /\W/, $enddate;
3527 (@_) = split /\W/, $startdate;
3529 (@_) = split /\W/, $enddate;
3534 $startdate = substr($startdate,0,4);
3535 $enddate = substr($enddate,0,4);
3537 while ($enddate >= $startdate) {
3538 push @all_years, $enddate--;
3543 $main::lxdebug->leave_sub();
3547 $main::lxdebug->enter_sub();
3551 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3553 $main::lxdebug->leave_sub();
3557 $main::lxdebug->enter_sub();
3562 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3564 $main::lxdebug->leave_sub();
3567 sub prepare_for_printing {
3570 $self->{templates} ||= $::myconfig{templates};
3571 $self->{formname} ||= $self->{type};
3572 $self->{media} ||= 'email';
3574 die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3576 # set shipto from billto unless set
3577 my $has_shipto = any { $self->{"shipto$_"} } qw(name street zipcode city country contact);
3578 if (!$has_shipto && ($self->{type} =~ m/^(?:purchase_order|request_quotation)$/)) {
3579 $self->{shiptoname} = $::myconfig{company};
3580 $self->{shiptostreet} = $::myconfig{address};
3583 my $language = $self->{language} ? '_' . $self->{language} : '';
3585 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3586 if ($self->{language_id}) {
3587 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3589 $output_dateformat = $::myconfig{dateformat};
3590 $output_numberformat = $::myconfig{numberformat};
3591 $output_longdates = 1;
3594 # Retrieve accounts for tax calculation.
3595 IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3597 if ($self->{type} =~ /_delivery_order$/) {
3598 DO->order_details();
3599 } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3600 OE->order_details(\%::myconfig, $self);
3602 IS->invoice_details(\%::myconfig, $self, $::locale);
3605 # Chose extension & set source file name
3606 my $extension = 'html';
3607 if ($self->{format} eq 'postscript') {
3608 $self->{postscript} = 1;
3610 } elsif ($self->{"format"} =~ /pdf/) {
3612 $extension = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3613 } elsif ($self->{"format"} =~ /opendocument/) {
3614 $self->{opendocument} = 1;
3616 } elsif ($self->{"format"} =~ /excel/) {
3621 my $printer_code = '_' . $self->{printer_code} if $self->{printer_code};
3622 my $email_extension = '_email' if -f "$self->{templates}/$self->{formname}_email${language}${printer_code}.${extension}";
3623 $self->{IN} = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3626 $self->format_dates($output_dateformat, $output_longdates,
3627 qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate datepaid
3628 transdate_oe deliverydate_oe employee_startdate employee_enddate),
3629 grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3631 $self->reformat_numbers($output_numberformat, 2,
3632 qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3633 grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3635 $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3637 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3639 if (scalar @{ $cvar_date_fields }) {
3640 $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3643 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3644 $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3651 my ($self, $dateformat, $longformat, @indices) = @_;
3653 $dateformat ||= $::myconfig{dateformat};
3655 foreach my $idx (@indices) {
3656 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3657 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3658 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3662 next unless defined $self->{$idx};
3664 if (!ref($self->{$idx})) {
3665 $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3667 } elsif (ref($self->{$idx}) eq "ARRAY") {
3668 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3669 $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3675 sub reformat_numbers {
3676 my ($self, $numberformat, $places, @indices) = @_;
3678 return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3680 foreach my $idx (@indices) {
3681 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3682 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3683 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3687 next unless defined $self->{$idx};
3689 if (!ref($self->{$idx})) {
3690 $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3692 } elsif (ref($self->{$idx}) eq "ARRAY") {
3693 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3694 $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3699 my $saved_numberformat = $::myconfig{numberformat};
3700 $::myconfig{numberformat} = $numberformat;
3702 foreach my $idx (@indices) {
3703 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3704 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3705 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3709 next unless defined $self->{$idx};
3711 if (!ref($self->{$idx})) {
3712 $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3714 } elsif (ref($self->{$idx}) eq "ARRAY") {
3715 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3716 $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3721 $::myconfig{numberformat} = $saved_numberformat;
3730 SL::Form.pm - main data object.
3734 This is the main data object of Lx-Office.
3735 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3736 Points of interest for a beginner are:
3738 - $form->error - renders a generic error in html. accepts an error message
3739 - $form->get_standard_dbh - returns a database connection for the
3741 =head1 SPECIAL FUNCTIONS
3743 =head2 C<_store_value()>
3745 parses a complex var name, and stores it in the form.
3748 $form->_store_value($key, $value);
3750 keys must start with a string, and can contain various tokens.
3751 supported key structures are:
3754 simple key strings work as expected
3759 separating two keys by a dot (.) will result in a hash lookup for the inner value
3760 this is similar to the behaviour of java and templating mechanisms.
3762 filter.description => $form->{filter}->{description}
3764 3. array+hashref access
3766 adding brackets ([]) before the dot will cause the next hash to be put into an array.
3767 using [+] instead of [] will force a new array index. this is useful for recurring
3768 data structures like part lists. put a [+] into the first varname, and use [] on the
3771 repeating these names in your template:
3774 invoice.items[].parts_id
3778 $form->{invoice}->{items}->[
3792 using brackets at the end of a name will result in a pure array to be created.
3793 note that you mustn't use [+], which is reserved for array+hash access and will
3794 result in undefined behaviour in array context.
3796 filter.status[] => $form->{status}->[ val1, val2, ... ]
3798 =head2 C<update_business> PARAMS
3801 \%config, - config hashref
3802 $business_id, - business id
3803 $dbh - optional database handle
3805 handles business (thats customer/vendor types) sequences.
3807 special behaviour for empty strings in customerinitnumber field:
3808 will in this case not increase the value, and return undef.
3810 =head2 C<redirect_header> $url
3812 Generates a HTTP redirection header for the new C<$url>. Constructs an
3813 absolute URL including scheme, host name and port. If C<$url> is a
3814 relative URL then it is considered relative to Lx-Office base URL.
3816 This function C<die>s if headers have already been created with
3817 C<$::form-E<gt>header>.
3821 print $::form->redirect_header('oe.pl?action=edit&id=1234');
3822 print $::form->redirect_header('http://www.lx-office.org/');
3826 Generates a general purpose http/html header and includes most of the scripts
3827 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3829 Only one header will be generated. If the method was already called in this
3830 request it will not output anything and return undef. Also if no
3831 HTTP_USER_AGENT is found, no header is generated.
3833 Although header does not accept parameters itself, it will honor special
3834 hashkeys of its Form instance:
3842 If one of these is set, a http-equiv refresh is generated. Missing parameters
3843 default to 3 seconds and the refering url.
3847 Either a scalar or an array ref. Will be inlined into the header. Add
3848 stylesheets with the L<use_stylesheet> function.
3852 If true, a css snippet will be generated that sets the page in landscape mode.
3856 Used to override the default favicon.
3860 A html page title will be generated from this