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 #======================================================================
59 use List::Util qw(first max min sum);
65 $standard_dbh->disconnect();
72 parses a complex var name, and stores it in the form.
75 $form->_store_value($key, $value);
77 keys must start with a string, and can contain various tokens.
78 supported key structures are:
81 simple key strings work as expected
86 separating two keys by a dot (.) will result in a hash lookup for the inner value
87 this is similar to the behaviour of java and templating mechanisms.
89 filter.description => $form->{filter}->{description}
91 3. array+hashref access
93 adding brackets ([]) before the dot will cause the next hash to be put into an array.
94 using [+] instead of [] will force a new array index. this is useful for recurring
95 data structures like part lists. put a [+] into the first varname, and use [] on the
98 repeating these names in your template:
101 invoice.items[].parts_id
105 $form->{invoice}->{items}->[
119 using brackets at the end of a name will result in a pure array to be created.
120 note that you mustn't use [+], which is reserved for array+hash access and will
121 result in undefined behaviour in array context.
123 filter.status[] => $form->{status}->[ val1, val2, ... ]
127 $main::lxdebug->enter_sub(2);
133 my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key;
137 if (scalar @tokens) {
138 $curr = \ $self->{ shift @tokens };
142 my $sep = shift @tokens;
143 my $key = shift @tokens;
145 $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]';
146 $curr = \ $$curr->[max 0, $#$$curr] if $sep eq '[].';
147 $curr = \ $$curr->[++$#$$curr] if $sep eq '[+].';
148 $curr = \ $$curr->{$key}
153 $main::lxdebug->leave_sub(2);
159 $main::lxdebug->enter_sub(2);
164 my @pairs = split(/&/, $input);
167 my ($key, $value) = split(/=/, $_, 2);
168 $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key);
171 $main::lxdebug->leave_sub(2);
174 sub _request_to_hash {
175 $main::lxdebug->enter_sub(2);
180 if (!$ENV{'CONTENT_TYPE'}
181 || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
183 $self->_input_to_hash($input);
185 $main::lxdebug->leave_sub(2);
189 my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
191 my $boundary = '--' . $1;
193 foreach my $line (split m/\n/, $input) {
194 last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
196 if (($line eq $boundary) || ($line eq "$boundary\r")) {
197 ${ $previous } =~ s|\r?\n$|| if $previous;
203 $content_type = "text/plain";
210 next unless $boundary_found;
212 if (!$headers_done) {
213 $line =~ s/[\r\n]*$//;
220 if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
221 if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
223 substr $line, $-[0], $+[0] - $-[0], "";
226 if ($line =~ m|name\s*=\s*"(.*?)"|i) {
228 substr $line, $-[0], $+[0] - $-[0], "";
231 $previous = $self->_store_value($name, '') if ($name);
232 $self->{FILENAME} = $filename if ($filename);
237 if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
244 next unless $previous;
246 ${ $previous } .= "${line}\n";
249 ${ $previous } =~ s|\r?\n$|| if $previous;
251 $main::lxdebug->leave_sub(2);
254 sub _recode_recursively {
255 $main::lxdebug->enter_sub();
256 my ($iconv, $param) = @_;
258 if (ref $param eq 'HASH') {
259 foreach my $key (keys %{ $param }) {
260 if (!ref $param->{$key}) {
261 $param->{$key} = $iconv->convert($param->{$key});
263 _recode_recursively($iconv, $param->{$key});
267 } elsif (ref $param eq 'ARRAY') {
268 foreach my $idx (0 .. scalar(@{ $param }) - 1) {
269 if (!ref $param->[$idx]) {
270 $param->[$idx] = $iconv->convert($param->[$idx]);
272 _recode_recursively($iconv, $param->[$idx]);
276 $main::lxdebug->leave_sub();
280 $main::lxdebug->enter_sub();
286 if ($LXDebug::watch_form) {
287 require SL::Watchdog;
288 tie %{ $self }, 'SL::Watchdog';
291 read(STDIN, $_, $ENV{CONTENT_LENGTH});
293 if ($ENV{QUERY_STRING}) {
294 $_ = $ENV{QUERY_STRING};
303 $self->_request_to_hash($_);
305 my $db_charset = $main::dbcharset;
306 $db_charset ||= Common::DEFAULT_CHARSET;
308 if ($self->{INPUT_ENCODING} && (lc $self->{INPUT_ENCODING} ne $db_charset)) {
310 my $iconv = Text::Iconv->new($self->{INPUT_ENCODING}, $db_charset);
312 _recode_recursively($iconv, $self);
314 delete $self{INPUT_ENCODING};
317 $self->{action} = lc $self->{action};
318 $self->{action} =~ s/( |-|,|\#)/_/g;
320 $self->{version} = "2.6.0";
322 $main::lxdebug->leave_sub();
327 sub _flatten_variables_rec {
328 $main::lxdebug->enter_sub(2);
337 if ('' eq ref $curr->{$key}) {
338 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
340 } elsif ('HASH' eq ref $curr->{$key}) {
341 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
342 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
346 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
347 my $first_array_entry = 1;
349 foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
350 push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
351 $first_array_entry = 0;
356 $main::lxdebug->leave_sub(2);
361 sub flatten_variables {
362 $main::lxdebug->enter_sub(2);
370 push @variables, $self->_flatten_variables_rec($self, '', $_);
373 $main::lxdebug->leave_sub(2);
378 sub flatten_standard_variables {
379 $main::lxdebug->enter_sub(2);
382 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
386 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
387 push @variables, $self->_flatten_variables_rec($self, '', $_);
390 $main::lxdebug->leave_sub(2);
396 $main::lxdebug->enter_sub();
402 map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
404 $main::lxdebug->leave_sub();
408 $main::lxdebug->enter_sub(2);
411 my $password = $self->{password};
413 $self->{password} = 'X' x 8;
415 local $Data::Dumper::Sortkeys = 1;
416 my $output = Dumper($self);
418 $self->{password} = $password;
420 $main::lxdebug->leave_sub(2);
426 $main::lxdebug->enter_sub(2);
428 my ($self, $str) = @_;
430 $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
432 $main::lxdebug->leave_sub(2);
438 $main::lxdebug->enter_sub(2);
440 my ($self, $str) = @_;
445 $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
447 $main::lxdebug->leave_sub(2);
453 $main::lxdebug->enter_sub();
454 my ($self, $str) = @_;
456 if ($str && !ref($str)) {
457 $str =~ s/\"/"/g;
460 $main::lxdebug->leave_sub();
466 $main::lxdebug->enter_sub();
467 my ($self, $str) = @_;
469 if ($str && !ref($str)) {
470 $str =~ s/"/\"/g;
473 $main::lxdebug->leave_sub();
479 $main::lxdebug->enter_sub();
483 map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
485 for (sort keys %$self) {
486 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
487 print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
490 $main::lxdebug->leave_sub();
494 $main::lxdebug->enter_sub();
496 $main::lxdebug->show_backtrace();
498 my ($self, $msg) = @_;
499 if ($ENV{HTTP_USER_AGENT}) {
501 $self->show_generic_error($msg);
508 $main::lxdebug->leave_sub();
512 $main::lxdebug->enter_sub();
514 my ($self, $msg) = @_;
516 if ($ENV{HTTP_USER_AGENT}) {
519 if (!$self->{header}) {
532 if ($self->{info_function}) {
533 &{ $self->{info_function} }($msg);
539 $main::lxdebug->leave_sub();
542 # calculates the number of rows in a textarea based on the content and column number
543 # can be capped with maxrows
545 $main::lxdebug->enter_sub();
546 my ($self, $str, $cols, $maxrows, $minrows) = @_;
550 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
553 $main::lxdebug->leave_sub();
555 return max(min($rows, $maxrows), $minrows);
559 $main::lxdebug->enter_sub();
561 my ($self, $msg) = @_;
563 $self->error("$msg\n" . $DBI::errstr);
565 $main::lxdebug->leave_sub();
569 $main::lxdebug->enter_sub();
571 my ($self, $name, $msg) = @_;
574 foreach my $part (split m/\./, $name) {
575 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
578 $curr = $curr->{$part};
581 $main::lxdebug->leave_sub();
584 sub create_http_response {
585 $main::lxdebug->enter_sub();
590 my $cgi = $main::cgi;
591 $cgi ||= CGI->new('');
595 if ($ENV{HTTP_X_FORWARDED_FOR}) {
596 $base_path = $ENV{HTTP_REFERER};
597 $base_path =~ s|^.*?://.*?/|/|;
599 $base_path = $ENV{REQUEST_URI};
601 $base_path =~ s|[^/]+$||;
602 $base_path =~ s|/$||;
605 if (defined $main::auth) {
606 my $session_cookie_value = $main::auth->get_session_id();
607 $session_cookie_value ||= 'NO_SESSION';
609 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
610 '-value' => $session_cookie_value,
611 '-path' => $base_path);
614 my %cgi_params = ('-type' => $params{content_type});
615 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
617 my $output = $cgi->header('-cookie' => $session_cookie,
620 $main::lxdebug->leave_sub();
627 $main::lxdebug->enter_sub();
629 my ($self, $extra_code) = @_;
631 if ($self->{header}) {
632 $main::lxdebug->leave_sub();
636 my ($stylesheet, $favicon, $pagelayout);
638 if ($ENV{HTTP_USER_AGENT}) {
641 if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
642 # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
643 $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
646 my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
648 $stylesheets =~ s|^\s*||;
649 $stylesheets =~ s|\s*$||;
650 foreach my $file (split m/\s+/, $stylesheets) {
652 next if (! -f "css/$file");
654 $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
657 $self->{favicon} = "favicon.ico" unless $self->{favicon};
659 if ($self->{favicon} && (-f "$self->{favicon}")) {
661 qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
665 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
667 if ($self->{landscape}) {
668 $pagelayout = qq|<style type="text/css">
669 \@page { size:landscape; }
673 my $fokus = qq| document.$self->{fokus}.focus();| if ($self->{"fokus"});
677 if ($self->{jsscript} == 1) {
680 <script type="text/javascript" src="js/common.js"></script>
681 <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
682 <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
683 <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
684 <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
691 ? "$self->{title} - $self->{titlebar}"
694 foreach my $item (@ { $self->{AJAX} }) {
695 $ajax .= $item->show_javascript();
698 print $self->create_http_response('content_type' => 'text/html',
699 'charset' => $db_charset,);
700 print qq|${doctype}<html>
702 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
703 <title>$self->{titlebar}</title>
710 <script type="text/javascript">
718 <meta name="robots" content="noindex,nofollow" />
719 <script type="text/javascript" src="js/highlight_input.js"></script>
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 ***********************************************/
739 $main::lxdebug->leave_sub();
742 sub ajax_response_header {
743 $main::lxdebug->enter_sub();
747 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
748 my $cgi = $main::cgi || CGI->new('');
749 my $output = $cgi->header('-charset' => $db_charset);
751 $main::lxdebug->leave_sub();
756 sub _prepare_html_template {
757 $main::lxdebug->enter_sub();
759 my ($self, $file, $additional_params) = @_;
762 if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
763 $language = $main::language;
765 $language = $main::myconfig{"countrycode"};
767 $language = "de" unless ($language);
769 if (-f "templates/webpages/${file}_${language}.html") {
770 if ((-f ".developer") &&
771 (-f "templates/webpages/${file}_master.html") &&
772 ((stat("templates/webpages/${file}_master.html"))[9] >
773 (stat("templates/webpages/${file}_${language}.html"))[9])) {
774 my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
775 "Please re-run 'locales.pl' in 'locale/${language}'.";
776 print(qq|<pre>$info</pre>|);
780 $file = "templates/webpages/${file}_${language}.html";
781 } elsif (-f "templates/webpages/${file}.html") {
782 $file = "templates/webpages/${file}.html";
784 my $info = "Web page template '${file}' not found.\n" .
785 "Please re-run 'locales.pl' in 'locale/${language}'.";
786 print(qq|<pre>$info</pre>|);
790 if ($self->{"DEBUG"}) {
791 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
794 if ($additional_params->{"DEBUG"}) {
795 $additional_params->{"DEBUG"} =
796 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
799 if (%main::myconfig) {
800 map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
801 my $jsc_dateformat = $main::myconfig{"dateformat"};
802 $jsc_dateformat =~ s/d+/\%d/gi;
803 $jsc_dateformat =~ s/m+/\%m/gi;
804 $jsc_dateformat =~ s/y+/\%Y/gi;
805 $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
808 $additional_params->{"conf_dbcharset"} = $main::dbcharset;
809 $additional_params->{"conf_webdav"} = $main::webdav;
810 $additional_params->{"conf_lizenzen"} = $main::lizenzen;
811 $additional_params->{"conf_latex_templates"} = $main::latex;
812 $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
814 if (%main::debug_options) {
815 map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
818 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
819 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
820 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
824 $main::lxdebug->leave_sub();
829 sub parse_html_template {
830 $main::lxdebug->enter_sub();
832 my ($self, $file, $additional_params) = @_;
834 $additional_params ||= { };
836 $file = $self->_prepare_html_template($file, $additional_params);
838 my $template = Template->new({ 'INTERPOLATE' => 0,
842 'PLUGIN_BASE' => 'SL::Template::Plugin',
843 'INCLUDE_PATH' => '.:templates/webpages',
846 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
848 my $in = IO::File->new($file, 'r');
851 print STDERR "Error opening template file: $!";
852 $main::lxdebug->leave_sub();
856 my $input = join('', <$in>);
860 $input = $main::locale->{iconv}->convert($input);
864 if (!$template->process(\$input, $additional_params, \$output)) {
865 print STDERR $template->error();
868 $main::lxdebug->leave_sub();
873 sub show_generic_error {
874 $main::lxdebug->enter_sub();
876 my ($self, $error, %params) = @_;
879 'title_error' => $params{title},
880 'label_error' => $error,
883 if ($params{action}) {
886 map { delete($self->{$_}); } qw(action);
887 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
889 $add_params->{SHOW_BUTTON} = 1;
890 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
891 $add_params->{VARIABLES} = \@vars;
893 } elsif ($params{back_button}) {
894 $add_params->{SHOW_BACK_BUTTON} = 1;
897 $self->{title} = $params{title} if $params{title};
900 print $self->parse_html_template("generic/error", $add_params);
902 $main::lxdebug->leave_sub();
904 die("Error: $error\n");
907 sub show_generic_information {
908 $main::lxdebug->enter_sub();
910 my ($self, $text, $title) = @_;
913 'title_information' => $title,
914 'label_information' => $text,
917 $self->{title} = $title if ($title);
920 print $self->parse_html_template("generic/information", $add_params);
922 $main::lxdebug->leave_sub();
924 die("Information: $text\n");
927 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
928 # changed it to accept an arbitrary number of triggers - sschoeling
930 $main::lxdebug->enter_sub();
933 my $myconfig = shift;
936 # set dateform for jsscript
939 "dd.mm.yy" => "%d.%m.%Y",
940 "dd-mm-yy" => "%d-%m-%Y",
941 "dd/mm/yy" => "%d/%m/%Y",
942 "mm/dd/yy" => "%m/%d/%Y",
943 "mm-dd-yy" => "%m-%d-%Y",
944 "yyyy-mm-dd" => "%Y-%m-%d",
947 my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
948 $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
955 inputField : "| . (shift) . qq|",
956 ifFormat :"$ifFormat",
957 align : "| . (shift) . qq|",
958 button : "| . (shift) . qq|"
964 <script type="text/javascript">
965 <!--| . join("", @triggers) . qq|//-->
969 $main::lxdebug->leave_sub();
972 } #end sub write_trigger
975 $main::lxdebug->enter_sub();
977 my ($self, $msg) = @_;
979 if ($self->{callback}) {
981 my ($script, $argv) = split(/\?/, $self->{callback}, 2);
983 $script =~ s|[^a-zA-Z0-9_\.]||g;
984 exec("perl", "$script", $argv);
992 $main::lxdebug->leave_sub();
995 # sort of columns removed - empty sub
997 $main::lxdebug->enter_sub();
999 my ($self, @columns) = @_;
1001 $main::lxdebug->leave_sub();
1007 $main::lxdebug->enter_sub(2);
1009 my ($self, $myconfig, $amount, $places, $dash) = @_;
1011 if ($amount eq "") {
1015 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
1017 my $neg = ($amount =~ s/^-//);
1018 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
1020 if (defined($places) && ($places ne '')) {
1026 my ($actual_places) = ($amount =~ /\.(\d+)/);
1027 $actual_places = length($actual_places);
1028 $places = $actual_places > $places ? $actual_places : $places;
1031 $amount = $self->round_amount($amount, $places);
1034 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
1035 my @p = split(/\./, $amount); # split amount at decimal point
1037 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
1040 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
1043 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
1044 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1045 ($neg ? "-$amount" : "$amount" ) ;
1049 $main::lxdebug->leave_sub(2);
1053 sub format_amount_units {
1054 $main::lxdebug->enter_sub();
1059 my $myconfig = \%main::myconfig;
1060 my $amount = $params{amount} * 1;
1061 my $places = $params{places};
1062 my $part_unit_name = $params{part_unit};
1063 my $amount_unit_name = $params{amount_unit};
1064 my $conv_units = $params{conv_units};
1065 my $max_places = $params{max_places};
1067 if (!$part_unit_name) {
1068 $main::lxdebug->leave_sub();
1072 AM->retrieve_all_units();
1073 my $all_units = $main::all_units;
1075 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1076 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1079 if (!scalar @{ $conv_units }) {
1080 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1081 $main::lxdebug->leave_sub();
1085 my $part_unit = $all_units->{$part_unit_name};
1086 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1088 $amount *= $conv_unit->{factor};
1093 foreach my $unit (@$conv_units) {
1094 my $last = $unit->{name} eq $part_unit->{name};
1096 $num = int($amount / $unit->{factor});
1097 $amount -= $num * $unit->{factor};
1100 if ($last ? $amount : $num) {
1101 push @values, { "unit" => $unit->{name},
1102 "amount" => $last ? $amount / $unit->{factor} : $num,
1103 "places" => $last ? $places : 0 };
1110 push @values, { "unit" => $part_unit_name,
1115 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1117 $main::lxdebug->leave_sub();
1123 $main::lxdebug->enter_sub(2);
1128 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1129 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1130 $input =~ s/\#\#/\#/g;
1132 $main::lxdebug->leave_sub(2);
1140 $main::lxdebug->enter_sub(2);
1142 my ($self, $myconfig, $amount) = @_;
1144 if ( ($myconfig->{numberformat} eq '1.000,00')
1145 || ($myconfig->{numberformat} eq '1000,00')) {
1150 if ($myconfig->{numberformat} eq "1'000.00") {
1156 $main::lxdebug->leave_sub(2);
1158 return ($amount * 1);
1162 $main::lxdebug->enter_sub(2);
1164 my ($self, $amount, $places) = @_;
1167 # Rounding like "Kaufmannsrunden"
1168 # Descr. http://de.wikipedia.org/wiki/Rundung
1170 # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
1173 $amount = $amount * (10**($places));
1174 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1176 $main::lxdebug->leave_sub(2);
1178 return $round_amount;
1182 sub parse_template {
1183 $main::lxdebug->enter_sub();
1185 my ($self, $myconfig, $userspath) = @_;
1186 my ($template, $out);
1190 $self->{"cwd"} = getcwd();
1191 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1195 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1196 $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1197 $ext_for_format = 'odt';
1199 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1200 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1201 $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1202 $ext_for_format = 'pdf';
1204 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1205 $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1206 $ext_for_format = 'html';
1208 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1209 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1210 $ext_for_format = 'xml';
1212 } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1213 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1215 } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1216 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1218 } elsif ( defined $self->{'format'}) {
1219 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1221 } elsif ( $self->{'format'} eq '' ) {
1222 $self->error("No Outputformat given: $self->{'format'}");
1224 } else { #Catch the rest
1225 $self->error("Outputformat not defined: $self->{'format'}");
1228 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1229 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1231 if (!$self->{employee_id}) {
1232 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1235 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1237 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1239 # OUT is used for the media, screen, printer, email
1240 # for postscript we store a copy in a temporary file
1242 my $prepend_userspath;
1244 if (!$self->{tmpfile}) {
1245 $self->{tmpfile} = "${fileid}.$self->{IN}";
1246 $prepend_userspath = 1;
1249 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1251 $self->{tmpfile} =~ s|.*/||;
1252 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1253 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1255 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1256 $out = $self->{OUT};
1257 $self->{OUT} = ">$self->{tmpfile}";
1261 open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1263 open(OUT, ">-") or $self->error("STDOUT : $!");
1267 if (!$template->parse(*OUT)) {
1269 $self->error("$self->{IN} : " . $template->get_error());
1274 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1276 if ($self->{media} eq 'email') {
1278 my $mail = new Mailer;
1280 map { $mail->{$_} = $self->{$_} }
1281 qw(cc bcc subject message version format);
1282 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1283 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1284 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1285 $mail->{fileid} = "$fileid.";
1286 $myconfig->{signature} =~ s/\r//g;
1288 # if we send html or plain text inline
1289 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1290 $mail->{contenttype} = "text/html";
1292 $mail->{message} =~ s/\r//g;
1293 $mail->{message} =~ s/\n/<br>\n/g;
1294 $myconfig->{signature} =~ s/\n/<br>\n/g;
1295 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1297 open(IN, $self->{tmpfile})
1298 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1300 $mail->{message} .= $_;
1307 if (!$self->{"do_not_attach"}) {
1308 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1309 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1310 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1311 "name" => $attachment_name }];
1314 $mail->{message} =~ s/\r//g;
1315 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1319 my $err = $mail->send();
1320 $self->error($self->cleanup . "$err") if ($err);
1324 $self->{OUT} = $out;
1326 my $numbytes = (-s $self->{tmpfile});
1327 open(IN, $self->{tmpfile})
1328 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1330 $self->{copies} = 1 unless $self->{media} eq 'printer';
1332 chdir("$self->{cwd}");
1333 #print(STDERR "Kopien $self->{copies}\n");
1334 #print(STDERR "OUT $self->{OUT}\n");
1335 for my $i (1 .. $self->{copies}) {
1337 open(OUT, $self->{OUT})
1338 or $self->error($self->cleanup . "$self->{OUT} : $!");
1340 $self->{attachment_filename} = ($self->{attachment_filename})
1341 ? $self->{attachment_filename}
1342 : $self->generate_attachment_filename();
1344 # launch application
1345 print qq|Content-Type: | . $template->get_mime_type() . qq|
1346 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1347 Content-Length: $numbytes
1351 open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1371 chdir("$self->{cwd}");
1372 $main::lxdebug->leave_sub();
1375 sub get_formname_translation {
1376 $main::lxdebug->enter_sub();
1377 my ($self, $formname) = @_;
1379 $formname ||= $self->{formname};
1381 my %formname_translations = (
1382 bin_list => $main::locale->text('Bin List'),
1383 credit_note => $main::locale->text('Credit Note'),
1384 invoice => $main::locale->text('Invoice'),
1385 packing_list => $main::locale->text('Packing List'),
1386 pick_list => $main::locale->text('Pick List'),
1387 proforma => $main::locale->text('Proforma Invoice'),
1388 purchase_order => $main::locale->text('Purchase Order'),
1389 request_quotation => $main::locale->text('RFQ'),
1390 sales_order => $main::locale->text('Confirmation'),
1391 sales_quotation => $main::locale->text('Quotation'),
1392 storno_invoice => $main::locale->text('Storno Invoice'),
1393 storno_packing_list => $main::locale->text('Storno Packing List'),
1394 sales_delivery_order => $main::locale->text('Delivery Order'),
1395 purchase_delivery_order => $main::locale->text('Delivery Order'),
1398 $main::lxdebug->leave_sub();
1399 return $formname_translations{$formname}
1402 sub get_number_prefix_for_type {
1403 $main::lxdebug->enter_sub();
1407 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1408 : ($self->{type} =~ /_quotation$/) ? 'quo'
1409 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1412 $main::lxdebug->leave_sub();
1416 sub get_extension_for_format {
1417 $main::lxdebug->enter_sub();
1420 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1421 : $self->{format} =~ /postscript/i ? ".ps"
1422 : $self->{format} =~ /opendocument/i ? ".odt"
1423 : $self->{format} =~ /html/i ? ".html"
1426 $main::lxdebug->leave_sub();
1430 sub generate_attachment_filename {
1431 $main::lxdebug->enter_sub();
1434 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1435 my $prefix = $self->get_number_prefix_for_type();
1437 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1438 $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1440 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1441 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1444 $attachment_filename = "";
1447 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1448 $attachment_filename =~ s|[\s/\\]+|_|g;
1450 $main::lxdebug->leave_sub();
1451 return $attachment_filename;
1454 sub generate_email_subject {
1455 $main::lxdebug->enter_sub();
1458 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1459 my $prefix = $self->get_number_prefix_for_type();
1461 if ($subject && $self->{"${prefix}number"}) {
1462 $subject .= " " . $self->{"${prefix}number"}
1465 $main::lxdebug->leave_sub();
1470 $main::lxdebug->enter_sub();
1474 chdir("$self->{tmpdir}");
1477 if (-f "$self->{tmpfile}.err") {
1478 open(FH, "$self->{tmpfile}.err");
1483 if ($self->{tmpfile}) {
1484 $self->{tmpfile} =~ s|.*/||g;
1486 $self->{tmpfile} =~ s/\.\w+$//g;
1487 my $tmpfile = $self->{tmpfile};
1488 unlink(<$tmpfile.*>);
1491 chdir("$self->{cwd}");
1493 $main::lxdebug->leave_sub();
1499 $main::lxdebug->enter_sub();
1501 my ($self, $date, $myconfig) = @_;
1504 if ($date && $date =~ /\D/) {
1506 if ($myconfig->{dateformat} =~ /^yy/) {
1507 ($yy, $mm, $dd) = split /\D/, $date;
1509 if ($myconfig->{dateformat} =~ /^mm/) {
1510 ($mm, $dd, $yy) = split /\D/, $date;
1512 if ($myconfig->{dateformat} =~ /^dd/) {
1513 ($dd, $mm, $yy) = split /\D/, $date;
1518 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1519 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1521 $dd = "0$dd" if ($dd < 10);
1522 $mm = "0$mm" if ($mm < 10);
1524 $date = "$yy$mm$dd";
1527 $main::lxdebug->leave_sub();
1532 # Database routines used throughout
1535 $main::lxdebug->enter_sub(2);
1537 my ($self, $myconfig) = @_;
1539 # connect to database
1541 DBI->connect($myconfig->{dbconnect},
1542 $myconfig->{dbuser}, $myconfig->{dbpasswd})
1546 if ($myconfig->{dboptions}) {
1547 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1550 $main::lxdebug->leave_sub(2);
1555 sub dbconnect_noauto {
1556 $main::lxdebug->enter_sub();
1558 my ($self, $myconfig) = @_;
1560 # connect to database
1562 DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1563 $myconfig->{dbpasswd}, { AutoCommit => 0 })
1567 if ($myconfig->{dboptions}) {
1568 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1571 $main::lxdebug->leave_sub();
1576 sub get_standard_dbh {
1577 $main::lxdebug->enter_sub(2);
1579 my ($self, $myconfig) = @_;
1581 if ($standard_dbh && !$standard_dbh->{Active}) {
1582 $main::lxdebug->message(LXDebug::INFO, "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1583 undef $standard_dbh;
1586 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1588 $main::lxdebug->leave_sub(2);
1590 return $standard_dbh;
1594 $main::lxdebug->enter_sub();
1596 my ($self, $date, $myconfig) = @_;
1597 my $dbh = $self->dbconnect($myconfig);
1599 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1600 my $sth = prepare_execute_query($self, $dbh, $query, $date);
1601 my ($closed) = $sth->fetchrow_array;
1603 $main::lxdebug->leave_sub();
1608 sub update_balance {
1609 $main::lxdebug->enter_sub();
1611 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1613 # if we have a value, go do it
1616 # retrieve balance from table
1617 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1618 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1619 my ($balance) = $sth->fetchrow_array;
1625 $query = "UPDATE $table SET $field = $balance WHERE $where";
1626 do_query($self, $dbh, $query, @values);
1628 $main::lxdebug->leave_sub();
1631 sub update_exchangerate {
1632 $main::lxdebug->enter_sub();
1634 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1636 # some sanity check for currency
1638 $main::lxdebug->leave_sub();
1641 $query = qq|SELECT curr FROM defaults|;
1643 my ($currency) = selectrow_query($self, $dbh, $query);
1644 my ($defaultcurrency) = split m/:/, $currency;
1647 if ($curr eq $defaultcurrency) {
1648 $main::lxdebug->leave_sub();
1652 $query = qq|SELECT e.curr FROM exchangerate e
1653 WHERE e.curr = ? AND e.transdate = ?
1655 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1664 $buy = conv_i($buy, "NULL");
1665 $sell = conv_i($sell, "NULL");
1668 if ($buy != 0 && $sell != 0) {
1669 $set = "buy = $buy, sell = $sell";
1670 } elsif ($buy != 0) {
1671 $set = "buy = $buy";
1672 } elsif ($sell != 0) {
1673 $set = "sell = $sell";
1676 if ($sth->fetchrow_array) {
1677 $query = qq|UPDATE exchangerate
1683 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1684 VALUES (?, $buy, $sell, ?)|;
1687 do_query($self, $dbh, $query, $curr, $transdate);
1689 $main::lxdebug->leave_sub();
1692 sub save_exchangerate {
1693 $main::lxdebug->enter_sub();
1695 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1697 my $dbh = $self->dbconnect($myconfig);
1701 $buy = $rate if $fld eq 'buy';
1702 $sell = $rate if $fld eq 'sell';
1705 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1710 $main::lxdebug->leave_sub();
1713 sub get_exchangerate {
1714 $main::lxdebug->enter_sub();
1716 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1719 unless ($transdate) {
1720 $main::lxdebug->leave_sub();
1724 $query = qq|SELECT curr FROM defaults|;
1726 my ($currency) = selectrow_query($self, $dbh, $query);
1727 my ($defaultcurrency) = split m/:/, $currency;
1729 if ($currency eq $defaultcurrency) {
1730 $main::lxdebug->leave_sub();
1734 $query = qq|SELECT e.$fld FROM exchangerate e
1735 WHERE e.curr = ? AND e.transdate = ?|;
1736 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1740 $main::lxdebug->leave_sub();
1742 return $exchangerate;
1745 sub check_exchangerate {
1746 $main::lxdebug->enter_sub();
1748 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1750 if ($fld !~/^buy|sell$/) {
1751 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1754 unless ($transdate) {
1755 $main::lxdebug->leave_sub();
1759 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1761 if ($currency eq $defaultcurrency) {
1762 $main::lxdebug->leave_sub();
1766 my $dbh = $self->get_standard_dbh($myconfig);
1767 my $query = qq|SELECT e.$fld FROM exchangerate e
1768 WHERE e.curr = ? AND e.transdate = ?|;
1770 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1772 $main::lxdebug->leave_sub();
1774 return $exchangerate;
1777 sub get_default_currency {
1778 $main::lxdebug->enter_sub();
1780 my ($self, $myconfig) = @_;
1781 my $dbh = $self->get_standard_dbh($myconfig);
1783 my $query = qq|SELECT curr FROM defaults|;
1785 my ($curr) = selectrow_query($self, $dbh, $query);
1786 my ($defaultcurrency) = split m/:/, $curr;
1788 $main::lxdebug->leave_sub();
1790 return $defaultcurrency;
1794 sub set_payment_options {
1795 $main::lxdebug->enter_sub();
1797 my ($self, $myconfig, $transdate) = @_;
1799 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1801 my $dbh = $self->get_standard_dbh($myconfig);
1804 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1805 qq|FROM payment_terms p | .
1808 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1809 $self->{payment_terms}) =
1810 selectrow_query($self, $dbh, $query, $self->{payment_id});
1812 if ($transdate eq "") {
1813 if ($self->{invdate}) {
1814 $transdate = $self->{invdate};
1816 $transdate = $self->{transdate};
1821 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1822 qq|FROM payment_terms|;
1823 ($self->{netto_date}, $self->{skonto_date}) =
1824 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1826 my ($invtotal, $total);
1827 my (%amounts, %formatted_amounts);
1829 if ($self->{type} =~ /_order$/) {
1830 $amounts{invtotal} = $self->{ordtotal};
1831 $amounts{total} = $self->{ordtotal};
1833 } elsif ($self->{type} =~ /_quotation$/) {
1834 $amounts{invtotal} = $self->{quototal};
1835 $amounts{total} = $self->{quototal};
1838 $amounts{invtotal} = $self->{invtotal};
1839 $amounts{total} = $self->{total};
1842 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1844 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1845 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1846 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1848 foreach (keys %amounts) {
1849 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1850 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1853 if ($self->{"language_id"}) {
1855 qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1856 qq|FROM translation_payment_terms t | .
1857 qq|LEFT JOIN language l ON t.language_id = l.id | .
1858 qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1859 my ($description_long, $output_numberformat, $output_dateformat,
1860 $output_longdates) =
1861 selectrow_query($self, $dbh, $query,
1862 $self->{"language_id"}, $self->{"payment_id"});
1864 $self->{payment_terms} = $description_long if ($description_long);
1866 if ($output_dateformat) {
1867 foreach my $key (qw(netto_date skonto_date)) {
1869 $main::locale->reformat_date($myconfig, $self->{$key},
1875 if ($output_numberformat &&
1876 ($output_numberformat ne $myconfig->{"numberformat"})) {
1877 my $saved_numberformat = $myconfig->{"numberformat"};
1878 $myconfig->{"numberformat"} = $output_numberformat;
1879 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1880 $myconfig->{"numberformat"} = $saved_numberformat;
1884 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1885 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1886 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1887 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1888 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1889 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1890 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1892 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1894 $main::lxdebug->leave_sub();
1898 sub get_template_language {
1899 $main::lxdebug->enter_sub();
1901 my ($self, $myconfig) = @_;
1903 my $template_code = "";
1905 if ($self->{language_id}) {
1906 my $dbh = $self->get_standard_dbh($myconfig);
1907 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1908 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1911 $main::lxdebug->leave_sub();
1913 return $template_code;
1916 sub get_printer_code {
1917 $main::lxdebug->enter_sub();
1919 my ($self, $myconfig) = @_;
1921 my $template_code = "";
1923 if ($self->{printer_id}) {
1924 my $dbh = $self->get_standard_dbh($myconfig);
1925 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1926 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1929 $main::lxdebug->leave_sub();
1931 return $template_code;
1935 $main::lxdebug->enter_sub();
1937 my ($self, $myconfig) = @_;
1939 my $template_code = "";
1941 if ($self->{shipto_id}) {
1942 my $dbh = $self->get_standard_dbh($myconfig);
1943 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1944 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1945 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1948 $main::lxdebug->leave_sub();
1952 $main::lxdebug->enter_sub();
1954 my ($self, $dbh, $id, $module) = @_;
1959 foreach my $item (qw(name department_1 department_2 street zipcode city country
1960 contact phone fax email)) {
1961 if ($self->{"shipto$item"}) {
1962 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1964 push(@values, $self->{"shipto${item}"});
1968 if ($self->{shipto_id}) {
1969 my $query = qq|UPDATE shipto set
1971 shiptodepartment_1 = ?,
1972 shiptodepartment_2 = ?,
1981 WHERE shipto_id = ?|;
1982 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1984 my $query = qq|SELECT * FROM shipto
1985 WHERE shiptoname = ? AND
1986 shiptodepartment_1 = ? AND
1987 shiptodepartment_2 = ? AND
1988 shiptostreet = ? AND
1989 shiptozipcode = ? AND
1991 shiptocountry = ? AND
1992 shiptocontact = ? AND
1998 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
2001 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
2002 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
2003 shiptocontact, shiptophone, shiptofax, shiptoemail, module)
2004 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
2005 do_query($self, $dbh, $query, $id, @values, $module);
2010 $main::lxdebug->leave_sub();
2014 $main::lxdebug->enter_sub();
2016 my ($self, $dbh) = @_;
2018 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2019 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2020 $self->{"employee_id"} *= 1;
2022 $main::lxdebug->leave_sub();
2025 sub get_employee_data {
2026 $main::lxdebug->enter_sub();
2031 Common::check_params(\%params, qw(prefix));
2032 Common::check_params_x(\%params, qw(id));
2035 $main::lxdebug->leave_sub();
2039 my $myconfig = \%main::myconfig;
2040 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
2042 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2045 my $user = User->new($login);
2046 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2048 $self->{$params{prefix} . '_login'} = $login;
2049 $self->{$params{prefix} . '_name'} ||= $login;
2052 $main::lxdebug->leave_sub();
2056 $main::lxdebug->enter_sub();
2058 my ($self, $myconfig, $reference_date) = @_;
2060 my $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2062 my $dbh = $self->get_standard_dbh($myconfig);
2063 my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2064 my ($duedate) = selectrow_query($self, $dbh, $query, $self->{payment_id});
2066 $main::lxdebug->leave_sub();
2072 $main::lxdebug->enter_sub();
2074 my ($self, $dbh, $id, $key) = @_;
2076 $key = "all_contacts" unless ($key);
2080 $main::lxdebug->leave_sub();
2085 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2086 qq|FROM contacts | .
2087 qq|WHERE cp_cv_id = ? | .
2088 qq|ORDER BY lower(cp_name)|;
2090 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2092 $main::lxdebug->leave_sub();
2096 $main::lxdebug->enter_sub();
2098 my ($self, $dbh, $key) = @_;
2100 my ($all, $old_id, $where, @values);
2102 if (ref($key) eq "HASH") {
2105 $key = "ALL_PROJECTS";
2107 foreach my $p (keys(%{$params})) {
2109 $all = $params->{$p};
2110 } elsif ($p eq "old_id") {
2111 $old_id = $params->{$p};
2112 } elsif ($p eq "key") {
2113 $key = $params->{$p};
2119 $where = "WHERE active ";
2121 if (ref($old_id) eq "ARRAY") {
2122 my @ids = grep({ $_ } @{$old_id});
2124 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2125 push(@values, @ids);
2128 $where .= " OR (id = ?) ";
2129 push(@values, $old_id);
2135 qq|SELECT id, projectnumber, description, active | .
2138 qq|ORDER BY lower(projectnumber)|;
2140 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2142 $main::lxdebug->leave_sub();
2146 $main::lxdebug->enter_sub();
2148 my ($self, $dbh, $vc_id, $key) = @_;
2150 $key = "all_shipto" unless ($key);
2153 # get shipping addresses
2154 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2156 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2162 $main::lxdebug->leave_sub();
2166 $main::lxdebug->enter_sub();
2168 my ($self, $dbh, $key) = @_;
2170 $key = "all_printers" unless ($key);
2172 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2174 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2176 $main::lxdebug->leave_sub();
2180 $main::lxdebug->enter_sub();
2182 my ($self, $dbh, $params) = @_;
2185 $key = $params->{key};
2186 $key = "all_charts" unless ($key);
2188 my $transdate = quote_db_date($params->{transdate});
2191 qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
2193 qq|LEFT JOIN taxkeys tk ON | .
2194 qq|(tk.id = (SELECT id FROM taxkeys | .
2195 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2196 qq| ORDER BY startdate DESC LIMIT 1)) | .
2197 qq|ORDER BY c.accno|;
2199 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2201 $main::lxdebug->leave_sub();
2204 sub _get_taxcharts {
2205 $main::lxdebug->enter_sub();
2207 my ($self, $dbh, $params) = @_;
2209 my $key = "all_taxcharts";
2212 if (ref $params eq 'HASH') {
2213 $key = $params->{key} if ($params->{key});
2214 if ($params->{module} eq 'AR') {
2215 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2217 } elsif ($params->{module} eq 'AP') {
2218 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2225 my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2227 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2229 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2231 $main::lxdebug->leave_sub();
2235 $main::lxdebug->enter_sub();
2237 my ($self, $dbh, $key) = @_;
2239 $key = "all_taxzones" unless ($key);
2241 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2243 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2245 $main::lxdebug->leave_sub();
2248 sub _get_employees {
2249 $main::lxdebug->enter_sub();
2251 my ($self, $dbh, $default_key, $key) = @_;
2253 $key = $default_key unless ($key);
2254 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2256 $main::lxdebug->leave_sub();
2259 sub _get_business_types {
2260 $main::lxdebug->enter_sub();
2262 my ($self, $dbh, $key) = @_;
2264 $key = "all_business_types" unless ($key);
2266 selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2268 $main::lxdebug->leave_sub();
2271 sub _get_languages {
2272 $main::lxdebug->enter_sub();
2274 my ($self, $dbh, $key) = @_;
2276 $key = "all_languages" unless ($key);
2278 my $query = qq|SELECT * FROM language ORDER BY id|;
2280 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2282 $main::lxdebug->leave_sub();
2285 sub _get_dunning_configs {
2286 $main::lxdebug->enter_sub();
2288 my ($self, $dbh, $key) = @_;
2290 $key = "all_dunning_configs" unless ($key);
2292 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2294 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2296 $main::lxdebug->leave_sub();
2299 sub _get_currencies {
2300 $main::lxdebug->enter_sub();
2302 my ($self, $dbh, $key) = @_;
2304 $key = "all_currencies" unless ($key);
2306 my $query = qq|SELECT curr AS currency FROM defaults|;
2308 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2310 $main::lxdebug->leave_sub();
2314 $main::lxdebug->enter_sub();
2316 my ($self, $dbh, $key) = @_;
2318 $key = "all_payments" unless ($key);
2320 my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2322 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2324 $main::lxdebug->leave_sub();
2327 sub _get_customers {
2328 $main::lxdebug->enter_sub();
2330 my ($self, $dbh, $key, $limit) = @_;
2332 $key = "all_customers" unless ($key);
2333 my $limit_clause = "LIMIT $limit" if $limit;
2335 my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2337 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2339 $main::lxdebug->leave_sub();
2343 $main::lxdebug->enter_sub();
2345 my ($self, $dbh, $key) = @_;
2347 $key = "all_vendors" unless ($key);
2349 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2351 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2353 $main::lxdebug->leave_sub();
2356 sub _get_departments {
2357 $main::lxdebug->enter_sub();
2359 my ($self, $dbh, $key) = @_;
2361 $key = "all_departments" unless ($key);
2363 my $query = qq|SELECT * FROM department ORDER BY description|;
2365 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2367 $main::lxdebug->leave_sub();
2370 sub _get_warehouses {
2371 $main::lxdebug->enter_sub();
2373 my ($self, $dbh, $param) = @_;
2375 my ($key, $bins_key);
2377 if ('' eq ref $param) {
2381 $key = $param->{key};
2382 $bins_key = $param->{bins};
2385 my $query = qq|SELECT w.* FROM warehouse w
2386 WHERE (NOT w.invalid) AND
2387 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2388 ORDER BY w.sortkey|;
2390 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2393 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2394 my $sth = prepare_query($self, $dbh, $query);
2396 foreach my $warehouse (@{ $self->{$key} }) {
2397 do_statement($self, $sth, $query, $warehouse->{id});
2398 $warehouse->{$bins_key} = [];
2400 while (my $ref = $sth->fetchrow_hashref()) {
2401 push @{ $warehouse->{$bins_key} }, $ref;
2407 $main::lxdebug->leave_sub();
2411 $main::lxdebug->enter_sub();
2413 my ($self, $dbh, $table, $key, $sortkey) = @_;
2415 my $query = qq|SELECT * FROM $table|;
2416 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2418 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2420 $main::lxdebug->leave_sub();
2424 # $main::lxdebug->enter_sub();
2426 # my ($self, $dbh, $key) = @_;
2428 # $key ||= "all_groups";
2430 # my $groups = $main::auth->read_groups();
2432 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2434 # $main::lxdebug->leave_sub();
2438 $main::lxdebug->enter_sub();
2443 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2444 my ($sth, $query, $ref);
2446 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2447 my $vc_id = $self->{"${vc}_id"};
2449 if ($params{"contacts"}) {
2450 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2453 if ($params{"shipto"}) {
2454 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2457 if ($params{"projects"} || $params{"all_projects"}) {
2458 $self->_get_projects($dbh, $params{"all_projects"} ?
2459 $params{"all_projects"} : $params{"projects"},
2460 $params{"all_projects"} ? 1 : 0);
2463 if ($params{"printers"}) {
2464 $self->_get_printers($dbh, $params{"printers"});
2467 if ($params{"languages"}) {
2468 $self->_get_languages($dbh, $params{"languages"});
2471 if ($params{"charts"}) {
2472 $self->_get_charts($dbh, $params{"charts"});
2475 if ($params{"taxcharts"}) {
2476 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2479 if ($params{"taxzones"}) {
2480 $self->_get_taxzones($dbh, $params{"taxzones"});
2483 if ($params{"employees"}) {
2484 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2487 if ($params{"salesmen"}) {
2488 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2491 if ($params{"business_types"}) {
2492 $self->_get_business_types($dbh, $params{"business_types"});
2495 if ($params{"dunning_configs"}) {
2496 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2499 if($params{"currencies"}) {
2500 $self->_get_currencies($dbh, $params{"currencies"});
2503 if($params{"customers"}) {
2504 if (ref $params{"customers"} eq 'HASH') {
2505 $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2507 $self->_get_customers($dbh, $params{"customers"});
2511 if($params{"vendors"}) {
2512 if (ref $params{"vendors"} eq 'HASH') {
2513 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2515 $self->_get_vendors($dbh, $params{"vendors"});
2519 if($params{"payments"}) {
2520 $self->_get_payments($dbh, $params{"payments"});
2523 if($params{"departments"}) {
2524 $self->_get_departments($dbh, $params{"departments"});
2527 if ($params{price_factors}) {
2528 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2531 if ($params{warehouses}) {
2532 $self->_get_warehouses($dbh, $params{warehouses});
2535 # if ($params{groups}) {
2536 # $self->_get_groups($dbh, $params{groups});
2539 if ($params{partsgroup}) {
2540 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2543 $main::lxdebug->leave_sub();
2546 # this sub gets the id and name from $table
2548 $main::lxdebug->enter_sub();
2550 my ($self, $myconfig, $table) = @_;
2552 # connect to database
2553 my $dbh = $self->get_standard_dbh($myconfig);
2555 $table = $table eq "customer" ? "customer" : "vendor";
2556 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2558 my ($query, @values);
2560 if (!$self->{openinvoices}) {
2562 if ($self->{customernumber} ne "") {
2563 $where = qq|(vc.customernumber ILIKE ?)|;
2564 push(@values, '%' . $self->{customernumber} . '%');
2566 $where = qq|(vc.name ILIKE ?)|;
2567 push(@values, '%' . $self->{$table} . '%');
2571 qq~SELECT vc.id, vc.name,
2572 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2574 WHERE $where AND (NOT vc.obsolete)
2578 qq~SELECT DISTINCT vc.id, vc.name,
2579 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2581 JOIN $table vc ON (a.${table}_id = vc.id)
2582 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2584 push(@values, '%' . $self->{$table} . '%');
2587 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2589 $main::lxdebug->leave_sub();
2591 return scalar(@{ $self->{name_list} });
2594 # the selection sub is used in the AR, AP, IS, IR and OE module
2597 $main::lxdebug->enter_sub();
2599 my ($self, $myconfig, $table, $module) = @_;
2602 my $dbh = $self->get_standard_dbh($myconfig);
2604 $table = $table eq "customer" ? "customer" : "vendor";
2606 my $query = qq|SELECT count(*) FROM $table|;
2607 my ($count) = selectrow_query($self, $dbh, $query);
2609 # build selection list
2610 if ($count < $myconfig->{vclimit}) {
2611 $query = qq|SELECT id, name, salesman_id
2612 FROM $table WHERE NOT obsolete
2614 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2618 $self->get_employee($dbh);
2620 # setup sales contacts
2621 $query = qq|SELECT e.id, e.name
2623 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2624 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2627 push(@{ $self->{all_employees} },
2628 { id => $self->{employee_id},
2629 name => $self->{employee} });
2631 # sort the whole thing
2632 @{ $self->{all_employees} } =
2633 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2635 if ($module eq 'AR') {
2637 # prepare query for departments
2638 $query = qq|SELECT id, description
2641 ORDER BY description|;
2644 $query = qq|SELECT id, description
2646 ORDER BY description|;
2649 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2652 $query = qq|SELECT id, description
2656 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2659 $query = qq|SELECT printer_description, id
2661 ORDER BY printer_description|;
2663 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2666 $query = qq|SELECT id, description
2670 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2672 $main::lxdebug->leave_sub();
2675 sub language_payment {
2676 $main::lxdebug->enter_sub();
2678 my ($self, $myconfig) = @_;
2680 my $dbh = $self->get_standard_dbh($myconfig);
2682 my $query = qq|SELECT id, description
2686 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2689 $query = qq|SELECT printer_description, id
2691 ORDER BY printer_description|;
2693 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2696 $query = qq|SELECT id, description
2700 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2702 # get buchungsgruppen
2703 $query = qq|SELECT id, description
2704 FROM buchungsgruppen|;
2706 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2708 $main::lxdebug->leave_sub();
2711 # this is only used for reports
2712 sub all_departments {
2713 $main::lxdebug->enter_sub();
2715 my ($self, $myconfig, $table) = @_;
2717 my $dbh = $self->get_standard_dbh($myconfig);
2720 if ($table eq 'customer') {
2721 $where = "WHERE role = 'P' ";
2724 my $query = qq|SELECT id, description
2727 ORDER BY description|;
2728 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2730 delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2732 $main::lxdebug->leave_sub();
2736 $main::lxdebug->enter_sub();
2738 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2741 if ($table eq "customer") {
2750 $self->all_vc($myconfig, $table, $module);
2752 # get last customers or vendors
2753 my ($query, $sth, $ref);
2755 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2760 my $transdate = "current_date";
2761 if ($self->{transdate}) {
2762 $transdate = $dbh->quote($self->{transdate});
2765 # now get the account numbers
2766 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2767 FROM chart c, taxkeys tk
2768 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2769 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2772 $sth = $dbh->prepare($query);
2774 do_statement($self, $sth, $query, '%' . $module . '%');
2776 $self->{accounts} = "";
2777 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2779 foreach my $key (split(/:/, $ref->{link})) {
2780 if ($key =~ /\Q$module\E/) {
2782 # cross reference for keys
2783 $xkeyref{ $ref->{accno} } = $key;
2785 push @{ $self->{"${module}_links"}{$key} },
2786 { accno => $ref->{accno},
2787 description => $ref->{description},
2788 taxkey => $ref->{taxkey_id},
2789 tax_id => $ref->{tax_id} };
2791 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2797 # get taxkeys and description
2798 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2799 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2801 if (($module eq "AP") || ($module eq "AR")) {
2802 # get tax rates and description
2803 $query = qq|SELECT * FROM tax|;
2804 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2810 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2811 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2812 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2813 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2815 d.description AS department,
2818 JOIN $table c ON (a.${table}_id = c.id)
2819 LEFT JOIN employee e ON (e.id = a.employee_id)
2820 LEFT JOIN department d ON (d.id = a.department_id)
2822 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2824 foreach my $key (keys %$ref) {
2825 $self->{$key} = $ref->{$key};
2828 my $transdate = "current_date";
2829 if ($self->{transdate}) {
2830 $transdate = $dbh->quote($self->{transdate});
2833 # now get the account numbers
2834 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2836 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2838 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2839 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2842 $sth = $dbh->prepare($query);
2843 do_statement($self, $sth, $query, "%$module%");
2845 $self->{accounts} = "";
2846 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2848 foreach my $key (split(/:/, $ref->{link})) {
2849 if ($key =~ /\Q$module\E/) {
2851 # cross reference for keys
2852 $xkeyref{ $ref->{accno} } = $key;
2854 push @{ $self->{"${module}_links"}{$key} },
2855 { accno => $ref->{accno},
2856 description => $ref->{description},
2857 taxkey => $ref->{taxkey_id},
2858 tax_id => $ref->{tax_id} };
2860 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2866 # get amounts from individual entries
2869 c.accno, c.description,
2870 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2874 LEFT JOIN chart c ON (c.id = a.chart_id)
2875 LEFT JOIN project p ON (p.id = a.project_id)
2876 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2877 WHERE (tk.taxkey_id=a.taxkey) AND
2878 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2879 THEN tk.chart_id = a.chart_id
2882 OR (c.link='%tax%')) AND
2883 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2884 WHERE a.trans_id = ?
2885 AND a.fx_transaction = '0'
2886 ORDER BY a.acc_trans_id, a.transdate|;
2887 $sth = $dbh->prepare($query);
2888 do_statement($self, $sth, $query, $self->{id});
2890 # get exchangerate for currency
2891 $self->{exchangerate} =
2892 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2895 # store amounts in {acc_trans}{$key} for multiple accounts
2896 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2897 $ref->{exchangerate} =
2898 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2899 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2902 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2903 $ref->{amount} *= -1;
2905 $ref->{index} = $index;
2907 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2913 d.curr AS currencies, d.closedto, d.revtrans,
2914 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2915 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2917 $ref = selectfirst_hashref_query($self, $dbh, $query);
2918 map { $self->{$_} = $ref->{$_} } keys %$ref;
2925 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2926 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2927 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2929 $ref = selectfirst_hashref_query($self, $dbh, $query);
2930 map { $self->{$_} = $ref->{$_} } keys %$ref;
2932 if ($self->{"$self->{vc}_id"}) {
2934 # only setup currency
2935 ($self->{currency}) = split(/:/, $self->{currencies});
2939 $self->lastname_used($dbh, $myconfig, $table, $module);
2941 # get exchangerate for currency
2942 $self->{exchangerate} =
2943 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2949 $main::lxdebug->leave_sub();
2953 $main::lxdebug->enter_sub();
2955 my ($self, $dbh, $myconfig, $table, $module) = @_;
2959 $table = $table eq "customer" ? "customer" : "vendor";
2960 my %column_map = ("a.curr" => "currency",
2961 "a.${table}_id" => "${table}_id",
2962 "a.department_id" => "department_id",
2963 "d.description" => "department",
2964 "ct.name" => $table,
2965 "current_date + ct.terms" => "duedate",
2968 if ($self->{type} =~ /delivery_order/) {
2969 $arap = 'delivery_orders';
2970 delete $column_map{"a.curr"};
2972 } elsif ($self->{type} =~ /_order/) {
2974 $where = "quotation = '0'";
2976 } elsif ($self->{type} =~ /_quotation/) {
2978 $where = "quotation = '1'";
2980 } elsif ($table eq 'customer') {
2988 $where = "($where) AND" if ($where);
2989 my $query = qq|SELECT MAX(id) FROM $arap
2990 WHERE $where ${table}_id > 0|;
2991 my ($trans_id) = selectrow_query($self, $dbh, $query);
2994 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2995 $query = qq|SELECT $column_spec
2997 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2998 LEFT JOIN department d ON (a.department_id = d.id)
3000 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3002 map { $self->{$_} = $ref->{$_} } values %column_map;
3004 $main::lxdebug->leave_sub();
3008 $main::lxdebug->enter_sub();
3010 my ($self, $myconfig, $thisdate, $days) = @_;
3012 my $dbh = $self->get_standard_dbh($myconfig);
3017 my $dateformat = $myconfig->{dateformat};
3018 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3019 $thisdate = $dbh->quote($thisdate);
3020 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3022 $query = qq|SELECT current_date AS thisdate|;
3025 ($thisdate) = selectrow_query($self, $dbh, $query);
3027 $main::lxdebug->leave_sub();
3033 $main::lxdebug->enter_sub();
3035 my ($self, $string) = @_;
3037 if ($string !~ /%/) {
3038 $string = "%$string%";
3041 $string =~ s/\'/\'\'/g;
3043 $main::lxdebug->leave_sub();
3049 $main::lxdebug->enter_sub();
3051 my ($self, $flds, $new, $count, $numrows) = @_;
3055 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3060 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3062 my $j = $item->{ndx} - 1;
3063 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3067 for $i ($count + 1 .. $numrows) {
3068 map { delete $self->{"${_}_$i"} } @{$flds};
3071 $main::lxdebug->leave_sub();
3075 $main::lxdebug->enter_sub();
3077 my ($self, $myconfig) = @_;
3081 my $dbh = $self->dbconnect_noauto($myconfig);
3083 my $query = qq|DELETE FROM status
3084 WHERE (formname = ?) AND (trans_id = ?)|;
3085 my $sth = prepare_query($self, $dbh, $query);
3087 if ($self->{formname} =~ /(check|receipt)/) {
3088 for $i (1 .. $self->{rowcount}) {
3089 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3092 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3096 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3097 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3099 my %queued = split / /, $self->{queued};
3102 if ($self->{formname} =~ /(check|receipt)/) {
3104 # this is a check or receipt, add one entry for each lineitem
3105 my ($accno) = split /--/, $self->{account};
3106 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3107 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3108 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3109 $sth = prepare_query($self, $dbh, $query);
3111 for $i (1 .. $self->{rowcount}) {
3112 if ($self->{"checked_$i"}) {
3113 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3119 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3120 VALUES (?, ?, ?, ?, ?)|;
3121 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3122 $queued{$self->{formname}}, $self->{formname});
3128 $main::lxdebug->leave_sub();
3132 $main::lxdebug->enter_sub();
3134 my ($self, $dbh) = @_;
3136 my ($query, $printed, $emailed);
3138 my $formnames = $self->{printed};
3139 my $emailforms = $self->{emailed};
3141 $query = qq|DELETE FROM status
3142 WHERE (formname = ?) AND (trans_id = ?)|;
3143 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3145 # this only applies to the forms
3146 # checks and receipts are posted when printed or queued
3148 if ($self->{queued}) {
3149 my %queued = split / /, $self->{queued};
3151 foreach my $formname (keys %queued) {
3152 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3153 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3155 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3156 VALUES (?, ?, ?, ?, ?)|;
3157 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3159 $formnames =~ s/\Q$self->{formname}\E//;
3160 $emailforms =~ s/\Q$self->{formname}\E//;
3165 # save printed, emailed info
3166 $formnames =~ s/^ +//g;
3167 $emailforms =~ s/^ +//g;
3170 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3171 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3173 foreach my $formname (keys %status) {
3174 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3175 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3177 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3178 VALUES (?, ?, ?, ?)|;
3179 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3182 $main::lxdebug->leave_sub();
3186 # $main::locale->text('SAVED')
3187 # $main::locale->text('DELETED')
3188 # $main::locale->text('ADDED')
3189 # $main::locale->text('PAYMENT POSTED')
3190 # $main::locale->text('POSTED')
3191 # $main::locale->text('POSTED AS NEW')
3192 # $main::locale->text('ELSE')
3193 # $main::locale->text('SAVED FOR DUNNING')
3194 # $main::locale->text('DUNNING STARTED')
3195 # $main::locale->text('PRINTED')
3196 # $main::locale->text('MAILED')
3197 # $main::locale->text('SCREENED')
3198 # $main::locale->text('CANCELED')
3199 # $main::locale->text('invoice')
3200 # $main::locale->text('proforma')
3201 # $main::locale->text('sales_order')
3202 # $main::locale->text('packing_list')
3203 # $main::locale->text('pick_list')
3204 # $main::locale->text('purchase_order')
3205 # $main::locale->text('bin_list')
3206 # $main::locale->text('sales_quotation')
3207 # $main::locale->text('request_quotation')
3210 $main::lxdebug->enter_sub();
3215 if(!exists $self->{employee_id}) {
3216 &get_employee($self, $dbh);
3220 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3221 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3222 my @values = (conv_i($self->{id}), $self->{login},
3223 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3224 do_query($self, $dbh, $query, @values);
3226 $main::lxdebug->leave_sub();
3230 $main::lxdebug->enter_sub();
3232 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3233 my ($orderBy, $desc) = split(/\-\-/, $order);
3234 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3237 if ($trans_id ne "") {
3239 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 | .
3240 qq|FROM history_erp h | .
3241 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3242 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3245 my $sth = $dbh->prepare($query) || $self->dberror($query);
3247 $sth->execute() || $self->dberror("$query");
3249 while(my $hash_ref = $sth->fetchrow_hashref()) {
3250 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3251 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3252 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3253 $tempArray[$i++] = $hash_ref;
3255 $main::lxdebug->leave_sub() and return \@tempArray
3256 if ($i > 0 && $tempArray[0] ne "");
3258 $main::lxdebug->leave_sub();
3262 sub update_defaults {
3263 $main::lxdebug->enter_sub();
3265 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3268 if ($provided_dbh) {
3269 $dbh = $provided_dbh;
3271 $dbh = $self->dbconnect_noauto($myconfig);
3273 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3274 my $sth = $dbh->prepare($query);
3276 $sth->execute || $self->dberror($query);
3277 my ($var) = $sth->fetchrow_array;
3280 if ($var =~ m/\d+$/) {
3281 my $new_var = (substr $var, $-[0]) * 1 + 1;
3282 my $len_diff = length($var) - $-[0] - length($new_var);
3283 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3289 $query = qq|UPDATE defaults SET $fld = ?|;
3290 do_query($self, $dbh, $query, $var);
3292 if (!$provided_dbh) {
3297 $main::lxdebug->leave_sub();
3302 =item update_business
3305 \%config, - config hashref
3306 $business_id, - business id
3307 $dbh - optional database handle
3309 handles business (thats customer/vendor types) sequences.
3311 special behaviour for empty strings in customerinitnumber field:
3312 will in this case not increase the value, and return undef.
3315 sub update_business {
3316 $main::lxdebug->enter_sub();
3318 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3321 if ($provided_dbh) {
3322 $dbh = $provided_dbh;
3324 $dbh = $self->dbconnect_noauto($myconfig);
3327 qq|SELECT customernumberinit FROM business
3328 WHERE id = ? FOR UPDATE|;
3329 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3331 return undef unless $var;
3333 if ($var =~ m/\d+$/) {
3334 my $new_var = (substr $var, $-[0]) * 1 + 1;
3335 my $len_diff = length($var) - $-[0] - length($new_var);
3336 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3342 $query = qq|UPDATE business
3343 SET customernumberinit = ?
3345 do_query($self, $dbh, $query, $var, $business_id);
3347 if (!$provided_dbh) {
3352 $main::lxdebug->leave_sub();
3357 sub get_partsgroup {
3358 $main::lxdebug->enter_sub();
3360 my ($self, $myconfig, $p) = @_;
3361 my $target = $p->{target} || 'all_partsgroup';
3363 my $dbh = $self->get_standard_dbh($myconfig);
3365 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3367 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3370 if ($p->{searchitems} eq 'part') {
3371 $query .= qq|WHERE p.inventory_accno_id > 0|;
3373 if ($p->{searchitems} eq 'service') {
3374 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3376 if ($p->{searchitems} eq 'assembly') {
3377 $query .= qq|WHERE p.assembly = '1'|;
3379 if ($p->{searchitems} eq 'labor') {
3380 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3383 $query .= qq|ORDER BY partsgroup|;
3386 $query = qq|SELECT id, partsgroup FROM partsgroup
3387 ORDER BY partsgroup|;
3390 if ($p->{language_code}) {
3391 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3392 t.description AS translation
3394 JOIN parts p ON (p.partsgroup_id = pg.id)
3395 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3396 ORDER BY translation|;
3397 @values = ($p->{language_code});
3400 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3402 $main::lxdebug->leave_sub();
3405 sub get_pricegroup {
3406 $main::lxdebug->enter_sub();
3408 my ($self, $myconfig, $p) = @_;
3410 my $dbh = $self->get_standard_dbh($myconfig);
3412 my $query = qq|SELECT p.id, p.pricegroup
3415 $query .= qq| ORDER BY pricegroup|;
3418 $query = qq|SELECT id, pricegroup FROM pricegroup
3419 ORDER BY pricegroup|;
3422 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3424 $main::lxdebug->leave_sub();
3428 # usage $form->all_years($myconfig, [$dbh])
3429 # return list of all years where bookings found
3432 $main::lxdebug->enter_sub();
3434 my ($self, $myconfig, $dbh) = @_;
3436 $dbh ||= $self->get_standard_dbh($myconfig);
3439 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3440 (SELECT MAX(transdate) FROM acc_trans)|;
3441 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3443 if ($myconfig->{dateformat} =~ /^yy/) {
3444 ($startdate) = split /\W/, $startdate;
3445 ($enddate) = split /\W/, $enddate;
3447 (@_) = split /\W/, $startdate;
3449 (@_) = split /\W/, $enddate;
3454 $startdate = substr($startdate,0,4);
3455 $enddate = substr($enddate,0,4);
3457 while ($enddate >= $startdate) {
3458 push @all_years, $enddate--;
3463 $main::lxdebug->leave_sub();
3467 $main::lxdebug->enter_sub();
3471 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3473 $main::lxdebug->leave_sub();
3477 $main::lxdebug->enter_sub();
3482 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3484 $main::lxdebug->leave_sub();