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();
71 $main::lxdebug->enter_sub(2);
77 while ($key =~ /\[\+?\]\.|\./) {
78 substr($key, 0, $+[0]) = '';
86 if (!scalar @{ $curr->{$`} } || $& eq '[+].') {
87 push @{ $curr->{$`} }, { };
90 $curr = $curr->{$`}->[-1];
94 $curr->{$key} = $value;
96 $main::lxdebug->leave_sub(2);
98 return \$curr->{$key};
102 $main::lxdebug->enter_sub(2);
107 my @pairs = split(/&/, $input);
110 my ($key, $value) = split(/=/, $_, 2);
111 _store_value($params, unescape(undef, $key), unescape(undef, $value));
114 $main::lxdebug->leave_sub(2);
117 sub _request_to_hash {
118 $main::lxdebug->enter_sub(2);
123 if (!$ENV{'CONTENT_TYPE'}
124 || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
126 _input_to_hash($params, $input);
128 $main::lxdebug->leave_sub(2);
132 my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
134 my $boundary = '--' . $1;
136 foreach my $line (split m/\n/, $input) {
137 last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
139 if (($line eq $boundary) || ($line eq "$boundary\r")) {
140 ${ $previous } =~ s|\r?\n$|| if $previous;
146 $content_type = "text/plain";
153 next unless $boundary_found;
155 if (!$headers_done) {
156 $line =~ s/[\r\n]*$//;
163 if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
164 if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
166 substr $line, $-[0], $+[0] - $-[0], "";
169 if ($line =~ m|name\s*=\s*"(.*?)"|i) {
171 substr $line, $-[0], $+[0] - $-[0], "";
174 $previous = _store_value($params, $name, '');
175 $params->{FILENAME} = $filename if ($filename);
180 if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
187 next unless $previous;
189 ${ $previous } .= "${line}\n";
192 ${ $previous } =~ s|\r?\n$|| if $previous;
194 $main::lxdebug->leave_sub(2);
197 sub _recode_recursively {
198 my ($iconv, $param) = @_;
200 if (ref $param eq 'HASH') {
201 foreach my $key (keys %{ $param }) {
202 if (!ref $param->{$key}) {
203 $param->{$key} = $iconv->convert($param->{$key});
205 _recode_recursively($iconv, $param->{$key});
209 } elsif (ref $param eq 'ARRAY') {
210 foreach my $idx (0 .. scalar(@{ $param }) - 1) {
211 if (!ref $param->[$idx]) {
212 $param->[$idx] = $iconv->convert($param->[$idx]);
214 _recode_recursively($iconv, $param->[$idx]);
221 $main::lxdebug->enter_sub();
227 if ($LXDebug::watch_form) {
228 require SL::Watchdog;
229 tie %{ $self }, 'SL::Watchdog';
232 read(STDIN, $_, $ENV{CONTENT_LENGTH});
234 if ($ENV{QUERY_STRING}) {
235 $_ = $ENV{QUERY_STRING};
244 my $parameters = { };
245 _request_to_hash($parameters, $_);
247 my $db_charset = $main::dbcharset;
248 $db_charset ||= Common::DEFAULT_CHARSET;
250 if ($parameters->{INPUT_ENCODING} && (lc $parameters->{INPUT_ENCODING} ne $db_charset)) {
252 my $iconv = Text::Iconv->new($parameters->{INPUT_ENCODING}, $db_charset);
254 _recode_recursively($iconv, $parameters);
256 delete $parameters{INPUT_ENCODING};
259 map { $self->{$_} = $parameters->{$_}; } keys %{ $parameters };
261 $self->{action} = lc $self->{action};
262 $self->{action} =~ s/( |-|,|\#)/_/g;
264 $self->{version} = "2.6.0 beta 1";
266 $main::lxdebug->leave_sub();
271 sub _flatten_variables_rec {
272 $main::lxdebug->enter_sub(2);
281 if ('' eq ref $curr->{$key}) {
282 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
284 } elsif ('HASH' eq ref $curr->{$key}) {
285 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
286 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
290 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
291 my $first_array_entry = 1;
293 foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
294 push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
295 $first_array_entry = 0;
300 $main::lxdebug->leave_sub(2);
305 sub flatten_variables {
306 $main::lxdebug->enter_sub(2);
314 push @variables, $self->_flatten_variables_rec($self, '', $_);
317 $main::lxdebug->leave_sub(2);
322 sub flatten_standard_variables {
323 $main::lxdebug->enter_sub(2);
326 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
330 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
331 push @variables, $self->_flatten_variables_rec($self, '', $_);
334 $main::lxdebug->leave_sub(2);
340 $main::lxdebug->enter_sub();
346 map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
348 $main::lxdebug->leave_sub();
352 $main::lxdebug->enter_sub(2);
355 my $password = $self->{password};
357 $self->{password} = 'X' x 8;
359 local $Data::Dumper::Sortkeys = 1;
360 my $output = Dumper($self);
362 $self->{password} = $password;
364 $main::lxdebug->leave_sub(2);
370 $main::lxdebug->enter_sub(2);
372 my ($self, $str) = @_;
374 $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
376 $main::lxdebug->leave_sub(2);
382 $main::lxdebug->enter_sub(2);
384 my ($self, $str) = @_;
389 $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
391 $main::lxdebug->leave_sub(2);
397 my ($self, $str) = @_;
399 if ($str && !ref($str)) {
400 $str =~ s/\"/"/g;
408 my ($self, $str) = @_;
410 if ($str && !ref($str)) {
411 $str =~ s/"/\"/g;
422 map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
424 for (sort keys %$self) {
425 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
426 print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
433 $main::lxdebug->enter_sub();
435 $main::lxdebug->show_backtrace();
437 my ($self, $msg) = @_;
438 if ($ENV{HTTP_USER_AGENT}) {
440 $self->show_generic_error($msg);
447 $main::lxdebug->leave_sub();
451 $main::lxdebug->enter_sub();
453 my ($self, $msg) = @_;
455 if ($ENV{HTTP_USER_AGENT}) {
458 if (!$self->{header}) {
471 if ($self->{info_function}) {
472 &{ $self->{info_function} }($msg);
478 $main::lxdebug->leave_sub();
481 # calculates the number of rows in a textarea based on the content and column number
482 # can be capped with maxrows
484 $main::lxdebug->enter_sub();
485 my ($self, $str, $cols, $maxrows, $minrows) = @_;
489 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
492 $main::lxdebug->leave_sub();
494 return max(min($rows, $maxrows), $minrows);
498 $main::lxdebug->enter_sub();
500 my ($self, $msg) = @_;
502 $self->error("$msg\n" . $DBI::errstr);
504 $main::lxdebug->leave_sub();
508 $main::lxdebug->enter_sub();
510 my ($self, $name, $msg) = @_;
513 foreach my $part (split m/\./, $name) {
514 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
517 $curr = $curr->{$part};
520 $main::lxdebug->leave_sub();
523 sub create_http_response {
524 $main::lxdebug->enter_sub();
529 my $cgi = $main::cgi;
530 $cgi ||= CGI->new('');
534 if ($ENV{HTTP_X_FORWARDED_FOR}) {
535 $base_path = $ENV{HTTP_REFERER};
536 $base_path =~ s|^.*?://.*?/|/|;
538 $base_path = $ENV{REQUEST_URI};
540 $base_path =~ s|[^/]+$||;
541 $base_path =~ s|/$||;
544 if (defined $main::auth) {
545 my $session_cookie_value = $main::auth->get_session_id();
546 $session_cookie_value ||= 'NO_SESSION';
548 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
549 '-value' => $session_cookie_value,
550 '-path' => $base_path);
553 my %cgi_params = ('-type' => $params{content_type});
554 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
556 my $output = $cgi->header('-cookie' => $session_cookie,
559 $main::lxdebug->leave_sub();
566 $main::lxdebug->enter_sub();
568 my ($self, $extra_code) = @_;
570 if ($self->{header}) {
571 $main::lxdebug->leave_sub();
575 my ($stylesheet, $favicon, $pagelayout);
577 if ($ENV{HTTP_USER_AGENT}) {
580 if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
581 # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
582 $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
585 my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
587 $stylesheets =~ s|^\s*||;
588 $stylesheets =~ s|\s*$||;
589 foreach my $file (split m/\s+/, $stylesheets) {
591 next if (! -f "css/$file");
593 $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
596 $self->{favicon} = "favicon.ico" unless $self->{favicon};
598 if ($self->{favicon} && (-f "$self->{favicon}")) {
600 qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
604 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
606 if ($self->{landscape}) {
607 $pagelayout = qq|<style type="text/css">
608 \@page { size:landscape; }
612 my $fokus = qq| document.$self->{fokus}.focus();| if ($self->{"fokus"});
616 if ($self->{jsscript} == 1) {
619 <script type="text/javascript" src="js/common.js"></script>
620 <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
621 <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
622 <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
623 <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
630 ? "$self->{title} - $self->{titlebar}"
633 foreach my $item (@ { $self->{AJAX} }) {
634 $ajax .= $item->show_javascript();
637 print $self->create_http_response('content_type' => 'text/html',
638 'charset' => $db_charset,);
639 print qq|${doctype}<html>
641 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
642 <title>$self->{titlebar}</title>
649 <script type="text/javascript">
657 <meta name="robots" content="noindex,nofollow" />
658 <script type="text/javascript" src="js/highlight_input.js"></script>
660 <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
661 <script type="text/javascript" src="js/tabcontent.js">
663 /***********************************************
664 * Tab Content script v2.2- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
665 * This notice MUST stay intact for legal use
666 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
667 ***********************************************/
678 $main::lxdebug->leave_sub();
681 sub ajax_response_header {
682 $main::lxdebug->enter_sub();
686 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
687 my $cgi = $main::cgi || CGI->new('');
688 my $output = $cgi->header('-charset' => $db_charset);
690 $main::lxdebug->leave_sub();
695 sub _prepare_html_template {
696 $main::lxdebug->enter_sub();
698 my ($self, $file, $additional_params) = @_;
701 if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
702 $language = $main::language;
704 $language = $main::myconfig{"countrycode"};
706 $language = "de" unless ($language);
708 if (-f "templates/webpages/${file}_${language}.html") {
709 if ((-f ".developer") &&
710 (-f "templates/webpages/${file}_master.html") &&
711 ((stat("templates/webpages/${file}_master.html"))[9] >
712 (stat("templates/webpages/${file}_${language}.html"))[9])) {
713 my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
714 "Please re-run 'locales.pl' in 'locale/${language}'.";
715 print(qq|<pre>$info</pre>|);
719 $file = "templates/webpages/${file}_${language}.html";
720 } elsif (-f "templates/webpages/${file}.html") {
721 $file = "templates/webpages/${file}.html";
723 my $info = "Web page template '${file}' not found.\n" .
724 "Please re-run 'locales.pl' in 'locale/${language}'.";
725 print(qq|<pre>$info</pre>|);
729 if ($self->{"DEBUG"}) {
730 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
733 if ($additional_params->{"DEBUG"}) {
734 $additional_params->{"DEBUG"} =
735 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
738 if (%main::myconfig) {
739 map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
740 my $jsc_dateformat = $main::myconfig{"dateformat"};
741 $jsc_dateformat =~ s/d+/\%d/gi;
742 $jsc_dateformat =~ s/m+/\%m/gi;
743 $jsc_dateformat =~ s/y+/\%Y/gi;
744 $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
747 $additional_params->{"conf_dbcharset"} = $main::dbcharset;
748 $additional_params->{"conf_webdav"} = $main::webdav;
749 $additional_params->{"conf_lizenzen"} = $main::lizenzen;
750 $additional_params->{"conf_latex_templates"} = $main::latex;
751 $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
753 if (%main::debug_options) {
754 map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
757 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
758 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
759 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
763 $main::lxdebug->leave_sub();
768 sub parse_html_template {
769 $main::lxdebug->enter_sub();
771 my ($self, $file, $additional_params) = @_;
773 $additional_params ||= { };
775 $file = $self->_prepare_html_template($file, $additional_params);
777 my $template = Template->new({ 'INTERPOLATE' => 0,
781 'PLUGIN_BASE' => 'SL::Template::Plugin',
782 'INCLUDE_PATH' => '.:templates/webpages',
785 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
787 my $in = IO::File->new($file, 'r');
790 print STDERR "Error opening template file: $!";
791 $main::lxdebug->leave_sub();
795 my $input = join('', <$in>);
799 $input = $main::locale->{iconv}->convert($input);
803 if (!$template->process(\$input, $additional_params, \$output)) {
804 print STDERR $template->error();
807 $main::lxdebug->leave_sub();
812 sub show_generic_error {
813 $main::lxdebug->enter_sub();
815 my ($self, $error, %params) = @_;
818 'title_error' => $params{title},
819 'label_error' => $error,
822 if ($params{action}) {
825 map { delete($self->{$_}); } qw(action);
826 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
828 $add_params->{SHOW_BUTTON} = 1;
829 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
830 $add_params->{VARIABLES} = \@vars;
832 } elsif ($params{back_button}) {
833 $add_params->{SHOW_BACK_BUTTON} = 1;
836 $self->{title} = $params{title} if $params{title};
839 print $self->parse_html_template("generic/error", $add_params);
841 $main::lxdebug->leave_sub();
843 die("Error: $error\n");
846 sub show_generic_information {
847 $main::lxdebug->enter_sub();
849 my ($self, $text, $title) = @_;
852 'title_information' => $title,
853 'label_information' => $text,
856 $self->{title} = $title if ($title);
859 print $self->parse_html_template("generic/information", $add_params);
861 $main::lxdebug->leave_sub();
863 die("Information: $text\n");
866 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
867 # changed it to accept an arbitrary number of triggers - sschoeling
869 $main::lxdebug->enter_sub();
872 my $myconfig = shift;
875 # set dateform for jsscript
878 "dd.mm.yy" => "%d.%m.%Y",
879 "dd-mm-yy" => "%d-%m-%Y",
880 "dd/mm/yy" => "%d/%m/%Y",
881 "mm/dd/yy" => "%m/%d/%Y",
882 "mm-dd-yy" => "%m-%d-%Y",
883 "yyyy-mm-dd" => "%Y-%m-%d",
886 my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
887 $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
894 inputField : "| . (shift) . qq|",
895 ifFormat :"$ifFormat",
896 align : "| . (shift) . qq|",
897 button : "| . (shift) . qq|"
903 <script type="text/javascript">
904 <!--| . join("", @triggers) . qq|//-->
908 $main::lxdebug->leave_sub();
911 } #end sub write_trigger
914 $main::lxdebug->enter_sub();
916 my ($self, $msg) = @_;
918 if ($self->{callback}) {
920 my ($script, $argv) = split(/\?/, $self->{callback}, 2);
922 $script =~ s|[^a-zA-Z0-9_\.]||g;
923 exec("perl", "$script", $argv);
931 $main::lxdebug->leave_sub();
934 # sort of columns removed - empty sub
936 $main::lxdebug->enter_sub();
938 my ($self, @columns) = @_;
940 $main::lxdebug->leave_sub();
946 $main::lxdebug->enter_sub(2);
948 my ($self, $myconfig, $amount, $places, $dash) = @_;
954 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
956 my $neg = ($amount =~ s/^-//);
957 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
959 if (defined($places) && ($places ne '')) {
965 my ($actual_places) = ($amount =~ /\.(\d+)/);
966 $actual_places = length($actual_places);
967 $places = $actual_places > $places ? $actual_places : $places;
970 $amount = $self->round_amount($amount, $places);
973 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
974 my @p = split(/\./, $amount); # split amount at decimal point
976 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
979 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
982 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
983 ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
984 ($neg ? "-$amount" : "$amount" ) ;
988 $main::lxdebug->leave_sub(2);
992 sub format_amount_units {
993 $main::lxdebug->enter_sub();
998 my $myconfig = \%main::myconfig;
999 my $amount = $params{amount} * 1;
1000 my $places = $params{places};
1001 my $part_unit_name = $params{part_unit};
1002 my $amount_unit_name = $params{amount_unit};
1003 my $conv_units = $params{conv_units};
1004 my $max_places = $params{max_places};
1006 if (!$part_unit_name) {
1007 $main::lxdebug->leave_sub();
1011 AM->retrieve_all_units();
1012 my $all_units = $main::all_units;
1014 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1015 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1018 if (!scalar @{ $conv_units }) {
1019 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1020 $main::lxdebug->leave_sub();
1024 my $part_unit = $all_units->{$part_unit_name};
1025 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1027 $amount *= $conv_unit->{factor};
1032 foreach my $unit (@$conv_units) {
1033 my $last = $unit->{name} eq $part_unit->{name};
1035 $num = int($amount / $unit->{factor});
1036 $amount -= $num * $unit->{factor};
1039 if ($last ? $amount : $num) {
1040 push @values, { "unit" => $unit->{name},
1041 "amount" => $last ? $amount / $unit->{factor} : $num,
1042 "places" => $last ? $places : 0 };
1049 push @values, { "unit" => $part_unit_name,
1054 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1056 $main::lxdebug->leave_sub();
1062 $main::lxdebug->enter_sub(2);
1067 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1068 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1069 $input =~ s/\#\#/\#/g;
1071 $main::lxdebug->leave_sub(2);
1079 $main::lxdebug->enter_sub(2);
1081 my ($self, $myconfig, $amount) = @_;
1083 if ( ($myconfig->{numberformat} eq '1.000,00')
1084 || ($myconfig->{numberformat} eq '1000,00')) {
1089 if ($myconfig->{numberformat} eq "1'000.00") {
1095 $main::lxdebug->leave_sub(2);
1097 return ($amount * 1);
1101 $main::lxdebug->enter_sub(2);
1103 my ($self, $amount, $places) = @_;
1106 # Rounding like "Kaufmannsrunden"
1107 # Descr. http://de.wikipedia.org/wiki/Rundung
1109 # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
1112 $amount = $amount * (10**($places));
1113 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1115 $main::lxdebug->leave_sub(2);
1117 return $round_amount;
1121 sub parse_template {
1122 $main::lxdebug->enter_sub();
1124 my ($self, $myconfig, $userspath) = @_;
1125 my ($template, $out);
1129 $self->{"cwd"} = getcwd();
1130 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1134 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1135 $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1136 $ext_for_format = 'odt';
1138 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1139 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1140 $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1141 $ext_for_format = 'pdf';
1143 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1144 $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1145 $ext_for_format = 'html';
1147 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1148 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1149 $ext_for_format = 'xml';
1151 } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1152 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1154 } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1155 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1157 } elsif ( defined $self->{'format'}) {
1158 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1160 } elsif ( $self->{'format'} eq '' ) {
1161 $self->error("No Outputformat given: $self->{'format'}");
1163 } else { #Catch the rest
1164 $self->error("Outputformat not defined: $self->{'format'}");
1167 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1168 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1170 if (!$self->{employee_id}) {
1171 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1174 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1176 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1178 # OUT is used for the media, screen, printer, email
1179 # for postscript we store a copy in a temporary file
1181 my $prepend_userspath;
1183 if (!$self->{tmpfile}) {
1184 $self->{tmpfile} = "${fileid}.$self->{IN}";
1185 $prepend_userspath = 1;
1188 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1190 $self->{tmpfile} =~ s|.*/||;
1191 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1192 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1194 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1195 $out = $self->{OUT};
1196 $self->{OUT} = ">$self->{tmpfile}";
1200 open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1202 open(OUT, ">-") or $self->error("STDOUT : $!");
1206 if (!$template->parse(*OUT)) {
1208 $self->error("$self->{IN} : " . $template->get_error());
1213 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1215 if ($self->{media} eq 'email') {
1217 my $mail = new Mailer;
1219 map { $mail->{$_} = $self->{$_} }
1220 qw(cc bcc subject message version format);
1221 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1222 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1223 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1224 $mail->{fileid} = "$fileid.";
1225 $myconfig->{signature} =~ s/\r//g;
1227 # if we send html or plain text inline
1228 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1229 $mail->{contenttype} = "text/html";
1231 $mail->{message} =~ s/\r//g;
1232 $mail->{message} =~ s/\n/<br>\n/g;
1233 $myconfig->{signature} =~ s/\n/<br>\n/g;
1234 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1236 open(IN, $self->{tmpfile})
1237 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1239 $mail->{message} .= $_;
1246 if (!$self->{"do_not_attach"}) {
1247 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1248 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1249 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1250 "name" => $attachment_name }];
1253 $mail->{message} =~ s/\r//g;
1254 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1258 my $err = $mail->send();
1259 $self->error($self->cleanup . "$err") if ($err);
1263 $self->{OUT} = $out;
1265 my $numbytes = (-s $self->{tmpfile});
1266 open(IN, $self->{tmpfile})
1267 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1269 $self->{copies} = 1 unless $self->{media} eq 'printer';
1271 chdir("$self->{cwd}");
1272 #print(STDERR "Kopien $self->{copies}\n");
1273 #print(STDERR "OUT $self->{OUT}\n");
1274 for my $i (1 .. $self->{copies}) {
1276 open(OUT, $self->{OUT})
1277 or $self->error($self->cleanup . "$self->{OUT} : $!");
1279 $self->{attachment_filename} = ($self->{attachment_filename})
1280 ? $self->{attachment_filename}
1281 : $self->generate_attachment_filename();
1283 # launch application
1284 print qq|Content-Type: | . $template->get_mime_type() . qq|
1285 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1286 Content-Length: $numbytes
1290 open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1310 chdir("$self->{cwd}");
1311 $main::lxdebug->leave_sub();
1314 sub get_formname_translation {
1315 my ($self, $formname) = @_;
1317 $formname ||= $self->{formname};
1319 my %formname_translations = (
1320 bin_list => $main::locale->text('Bin List'),
1321 credit_note => $main::locale->text('Credit Note'),
1322 invoice => $main::locale->text('Invoice'),
1323 packing_list => $main::locale->text('Packing List'),
1324 pick_list => $main::locale->text('Pick List'),
1325 proforma => $main::locale->text('Proforma Invoice'),
1326 purchase_order => $main::locale->text('Purchase Order'),
1327 request_quotation => $main::locale->text('RFQ'),
1328 sales_order => $main::locale->text('Confirmation'),
1329 sales_quotation => $main::locale->text('Quotation'),
1330 storno_invoice => $main::locale->text('Storno Invoice'),
1331 storno_packing_list => $main::locale->text('Storno Packing List'),
1332 sales_delivery_order => $main::locale->text('Delivery Order'),
1333 purchase_delivery_order => $main::locale->text('Delivery Order'),
1336 return $formname_translations{$formname}
1339 sub get_number_prefix_for_type {
1343 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1344 : ($self->{type} =~ /_quotation$/) ? 'quo'
1345 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1351 sub get_extension_for_format {
1354 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1355 : $self->{format} =~ /postscript/i ? ".ps"
1356 : $self->{format} =~ /opendocument/i ? ".odt"
1357 : $self->{format} =~ /html/i ? ".html"
1363 sub generate_attachment_filename {
1366 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1367 my $prefix = $self->get_number_prefix_for_type();
1369 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1370 $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1372 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1373 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1376 $attachment_filename = "";
1379 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1380 $attachment_filename =~ s|[\s/\\]+|_|g;
1382 return $attachment_filename;
1385 sub generate_email_subject {
1388 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1389 my $prefix = $self->get_number_prefix_for_type();
1391 if ($subject && $self->{"${prefix}number"}) {
1392 $subject .= " " . $self->{"${prefix}number"}
1399 $main::lxdebug->enter_sub();
1403 chdir("$self->{tmpdir}");
1406 if (-f "$self->{tmpfile}.err") {
1407 open(FH, "$self->{tmpfile}.err");
1412 if ($self->{tmpfile}) {
1413 $self->{tmpfile} =~ s|.*/||g;
1415 $self->{tmpfile} =~ s/\.\w+$//g;
1416 my $tmpfile = $self->{tmpfile};
1417 unlink(<$tmpfile.*>);
1420 chdir("$self->{cwd}");
1422 $main::lxdebug->leave_sub();
1428 $main::lxdebug->enter_sub();
1430 my ($self, $date, $myconfig) = @_;
1433 if ($date && $date =~ /\D/) {
1435 if ($myconfig->{dateformat} =~ /^yy/) {
1436 ($yy, $mm, $dd) = split /\D/, $date;
1438 if ($myconfig->{dateformat} =~ /^mm/) {
1439 ($mm, $dd, $yy) = split /\D/, $date;
1441 if ($myconfig->{dateformat} =~ /^dd/) {
1442 ($dd, $mm, $yy) = split /\D/, $date;
1447 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1448 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1450 $dd = "0$dd" if ($dd < 10);
1451 $mm = "0$mm" if ($mm < 10);
1453 $date = "$yy$mm$dd";
1456 $main::lxdebug->leave_sub();
1461 # Database routines used throughout
1464 $main::lxdebug->enter_sub(2);
1466 my ($self, $myconfig) = @_;
1468 # connect to database
1470 DBI->connect($myconfig->{dbconnect},
1471 $myconfig->{dbuser}, $myconfig->{dbpasswd})
1475 if ($myconfig->{dboptions}) {
1476 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1479 $main::lxdebug->leave_sub(2);
1484 sub dbconnect_noauto {
1485 $main::lxdebug->enter_sub();
1487 my ($self, $myconfig) = @_;
1489 # connect to database
1491 DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1492 $myconfig->{dbpasswd}, { AutoCommit => 0 })
1496 if ($myconfig->{dboptions}) {
1497 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1500 $main::lxdebug->leave_sub();
1505 sub get_standard_dbh {
1506 $main::lxdebug->enter_sub(2);
1508 my ($self, $myconfig) = @_;
1510 if ($standard_dbh && !$standard_dbh->{Active}) {
1511 $main::lxdebug->message(LXDebug::INFO, "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1512 undef $standard_dbh;
1515 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1517 $main::lxdebug->leave_sub(2);
1519 return $standard_dbh;
1523 $main::lxdebug->enter_sub();
1525 my ($self, $date, $myconfig) = @_;
1526 my $dbh = $self->dbconnect($myconfig);
1528 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1529 my $sth = prepare_execute_query($self, $dbh, $query, $date);
1530 my ($closed) = $sth->fetchrow_array;
1532 $main::lxdebug->leave_sub();
1537 sub update_balance {
1538 $main::lxdebug->enter_sub();
1540 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1542 # if we have a value, go do it
1545 # retrieve balance from table
1546 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1547 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1548 my ($balance) = $sth->fetchrow_array;
1554 $query = "UPDATE $table SET $field = $balance WHERE $where";
1555 do_query($self, $dbh, $query, @values);
1557 $main::lxdebug->leave_sub();
1560 sub update_exchangerate {
1561 $main::lxdebug->enter_sub();
1563 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1565 # some sanity check for currency
1567 $main::lxdebug->leave_sub();
1570 $query = qq|SELECT curr FROM defaults|;
1572 my ($currency) = selectrow_query($self, $dbh, $query);
1573 my ($defaultcurrency) = split m/:/, $currency;
1576 if ($curr eq $defaultcurrency) {
1577 $main::lxdebug->leave_sub();
1581 $query = qq|SELECT e.curr FROM exchangerate e
1582 WHERE e.curr = ? AND e.transdate = ?
1584 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1593 $buy = conv_i($buy, "NULL");
1594 $sell = conv_i($sell, "NULL");
1597 if ($buy != 0 && $sell != 0) {
1598 $set = "buy = $buy, sell = $sell";
1599 } elsif ($buy != 0) {
1600 $set = "buy = $buy";
1601 } elsif ($sell != 0) {
1602 $set = "sell = $sell";
1605 if ($sth->fetchrow_array) {
1606 $query = qq|UPDATE exchangerate
1612 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1613 VALUES (?, $buy, $sell, ?)|;
1616 do_query($self, $dbh, $query, $curr, $transdate);
1618 $main::lxdebug->leave_sub();
1621 sub save_exchangerate {
1622 $main::lxdebug->enter_sub();
1624 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1626 my $dbh = $self->dbconnect($myconfig);
1630 $buy = $rate if $fld eq 'buy';
1631 $sell = $rate if $fld eq 'sell';
1634 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1639 $main::lxdebug->leave_sub();
1642 sub get_exchangerate {
1643 $main::lxdebug->enter_sub();
1645 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1648 unless ($transdate) {
1649 $main::lxdebug->leave_sub();
1653 $query = qq|SELECT curr FROM defaults|;
1655 my ($currency) = selectrow_query($self, $dbh, $query);
1656 my ($defaultcurrency) = split m/:/, $currency;
1658 if ($currency eq $defaultcurrency) {
1659 $main::lxdebug->leave_sub();
1663 $query = qq|SELECT e.$fld FROM exchangerate e
1664 WHERE e.curr = ? AND e.transdate = ?|;
1665 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1669 $main::lxdebug->leave_sub();
1671 return $exchangerate;
1674 sub check_exchangerate {
1675 $main::lxdebug->enter_sub();
1677 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1679 if ($fld !~/^buy|sell$/) {
1680 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1683 unless ($transdate) {
1684 $main::lxdebug->leave_sub();
1688 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1690 if ($currency eq $defaultcurrency) {
1691 $main::lxdebug->leave_sub();
1695 my $dbh = $self->get_standard_dbh($myconfig);
1696 my $query = qq|SELECT e.$fld FROM exchangerate e
1697 WHERE e.curr = ? AND e.transdate = ?|;
1699 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1701 $main::lxdebug->leave_sub();
1703 return $exchangerate;
1706 sub get_default_currency {
1707 $main::lxdebug->enter_sub();
1709 my ($self, $myconfig) = @_;
1710 my $dbh = $self->get_standard_dbh($myconfig);
1712 my $query = qq|SELECT curr FROM defaults|;
1714 my ($curr) = selectrow_query($self, $dbh, $query);
1715 my ($defaultcurrency) = split m/:/, $curr;
1717 $main::lxdebug->leave_sub();
1719 return $defaultcurrency;
1723 sub set_payment_options {
1724 $main::lxdebug->enter_sub();
1726 my ($self, $myconfig, $transdate) = @_;
1728 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1730 my $dbh = $self->get_standard_dbh($myconfig);
1733 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1734 qq|FROM payment_terms p | .
1737 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1738 $self->{payment_terms}) =
1739 selectrow_query($self, $dbh, $query, $self->{payment_id});
1741 if ($transdate eq "") {
1742 if ($self->{invdate}) {
1743 $transdate = $self->{invdate};
1745 $transdate = $self->{transdate};
1750 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1751 qq|FROM payment_terms|;
1752 ($self->{netto_date}, $self->{skonto_date}) =
1753 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1755 my ($invtotal, $total);
1756 my (%amounts, %formatted_amounts);
1758 if ($self->{type} =~ /_order$/) {
1759 $amounts{invtotal} = $self->{ordtotal};
1760 $amounts{total} = $self->{ordtotal};
1762 } elsif ($self->{type} =~ /_quotation$/) {
1763 $amounts{invtotal} = $self->{quototal};
1764 $amounts{total} = $self->{quototal};
1767 $amounts{invtotal} = $self->{invtotal};
1768 $amounts{total} = $self->{total};
1771 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1773 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1774 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1775 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1777 foreach (keys %amounts) {
1778 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1779 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1782 if ($self->{"language_id"}) {
1784 qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1785 qq|FROM translation_payment_terms t | .
1786 qq|LEFT JOIN language l ON t.language_id = l.id | .
1787 qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1788 my ($description_long, $output_numberformat, $output_dateformat,
1789 $output_longdates) =
1790 selectrow_query($self, $dbh, $query,
1791 $self->{"language_id"}, $self->{"payment_id"});
1793 $self->{payment_terms} = $description_long if ($description_long);
1795 if ($output_dateformat) {
1796 foreach my $key (qw(netto_date skonto_date)) {
1798 $main::locale->reformat_date($myconfig, $self->{$key},
1804 if ($output_numberformat &&
1805 ($output_numberformat ne $myconfig->{"numberformat"})) {
1806 my $saved_numberformat = $myconfig->{"numberformat"};
1807 $myconfig->{"numberformat"} = $output_numberformat;
1808 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1809 $myconfig->{"numberformat"} = $saved_numberformat;
1813 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1814 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1815 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1816 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1817 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1818 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1819 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1821 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1823 $main::lxdebug->leave_sub();
1827 sub get_template_language {
1828 $main::lxdebug->enter_sub();
1830 my ($self, $myconfig) = @_;
1832 my $template_code = "";
1834 if ($self->{language_id}) {
1835 my $dbh = $self->get_standard_dbh($myconfig);
1836 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1837 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1840 $main::lxdebug->leave_sub();
1842 return $template_code;
1845 sub get_printer_code {
1846 $main::lxdebug->enter_sub();
1848 my ($self, $myconfig) = @_;
1850 my $template_code = "";
1852 if ($self->{printer_id}) {
1853 my $dbh = $self->get_standard_dbh($myconfig);
1854 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1855 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1858 $main::lxdebug->leave_sub();
1860 return $template_code;
1864 $main::lxdebug->enter_sub();
1866 my ($self, $myconfig) = @_;
1868 my $template_code = "";
1870 if ($self->{shipto_id}) {
1871 my $dbh = $self->get_standard_dbh($myconfig);
1872 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1873 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1874 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1877 $main::lxdebug->leave_sub();
1881 $main::lxdebug->enter_sub();
1883 my ($self, $dbh, $id, $module) = @_;
1888 foreach my $item (qw(name department_1 department_2 street zipcode city country
1889 contact phone fax email)) {
1890 if ($self->{"shipto$item"}) {
1891 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1893 push(@values, $self->{"shipto${item}"});
1897 if ($self->{shipto_id}) {
1898 my $query = qq|UPDATE shipto set
1900 shiptodepartment_1 = ?,
1901 shiptodepartment_2 = ?,
1910 WHERE shipto_id = ?|;
1911 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1913 my $query = qq|SELECT * FROM shipto
1914 WHERE shiptoname = ? AND
1915 shiptodepartment_1 = ? AND
1916 shiptodepartment_2 = ? AND
1917 shiptostreet = ? AND
1918 shiptozipcode = ? AND
1920 shiptocountry = ? AND
1921 shiptocontact = ? AND
1927 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1930 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1931 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1932 shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1933 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1934 do_query($self, $dbh, $query, $id, @values, $module);
1939 $main::lxdebug->leave_sub();
1943 $main::lxdebug->enter_sub();
1945 my ($self, $dbh) = @_;
1947 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1948 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1949 $self->{"employee_id"} *= 1;
1951 $main::lxdebug->leave_sub();
1954 sub get_employee_data {
1955 $main::lxdebug->enter_sub();
1960 Common::check_params(\%params, qw(prefix));
1961 Common::check_params_x(\%params, qw(id));
1964 $main::lxdebug->leave_sub();
1968 my $myconfig = \%main::myconfig;
1969 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
1971 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
1974 my $user = User->new($login);
1975 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
1977 $self->{$params{prefix} . '_login'} = $login;
1978 $self->{$params{prefix} . '_name'} ||= $login;
1981 $main::lxdebug->leave_sub();
1985 $main::lxdebug->enter_sub();
1987 my ($self, $myconfig) = @_;
1989 my $dbh = $self->get_standard_dbh($myconfig);
1990 my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1991 ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1993 $main::lxdebug->leave_sub();
1997 $main::lxdebug->enter_sub();
1999 my ($self, $dbh, $id, $key) = @_;
2001 $key = "all_contacts" unless ($key);
2005 $main::lxdebug->leave_sub();
2010 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2011 qq|FROM contacts | .
2012 qq|WHERE cp_cv_id = ? | .
2013 qq|ORDER BY lower(cp_name)|;
2015 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2017 $main::lxdebug->leave_sub();
2021 $main::lxdebug->enter_sub();
2023 my ($self, $dbh, $key) = @_;
2025 my ($all, $old_id, $where, @values);
2027 if (ref($key) eq "HASH") {
2030 $key = "ALL_PROJECTS";
2032 foreach my $p (keys(%{$params})) {
2034 $all = $params->{$p};
2035 } elsif ($p eq "old_id") {
2036 $old_id = $params->{$p};
2037 } elsif ($p eq "key") {
2038 $key = $params->{$p};
2044 $where = "WHERE active ";
2046 if (ref($old_id) eq "ARRAY") {
2047 my @ids = grep({ $_ } @{$old_id});
2049 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2050 push(@values, @ids);
2053 $where .= " OR (id = ?) ";
2054 push(@values, $old_id);
2060 qq|SELECT id, projectnumber, description, active | .
2063 qq|ORDER BY lower(projectnumber)|;
2065 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2067 $main::lxdebug->leave_sub();
2071 $main::lxdebug->enter_sub();
2073 my ($self, $dbh, $vc_id, $key) = @_;
2075 $key = "all_shipto" unless ($key);
2078 # get shipping addresses
2079 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2081 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2087 $main::lxdebug->leave_sub();
2091 $main::lxdebug->enter_sub();
2093 my ($self, $dbh, $key) = @_;
2095 $key = "all_printers" unless ($key);
2097 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2099 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2101 $main::lxdebug->leave_sub();
2105 $main::lxdebug->enter_sub();
2107 my ($self, $dbh, $params) = @_;
2110 $key = $params->{key};
2111 $key = "all_charts" unless ($key);
2113 my $transdate = quote_db_date($params->{transdate});
2116 qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
2118 qq|LEFT JOIN taxkeys tk ON | .
2119 qq|(tk.id = (SELECT id FROM taxkeys | .
2120 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2121 qq| ORDER BY startdate DESC LIMIT 1)) | .
2122 qq|ORDER BY c.accno|;
2124 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2126 $main::lxdebug->leave_sub();
2129 sub _get_taxcharts {
2130 $main::lxdebug->enter_sub();
2132 my ($self, $dbh, $params) = @_;
2134 my $key = "all_taxcharts";
2137 if (ref $params eq 'HASH') {
2138 $key = $params->{key} if ($params->{key});
2139 if ($params->{module} eq 'AR') {
2140 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2142 } elsif ($params->{module} eq 'AP') {
2143 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2150 my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2152 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2154 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2156 $main::lxdebug->leave_sub();
2160 $main::lxdebug->enter_sub();
2162 my ($self, $dbh, $key) = @_;
2164 $key = "all_taxzones" unless ($key);
2166 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2168 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2170 $main::lxdebug->leave_sub();
2173 sub _get_employees {
2174 $main::lxdebug->enter_sub();
2176 my ($self, $dbh, $default_key, $key) = @_;
2178 $key = $default_key unless ($key);
2179 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2181 $main::lxdebug->leave_sub();
2184 sub _get_business_types {
2185 $main::lxdebug->enter_sub();
2187 my ($self, $dbh, $key) = @_;
2189 $key = "all_business_types" unless ($key);
2191 selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2193 $main::lxdebug->leave_sub();
2196 sub _get_languages {
2197 $main::lxdebug->enter_sub();
2199 my ($self, $dbh, $key) = @_;
2201 $key = "all_languages" unless ($key);
2203 my $query = qq|SELECT * FROM language ORDER BY id|;
2205 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2207 $main::lxdebug->leave_sub();
2210 sub _get_dunning_configs {
2211 $main::lxdebug->enter_sub();
2213 my ($self, $dbh, $key) = @_;
2215 $key = "all_dunning_configs" unless ($key);
2217 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2219 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2221 $main::lxdebug->leave_sub();
2224 sub _get_currencies {
2225 $main::lxdebug->enter_sub();
2227 my ($self, $dbh, $key) = @_;
2229 $key = "all_currencies" unless ($key);
2231 my $query = qq|SELECT curr AS currency FROM defaults|;
2233 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2235 $main::lxdebug->leave_sub();
2239 $main::lxdebug->enter_sub();
2241 my ($self, $dbh, $key) = @_;
2243 $key = "all_payments" unless ($key);
2245 my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2247 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2249 $main::lxdebug->leave_sub();
2252 sub _get_customers {
2253 $main::lxdebug->enter_sub();
2255 my ($self, $dbh, $key, $limit) = @_;
2257 $key = "all_customers" unless ($key);
2258 my $limit_clause = "LIMIT $limit" if $limit;
2260 my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2262 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2264 $main::lxdebug->leave_sub();
2268 $main::lxdebug->enter_sub();
2270 my ($self, $dbh, $key) = @_;
2272 $key = "all_vendors" unless ($key);
2274 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2276 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2278 $main::lxdebug->leave_sub();
2281 sub _get_departments {
2282 $main::lxdebug->enter_sub();
2284 my ($self, $dbh, $key) = @_;
2286 $key = "all_departments" unless ($key);
2288 my $query = qq|SELECT * FROM department ORDER BY description|;
2290 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2292 $main::lxdebug->leave_sub();
2295 sub _get_warehouses {
2296 $main::lxdebug->enter_sub();
2298 my ($self, $dbh, $param) = @_;
2300 my ($key, $bins_key);
2302 if ('' eq ref $param) {
2306 $key = $param->{key};
2307 $bins_key = $param->{bins};
2310 my $query = qq|SELECT w.* FROM warehouse w
2311 WHERE (NOT w.invalid) AND
2312 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2313 ORDER BY w.sortkey|;
2315 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2318 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2319 my $sth = prepare_query($self, $dbh, $query);
2321 foreach my $warehouse (@{ $self->{$key} }) {
2322 do_statement($self, $sth, $query, $warehouse->{id});
2323 $warehouse->{$bins_key} = [];
2325 while (my $ref = $sth->fetchrow_hashref()) {
2326 push @{ $warehouse->{$bins_key} }, $ref;
2332 $main::lxdebug->leave_sub();
2336 $main::lxdebug->enter_sub();
2338 my ($self, $dbh, $table, $key, $sortkey) = @_;
2340 my $query = qq|SELECT * FROM $table|;
2341 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2343 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2345 $main::lxdebug->leave_sub();
2349 # $main::lxdebug->enter_sub();
2351 # my ($self, $dbh, $key) = @_;
2353 # $key ||= "all_groups";
2355 # my $groups = $main::auth->read_groups();
2357 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2359 # $main::lxdebug->leave_sub();
2363 $main::lxdebug->enter_sub();
2368 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2369 my ($sth, $query, $ref);
2371 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2372 my $vc_id = $self->{"${vc}_id"};
2374 if ($params{"contacts"}) {
2375 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2378 if ($params{"shipto"}) {
2379 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2382 if ($params{"projects"} || $params{"all_projects"}) {
2383 $self->_get_projects($dbh, $params{"all_projects"} ?
2384 $params{"all_projects"} : $params{"projects"},
2385 $params{"all_projects"} ? 1 : 0);
2388 if ($params{"printers"}) {
2389 $self->_get_printers($dbh, $params{"printers"});
2392 if ($params{"languages"}) {
2393 $self->_get_languages($dbh, $params{"languages"});
2396 if ($params{"charts"}) {
2397 $self->_get_charts($dbh, $params{"charts"});
2400 if ($params{"taxcharts"}) {
2401 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2404 if ($params{"taxzones"}) {
2405 $self->_get_taxzones($dbh, $params{"taxzones"});
2408 if ($params{"employees"}) {
2409 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2412 if ($params{"salesmen"}) {
2413 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2416 if ($params{"business_types"}) {
2417 $self->_get_business_types($dbh, $params{"business_types"});
2420 if ($params{"dunning_configs"}) {
2421 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2424 if($params{"currencies"}) {
2425 $self->_get_currencies($dbh, $params{"currencies"});
2428 if($params{"customers"}) {
2429 if (ref $params{"customers"} eq 'HASH') {
2430 $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2432 $self->_get_customers($dbh, $params{"customers"});
2436 if($params{"vendors"}) {
2437 if (ref $params{"vendors"} eq 'HASH') {
2438 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2440 $self->_get_vendors($dbh, $params{"vendors"});
2444 if($params{"payments"}) {
2445 $self->_get_payments($dbh, $params{"payments"});
2448 if($params{"departments"}) {
2449 $self->_get_departments($dbh, $params{"departments"});
2452 if ($params{price_factors}) {
2453 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2456 if ($params{warehouses}) {
2457 $self->_get_warehouses($dbh, $params{warehouses});
2460 # if ($params{groups}) {
2461 # $self->_get_groups($dbh, $params{groups});
2464 if ($params{partsgroup}) {
2465 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2468 $main::lxdebug->leave_sub();
2471 # this sub gets the id and name from $table
2473 $main::lxdebug->enter_sub();
2475 my ($self, $myconfig, $table) = @_;
2477 # connect to database
2478 my $dbh = $self->get_standard_dbh($myconfig);
2480 $table = $table eq "customer" ? "customer" : "vendor";
2481 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2483 my ($query, @values);
2485 if (!$self->{openinvoices}) {
2487 if ($self->{customernumber} ne "") {
2488 $where = qq|(vc.customernumber ILIKE ?)|;
2489 push(@values, '%' . $self->{customernumber} . '%');
2491 $where = qq|(vc.name ILIKE ?)|;
2492 push(@values, '%' . $self->{$table} . '%');
2496 qq~SELECT vc.id, vc.name,
2497 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2499 WHERE $where AND (NOT vc.obsolete)
2503 qq~SELECT DISTINCT vc.id, vc.name,
2504 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2506 JOIN $table vc ON (a.${table}_id = vc.id)
2507 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2509 push(@values, '%' . $self->{$table} . '%');
2512 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2514 $main::lxdebug->leave_sub();
2516 return scalar(@{ $self->{name_list} });
2519 # the selection sub is used in the AR, AP, IS, IR and OE module
2522 $main::lxdebug->enter_sub();
2524 my ($self, $myconfig, $table, $module) = @_;
2527 my $dbh = $self->get_standard_dbh($myconfig);
2529 $table = $table eq "customer" ? "customer" : "vendor";
2531 my $query = qq|SELECT count(*) FROM $table|;
2532 my ($count) = selectrow_query($self, $dbh, $query);
2534 # build selection list
2535 if ($count < $myconfig->{vclimit}) {
2536 $query = qq|SELECT id, name, salesman_id
2537 FROM $table WHERE NOT obsolete
2539 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2543 $self->get_employee($dbh);
2545 # setup sales contacts
2546 $query = qq|SELECT e.id, e.name
2548 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2549 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2552 push(@{ $self->{all_employees} },
2553 { id => $self->{employee_id},
2554 name => $self->{employee} });
2556 # sort the whole thing
2557 @{ $self->{all_employees} } =
2558 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2560 if ($module eq 'AR') {
2562 # prepare query for departments
2563 $query = qq|SELECT id, description
2566 ORDER BY description|;
2569 $query = qq|SELECT id, description
2571 ORDER BY description|;
2574 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2577 $query = qq|SELECT id, description
2581 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2584 $query = qq|SELECT printer_description, id
2586 ORDER BY printer_description|;
2588 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2591 $query = qq|SELECT id, description
2595 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2597 $main::lxdebug->leave_sub();
2600 sub language_payment {
2601 $main::lxdebug->enter_sub();
2603 my ($self, $myconfig) = @_;
2605 my $dbh = $self->get_standard_dbh($myconfig);
2607 my $query = qq|SELECT id, description
2611 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2614 $query = qq|SELECT printer_description, id
2616 ORDER BY printer_description|;
2618 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2621 $query = qq|SELECT id, description
2625 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2627 # get buchungsgruppen
2628 $query = qq|SELECT id, description
2629 FROM buchungsgruppen|;
2631 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2633 $main::lxdebug->leave_sub();
2636 # this is only used for reports
2637 sub all_departments {
2638 $main::lxdebug->enter_sub();
2640 my ($self, $myconfig, $table) = @_;
2642 my $dbh = $self->get_standard_dbh($myconfig);
2645 if ($table eq 'customer') {
2646 $where = "WHERE role = 'P' ";
2649 my $query = qq|SELECT id, description
2652 ORDER BY description|;
2653 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2655 delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2657 $main::lxdebug->leave_sub();
2661 $main::lxdebug->enter_sub();
2663 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2666 if ($table eq "customer") {
2675 $self->all_vc($myconfig, $table, $module);
2677 # get last customers or vendors
2678 my ($query, $sth, $ref);
2680 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2685 my $transdate = "current_date";
2686 if ($self->{transdate}) {
2687 $transdate = $dbh->quote($self->{transdate});
2690 # now get the account numbers
2691 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2692 FROM chart c, taxkeys tk
2693 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2694 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2697 $sth = $dbh->prepare($query);
2699 do_statement($self, $sth, $query, '%' . $module . '%');
2701 $self->{accounts} = "";
2702 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2704 foreach my $key (split(/:/, $ref->{link})) {
2705 if ($key =~ /\Q$module\E/) {
2707 # cross reference for keys
2708 $xkeyref{ $ref->{accno} } = $key;
2710 push @{ $self->{"${module}_links"}{$key} },
2711 { accno => $ref->{accno},
2712 description => $ref->{description},
2713 taxkey => $ref->{taxkey_id},
2714 tax_id => $ref->{tax_id} };
2716 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2722 # get taxkeys and description
2723 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2724 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2726 if (($module eq "AP") || ($module eq "AR")) {
2727 # get tax rates and description
2728 $query = qq|SELECT * FROM tax|;
2729 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2735 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2736 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2737 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2738 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2740 d.description AS department,
2743 JOIN $table c ON (a.${table}_id = c.id)
2744 LEFT JOIN employee e ON (e.id = a.employee_id)
2745 LEFT JOIN department d ON (d.id = a.department_id)
2747 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2749 foreach my $key (keys %$ref) {
2750 $self->{$key} = $ref->{$key};
2753 my $transdate = "current_date";
2754 if ($self->{transdate}) {
2755 $transdate = $dbh->quote($self->{transdate});
2758 # now get the account numbers
2759 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2761 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2763 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2764 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2767 $sth = $dbh->prepare($query);
2768 do_statement($self, $sth, $query, "%$module%");
2770 $self->{accounts} = "";
2771 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2773 foreach my $key (split(/:/, $ref->{link})) {
2774 if ($key =~ /\Q$module\E/) {
2776 # cross reference for keys
2777 $xkeyref{ $ref->{accno} } = $key;
2779 push @{ $self->{"${module}_links"}{$key} },
2780 { accno => $ref->{accno},
2781 description => $ref->{description},
2782 taxkey => $ref->{taxkey_id},
2783 tax_id => $ref->{tax_id} };
2785 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2791 # get amounts from individual entries
2794 c.accno, c.description,
2795 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2799 LEFT JOIN chart c ON (c.id = a.chart_id)
2800 LEFT JOIN project p ON (p.id = a.project_id)
2801 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2802 WHERE (tk.taxkey_id=a.taxkey) AND
2803 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2804 THEN tk.chart_id = a.chart_id
2807 OR (c.link='%tax%')) AND
2808 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2809 WHERE a.trans_id = ?
2810 AND a.fx_transaction = '0'
2811 ORDER BY a.oid, a.transdate|;
2812 $sth = $dbh->prepare($query);
2813 do_statement($self, $sth, $query, $self->{id});
2815 # get exchangerate for currency
2816 $self->{exchangerate} =
2817 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2820 # store amounts in {acc_trans}{$key} for multiple accounts
2821 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2822 $ref->{exchangerate} =
2823 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2824 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2827 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2828 $ref->{amount} *= -1;
2830 $ref->{index} = $index;
2832 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2838 d.curr AS currencies, d.closedto, d.revtrans,
2839 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2840 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2842 $ref = selectfirst_hashref_query($self, $dbh, $query);
2843 map { $self->{$_} = $ref->{$_} } keys %$ref;
2850 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2851 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2852 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2854 $ref = selectfirst_hashref_query($self, $dbh, $query);
2855 map { $self->{$_} = $ref->{$_} } keys %$ref;
2857 if ($self->{"$self->{vc}_id"}) {
2859 # only setup currency
2860 ($self->{currency}) = split(/:/, $self->{currencies});
2864 $self->lastname_used($dbh, $myconfig, $table, $module);
2866 # get exchangerate for currency
2867 $self->{exchangerate} =
2868 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2874 $main::lxdebug->leave_sub();
2878 $main::lxdebug->enter_sub();
2880 my ($self, $dbh, $myconfig, $table, $module) = @_;
2884 $table = $table eq "customer" ? "customer" : "vendor";
2885 my %column_map = ("a.curr" => "currency",
2886 "a.${table}_id" => "${table}_id",
2887 "a.department_id" => "department_id",
2888 "d.description" => "department",
2889 "ct.name" => $table,
2890 "current_date + ct.terms" => "duedate",
2893 if ($self->{type} =~ /delivery_order/) {
2894 $arap = 'delivery_orders';
2895 delete $column_map{"a.curr"};
2897 } elsif ($self->{type} =~ /_order/) {
2899 $where = "quotation = '0'";
2901 } elsif ($self->{type} =~ /_quotation/) {
2903 $where = "quotation = '1'";
2905 } elsif ($table eq 'customer') {
2913 $where = "($where) AND" if ($where);
2914 my $query = qq|SELECT MAX(id) FROM $arap
2915 WHERE $where ${table}_id > 0|;
2916 my ($trans_id) = selectrow_query($self, $dbh, $query);
2919 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2920 $query = qq|SELECT $column_spec
2922 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2923 LEFT JOIN department d ON (a.department_id = d.id)
2925 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2927 map { $self->{$_} = $ref->{$_} } values %column_map;
2929 $main::lxdebug->leave_sub();
2933 $main::lxdebug->enter_sub();
2935 my ($self, $myconfig, $thisdate, $days) = @_;
2937 my $dbh = $self->get_standard_dbh($myconfig);
2942 my $dateformat = $myconfig->{dateformat};
2943 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2944 $thisdate = $dbh->quote($thisdate);
2945 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2947 $query = qq|SELECT current_date AS thisdate|;
2950 ($thisdate) = selectrow_query($self, $dbh, $query);
2952 $main::lxdebug->leave_sub();
2958 $main::lxdebug->enter_sub();
2960 my ($self, $string) = @_;
2962 if ($string !~ /%/) {
2963 $string = "%$string%";
2966 $string =~ s/\'/\'\'/g;
2968 $main::lxdebug->leave_sub();
2974 $main::lxdebug->enter_sub();
2976 my ($self, $flds, $new, $count, $numrows) = @_;
2980 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2985 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2987 my $j = $item->{ndx} - 1;
2988 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2992 for $i ($count + 1 .. $numrows) {
2993 map { delete $self->{"${_}_$i"} } @{$flds};
2996 $main::lxdebug->leave_sub();
3000 $main::lxdebug->enter_sub();
3002 my ($self, $myconfig) = @_;
3006 my $dbh = $self->dbconnect_noauto($myconfig);
3008 my $query = qq|DELETE FROM status
3009 WHERE (formname = ?) AND (trans_id = ?)|;
3010 my $sth = prepare_query($self, $dbh, $query);
3012 if ($self->{formname} =~ /(check|receipt)/) {
3013 for $i (1 .. $self->{rowcount}) {
3014 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3017 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3021 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3022 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3024 my %queued = split / /, $self->{queued};
3027 if ($self->{formname} =~ /(check|receipt)/) {
3029 # this is a check or receipt, add one entry for each lineitem
3030 my ($accno) = split /--/, $self->{account};
3031 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3032 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3033 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3034 $sth = prepare_query($self, $dbh, $query);
3036 for $i (1 .. $self->{rowcount}) {
3037 if ($self->{"checked_$i"}) {
3038 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3044 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3045 VALUES (?, ?, ?, ?, ?)|;
3046 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3047 $queued{$self->{formname}}, $self->{formname});
3053 $main::lxdebug->leave_sub();
3057 $main::lxdebug->enter_sub();
3059 my ($self, $dbh) = @_;
3061 my ($query, $printed, $emailed);
3063 my $formnames = $self->{printed};
3064 my $emailforms = $self->{emailed};
3066 $query = qq|DELETE FROM status
3067 WHERE (formname = ?) AND (trans_id = ?)|;
3068 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3070 # this only applies to the forms
3071 # checks and receipts are posted when printed or queued
3073 if ($self->{queued}) {
3074 my %queued = split / /, $self->{queued};
3076 foreach my $formname (keys %queued) {
3077 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3078 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3080 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3081 VALUES (?, ?, ?, ?, ?)|;
3082 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3084 $formnames =~ s/\Q$self->{formname}\E//;
3085 $emailforms =~ s/\Q$self->{formname}\E//;
3090 # save printed, emailed info
3091 $formnames =~ s/^ +//g;
3092 $emailforms =~ s/^ +//g;
3095 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3096 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3098 foreach my $formname (keys %status) {
3099 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3100 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3102 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3103 VALUES (?, ?, ?, ?)|;
3104 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3107 $main::lxdebug->leave_sub();
3111 # $main::locale->text('SAVED')
3112 # $main::locale->text('DELETED')
3113 # $main::locale->text('ADDED')
3114 # $main::locale->text('PAYMENT POSTED')
3115 # $main::locale->text('POSTED')
3116 # $main::locale->text('POSTED AS NEW')
3117 # $main::locale->text('ELSE')
3118 # $main::locale->text('SAVED FOR DUNNING')
3119 # $main::locale->text('DUNNING STARTED')
3120 # $main::locale->text('PRINTED')
3121 # $main::locale->text('MAILED')
3122 # $main::locale->text('SCREENED')
3123 # $main::locale->text('CANCELED')
3124 # $main::locale->text('invoice')
3125 # $main::locale->text('proforma')
3126 # $main::locale->text('sales_order')
3127 # $main::locale->text('packing_list')
3128 # $main::locale->text('pick_list')
3129 # $main::locale->text('purchase_order')
3130 # $main::locale->text('bin_list')
3131 # $main::locale->text('sales_quotation')
3132 # $main::locale->text('request_quotation')
3135 $main::lxdebug->enter_sub();
3140 if(!exists $self->{employee_id}) {
3141 &get_employee($self, $dbh);
3145 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3146 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3147 my @values = (conv_i($self->{id}), $self->{login},
3148 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3149 do_query($self, $dbh, $query, @values);
3151 $main::lxdebug->leave_sub();
3155 $main::lxdebug->enter_sub();
3157 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3158 my ($orderBy, $desc) = split(/\-\-/, $order);
3159 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3162 if ($trans_id ne "") {
3164 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 | .
3165 qq|FROM history_erp h | .
3166 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3167 qq|WHERE trans_id = | . $trans_id
3168 . $restriction . qq| |
3171 my $sth = $dbh->prepare($query) || $self->dberror($query);
3173 $sth->execute() || $self->dberror("$query");
3175 while(my $hash_ref = $sth->fetchrow_hashref()) {
3176 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3177 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3178 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3179 $tempArray[$i++] = $hash_ref;
3181 $main::lxdebug->leave_sub() and return \@tempArray
3182 if ($i > 0 && $tempArray[0] ne "");
3184 $main::lxdebug->leave_sub();
3188 sub update_defaults {
3189 $main::lxdebug->enter_sub();
3191 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3194 if ($provided_dbh) {
3195 $dbh = $provided_dbh;
3197 $dbh = $self->dbconnect_noauto($myconfig);
3199 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3200 my $sth = $dbh->prepare($query);
3202 $sth->execute || $self->dberror($query);
3203 my ($var) = $sth->fetchrow_array;
3206 if ($var =~ m/\d+$/) {
3207 my $new_var = (substr $var, $-[0]) * 1 + 1;
3208 my $len_diff = length($var) - $-[0] - length($new_var);
3209 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3215 $query = qq|UPDATE defaults SET $fld = ?|;
3216 do_query($self, $dbh, $query, $var);
3218 if (!$provided_dbh) {
3223 $main::lxdebug->leave_sub();
3228 sub update_business {
3229 $main::lxdebug->enter_sub();
3231 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3234 if ($provided_dbh) {
3235 $dbh = $provided_dbh;
3237 $dbh = $self->dbconnect_noauto($myconfig);
3240 qq|SELECT customernumberinit FROM business
3241 WHERE id = ? FOR UPDATE|;
3242 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3244 if ($var =~ m/\d+$/) {
3245 my $new_var = (substr $var, $-[0]) * 1 + 1;
3246 my $len_diff = length($var) - $-[0] - length($new_var);
3247 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3253 $query = qq|UPDATE business
3254 SET customernumberinit = ?
3256 do_query($self, $dbh, $query, $var, $business_id);
3258 if (!$provided_dbh) {
3263 $main::lxdebug->leave_sub();
3268 sub get_partsgroup {
3269 $main::lxdebug->enter_sub();
3271 my ($self, $myconfig, $p) = @_;
3272 my $target = $p->{target} || 'all_partsgroup';
3274 my $dbh = $self->get_standard_dbh($myconfig);
3276 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3278 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3281 if ($p->{searchitems} eq 'part') {
3282 $query .= qq|WHERE p.inventory_accno_id > 0|;
3284 if ($p->{searchitems} eq 'service') {
3285 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3287 if ($p->{searchitems} eq 'assembly') {
3288 $query .= qq|WHERE p.assembly = '1'|;
3290 if ($p->{searchitems} eq 'labor') {
3291 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3294 $query .= qq|ORDER BY partsgroup|;
3297 $query = qq|SELECT id, partsgroup FROM partsgroup
3298 ORDER BY partsgroup|;
3301 if ($p->{language_code}) {
3302 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3303 t.description AS translation
3305 JOIN parts p ON (p.partsgroup_id = pg.id)
3306 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3307 ORDER BY translation|;
3308 @values = ($p->{language_code});
3311 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3313 $main::lxdebug->leave_sub();
3316 sub get_pricegroup {
3317 $main::lxdebug->enter_sub();
3319 my ($self, $myconfig, $p) = @_;
3321 my $dbh = $self->get_standard_dbh($myconfig);
3323 my $query = qq|SELECT p.id, p.pricegroup
3326 $query .= qq| ORDER BY pricegroup|;
3329 $query = qq|SELECT id, pricegroup FROM pricegroup
3330 ORDER BY pricegroup|;
3333 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3335 $main::lxdebug->leave_sub();
3339 # usage $form->all_years($myconfig, [$dbh])
3340 # return list of all years where bookings found
3343 $main::lxdebug->enter_sub();
3345 my ($self, $myconfig, $dbh) = @_;
3347 $dbh ||= $self->get_standard_dbh($myconfig);
3350 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3351 (SELECT MAX(transdate) FROM acc_trans)|;
3352 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3354 if ($myconfig->{dateformat} =~ /^yy/) {
3355 ($startdate) = split /\W/, $startdate;
3356 ($enddate) = split /\W/, $enddate;
3358 (@_) = split /\W/, $startdate;
3360 (@_) = split /\W/, $enddate;
3365 $startdate = substr($startdate,0,4);
3366 $enddate = substr($enddate,0,4);
3368 while ($enddate >= $startdate) {
3369 push @all_years, $enddate--;
3374 $main::lxdebug->leave_sub();
3378 $main::lxdebug->enter_sub();
3382 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if $self->{$_} } @vars;
3384 $main::lxdebug->leave_sub();
3388 $main::lxdebug->enter_sub();
3393 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if $self->{_VAR_BACKUP}->{$_} } @vars;
3395 $main::lxdebug->leave_sub();