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 #======================================================================
57 use List::Util qw(first max min sum);
58 use List::MoreUtils qw(any);
66 $standard_dbh->disconnect();
72 $main::lxdebug->enter_sub(2);
78 my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key;
83 $curr = \ $self->{ shift @tokens };
87 my $sep = shift @tokens;
88 my $key = shift @tokens;
90 $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]';
91 $curr = \ $$curr->[max 0, $#$$curr] if $sep eq '[].';
92 $curr = \ $$curr->[++$#$$curr] if $sep eq '[+].';
93 $curr = \ $$curr->{$key}
98 $main::lxdebug->leave_sub(2);
104 $main::lxdebug->enter_sub(2);
109 my @pairs = split(/&/, $input);
112 my ($key, $value) = split(/=/, $_, 2);
113 $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key);
116 $main::lxdebug->leave_sub(2);
119 sub _request_to_hash {
120 $main::lxdebug->enter_sub(2);
125 if (!$ENV{'CONTENT_TYPE'}
126 || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
128 $self->_input_to_hash($input);
130 $main::lxdebug->leave_sub(2);
134 my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
136 my $boundary = '--' . $1;
138 foreach my $line (split m/\n/, $input) {
139 last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
141 if (($line eq $boundary) || ($line eq "$boundary\r")) {
142 ${ $previous } =~ s|\r?\n$|| if $previous;
148 $content_type = "text/plain";
155 next unless $boundary_found;
157 if (!$headers_done) {
158 $line =~ s/[\r\n]*$//;
165 if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
166 if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
168 substr $line, $-[0], $+[0] - $-[0], "";
171 if ($line =~ m|name\s*=\s*"(.*?)"|i) {
173 substr $line, $-[0], $+[0] - $-[0], "";
176 $previous = $self->_store_value($name, '') if ($name);
177 $self->{FILENAME} = $filename if ($filename);
182 if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
189 next unless $previous;
191 ${ $previous } .= "${line}\n";
194 ${ $previous } =~ s|\r?\n$|| if $previous;
196 $main::lxdebug->leave_sub(2);
199 sub _recode_recursively {
200 $main::lxdebug->enter_sub();
201 my ($iconv, $param) = @_;
203 if (any { ref $param eq $_ } qw(Form HASH)) {
204 foreach my $key (keys %{ $param }) {
205 if (!ref $param->{$key}) {
206 $param->{$key} = $iconv->convert($param->{$key});
208 _recode_recursively($iconv, $param->{$key});
212 } elsif (ref $param eq 'ARRAY') {
213 foreach my $idx (0 .. scalar(@{ $param }) - 1) {
214 if (!ref $param->[$idx]) {
215 $param->[$idx] = $iconv->convert($param->[$idx]);
217 _recode_recursively($iconv, $param->[$idx]);
221 $main::lxdebug->leave_sub();
225 $main::lxdebug->enter_sub();
231 if ($LXDebug::watch_form) {
232 require SL::Watchdog;
233 tie %{ $self }, 'SL::Watchdog';
236 read(STDIN, $_, $ENV{CONTENT_LENGTH});
238 if ($ENV{QUERY_STRING}) {
239 $_ = $ENV{QUERY_STRING};
248 $self->_request_to_hash($_);
250 my $db_charset = $main::dbcharset;
251 $db_charset ||= Common::DEFAULT_CHARSET;
253 if ($self->{INPUT_ENCODING}) {
254 if (lc $self->{INPUT_ENCODING} ne lc $db_charset) {
256 my $iconv = Text::Iconv->new($self->{INPUT_ENCODING}, $db_charset);
258 _recode_recursively($iconv, $self);
261 delete $self->{INPUT_ENCODING};
264 $self->{action} = lc $self->{action};
265 $self->{action} =~ s/( |-|,|\#)/_/g;
267 $self->{version} = "2.6.0";
269 $main::lxdebug->leave_sub();
274 sub _flatten_variables_rec {
275 $main::lxdebug->enter_sub(2);
284 if ('' eq ref $curr->{$key}) {
285 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
287 } elsif ('HASH' eq ref $curr->{$key}) {
288 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
289 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
293 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
294 my $first_array_entry = 1;
296 foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
297 push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
298 $first_array_entry = 0;
303 $main::lxdebug->leave_sub(2);
308 sub flatten_variables {
309 $main::lxdebug->enter_sub(2);
317 push @variables, $self->_flatten_variables_rec($self, '', $_);
320 $main::lxdebug->leave_sub(2);
325 sub flatten_standard_variables {
326 $main::lxdebug->enter_sub(2);
329 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
333 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
334 push @variables, $self->_flatten_variables_rec($self, '', $_);
337 $main::lxdebug->leave_sub(2);
343 $main::lxdebug->enter_sub();
349 map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
351 $main::lxdebug->leave_sub();
355 $main::lxdebug->enter_sub(2);
358 my $password = $self->{password};
360 $self->{password} = 'X' x 8;
362 local $Data::Dumper::Sortkeys = 1;
363 my $output = Dumper($self);
365 $self->{password} = $password;
367 $main::lxdebug->leave_sub(2);
373 $main::lxdebug->enter_sub(2);
375 my ($self, $str) = @_;
377 $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
379 $main::lxdebug->leave_sub(2);
385 $main::lxdebug->enter_sub(2);
387 my ($self, $str) = @_;
392 $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
394 $main::lxdebug->leave_sub(2);
400 $main::lxdebug->enter_sub();
401 my ($self, $str) = @_;
403 if ($str && !ref($str)) {
404 $str =~ s/\"/"/g;
407 $main::lxdebug->leave_sub();
413 $main::lxdebug->enter_sub();
414 my ($self, $str) = @_;
416 if ($str && !ref($str)) {
417 $str =~ s/"/\"/g;
420 $main::lxdebug->leave_sub();
426 $main::lxdebug->enter_sub();
430 map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
432 for (sort keys %$self) {
433 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
434 print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
437 $main::lxdebug->leave_sub();
441 $main::lxdebug->enter_sub();
443 $main::lxdebug->show_backtrace();
445 my ($self, $msg) = @_;
446 if ($ENV{HTTP_USER_AGENT}) {
448 $self->show_generic_error($msg);
455 $main::lxdebug->leave_sub();
459 $main::lxdebug->enter_sub();
461 my ($self, $msg) = @_;
463 if ($ENV{HTTP_USER_AGENT}) {
466 if (!$self->{header}) {
479 if ($self->{info_function}) {
480 &{ $self->{info_function} }($msg);
486 $main::lxdebug->leave_sub();
489 # calculates the number of rows in a textarea based on the content and column number
490 # can be capped with maxrows
492 $main::lxdebug->enter_sub();
493 my ($self, $str, $cols, $maxrows, $minrows) = @_;
497 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
500 $main::lxdebug->leave_sub();
502 return max(min($rows, $maxrows), $minrows);
506 $main::lxdebug->enter_sub();
508 my ($self, $msg) = @_;
510 $self->error("$msg\n" . $DBI::errstr);
512 $main::lxdebug->leave_sub();
516 $main::lxdebug->enter_sub();
518 my ($self, $name, $msg) = @_;
521 foreach my $part (split m/\./, $name) {
522 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
525 $curr = $curr->{$part};
528 $main::lxdebug->leave_sub();
531 sub create_http_response {
532 $main::lxdebug->enter_sub();
537 my $cgi = $main::cgi;
538 $cgi ||= CGI->new('');
542 if ($ENV{HTTP_X_FORWARDED_FOR}) {
543 $base_path = $ENV{HTTP_REFERER};
544 $base_path =~ s|^.*?://.*?/|/|;
546 $base_path = $ENV{REQUEST_URI};
548 $base_path =~ s|[^/]+$||;
549 $base_path =~ s|/$||;
552 if (defined $main::auth) {
553 my $session_cookie_value = $main::auth->get_session_id();
554 $session_cookie_value ||= 'NO_SESSION';
556 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
557 '-value' => $session_cookie_value,
558 '-path' => $base_path,
559 '-secure' => $ENV{HTTPS});
562 my %cgi_params = ('-type' => $params{content_type});
563 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
565 my $output = $cgi->header('-cookie' => $session_cookie,
568 $main::lxdebug->leave_sub();
575 $main::lxdebug->enter_sub();
577 # extra code ist currently only used by menuv3 and menuv4 to set their css.
578 # it is strongly deprecated, and will be changed in a future version.
579 my ($self, $extra_code) = @_;
581 if ($self->{header}) {
582 $main::lxdebug->leave_sub();
586 my ($stylesheet, $favicon, $pagelayout);
588 if ($ENV{HTTP_USER_AGENT}) {
591 if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
592 # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
593 $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
596 my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
598 $stylesheets =~ s|^\s*||;
599 $stylesheets =~ s|\s*$||;
600 foreach my $file (split m/\s+/, $stylesheets) {
602 next if (! -f "css/$file");
604 $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
607 $self->{favicon} = "favicon.ico" unless $self->{favicon};
609 if ($self->{favicon} && (-f "$self->{favicon}")) {
611 qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
615 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
617 if ($self->{landscape}) {
618 $pagelayout = qq|<style type="text/css">
619 \@page { size:landscape; }
624 <script type="text/javascript">
627 document.$self->{fokus}.focus();
631 | if $self->{"fokus"};
635 if ($self->{jsscript} == 1) {
638 <script type="text/javascript" src="js/jquery.js"></script>
639 <script type="text/javascript" src="js/common.js"></script>
640 <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
641 <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
642 <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
643 <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
650 ? "$self->{title} - $self->{titlebar}"
653 foreach my $item (@ { $self->{AJAX} }) {
654 $ajax .= $item->show_javascript();
657 print $self->create_http_response('content_type' => 'text/html',
658 'charset' => $db_charset,);
659 print qq|${doctype}<html>
661 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
662 <title>$self->{titlebar}</title>
671 <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
673 <meta name="robots" content="noindex,nofollow" />
674 <script type="text/javascript" src="js/highlight_input.js"></script>
676 <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
677 <script type="text/javascript" src="js/tabcontent.js">
679 /***********************************************
680 * Tab Content script v2.2- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
681 * This notice MUST stay intact for legal use
682 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
683 ***********************************************/
694 $main::lxdebug->leave_sub();
697 sub ajax_response_header {
698 $main::lxdebug->enter_sub();
702 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
703 my $cgi = $main::cgi || CGI->new('');
704 my $output = $cgi->header('-charset' => $db_charset);
706 $main::lxdebug->leave_sub();
711 sub _prepare_html_template {
712 $main::lxdebug->enter_sub();
714 my ($self, $file, $additional_params) = @_;
717 if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
718 $language = $main::language;
720 $language = $main::myconfig{"countrycode"};
722 $language = "de" unless ($language);
724 if (-f "templates/webpages/${file}_${language}.html") {
725 if ((-f ".developer") &&
726 (-f "templates/webpages/${file}_master.html") &&
727 ((stat("templates/webpages/${file}_master.html"))[9] >
728 (stat("templates/webpages/${file}_${language}.html"))[9])) {
729 my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
730 "Please re-run 'locales.pl' in 'locale/${language}'.";
731 print(qq|<pre>$info</pre>|);
735 $file = "templates/webpages/${file}_${language}.html";
736 } elsif (-f "templates/webpages/${file}.html") {
737 $file = "templates/webpages/${file}.html";
739 my $info = "Web page template '${file}' not found.\n" .
740 "Please re-run 'locales.pl' in 'locale/${language}'.";
741 print(qq|<pre>$info</pre>|);
745 if ($self->{"DEBUG"}) {
746 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
749 if ($additional_params->{"DEBUG"}) {
750 $additional_params->{"DEBUG"} =
751 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
754 if (%main::myconfig) {
755 map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
756 my $jsc_dateformat = $main::myconfig{"dateformat"};
757 $jsc_dateformat =~ s/d+/\%d/gi;
758 $jsc_dateformat =~ s/m+/\%m/gi;
759 $jsc_dateformat =~ s/y+/\%Y/gi;
760 $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
763 $additional_params->{"conf_dbcharset"} = $main::dbcharset;
764 $additional_params->{"conf_webdav"} = $main::webdav;
765 $additional_params->{"conf_lizenzen"} = $main::lizenzen;
766 $additional_params->{"conf_latex_templates"} = $main::latex;
767 $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
769 if (%main::debug_options) {
770 map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
773 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
774 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
775 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
779 $main::lxdebug->leave_sub();
784 sub parse_html_template {
785 $main::lxdebug->enter_sub();
787 my ($self, $file, $additional_params) = @_;
789 $additional_params ||= { };
791 $file = $self->_prepare_html_template($file, $additional_params);
793 my $template = Template->new({ 'INTERPOLATE' => 0,
797 'PLUGIN_BASE' => 'SL::Template::Plugin',
798 'INCLUDE_PATH' => '.:templates/webpages',
801 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
803 my $in = IO::File->new($file, 'r');
806 print STDERR "Error opening template file: $!";
807 $main::lxdebug->leave_sub();
811 my $input = join('', <$in>);
815 $input = $main::locale->{iconv}->convert($input);
819 if (!$template->process(\$input, $additional_params, \$output)) {
820 print STDERR $template->error();
823 $main::lxdebug->leave_sub();
828 sub show_generic_error {
829 $main::lxdebug->enter_sub();
831 my ($self, $error, %params) = @_;
834 'title_error' => $params{title},
835 'label_error' => $error,
838 if ($params{action}) {
841 map { delete($self->{$_}); } qw(action);
842 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
844 $add_params->{SHOW_BUTTON} = 1;
845 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
846 $add_params->{VARIABLES} = \@vars;
848 } elsif ($params{back_button}) {
849 $add_params->{SHOW_BACK_BUTTON} = 1;
852 $self->{title} = $params{title} if $params{title};
855 print $self->parse_html_template("generic/error", $add_params);
857 $main::lxdebug->leave_sub();
859 die("Error: $error\n");
862 sub show_generic_information {
863 $main::lxdebug->enter_sub();
865 my ($self, $text, $title) = @_;
868 'title_information' => $title,
869 'label_information' => $text,
872 $self->{title} = $title if ($title);
875 print $self->parse_html_template("generic/information", $add_params);
877 $main::lxdebug->leave_sub();
879 die("Information: $text\n");
882 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
883 # changed it to accept an arbitrary number of triggers - sschoeling
885 $main::lxdebug->enter_sub();
888 my $myconfig = shift;
891 # set dateform for jsscript
894 "dd.mm.yy" => "%d.%m.%Y",
895 "dd-mm-yy" => "%d-%m-%Y",
896 "dd/mm/yy" => "%d/%m/%Y",
897 "mm/dd/yy" => "%m/%d/%Y",
898 "mm-dd-yy" => "%m-%d-%Y",
899 "yyyy-mm-dd" => "%Y-%m-%d",
902 my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
903 $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
910 inputField : "| . (shift) . qq|",
911 ifFormat :"$ifFormat",
912 align : "| . (shift) . qq|",
913 button : "| . (shift) . qq|"
919 <script type="text/javascript">
920 <!--| . join("", @triggers) . qq|//-->
924 $main::lxdebug->leave_sub();
927 } #end sub write_trigger
930 $main::lxdebug->enter_sub();
932 my ($self, $msg) = @_;
934 if ($self->{callback}) {
936 my ($script, $argv) = split(/\?/, $self->{callback}, 2);
938 $script =~ s|[^a-zA-Z0-9_\.]||g;
939 exec("perl", "$script", $argv);
947 $main::lxdebug->leave_sub();
950 # sort of columns removed - empty sub
952 $main::lxdebug->enter_sub();
954 my ($self, @columns) = @_;
956 $main::lxdebug->leave_sub();
962 $main::lxdebug->enter_sub(2);
964 my ($self, $myconfig, $amount, $places, $dash) = @_;
970 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
972 my $neg = ($amount =~ s/^-//);
973 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
975 if (defined($places) && ($places ne '')) {
981 my ($actual_places) = ($amount =~ /\.(\d+)/);
982 $actual_places = length($actual_places);
983 $places = $actual_places > $places ? $actual_places : $places;
986 $amount = $self->round_amount($amount, $places);
989 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
990 my @p = split(/\./, $amount); # split amount at decimal point
992 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
995 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
998 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
999 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1000 ($neg ? "-$amount" : "$amount" ) ;
1004 $main::lxdebug->leave_sub(2);
1008 sub format_amount_units {
1009 $main::lxdebug->enter_sub();
1014 my $myconfig = \%main::myconfig;
1015 my $amount = $params{amount} * 1;
1016 my $places = $params{places};
1017 my $part_unit_name = $params{part_unit};
1018 my $amount_unit_name = $params{amount_unit};
1019 my $conv_units = $params{conv_units};
1020 my $max_places = $params{max_places};
1022 if (!$part_unit_name) {
1023 $main::lxdebug->leave_sub();
1027 AM->retrieve_all_units();
1028 my $all_units = $main::all_units;
1030 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1031 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1034 if (!scalar @{ $conv_units }) {
1035 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1036 $main::lxdebug->leave_sub();
1040 my $part_unit = $all_units->{$part_unit_name};
1041 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1043 $amount *= $conv_unit->{factor};
1048 foreach my $unit (@$conv_units) {
1049 my $last = $unit->{name} eq $part_unit->{name};
1051 $num = int($amount / $unit->{factor});
1052 $amount -= $num * $unit->{factor};
1055 if ($last ? $amount : $num) {
1056 push @values, { "unit" => $unit->{name},
1057 "amount" => $last ? $amount / $unit->{factor} : $num,
1058 "places" => $last ? $places : 0 };
1065 push @values, { "unit" => $part_unit_name,
1070 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1072 $main::lxdebug->leave_sub();
1078 $main::lxdebug->enter_sub(2);
1083 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1084 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1085 $input =~ s/\#\#/\#/g;
1087 $main::lxdebug->leave_sub(2);
1095 $main::lxdebug->enter_sub(2);
1097 my ($self, $myconfig, $amount) = @_;
1099 if ( ($myconfig->{numberformat} eq '1.000,00')
1100 || ($myconfig->{numberformat} eq '1000,00')) {
1105 if ($myconfig->{numberformat} eq "1'000.00") {
1111 $main::lxdebug->leave_sub(2);
1113 return ($amount * 1);
1117 $main::lxdebug->enter_sub(2);
1119 my ($self, $amount, $places) = @_;
1122 # Rounding like "Kaufmannsrunden"
1123 # Descr. http://de.wikipedia.org/wiki/Rundung
1125 # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
1128 $amount = $amount * (10**($places));
1129 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1131 $main::lxdebug->leave_sub(2);
1133 return $round_amount;
1137 sub parse_template {
1138 $main::lxdebug->enter_sub();
1140 my ($self, $myconfig, $userspath) = @_;
1141 my ($template, $out);
1145 $self->{"cwd"} = getcwd();
1146 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1150 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1151 $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1152 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
1154 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1155 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1156 $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1157 $ext_for_format = 'pdf';
1159 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1160 $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1161 $ext_for_format = 'html';
1163 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1164 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1165 $ext_for_format = 'xml';
1167 } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1168 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1170 } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1171 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1173 } elsif ( defined $self->{'format'}) {
1174 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1176 } elsif ( $self->{'format'} eq '' ) {
1177 $self->error("No Outputformat given: $self->{'format'}");
1179 } else { #Catch the rest
1180 $self->error("Outputformat not defined: $self->{'format'}");
1183 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1184 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1186 if (!$self->{employee_id}) {
1187 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1190 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1192 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1194 # OUT is used for the media, screen, printer, email
1195 # for postscript we store a copy in a temporary file
1197 my $prepend_userspath;
1199 if (!$self->{tmpfile}) {
1200 $self->{tmpfile} = "${fileid}.$self->{IN}";
1201 $prepend_userspath = 1;
1204 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1206 $self->{tmpfile} =~ s|.*/||;
1207 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1208 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1210 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1211 $out = $self->{OUT};
1212 $self->{OUT} = ">$self->{tmpfile}";
1216 open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1218 open(OUT, ">-") or $self->error("STDOUT : $!");
1222 if (!$template->parse(*OUT)) {
1224 $self->error("$self->{IN} : " . $template->get_error());
1229 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1231 if ($self->{media} eq 'email') {
1233 my $mail = new Mailer;
1235 map { $mail->{$_} = $self->{$_} }
1236 qw(cc bcc subject message version format);
1237 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1238 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1239 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1240 $mail->{fileid} = "$fileid.";
1241 $myconfig->{signature} =~ s/\r//g;
1243 # if we send html or plain text inline
1244 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1245 $mail->{contenttype} = "text/html";
1247 $mail->{message} =~ s/\r//g;
1248 $mail->{message} =~ s/\n/<br>\n/g;
1249 $myconfig->{signature} =~ s/\n/<br>\n/g;
1250 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1252 open(IN, $self->{tmpfile})
1253 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1255 $mail->{message} .= $_;
1262 if (!$self->{"do_not_attach"}) {
1263 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1264 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1265 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1266 "name" => $attachment_name }];
1269 $mail->{message} =~ s/\r//g;
1270 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1274 my $err = $mail->send();
1275 $self->error($self->cleanup . "$err") if ($err);
1279 $self->{OUT} = $out;
1281 my $numbytes = (-s $self->{tmpfile});
1282 open(IN, $self->{tmpfile})
1283 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1285 $self->{copies} = 1 unless $self->{media} eq 'printer';
1287 chdir("$self->{cwd}");
1288 #print(STDERR "Kopien $self->{copies}\n");
1289 #print(STDERR "OUT $self->{OUT}\n");
1290 for my $i (1 .. $self->{copies}) {
1292 open(OUT, $self->{OUT})
1293 or $self->error($self->cleanup . "$self->{OUT} : $!");
1295 $self->{attachment_filename} = ($self->{attachment_filename})
1296 ? $self->{attachment_filename}
1297 : $self->generate_attachment_filename();
1299 # launch application
1300 print qq|Content-Type: | . $template->get_mime_type() . qq|
1301 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1302 Content-Length: $numbytes
1306 open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1327 chdir("$self->{cwd}");
1328 $main::lxdebug->leave_sub();
1331 sub get_formname_translation {
1332 $main::lxdebug->enter_sub();
1333 my ($self, $formname) = @_;
1335 $formname ||= $self->{formname};
1337 my %formname_translations = (
1338 bin_list => $main::locale->text('Bin List'),
1339 credit_note => $main::locale->text('Credit Note'),
1340 invoice => $main::locale->text('Invoice'),
1341 packing_list => $main::locale->text('Packing List'),
1342 pick_list => $main::locale->text('Pick List'),
1343 proforma => $main::locale->text('Proforma Invoice'),
1344 purchase_order => $main::locale->text('Purchase Order'),
1345 request_quotation => $main::locale->text('RFQ'),
1346 sales_order => $main::locale->text('Confirmation'),
1347 sales_quotation => $main::locale->text('Quotation'),
1348 storno_invoice => $main::locale->text('Storno Invoice'),
1349 storno_packing_list => $main::locale->text('Storno Packing List'),
1350 sales_delivery_order => $main::locale->text('Delivery Order'),
1351 purchase_delivery_order => $main::locale->text('Delivery Order'),
1352 dunning => $main::locale->text('Dunning'),
1355 $main::lxdebug->leave_sub();
1356 return $formname_translations{$formname}
1359 sub get_number_prefix_for_type {
1360 $main::lxdebug->enter_sub();
1364 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1365 : ($self->{type} =~ /_quotation$/) ? 'quo'
1366 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1369 $main::lxdebug->leave_sub();
1373 sub get_extension_for_format {
1374 $main::lxdebug->enter_sub();
1377 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1378 : $self->{format} =~ /postscript/i ? ".ps"
1379 : $self->{format} =~ /opendocument/i ? ".odt"
1380 : $self->{format} =~ /html/i ? ".html"
1383 $main::lxdebug->leave_sub();
1387 sub generate_attachment_filename {
1388 $main::lxdebug->enter_sub();
1391 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1392 my $prefix = $self->get_number_prefix_for_type();
1394 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1395 $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1397 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1398 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1401 $attachment_filename = "";
1404 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1405 $attachment_filename =~ s|[\s/\\]+|_|g;
1407 $main::lxdebug->leave_sub();
1408 return $attachment_filename;
1411 sub generate_email_subject {
1412 $main::lxdebug->enter_sub();
1415 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1416 my $prefix = $self->get_number_prefix_for_type();
1418 if ($subject && $self->{"${prefix}number"}) {
1419 $subject .= " " . $self->{"${prefix}number"}
1422 $main::lxdebug->leave_sub();
1427 $main::lxdebug->enter_sub();
1431 chdir("$self->{tmpdir}");
1434 if (-f "$self->{tmpfile}.err") {
1435 open(FH, "$self->{tmpfile}.err");
1440 if ($self->{tmpfile} && ! $::keep_temp_files) {
1441 $self->{tmpfile} =~ s|.*/||g;
1443 $self->{tmpfile} =~ s/\.\w+$//g;
1444 my $tmpfile = $self->{tmpfile};
1445 unlink(<$tmpfile.*>);
1448 chdir("$self->{cwd}");
1450 $main::lxdebug->leave_sub();
1456 $main::lxdebug->enter_sub();
1458 my ($self, $date, $myconfig) = @_;
1461 if ($date && $date =~ /\D/) {
1463 if ($myconfig->{dateformat} =~ /^yy/) {
1464 ($yy, $mm, $dd) = split /\D/, $date;
1466 if ($myconfig->{dateformat} =~ /^mm/) {
1467 ($mm, $dd, $yy) = split /\D/, $date;
1469 if ($myconfig->{dateformat} =~ /^dd/) {
1470 ($dd, $mm, $yy) = split /\D/, $date;
1475 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1476 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1478 $dd = "0$dd" if ($dd < 10);
1479 $mm = "0$mm" if ($mm < 10);
1481 $date = "$yy$mm$dd";
1484 $main::lxdebug->leave_sub();
1489 # Database routines used throughout
1492 $main::lxdebug->enter_sub(2);
1494 my ($self, $myconfig) = @_;
1496 # connect to database
1498 DBI->connect($myconfig->{dbconnect},
1499 $myconfig->{dbuser}, $myconfig->{dbpasswd})
1503 if ($myconfig->{dboptions}) {
1504 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1507 $main::lxdebug->leave_sub(2);
1512 sub dbconnect_noauto {
1513 $main::lxdebug->enter_sub();
1515 my ($self, $myconfig) = @_;
1517 # connect to database
1519 DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1520 $myconfig->{dbpasswd}, { AutoCommit => 0 })
1524 if ($myconfig->{dboptions}) {
1525 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1528 $main::lxdebug->leave_sub();
1533 sub get_standard_dbh {
1534 $main::lxdebug->enter_sub(2);
1536 my ($self, $myconfig) = @_;
1538 if ($standard_dbh && !$standard_dbh->{Active}) {
1539 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1540 undef $standard_dbh;
1543 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1545 $main::lxdebug->leave_sub(2);
1547 return $standard_dbh;
1551 $main::lxdebug->enter_sub();
1553 my ($self, $date, $myconfig) = @_;
1554 my $dbh = $self->dbconnect($myconfig);
1556 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1557 my $sth = prepare_execute_query($self, $dbh, $query, $date);
1558 my ($closed) = $sth->fetchrow_array;
1560 $main::lxdebug->leave_sub();
1565 sub update_balance {
1566 $main::lxdebug->enter_sub();
1568 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1570 # if we have a value, go do it
1573 # retrieve balance from table
1574 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1575 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1576 my ($balance) = $sth->fetchrow_array;
1582 $query = "UPDATE $table SET $field = $balance WHERE $where";
1583 do_query($self, $dbh, $query, @values);
1585 $main::lxdebug->leave_sub();
1588 sub update_exchangerate {
1589 $main::lxdebug->enter_sub();
1591 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1593 # some sanity check for currency
1595 $main::lxdebug->leave_sub();
1598 $query = qq|SELECT curr FROM defaults|;
1600 my ($currency) = selectrow_query($self, $dbh, $query);
1601 my ($defaultcurrency) = split m/:/, $currency;
1604 if ($curr eq $defaultcurrency) {
1605 $main::lxdebug->leave_sub();
1609 $query = qq|SELECT e.curr FROM exchangerate e
1610 WHERE e.curr = ? AND e.transdate = ?
1612 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1621 $buy = conv_i($buy, "NULL");
1622 $sell = conv_i($sell, "NULL");
1625 if ($buy != 0 && $sell != 0) {
1626 $set = "buy = $buy, sell = $sell";
1627 } elsif ($buy != 0) {
1628 $set = "buy = $buy";
1629 } elsif ($sell != 0) {
1630 $set = "sell = $sell";
1633 if ($sth->fetchrow_array) {
1634 $query = qq|UPDATE exchangerate
1640 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1641 VALUES (?, $buy, $sell, ?)|;
1644 do_query($self, $dbh, $query, $curr, $transdate);
1646 $main::lxdebug->leave_sub();
1649 sub save_exchangerate {
1650 $main::lxdebug->enter_sub();
1652 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1654 my $dbh = $self->dbconnect($myconfig);
1658 $buy = $rate if $fld eq 'buy';
1659 $sell = $rate if $fld eq 'sell';
1662 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1667 $main::lxdebug->leave_sub();
1670 sub get_exchangerate {
1671 $main::lxdebug->enter_sub();
1673 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1676 unless ($transdate) {
1677 $main::lxdebug->leave_sub();
1681 $query = qq|SELECT curr FROM defaults|;
1683 my ($currency) = selectrow_query($self, $dbh, $query);
1684 my ($defaultcurrency) = split m/:/, $currency;
1686 if ($currency eq $defaultcurrency) {
1687 $main::lxdebug->leave_sub();
1691 $query = qq|SELECT e.$fld FROM exchangerate e
1692 WHERE e.curr = ? AND e.transdate = ?|;
1693 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1697 $main::lxdebug->leave_sub();
1699 return $exchangerate;
1702 sub check_exchangerate {
1703 $main::lxdebug->enter_sub();
1705 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1707 if ($fld !~/^buy|sell$/) {
1708 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1711 unless ($transdate) {
1712 $main::lxdebug->leave_sub();
1716 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1718 if ($currency eq $defaultcurrency) {
1719 $main::lxdebug->leave_sub();
1723 my $dbh = $self->get_standard_dbh($myconfig);
1724 my $query = qq|SELECT e.$fld FROM exchangerate e
1725 WHERE e.curr = ? AND e.transdate = ?|;
1727 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1729 $main::lxdebug->leave_sub();
1731 return $exchangerate;
1734 sub get_default_currency {
1735 $main::lxdebug->enter_sub();
1737 my ($self, $myconfig) = @_;
1738 my $dbh = $self->get_standard_dbh($myconfig);
1740 my $query = qq|SELECT curr FROM defaults|;
1742 my ($curr) = selectrow_query($self, $dbh, $query);
1743 my ($defaultcurrency) = split m/:/, $curr;
1745 $main::lxdebug->leave_sub();
1747 return $defaultcurrency;
1751 sub set_payment_options {
1752 $main::lxdebug->enter_sub();
1754 my ($self, $myconfig, $transdate) = @_;
1756 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1758 my $dbh = $self->get_standard_dbh($myconfig);
1761 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1762 qq|FROM payment_terms p | .
1765 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1766 $self->{payment_terms}) =
1767 selectrow_query($self, $dbh, $query, $self->{payment_id});
1769 if ($transdate eq "") {
1770 if ($self->{invdate}) {
1771 $transdate = $self->{invdate};
1773 $transdate = $self->{transdate};
1778 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1779 qq|FROM payment_terms|;
1780 ($self->{netto_date}, $self->{skonto_date}) =
1781 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1783 my ($invtotal, $total);
1784 my (%amounts, %formatted_amounts);
1786 if ($self->{type} =~ /_order$/) {
1787 $amounts{invtotal} = $self->{ordtotal};
1788 $amounts{total} = $self->{ordtotal};
1790 } elsif ($self->{type} =~ /_quotation$/) {
1791 $amounts{invtotal} = $self->{quototal};
1792 $amounts{total} = $self->{quototal};
1795 $amounts{invtotal} = $self->{invtotal};
1796 $amounts{total} = $self->{total};
1799 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1801 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1802 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1803 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1805 foreach (keys %amounts) {
1806 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1807 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1810 if ($self->{"language_id"}) {
1812 qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1813 qq|FROM translation_payment_terms t | .
1814 qq|LEFT JOIN language l ON t.language_id = l.id | .
1815 qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1816 my ($description_long, $output_numberformat, $output_dateformat,
1817 $output_longdates) =
1818 selectrow_query($self, $dbh, $query,
1819 $self->{"language_id"}, $self->{"payment_id"});
1821 $self->{payment_terms} = $description_long if ($description_long);
1823 if ($output_dateformat) {
1824 foreach my $key (qw(netto_date skonto_date)) {
1826 $main::locale->reformat_date($myconfig, $self->{$key},
1832 if ($output_numberformat &&
1833 ($output_numberformat ne $myconfig->{"numberformat"})) {
1834 my $saved_numberformat = $myconfig->{"numberformat"};
1835 $myconfig->{"numberformat"} = $output_numberformat;
1836 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1837 $myconfig->{"numberformat"} = $saved_numberformat;
1841 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1842 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1843 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1844 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1845 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1846 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1847 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1849 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1851 $main::lxdebug->leave_sub();
1855 sub get_template_language {
1856 $main::lxdebug->enter_sub();
1858 my ($self, $myconfig) = @_;
1860 my $template_code = "";
1862 if ($self->{language_id}) {
1863 my $dbh = $self->get_standard_dbh($myconfig);
1864 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1865 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1868 $main::lxdebug->leave_sub();
1870 return $template_code;
1873 sub get_printer_code {
1874 $main::lxdebug->enter_sub();
1876 my ($self, $myconfig) = @_;
1878 my $template_code = "";
1880 if ($self->{printer_id}) {
1881 my $dbh = $self->get_standard_dbh($myconfig);
1882 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1883 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1886 $main::lxdebug->leave_sub();
1888 return $template_code;
1892 $main::lxdebug->enter_sub();
1894 my ($self, $myconfig) = @_;
1896 my $template_code = "";
1898 if ($self->{shipto_id}) {
1899 my $dbh = $self->get_standard_dbh($myconfig);
1900 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1901 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1902 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1905 $main::lxdebug->leave_sub();
1909 $main::lxdebug->enter_sub();
1911 my ($self, $dbh, $id, $module) = @_;
1916 foreach my $item (qw(name department_1 department_2 street zipcode city country
1917 contact phone fax email)) {
1918 if ($self->{"shipto$item"}) {
1919 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1921 push(@values, $self->{"shipto${item}"});
1925 if ($self->{shipto_id}) {
1926 my $query = qq|UPDATE shipto set
1928 shiptodepartment_1 = ?,
1929 shiptodepartment_2 = ?,
1938 WHERE shipto_id = ?|;
1939 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1941 my $query = qq|SELECT * FROM shipto
1942 WHERE shiptoname = ? AND
1943 shiptodepartment_1 = ? AND
1944 shiptodepartment_2 = ? AND
1945 shiptostreet = ? AND
1946 shiptozipcode = ? AND
1948 shiptocountry = ? AND
1949 shiptocontact = ? AND
1955 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1958 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1959 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1960 shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1961 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1962 do_query($self, $dbh, $query, $id, @values, $module);
1967 $main::lxdebug->leave_sub();
1971 $main::lxdebug->enter_sub();
1973 my ($self, $dbh) = @_;
1975 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1977 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1978 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1979 $self->{"employee_id"} *= 1;
1981 $main::lxdebug->leave_sub();
1984 sub get_employee_data {
1985 $main::lxdebug->enter_sub();
1990 Common::check_params(\%params, qw(prefix));
1991 Common::check_params_x(\%params, qw(id));
1994 $main::lxdebug->leave_sub();
1998 my $myconfig = \%main::myconfig;
1999 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
2001 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2004 my $user = User->new($login);
2005 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2007 $self->{$params{prefix} . '_login'} = $login;
2008 $self->{$params{prefix} . '_name'} ||= $login;
2011 $main::lxdebug->leave_sub();
2015 $main::lxdebug->enter_sub();
2017 my ($self, $myconfig, $reference_date) = @_;
2019 $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2021 my $dbh = $self->get_standard_dbh($myconfig);
2022 my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2023 my ($duedate) = selectrow_query($self, $dbh, $query, $self->{payment_id});
2025 $main::lxdebug->leave_sub();
2031 $main::lxdebug->enter_sub();
2033 my ($self, $dbh, $id, $key) = @_;
2035 $key = "all_contacts" unless ($key);
2039 $main::lxdebug->leave_sub();
2044 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2045 qq|FROM contacts | .
2046 qq|WHERE cp_cv_id = ? | .
2047 qq|ORDER BY lower(cp_name)|;
2049 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2051 $main::lxdebug->leave_sub();
2055 $main::lxdebug->enter_sub();
2057 my ($self, $dbh, $key) = @_;
2059 my ($all, $old_id, $where, @values);
2061 if (ref($key) eq "HASH") {
2064 $key = "ALL_PROJECTS";
2066 foreach my $p (keys(%{$params})) {
2068 $all = $params->{$p};
2069 } elsif ($p eq "old_id") {
2070 $old_id = $params->{$p};
2071 } elsif ($p eq "key") {
2072 $key = $params->{$p};
2078 $where = "WHERE active ";
2080 if (ref($old_id) eq "ARRAY") {
2081 my @ids = grep({ $_ } @{$old_id});
2083 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2084 push(@values, @ids);
2087 $where .= " OR (id = ?) ";
2088 push(@values, $old_id);
2094 qq|SELECT id, projectnumber, description, active | .
2097 qq|ORDER BY lower(projectnumber)|;
2099 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2101 $main::lxdebug->leave_sub();
2105 $main::lxdebug->enter_sub();
2107 my ($self, $dbh, $vc_id, $key) = @_;
2109 $key = "all_shipto" unless ($key);
2112 # get shipping addresses
2113 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2115 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2121 $main::lxdebug->leave_sub();
2125 $main::lxdebug->enter_sub();
2127 my ($self, $dbh, $key) = @_;
2129 $key = "all_printers" unless ($key);
2131 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2133 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2135 $main::lxdebug->leave_sub();
2139 $main::lxdebug->enter_sub();
2141 my ($self, $dbh, $params) = @_;
2144 $key = $params->{key};
2145 $key = "all_charts" unless ($key);
2147 my $transdate = quote_db_date($params->{transdate});
2150 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2152 qq|LEFT JOIN taxkeys tk ON | .
2153 qq|(tk.id = (SELECT id FROM taxkeys | .
2154 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2155 qq| ORDER BY startdate DESC LIMIT 1)) | .
2156 qq|ORDER BY c.accno|;
2158 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2160 $main::lxdebug->leave_sub();
2163 sub _get_taxcharts {
2164 $main::lxdebug->enter_sub();
2166 my ($self, $dbh, $params) = @_;
2168 my $key = "all_taxcharts";
2171 if (ref $params eq 'HASH') {
2172 $key = $params->{key} if ($params->{key});
2173 if ($params->{module} eq 'AR') {
2174 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2176 } elsif ($params->{module} eq 'AP') {
2177 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2184 my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2186 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2188 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2190 $main::lxdebug->leave_sub();
2194 $main::lxdebug->enter_sub();
2196 my ($self, $dbh, $key) = @_;
2198 $key = "all_taxzones" unless ($key);
2200 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2202 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2204 $main::lxdebug->leave_sub();
2207 sub _get_employees {
2208 $main::lxdebug->enter_sub();
2210 my ($self, $dbh, $default_key, $key) = @_;
2212 $key = $default_key unless ($key);
2213 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2215 $main::lxdebug->leave_sub();
2218 sub _get_business_types {
2219 $main::lxdebug->enter_sub();
2221 my ($self, $dbh, $key) = @_;
2223 $key = "all_business_types" unless ($key);
2225 selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2227 $main::lxdebug->leave_sub();
2230 sub _get_languages {
2231 $main::lxdebug->enter_sub();
2233 my ($self, $dbh, $key) = @_;
2235 $key = "all_languages" unless ($key);
2237 my $query = qq|SELECT * FROM language ORDER BY id|;
2239 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2241 $main::lxdebug->leave_sub();
2244 sub _get_dunning_configs {
2245 $main::lxdebug->enter_sub();
2247 my ($self, $dbh, $key) = @_;
2249 $key = "all_dunning_configs" unless ($key);
2251 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2253 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2255 $main::lxdebug->leave_sub();
2258 sub _get_currencies {
2259 $main::lxdebug->enter_sub();
2261 my ($self, $dbh, $key) = @_;
2263 $key = "all_currencies" unless ($key);
2265 my $query = qq|SELECT curr AS currency FROM defaults|;
2267 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2269 $main::lxdebug->leave_sub();
2273 $main::lxdebug->enter_sub();
2275 my ($self, $dbh, $key) = @_;
2277 $key = "all_payments" unless ($key);
2279 my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2281 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2283 $main::lxdebug->leave_sub();
2286 sub _get_customers {
2287 $main::lxdebug->enter_sub();
2289 my ($self, $dbh, $key, $limit) = @_;
2291 $key = "all_customers" unless ($key);
2292 my $limit_clause = "LIMIT $limit" if $limit;
2294 my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2296 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2298 $main::lxdebug->leave_sub();
2302 $main::lxdebug->enter_sub();
2304 my ($self, $dbh, $key) = @_;
2306 $key = "all_vendors" unless ($key);
2308 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2310 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2312 $main::lxdebug->leave_sub();
2315 sub _get_departments {
2316 $main::lxdebug->enter_sub();
2318 my ($self, $dbh, $key) = @_;
2320 $key = "all_departments" unless ($key);
2322 my $query = qq|SELECT * FROM department ORDER BY description|;
2324 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2326 $main::lxdebug->leave_sub();
2329 sub _get_warehouses {
2330 $main::lxdebug->enter_sub();
2332 my ($self, $dbh, $param) = @_;
2334 my ($key, $bins_key);
2336 if ('' eq ref $param) {
2340 $key = $param->{key};
2341 $bins_key = $param->{bins};
2344 my $query = qq|SELECT w.* FROM warehouse w
2345 WHERE (NOT w.invalid) AND
2346 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2347 ORDER BY w.sortkey|;
2349 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2352 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2353 my $sth = prepare_query($self, $dbh, $query);
2355 foreach my $warehouse (@{ $self->{$key} }) {
2356 do_statement($self, $sth, $query, $warehouse->{id});
2357 $warehouse->{$bins_key} = [];
2359 while (my $ref = $sth->fetchrow_hashref()) {
2360 push @{ $warehouse->{$bins_key} }, $ref;
2366 $main::lxdebug->leave_sub();
2370 $main::lxdebug->enter_sub();
2372 my ($self, $dbh, $table, $key, $sortkey) = @_;
2374 my $query = qq|SELECT * FROM $table|;
2375 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2377 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2379 $main::lxdebug->leave_sub();
2383 # $main::lxdebug->enter_sub();
2385 # my ($self, $dbh, $key) = @_;
2387 # $key ||= "all_groups";
2389 # my $groups = $main::auth->read_groups();
2391 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2393 # $main::lxdebug->leave_sub();
2397 $main::lxdebug->enter_sub();
2402 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2403 my ($sth, $query, $ref);
2405 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2406 my $vc_id = $self->{"${vc}_id"};
2408 if ($params{"contacts"}) {
2409 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2412 if ($params{"shipto"}) {
2413 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2416 if ($params{"projects"} || $params{"all_projects"}) {
2417 $self->_get_projects($dbh, $params{"all_projects"} ?
2418 $params{"all_projects"} : $params{"projects"},
2419 $params{"all_projects"} ? 1 : 0);
2422 if ($params{"printers"}) {
2423 $self->_get_printers($dbh, $params{"printers"});
2426 if ($params{"languages"}) {
2427 $self->_get_languages($dbh, $params{"languages"});
2430 if ($params{"charts"}) {
2431 $self->_get_charts($dbh, $params{"charts"});
2434 if ($params{"taxcharts"}) {
2435 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2438 if ($params{"taxzones"}) {
2439 $self->_get_taxzones($dbh, $params{"taxzones"});
2442 if ($params{"employees"}) {
2443 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2446 if ($params{"salesmen"}) {
2447 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2450 if ($params{"business_types"}) {
2451 $self->_get_business_types($dbh, $params{"business_types"});
2454 if ($params{"dunning_configs"}) {
2455 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2458 if($params{"currencies"}) {
2459 $self->_get_currencies($dbh, $params{"currencies"});
2462 if($params{"customers"}) {
2463 if (ref $params{"customers"} eq 'HASH') {
2464 $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2466 $self->_get_customers($dbh, $params{"customers"});
2470 if($params{"vendors"}) {
2471 if (ref $params{"vendors"} eq 'HASH') {
2472 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2474 $self->_get_vendors($dbh, $params{"vendors"});
2478 if($params{"payments"}) {
2479 $self->_get_payments($dbh, $params{"payments"});
2482 if($params{"departments"}) {
2483 $self->_get_departments($dbh, $params{"departments"});
2486 if ($params{price_factors}) {
2487 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2490 if ($params{warehouses}) {
2491 $self->_get_warehouses($dbh, $params{warehouses});
2494 # if ($params{groups}) {
2495 # $self->_get_groups($dbh, $params{groups});
2498 if ($params{partsgroup}) {
2499 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2502 $main::lxdebug->leave_sub();
2505 # this sub gets the id and name from $table
2507 $main::lxdebug->enter_sub();
2509 my ($self, $myconfig, $table) = @_;
2511 # connect to database
2512 my $dbh = $self->get_standard_dbh($myconfig);
2514 $table = $table eq "customer" ? "customer" : "vendor";
2515 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2517 my ($query, @values);
2519 if (!$self->{openinvoices}) {
2521 if ($self->{customernumber} ne "") {
2522 $where = qq|(vc.customernumber ILIKE ?)|;
2523 push(@values, '%' . $self->{customernumber} . '%');
2525 $where = qq|(vc.name ILIKE ?)|;
2526 push(@values, '%' . $self->{$table} . '%');
2530 qq~SELECT vc.id, vc.name,
2531 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2533 WHERE $where AND (NOT vc.obsolete)
2537 qq~SELECT DISTINCT vc.id, vc.name,
2538 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2540 JOIN $table vc ON (a.${table}_id = vc.id)
2541 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2543 push(@values, '%' . $self->{$table} . '%');
2546 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2548 $main::lxdebug->leave_sub();
2550 return scalar(@{ $self->{name_list} });
2553 # the selection sub is used in the AR, AP, IS, IR and OE module
2556 $main::lxdebug->enter_sub();
2558 my ($self, $myconfig, $table, $module) = @_;
2561 my $dbh = $self->get_standard_dbh($myconfig);
2563 $table = $table eq "customer" ? "customer" : "vendor";
2565 my $query = qq|SELECT count(*) FROM $table|;
2566 my ($count) = selectrow_query($self, $dbh, $query);
2568 # build selection list
2569 if ($count < $myconfig->{vclimit}) {
2570 $query = qq|SELECT id, name, salesman_id
2571 FROM $table WHERE NOT obsolete
2573 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2577 $self->get_employee($dbh);
2579 # setup sales contacts
2580 $query = qq|SELECT e.id, e.name
2582 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2583 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2586 push(@{ $self->{all_employees} },
2587 { id => $self->{employee_id},
2588 name => $self->{employee} });
2590 # sort the whole thing
2591 @{ $self->{all_employees} } =
2592 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2594 if ($module eq 'AR') {
2596 # prepare query for departments
2597 $query = qq|SELECT id, description
2600 ORDER BY description|;
2603 $query = qq|SELECT id, description
2605 ORDER BY description|;
2608 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2611 $query = qq|SELECT id, description
2615 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2618 $query = qq|SELECT printer_description, id
2620 ORDER BY printer_description|;
2622 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2625 $query = qq|SELECT id, description
2629 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2631 $main::lxdebug->leave_sub();
2634 sub language_payment {
2635 $main::lxdebug->enter_sub();
2637 my ($self, $myconfig) = @_;
2639 my $dbh = $self->get_standard_dbh($myconfig);
2641 my $query = qq|SELECT id, description
2645 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2648 $query = qq|SELECT printer_description, id
2650 ORDER BY printer_description|;
2652 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2655 $query = qq|SELECT id, description
2659 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2661 # get buchungsgruppen
2662 $query = qq|SELECT id, description
2663 FROM buchungsgruppen|;
2665 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2667 $main::lxdebug->leave_sub();
2670 # this is only used for reports
2671 sub all_departments {
2672 $main::lxdebug->enter_sub();
2674 my ($self, $myconfig, $table) = @_;
2676 my $dbh = $self->get_standard_dbh($myconfig);
2679 if ($table eq 'customer') {
2680 $where = "WHERE role = 'P' ";
2683 my $query = qq|SELECT id, description
2686 ORDER BY description|;
2687 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2689 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2691 $main::lxdebug->leave_sub();
2695 $main::lxdebug->enter_sub();
2697 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2700 if ($table eq "customer") {
2709 $self->all_vc($myconfig, $table, $module);
2711 # get last customers or vendors
2712 my ($query, $sth, $ref);
2714 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2719 my $transdate = "current_date";
2720 if ($self->{transdate}) {
2721 $transdate = $dbh->quote($self->{transdate});
2724 # now get the account numbers
2725 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2726 FROM chart c, taxkeys tk
2727 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2728 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2731 $sth = $dbh->prepare($query);
2733 do_statement($self, $sth, $query, '%' . $module . '%');
2735 $self->{accounts} = "";
2736 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2738 foreach my $key (split(/:/, $ref->{link})) {
2739 if ($key =~ /\Q$module\E/) {
2741 # cross reference for keys
2742 $xkeyref{ $ref->{accno} } = $key;
2744 push @{ $self->{"${module}_links"}{$key} },
2745 { accno => $ref->{accno},
2746 description => $ref->{description},
2747 taxkey => $ref->{taxkey_id},
2748 tax_id => $ref->{tax_id} };
2750 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2756 # get taxkeys and description
2757 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2758 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2760 if (($module eq "AP") || ($module eq "AR")) {
2761 # get tax rates and description
2762 $query = qq|SELECT * FROM tax|;
2763 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2769 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2770 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2771 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2772 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2774 d.description AS department,
2777 JOIN $table c ON (a.${table}_id = c.id)
2778 LEFT JOIN employee e ON (e.id = a.employee_id)
2779 LEFT JOIN department d ON (d.id = a.department_id)
2781 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2783 foreach my $key (keys %$ref) {
2784 $self->{$key} = $ref->{$key};
2787 my $transdate = "current_date";
2788 if ($self->{transdate}) {
2789 $transdate = $dbh->quote($self->{transdate});
2792 # now get the account numbers
2793 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2795 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2797 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2798 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2801 $sth = $dbh->prepare($query);
2802 do_statement($self, $sth, $query, "%$module%");
2804 $self->{accounts} = "";
2805 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2807 foreach my $key (split(/:/, $ref->{link})) {
2808 if ($key =~ /\Q$module\E/) {
2810 # cross reference for keys
2811 $xkeyref{ $ref->{accno} } = $key;
2813 push @{ $self->{"${module}_links"}{$key} },
2814 { accno => $ref->{accno},
2815 description => $ref->{description},
2816 taxkey => $ref->{taxkey_id},
2817 tax_id => $ref->{tax_id} };
2819 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2825 # get amounts from individual entries
2828 c.accno, c.description,
2829 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2833 LEFT JOIN chart c ON (c.id = a.chart_id)
2834 LEFT JOIN project p ON (p.id = a.project_id)
2835 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2836 WHERE (tk.taxkey_id=a.taxkey) AND
2837 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2838 THEN tk.chart_id = a.chart_id
2841 OR (c.link='%tax%')) AND
2842 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2843 WHERE a.trans_id = ?
2844 AND a.fx_transaction = '0'
2845 ORDER BY a.acc_trans_id, a.transdate|;
2846 $sth = $dbh->prepare($query);
2847 do_statement($self, $sth, $query, $self->{id});
2849 # get exchangerate for currency
2850 $self->{exchangerate} =
2851 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2854 # store amounts in {acc_trans}{$key} for multiple accounts
2855 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2856 $ref->{exchangerate} =
2857 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2858 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2861 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2862 $ref->{amount} *= -1;
2864 $ref->{index} = $index;
2866 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2872 d.curr AS currencies, d.closedto, d.revtrans,
2873 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2874 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2876 $ref = selectfirst_hashref_query($self, $dbh, $query);
2877 map { $self->{$_} = $ref->{$_} } keys %$ref;
2884 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2885 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2886 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2888 $ref = selectfirst_hashref_query($self, $dbh, $query);
2889 map { $self->{$_} = $ref->{$_} } keys %$ref;
2891 if ($self->{"$self->{vc}_id"}) {
2893 # only setup currency
2894 ($self->{currency}) = split(/:/, $self->{currencies});
2898 $self->lastname_used($dbh, $myconfig, $table, $module);
2900 # get exchangerate for currency
2901 $self->{exchangerate} =
2902 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2908 $main::lxdebug->leave_sub();
2912 $main::lxdebug->enter_sub();
2914 my ($self, $dbh, $myconfig, $table, $module) = @_;
2918 $table = $table eq "customer" ? "customer" : "vendor";
2919 my %column_map = ("a.curr" => "currency",
2920 "a.${table}_id" => "${table}_id",
2921 "a.department_id" => "department_id",
2922 "d.description" => "department",
2923 "ct.name" => $table,
2924 "current_date + ct.terms" => "duedate",
2927 if ($self->{type} =~ /delivery_order/) {
2928 $arap = 'delivery_orders';
2929 delete $column_map{"a.curr"};
2931 } elsif ($self->{type} =~ /_order/) {
2933 $where = "quotation = '0'";
2935 } elsif ($self->{type} =~ /_quotation/) {
2937 $where = "quotation = '1'";
2939 } elsif ($table eq 'customer') {
2947 $where = "($where) AND" if ($where);
2948 my $query = qq|SELECT MAX(id) FROM $arap
2949 WHERE $where ${table}_id > 0|;
2950 my ($trans_id) = selectrow_query($self, $dbh, $query);
2953 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2954 $query = qq|SELECT $column_spec
2956 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2957 LEFT JOIN department d ON (a.department_id = d.id)
2959 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2961 map { $self->{$_} = $ref->{$_} } values %column_map;
2963 $main::lxdebug->leave_sub();
2967 $main::lxdebug->enter_sub();
2970 my $myconfig = shift || \%::myconfig;
2971 my ($thisdate, $days) = @_;
2973 my $dbh = $self->get_standard_dbh($myconfig);
2978 my $dateformat = $myconfig->{dateformat};
2979 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2980 $thisdate = $dbh->quote($thisdate);
2981 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2983 $query = qq|SELECT current_date AS thisdate|;
2986 ($thisdate) = selectrow_query($self, $dbh, $query);
2988 $main::lxdebug->leave_sub();
2994 $main::lxdebug->enter_sub();
2996 my ($self, $string) = @_;
2998 if ($string !~ /%/) {
2999 $string = "%$string%";
3002 $string =~ s/\'/\'\'/g;
3004 $main::lxdebug->leave_sub();
3010 $main::lxdebug->enter_sub();
3012 my ($self, $flds, $new, $count, $numrows) = @_;
3016 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3021 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3023 my $j = $item->{ndx} - 1;
3024 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3028 for $i ($count + 1 .. $numrows) {
3029 map { delete $self->{"${_}_$i"} } @{$flds};
3032 $main::lxdebug->leave_sub();
3036 $main::lxdebug->enter_sub();
3038 my ($self, $myconfig) = @_;
3042 my $dbh = $self->dbconnect_noauto($myconfig);
3044 my $query = qq|DELETE FROM status
3045 WHERE (formname = ?) AND (trans_id = ?)|;
3046 my $sth = prepare_query($self, $dbh, $query);
3048 if ($self->{formname} =~ /(check|receipt)/) {
3049 for $i (1 .. $self->{rowcount}) {
3050 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3053 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3057 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3058 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3060 my %queued = split / /, $self->{queued};
3063 if ($self->{formname} =~ /(check|receipt)/) {
3065 # this is a check or receipt, add one entry for each lineitem
3066 my ($accno) = split /--/, $self->{account};
3067 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3068 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3069 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3070 $sth = prepare_query($self, $dbh, $query);
3072 for $i (1 .. $self->{rowcount}) {
3073 if ($self->{"checked_$i"}) {
3074 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3080 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3081 VALUES (?, ?, ?, ?, ?)|;
3082 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3083 $queued{$self->{formname}}, $self->{formname});
3089 $main::lxdebug->leave_sub();
3093 $main::lxdebug->enter_sub();
3095 my ($self, $dbh) = @_;
3097 my ($query, $printed, $emailed);
3099 my $formnames = $self->{printed};
3100 my $emailforms = $self->{emailed};
3102 $query = qq|DELETE FROM status
3103 WHERE (formname = ?) AND (trans_id = ?)|;
3104 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3106 # this only applies to the forms
3107 # checks and receipts are posted when printed or queued
3109 if ($self->{queued}) {
3110 my %queued = split / /, $self->{queued};
3112 foreach my $formname (keys %queued) {
3113 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3114 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3116 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3117 VALUES (?, ?, ?, ?, ?)|;
3118 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3120 $formnames =~ s/\Q$self->{formname}\E//;
3121 $emailforms =~ s/\Q$self->{formname}\E//;
3126 # save printed, emailed info
3127 $formnames =~ s/^ +//g;
3128 $emailforms =~ s/^ +//g;
3131 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3132 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3134 foreach my $formname (keys %status) {
3135 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3136 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3138 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3139 VALUES (?, ?, ?, ?)|;
3140 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3143 $main::lxdebug->leave_sub();
3147 # $main::locale->text('SAVED')
3148 # $main::locale->text('DELETED')
3149 # $main::locale->text('ADDED')
3150 # $main::locale->text('PAYMENT POSTED')
3151 # $main::locale->text('POSTED')
3152 # $main::locale->text('POSTED AS NEW')
3153 # $main::locale->text('ELSE')
3154 # $main::locale->text('SAVED FOR DUNNING')
3155 # $main::locale->text('DUNNING STARTED')
3156 # $main::locale->text('PRINTED')
3157 # $main::locale->text('MAILED')
3158 # $main::locale->text('SCREENED')
3159 # $main::locale->text('CANCELED')
3160 # $main::locale->text('invoice')
3161 # $main::locale->text('proforma')
3162 # $main::locale->text('sales_order')
3163 # $main::locale->text('packing_list')
3164 # $main::locale->text('pick_list')
3165 # $main::locale->text('purchase_order')
3166 # $main::locale->text('bin_list')
3167 # $main::locale->text('sales_quotation')
3168 # $main::locale->text('request_quotation')
3171 $main::lxdebug->enter_sub();
3176 if(!exists $self->{employee_id}) {
3177 &get_employee($self, $dbh);
3181 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3182 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3183 my @values = (conv_i($self->{id}), $self->{login},
3184 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3185 do_query($self, $dbh, $query, @values);
3187 $main::lxdebug->leave_sub();
3191 $main::lxdebug->enter_sub();
3193 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3194 my ($orderBy, $desc) = split(/\-\-/, $order);
3195 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3198 if ($trans_id ne "") {
3200 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 | .
3201 qq|FROM history_erp h | .
3202 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3203 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3206 my $sth = $dbh->prepare($query) || $self->dberror($query);
3208 $sth->execute() || $self->dberror("$query");
3210 while(my $hash_ref = $sth->fetchrow_hashref()) {
3211 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3212 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3213 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3214 $tempArray[$i++] = $hash_ref;
3216 $main::lxdebug->leave_sub() and return \@tempArray
3217 if ($i > 0 && $tempArray[0] ne "");
3219 $main::lxdebug->leave_sub();
3223 sub update_defaults {
3224 $main::lxdebug->enter_sub();
3226 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3229 if ($provided_dbh) {
3230 $dbh = $provided_dbh;
3232 $dbh = $self->dbconnect_noauto($myconfig);
3234 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3235 my $sth = $dbh->prepare($query);
3237 $sth->execute || $self->dberror($query);
3238 my ($var) = $sth->fetchrow_array;
3241 if ($var =~ m/\d+$/) {
3242 my $new_var = (substr $var, $-[0]) * 1 + 1;
3243 my $len_diff = length($var) - $-[0] - length($new_var);
3244 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3250 $query = qq|UPDATE defaults SET $fld = ?|;
3251 do_query($self, $dbh, $query, $var);
3253 if (!$provided_dbh) {
3258 $main::lxdebug->leave_sub();
3263 sub update_business {
3264 $main::lxdebug->enter_sub();
3266 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3269 if ($provided_dbh) {
3270 $dbh = $provided_dbh;
3272 $dbh = $self->dbconnect_noauto($myconfig);
3275 qq|SELECT customernumberinit FROM business
3276 WHERE id = ? FOR UPDATE|;
3277 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3279 return undef unless $var;
3281 if ($var =~ m/\d+$/) {
3282 my $new_var = (substr $var, $-[0]) * 1 + 1;
3283 my $len_diff = length($var) - $-[0] - length($new_var);
3284 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3290 $query = qq|UPDATE business
3291 SET customernumberinit = ?
3293 do_query($self, $dbh, $query, $var, $business_id);
3295 if (!$provided_dbh) {
3300 $main::lxdebug->leave_sub();
3305 sub get_partsgroup {
3306 $main::lxdebug->enter_sub();
3308 my ($self, $myconfig, $p) = @_;
3309 my $target = $p->{target} || 'all_partsgroup';
3311 my $dbh = $self->get_standard_dbh($myconfig);
3313 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3315 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3318 if ($p->{searchitems} eq 'part') {
3319 $query .= qq|WHERE p.inventory_accno_id > 0|;
3321 if ($p->{searchitems} eq 'service') {
3322 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3324 if ($p->{searchitems} eq 'assembly') {
3325 $query .= qq|WHERE p.assembly = '1'|;
3327 if ($p->{searchitems} eq 'labor') {
3328 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3331 $query .= qq|ORDER BY partsgroup|;
3334 $query = qq|SELECT id, partsgroup FROM partsgroup
3335 ORDER BY partsgroup|;
3338 if ($p->{language_code}) {
3339 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3340 t.description AS translation
3342 JOIN parts p ON (p.partsgroup_id = pg.id)
3343 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3344 ORDER BY translation|;
3345 @values = ($p->{language_code});
3348 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3350 $main::lxdebug->leave_sub();
3353 sub get_pricegroup {
3354 $main::lxdebug->enter_sub();
3356 my ($self, $myconfig, $p) = @_;
3358 my $dbh = $self->get_standard_dbh($myconfig);
3360 my $query = qq|SELECT p.id, p.pricegroup
3363 $query .= qq| ORDER BY pricegroup|;
3366 $query = qq|SELECT id, pricegroup FROM pricegroup
3367 ORDER BY pricegroup|;
3370 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3372 $main::lxdebug->leave_sub();
3376 # usage $form->all_years($myconfig, [$dbh])
3377 # return list of all years where bookings found
3380 $main::lxdebug->enter_sub();
3382 my ($self, $myconfig, $dbh) = @_;
3384 $dbh ||= $self->get_standard_dbh($myconfig);
3387 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3388 (SELECT MAX(transdate) FROM acc_trans)|;
3389 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3391 if ($myconfig->{dateformat} =~ /^yy/) {
3392 ($startdate) = split /\W/, $startdate;
3393 ($enddate) = split /\W/, $enddate;
3395 (@_) = split /\W/, $startdate;
3397 (@_) = split /\W/, $enddate;
3402 $startdate = substr($startdate,0,4);
3403 $enddate = substr($enddate,0,4);
3405 while ($enddate >= $startdate) {
3406 push @all_years, $enddate--;
3411 $main::lxdebug->leave_sub();
3415 $main::lxdebug->enter_sub();
3419 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3421 $main::lxdebug->leave_sub();
3425 $main::lxdebug->enter_sub();
3430 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3432 $main::lxdebug->leave_sub();
3441 SL::Form.pm - main data object.
3445 This is the main data object of Lx-Office.
3446 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3447 Points of interest for a beginner are:
3449 - $form->error - renders a generic error in html. accepts an error message
3450 - $form->get_standard_dbh - returns a database connection for the
3452 =head1 SPECIAL FUNCTIONS
3456 =item _store_value()
3458 parses a complex var name, and stores it in the form.
3461 $form->_store_value($key, $value);
3463 keys must start with a string, and can contain various tokens.
3464 supported key structures are:
3467 simple key strings work as expected
3472 separating two keys by a dot (.) will result in a hash lookup for the inner value
3473 this is similar to the behaviour of java and templating mechanisms.
3475 filter.description => $form->{filter}->{description}
3477 3. array+hashref access
3479 adding brackets ([]) before the dot will cause the next hash to be put into an array.
3480 using [+] instead of [] will force a new array index. this is useful for recurring
3481 data structures like part lists. put a [+] into the first varname, and use [] on the
3484 repeating these names in your template:
3487 invoice.items[].parts_id
3491 $form->{invoice}->{items}->[
3505 using brackets at the end of a name will result in a pure array to be created.
3506 note that you mustn't use [+], which is reserved for array+hash access and will
3507 result in undefined behaviour in array context.
3509 filter.status[] => $form->{status}->[ val1, val2, ... ]
3511 =item update_business PARAMS
3514 \%config, - config hashref
3515 $business_id, - business id
3516 $dbh - optional database handle
3518 handles business (thats customer/vendor types) sequences.
3520 special behaviour for empty strings in customerinitnumber field:
3521 will in this case not increase the value, and return undef.