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;
768 $additional_params->{"conf_vertreter"} = $main::vertreter;
770 if (%main::debug_options) {
771 map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
774 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
775 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
776 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
780 $main::lxdebug->leave_sub();
785 sub parse_html_template {
786 $main::lxdebug->enter_sub();
788 my ($self, $file, $additional_params) = @_;
790 $additional_params ||= { };
792 $file = $self->_prepare_html_template($file, $additional_params);
794 my $template = Template->new({ 'INTERPOLATE' => 0,
798 'PLUGIN_BASE' => 'SL::Template::Plugin',
799 'INCLUDE_PATH' => '.:templates/webpages',
802 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
804 my $in = IO::File->new($file, 'r');
807 print STDERR "Error opening template file: $!";
808 $main::lxdebug->leave_sub();
812 my $input = join('', <$in>);
816 $input = $main::locale->{iconv}->convert($input);
820 if (!$template->process(\$input, $additional_params, \$output)) {
821 print STDERR $template->error();
824 $main::lxdebug->leave_sub();
829 sub show_generic_error {
830 $main::lxdebug->enter_sub();
832 my ($self, $error, %params) = @_;
835 'title_error' => $params{title},
836 'label_error' => $error,
839 if ($params{action}) {
842 map { delete($self->{$_}); } qw(action);
843 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
845 $add_params->{SHOW_BUTTON} = 1;
846 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
847 $add_params->{VARIABLES} = \@vars;
849 } elsif ($params{back_button}) {
850 $add_params->{SHOW_BACK_BUTTON} = 1;
853 $self->{title} = $params{title} if $params{title};
856 print $self->parse_html_template("generic/error", $add_params);
858 $main::lxdebug->leave_sub();
860 die("Error: $error\n");
863 sub show_generic_information {
864 $main::lxdebug->enter_sub();
866 my ($self, $text, $title) = @_;
869 'title_information' => $title,
870 'label_information' => $text,
873 $self->{title} = $title if ($title);
876 print $self->parse_html_template("generic/information", $add_params);
878 $main::lxdebug->leave_sub();
880 die("Information: $text\n");
883 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
884 # changed it to accept an arbitrary number of triggers - sschoeling
886 $main::lxdebug->enter_sub();
889 my $myconfig = shift;
892 # set dateform for jsscript
895 "dd.mm.yy" => "%d.%m.%Y",
896 "dd-mm-yy" => "%d-%m-%Y",
897 "dd/mm/yy" => "%d/%m/%Y",
898 "mm/dd/yy" => "%m/%d/%Y",
899 "mm-dd-yy" => "%m-%d-%Y",
900 "yyyy-mm-dd" => "%Y-%m-%d",
903 my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
904 $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
911 inputField : "| . (shift) . qq|",
912 ifFormat :"$ifFormat",
913 align : "| . (shift) . qq|",
914 button : "| . (shift) . qq|"
920 <script type="text/javascript">
921 <!--| . join("", @triggers) . qq|//-->
925 $main::lxdebug->leave_sub();
928 } #end sub write_trigger
931 $main::lxdebug->enter_sub();
933 my ($self, $msg) = @_;
935 if ($self->{callback}) {
937 my ($script, $argv) = split(/\?/, $self->{callback}, 2);
939 $script =~ s|[^a-zA-Z0-9_\.]||g;
940 exec("perl", "$script", $argv);
948 $main::lxdebug->leave_sub();
951 # sort of columns removed - empty sub
953 $main::lxdebug->enter_sub();
955 my ($self, @columns) = @_;
957 $main::lxdebug->leave_sub();
963 $main::lxdebug->enter_sub(2);
965 my ($self, $myconfig, $amount, $places, $dash) = @_;
971 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
973 my $neg = ($amount =~ s/^-//);
974 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
976 if (defined($places) && ($places ne '')) {
982 my ($actual_places) = ($amount =~ /\.(\d+)/);
983 $actual_places = length($actual_places);
984 $places = $actual_places > $places ? $actual_places : $places;
987 $amount = $self->round_amount($amount, $places);
990 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
991 my @p = split(/\./, $amount); # split amount at decimal point
993 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
996 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
999 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
1000 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1001 ($neg ? "-$amount" : "$amount" ) ;
1005 $main::lxdebug->leave_sub(2);
1009 sub format_amount_units {
1010 $main::lxdebug->enter_sub();
1015 my $myconfig = \%main::myconfig;
1016 my $amount = $params{amount} * 1;
1017 my $places = $params{places};
1018 my $part_unit_name = $params{part_unit};
1019 my $amount_unit_name = $params{amount_unit};
1020 my $conv_units = $params{conv_units};
1021 my $max_places = $params{max_places};
1023 if (!$part_unit_name) {
1024 $main::lxdebug->leave_sub();
1028 AM->retrieve_all_units();
1029 my $all_units = $main::all_units;
1031 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1032 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1035 if (!scalar @{ $conv_units }) {
1036 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1037 $main::lxdebug->leave_sub();
1041 my $part_unit = $all_units->{$part_unit_name};
1042 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1044 $amount *= $conv_unit->{factor};
1049 foreach my $unit (@$conv_units) {
1050 my $last = $unit->{name} eq $part_unit->{name};
1052 $num = int($amount / $unit->{factor});
1053 $amount -= $num * $unit->{factor};
1056 if ($last ? $amount : $num) {
1057 push @values, { "unit" => $unit->{name},
1058 "amount" => $last ? $amount / $unit->{factor} : $num,
1059 "places" => $last ? $places : 0 };
1066 push @values, { "unit" => $part_unit_name,
1071 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1073 $main::lxdebug->leave_sub();
1079 $main::lxdebug->enter_sub(2);
1084 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1085 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1086 $input =~ s/\#\#/\#/g;
1088 $main::lxdebug->leave_sub(2);
1096 $main::lxdebug->enter_sub(2);
1098 my ($self, $myconfig, $amount) = @_;
1100 if ( ($myconfig->{numberformat} eq '1.000,00')
1101 || ($myconfig->{numberformat} eq '1000,00')) {
1106 if ($myconfig->{numberformat} eq "1'000.00") {
1112 $main::lxdebug->leave_sub(2);
1114 return ($amount * 1);
1118 $main::lxdebug->enter_sub(2);
1120 my ($self, $amount, $places) = @_;
1123 # Rounding like "Kaufmannsrunden"
1124 # Descr. http://de.wikipedia.org/wiki/Rundung
1126 # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
1129 $amount = $amount * (10**($places));
1130 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1132 $main::lxdebug->leave_sub(2);
1134 return $round_amount;
1138 sub parse_template {
1139 $main::lxdebug->enter_sub();
1141 my ($self, $myconfig, $userspath) = @_;
1142 my ($template, $out);
1146 $self->{"cwd"} = getcwd();
1147 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1151 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1152 $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1153 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
1155 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1156 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1157 $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1158 $ext_for_format = 'pdf';
1160 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1161 $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1162 $ext_for_format = 'html';
1164 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1165 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1166 $ext_for_format = 'xml';
1168 } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1169 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1171 } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1172 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1174 } elsif ( defined $self->{'format'}) {
1175 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1177 } elsif ( $self->{'format'} eq '' ) {
1178 $self->error("No Outputformat given: $self->{'format'}");
1180 } else { #Catch the rest
1181 $self->error("Outputformat not defined: $self->{'format'}");
1184 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1185 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1187 if (!$self->{employee_id}) {
1188 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1191 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1193 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1195 # OUT is used for the media, screen, printer, email
1196 # for postscript we store a copy in a temporary file
1198 my $prepend_userspath;
1200 if (!$self->{tmpfile}) {
1201 $self->{tmpfile} = "${fileid}.$self->{IN}";
1202 $prepend_userspath = 1;
1205 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1207 $self->{tmpfile} =~ s|.*/||;
1208 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1209 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1211 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1212 $out = $self->{OUT};
1213 $self->{OUT} = ">$self->{tmpfile}";
1217 open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1219 open(OUT, ">-") or $self->error("STDOUT : $!");
1223 if (!$template->parse(*OUT)) {
1225 $self->error("$self->{IN} : " . $template->get_error());
1230 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1232 if ($self->{media} eq 'email') {
1234 my $mail = new Mailer;
1236 map { $mail->{$_} = $self->{$_} }
1237 qw(cc bcc subject message version format);
1238 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1239 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1240 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1241 $mail->{fileid} = "$fileid.";
1242 $myconfig->{signature} =~ s/\r//g;
1244 # if we send html or plain text inline
1245 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1246 $mail->{contenttype} = "text/html";
1248 $mail->{message} =~ s/\r//g;
1249 $mail->{message} =~ s/\n/<br>\n/g;
1250 $myconfig->{signature} =~ s/\n/<br>\n/g;
1251 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1253 open(IN, $self->{tmpfile})
1254 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1256 $mail->{message} .= $_;
1263 if (!$self->{"do_not_attach"}) {
1264 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1265 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1266 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1267 "name" => $attachment_name }];
1270 $mail->{message} =~ s/\r//g;
1271 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1275 my $err = $mail->send();
1276 $self->error($self->cleanup . "$err") if ($err);
1280 $self->{OUT} = $out;
1282 my $numbytes = (-s $self->{tmpfile});
1283 open(IN, $self->{tmpfile})
1284 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1286 $self->{copies} = 1 unless $self->{media} eq 'printer';
1288 chdir("$self->{cwd}");
1289 #print(STDERR "Kopien $self->{copies}\n");
1290 #print(STDERR "OUT $self->{OUT}\n");
1291 for my $i (1 .. $self->{copies}) {
1293 open(OUT, $self->{OUT})
1294 or $self->error($self->cleanup . "$self->{OUT} : $!");
1296 $self->{attachment_filename} = ($self->{attachment_filename})
1297 ? $self->{attachment_filename}
1298 : $self->generate_attachment_filename();
1300 # launch application
1301 print qq|Content-Type: | . $template->get_mime_type() . qq|
1302 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1303 Content-Length: $numbytes
1307 open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1328 chdir("$self->{cwd}");
1329 $main::lxdebug->leave_sub();
1332 sub get_formname_translation {
1333 $main::lxdebug->enter_sub();
1334 my ($self, $formname) = @_;
1336 $formname ||= $self->{formname};
1338 my %formname_translations = (
1339 bin_list => $main::locale->text('Bin List'),
1340 credit_note => $main::locale->text('Credit Note'),
1341 invoice => $main::locale->text('Invoice'),
1342 packing_list => $main::locale->text('Packing List'),
1343 pick_list => $main::locale->text('Pick List'),
1344 proforma => $main::locale->text('Proforma Invoice'),
1345 purchase_order => $main::locale->text('Purchase Order'),
1346 request_quotation => $main::locale->text('RFQ'),
1347 sales_order => $main::locale->text('Confirmation'),
1348 sales_quotation => $main::locale->text('Quotation'),
1349 storno_invoice => $main::locale->text('Storno Invoice'),
1350 storno_packing_list => $main::locale->text('Storno Packing List'),
1351 sales_delivery_order => $main::locale->text('Delivery Order'),
1352 purchase_delivery_order => $main::locale->text('Delivery Order'),
1353 dunning => $main::locale->text('Dunning'),
1356 $main::lxdebug->leave_sub();
1357 return $formname_translations{$formname}
1360 sub get_number_prefix_for_type {
1361 $main::lxdebug->enter_sub();
1365 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1366 : ($self->{type} =~ /_quotation$/) ? 'quo'
1367 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1370 $main::lxdebug->leave_sub();
1374 sub get_extension_for_format {
1375 $main::lxdebug->enter_sub();
1378 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1379 : $self->{format} =~ /postscript/i ? ".ps"
1380 : $self->{format} =~ /opendocument/i ? ".odt"
1381 : $self->{format} =~ /html/i ? ".html"
1384 $main::lxdebug->leave_sub();
1388 sub generate_attachment_filename {
1389 $main::lxdebug->enter_sub();
1392 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1393 my $prefix = $self->get_number_prefix_for_type();
1395 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1396 $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1398 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1399 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1402 $attachment_filename = "";
1405 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1406 $attachment_filename =~ s|[\s/\\]+|_|g;
1408 $main::lxdebug->leave_sub();
1409 return $attachment_filename;
1412 sub generate_email_subject {
1413 $main::lxdebug->enter_sub();
1416 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1417 my $prefix = $self->get_number_prefix_for_type();
1419 if ($subject && $self->{"${prefix}number"}) {
1420 $subject .= " " . $self->{"${prefix}number"}
1423 $main::lxdebug->leave_sub();
1428 $main::lxdebug->enter_sub();
1432 chdir("$self->{tmpdir}");
1435 if (-f "$self->{tmpfile}.err") {
1436 open(FH, "$self->{tmpfile}.err");
1441 if ($self->{tmpfile} && ! $::keep_temp_files) {
1442 $self->{tmpfile} =~ s|.*/||g;
1444 $self->{tmpfile} =~ s/\.\w+$//g;
1445 my $tmpfile = $self->{tmpfile};
1446 unlink(<$tmpfile.*>);
1449 chdir("$self->{cwd}");
1451 $main::lxdebug->leave_sub();
1457 $main::lxdebug->enter_sub();
1459 my ($self, $date, $myconfig) = @_;
1462 if ($date && $date =~ /\D/) {
1464 if ($myconfig->{dateformat} =~ /^yy/) {
1465 ($yy, $mm, $dd) = split /\D/, $date;
1467 if ($myconfig->{dateformat} =~ /^mm/) {
1468 ($mm, $dd, $yy) = split /\D/, $date;
1470 if ($myconfig->{dateformat} =~ /^dd/) {
1471 ($dd, $mm, $yy) = split /\D/, $date;
1476 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1477 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1479 $dd = "0$dd" if ($dd < 10);
1480 $mm = "0$mm" if ($mm < 10);
1482 $date = "$yy$mm$dd";
1485 $main::lxdebug->leave_sub();
1490 # Database routines used throughout
1493 $main::lxdebug->enter_sub(2);
1495 my ($self, $myconfig) = @_;
1497 # connect to database
1499 DBI->connect($myconfig->{dbconnect},
1500 $myconfig->{dbuser}, $myconfig->{dbpasswd})
1504 if ($myconfig->{dboptions}) {
1505 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1508 $main::lxdebug->leave_sub(2);
1513 sub dbconnect_noauto {
1514 $main::lxdebug->enter_sub();
1516 my ($self, $myconfig) = @_;
1518 # connect to database
1520 DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1521 $myconfig->{dbpasswd}, { AutoCommit => 0 })
1525 if ($myconfig->{dboptions}) {
1526 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1529 $main::lxdebug->leave_sub();
1534 sub get_standard_dbh {
1535 $main::lxdebug->enter_sub(2);
1537 my ($self, $myconfig) = @_;
1539 if ($standard_dbh && !$standard_dbh->{Active}) {
1540 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1541 undef $standard_dbh;
1544 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1546 $main::lxdebug->leave_sub(2);
1548 return $standard_dbh;
1552 $main::lxdebug->enter_sub();
1554 my ($self, $date, $myconfig) = @_;
1555 my $dbh = $self->dbconnect($myconfig);
1557 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1558 my $sth = prepare_execute_query($self, $dbh, $query, $date);
1559 my ($closed) = $sth->fetchrow_array;
1561 $main::lxdebug->leave_sub();
1566 sub update_balance {
1567 $main::lxdebug->enter_sub();
1569 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1571 # if we have a value, go do it
1574 # retrieve balance from table
1575 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1576 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1577 my ($balance) = $sth->fetchrow_array;
1583 $query = "UPDATE $table SET $field = $balance WHERE $where";
1584 do_query($self, $dbh, $query, @values);
1586 $main::lxdebug->leave_sub();
1589 sub update_exchangerate {
1590 $main::lxdebug->enter_sub();
1592 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1594 # some sanity check for currency
1596 $main::lxdebug->leave_sub();
1599 $query = qq|SELECT curr FROM defaults|;
1601 my ($currency) = selectrow_query($self, $dbh, $query);
1602 my ($defaultcurrency) = split m/:/, $currency;
1605 if ($curr eq $defaultcurrency) {
1606 $main::lxdebug->leave_sub();
1610 $query = qq|SELECT e.curr FROM exchangerate e
1611 WHERE e.curr = ? AND e.transdate = ?
1613 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1622 $buy = conv_i($buy, "NULL");
1623 $sell = conv_i($sell, "NULL");
1626 if ($buy != 0 && $sell != 0) {
1627 $set = "buy = $buy, sell = $sell";
1628 } elsif ($buy != 0) {
1629 $set = "buy = $buy";
1630 } elsif ($sell != 0) {
1631 $set = "sell = $sell";
1634 if ($sth->fetchrow_array) {
1635 $query = qq|UPDATE exchangerate
1641 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1642 VALUES (?, $buy, $sell, ?)|;
1645 do_query($self, $dbh, $query, $curr, $transdate);
1647 $main::lxdebug->leave_sub();
1650 sub save_exchangerate {
1651 $main::lxdebug->enter_sub();
1653 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1655 my $dbh = $self->dbconnect($myconfig);
1659 $buy = $rate if $fld eq 'buy';
1660 $sell = $rate if $fld eq 'sell';
1663 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1668 $main::lxdebug->leave_sub();
1671 sub get_exchangerate {
1672 $main::lxdebug->enter_sub();
1674 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1677 unless ($transdate) {
1678 $main::lxdebug->leave_sub();
1682 $query = qq|SELECT curr FROM defaults|;
1684 my ($currency) = selectrow_query($self, $dbh, $query);
1685 my ($defaultcurrency) = split m/:/, $currency;
1687 if ($currency eq $defaultcurrency) {
1688 $main::lxdebug->leave_sub();
1692 $query = qq|SELECT e.$fld FROM exchangerate e
1693 WHERE e.curr = ? AND e.transdate = ?|;
1694 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1698 $main::lxdebug->leave_sub();
1700 return $exchangerate;
1703 sub check_exchangerate {
1704 $main::lxdebug->enter_sub();
1706 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1708 if ($fld !~/^buy|sell$/) {
1709 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1712 unless ($transdate) {
1713 $main::lxdebug->leave_sub();
1717 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1719 if ($currency eq $defaultcurrency) {
1720 $main::lxdebug->leave_sub();
1724 my $dbh = $self->get_standard_dbh($myconfig);
1725 my $query = qq|SELECT e.$fld FROM exchangerate e
1726 WHERE e.curr = ? AND e.transdate = ?|;
1728 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1730 $main::lxdebug->leave_sub();
1732 return $exchangerate;
1735 sub get_default_currency {
1736 $main::lxdebug->enter_sub();
1738 my ($self, $myconfig) = @_;
1739 my $dbh = $self->get_standard_dbh($myconfig);
1741 my $query = qq|SELECT curr FROM defaults|;
1743 my ($curr) = selectrow_query($self, $dbh, $query);
1744 my ($defaultcurrency) = split m/:/, $curr;
1746 $main::lxdebug->leave_sub();
1748 return $defaultcurrency;
1752 sub set_payment_options {
1753 $main::lxdebug->enter_sub();
1755 my ($self, $myconfig, $transdate) = @_;
1757 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1759 my $dbh = $self->get_standard_dbh($myconfig);
1762 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1763 qq|FROM payment_terms p | .
1766 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1767 $self->{payment_terms}) =
1768 selectrow_query($self, $dbh, $query, $self->{payment_id});
1770 if ($transdate eq "") {
1771 if ($self->{invdate}) {
1772 $transdate = $self->{invdate};
1774 $transdate = $self->{transdate};
1779 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1780 qq|FROM payment_terms|;
1781 ($self->{netto_date}, $self->{skonto_date}) =
1782 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1784 my ($invtotal, $total);
1785 my (%amounts, %formatted_amounts);
1787 if ($self->{type} =~ /_order$/) {
1788 $amounts{invtotal} = $self->{ordtotal};
1789 $amounts{total} = $self->{ordtotal};
1791 } elsif ($self->{type} =~ /_quotation$/) {
1792 $amounts{invtotal} = $self->{quototal};
1793 $amounts{total} = $self->{quototal};
1796 $amounts{invtotal} = $self->{invtotal};
1797 $amounts{total} = $self->{total};
1800 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1802 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1803 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1804 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1806 foreach (keys %amounts) {
1807 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1808 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1811 if ($self->{"language_id"}) {
1813 qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1814 qq|FROM translation_payment_terms t | .
1815 qq|LEFT JOIN language l ON t.language_id = l.id | .
1816 qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1817 my ($description_long, $output_numberformat, $output_dateformat,
1818 $output_longdates) =
1819 selectrow_query($self, $dbh, $query,
1820 $self->{"language_id"}, $self->{"payment_id"});
1822 $self->{payment_terms} = $description_long if ($description_long);
1824 if ($output_dateformat) {
1825 foreach my $key (qw(netto_date skonto_date)) {
1827 $main::locale->reformat_date($myconfig, $self->{$key},
1833 if ($output_numberformat &&
1834 ($output_numberformat ne $myconfig->{"numberformat"})) {
1835 my $saved_numberformat = $myconfig->{"numberformat"};
1836 $myconfig->{"numberformat"} = $output_numberformat;
1837 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1838 $myconfig->{"numberformat"} = $saved_numberformat;
1842 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1843 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1844 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1845 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1846 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1847 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1848 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1850 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1852 $main::lxdebug->leave_sub();
1856 sub get_template_language {
1857 $main::lxdebug->enter_sub();
1859 my ($self, $myconfig) = @_;
1861 my $template_code = "";
1863 if ($self->{language_id}) {
1864 my $dbh = $self->get_standard_dbh($myconfig);
1865 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1866 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1869 $main::lxdebug->leave_sub();
1871 return $template_code;
1874 sub get_printer_code {
1875 $main::lxdebug->enter_sub();
1877 my ($self, $myconfig) = @_;
1879 my $template_code = "";
1881 if ($self->{printer_id}) {
1882 my $dbh = $self->get_standard_dbh($myconfig);
1883 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1884 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1887 $main::lxdebug->leave_sub();
1889 return $template_code;
1893 $main::lxdebug->enter_sub();
1895 my ($self, $myconfig) = @_;
1897 my $template_code = "";
1899 if ($self->{shipto_id}) {
1900 my $dbh = $self->get_standard_dbh($myconfig);
1901 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1902 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1903 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1906 $main::lxdebug->leave_sub();
1910 $main::lxdebug->enter_sub();
1912 my ($self, $dbh, $id, $module) = @_;
1917 foreach my $item (qw(name department_1 department_2 street zipcode city country
1918 contact phone fax email)) {
1919 if ($self->{"shipto$item"}) {
1920 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1922 push(@values, $self->{"shipto${item}"});
1926 if ($self->{shipto_id}) {
1927 my $query = qq|UPDATE shipto set
1929 shiptodepartment_1 = ?,
1930 shiptodepartment_2 = ?,
1939 WHERE shipto_id = ?|;
1940 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1942 my $query = qq|SELECT * FROM shipto
1943 WHERE shiptoname = ? AND
1944 shiptodepartment_1 = ? AND
1945 shiptodepartment_2 = ? AND
1946 shiptostreet = ? AND
1947 shiptozipcode = ? AND
1949 shiptocountry = ? AND
1950 shiptocontact = ? AND
1956 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1959 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1960 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1961 shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1962 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1963 do_query($self, $dbh, $query, $id, @values, $module);
1968 $main::lxdebug->leave_sub();
1972 $main::lxdebug->enter_sub();
1974 my ($self, $dbh) = @_;
1976 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1978 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1979 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1980 $self->{"employee_id"} *= 1;
1982 $main::lxdebug->leave_sub();
1985 sub get_employee_data {
1986 $main::lxdebug->enter_sub();
1991 Common::check_params(\%params, qw(prefix));
1992 Common::check_params_x(\%params, qw(id));
1995 $main::lxdebug->leave_sub();
1999 my $myconfig = \%main::myconfig;
2000 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
2002 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2005 my $user = User->new($login);
2006 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2008 $self->{$params{prefix} . '_login'} = $login;
2009 $self->{$params{prefix} . '_name'} ||= $login;
2012 $main::lxdebug->leave_sub();
2016 $main::lxdebug->enter_sub();
2018 my ($self, $myconfig, $reference_date) = @_;
2020 $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2022 my $dbh = $self->get_standard_dbh($myconfig);
2023 my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2024 my ($duedate) = selectrow_query($self, $dbh, $query, $self->{payment_id});
2026 $main::lxdebug->leave_sub();
2032 $main::lxdebug->enter_sub();
2034 my ($self, $dbh, $id, $key) = @_;
2036 $key = "all_contacts" unless ($key);
2040 $main::lxdebug->leave_sub();
2045 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2046 qq|FROM contacts | .
2047 qq|WHERE cp_cv_id = ? | .
2048 qq|ORDER BY lower(cp_name)|;
2050 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2052 $main::lxdebug->leave_sub();
2056 $main::lxdebug->enter_sub();
2058 my ($self, $dbh, $key) = @_;
2060 my ($all, $old_id, $where, @values);
2062 if (ref($key) eq "HASH") {
2065 $key = "ALL_PROJECTS";
2067 foreach my $p (keys(%{$params})) {
2069 $all = $params->{$p};
2070 } elsif ($p eq "old_id") {
2071 $old_id = $params->{$p};
2072 } elsif ($p eq "key") {
2073 $key = $params->{$p};
2079 $where = "WHERE active ";
2081 if (ref($old_id) eq "ARRAY") {
2082 my @ids = grep({ $_ } @{$old_id});
2084 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2085 push(@values, @ids);
2088 $where .= " OR (id = ?) ";
2089 push(@values, $old_id);
2095 qq|SELECT id, projectnumber, description, active | .
2098 qq|ORDER BY lower(projectnumber)|;
2100 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2102 $main::lxdebug->leave_sub();
2106 $main::lxdebug->enter_sub();
2108 my ($self, $dbh, $vc_id, $key) = @_;
2110 $key = "all_shipto" unless ($key);
2113 # get shipping addresses
2114 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2116 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2122 $main::lxdebug->leave_sub();
2126 $main::lxdebug->enter_sub();
2128 my ($self, $dbh, $key) = @_;
2130 $key = "all_printers" unless ($key);
2132 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2134 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2136 $main::lxdebug->leave_sub();
2140 $main::lxdebug->enter_sub();
2142 my ($self, $dbh, $params) = @_;
2145 $key = $params->{key};
2146 $key = "all_charts" unless ($key);
2148 my $transdate = quote_db_date($params->{transdate});
2151 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2153 qq|LEFT JOIN taxkeys tk ON | .
2154 qq|(tk.id = (SELECT id FROM taxkeys | .
2155 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2156 qq| ORDER BY startdate DESC LIMIT 1)) | .
2157 qq|ORDER BY c.accno|;
2159 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2161 $main::lxdebug->leave_sub();
2164 sub _get_taxcharts {
2165 $main::lxdebug->enter_sub();
2167 my ($self, $dbh, $params) = @_;
2169 my $key = "all_taxcharts";
2172 if (ref $params eq 'HASH') {
2173 $key = $params->{key} if ($params->{key});
2174 if ($params->{module} eq 'AR') {
2175 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2177 } elsif ($params->{module} eq 'AP') {
2178 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2185 my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2187 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2189 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2191 $main::lxdebug->leave_sub();
2195 $main::lxdebug->enter_sub();
2197 my ($self, $dbh, $key) = @_;
2199 $key = "all_taxzones" unless ($key);
2201 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2203 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2205 $main::lxdebug->leave_sub();
2208 sub _get_employees {
2209 $main::lxdebug->enter_sub();
2211 my ($self, $dbh, $default_key, $key) = @_;
2213 $key = $default_key unless ($key);
2214 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2216 $main::lxdebug->leave_sub();
2219 sub _get_business_types {
2220 $main::lxdebug->enter_sub();
2222 my ($self, $dbh, $key) = @_;
2224 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2225 $options->{key} ||= "all_business_types";
2228 if (exists $options->{salesman}) {
2229 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2232 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2234 $main::lxdebug->leave_sub();
2237 sub _get_languages {
2238 $main::lxdebug->enter_sub();
2240 my ($self, $dbh, $key) = @_;
2242 $key = "all_languages" unless ($key);
2244 my $query = qq|SELECT * FROM language ORDER BY id|;
2246 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2248 $main::lxdebug->leave_sub();
2251 sub _get_dunning_configs {
2252 $main::lxdebug->enter_sub();
2254 my ($self, $dbh, $key) = @_;
2256 $key = "all_dunning_configs" unless ($key);
2258 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2260 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2262 $main::lxdebug->leave_sub();
2265 sub _get_currencies {
2266 $main::lxdebug->enter_sub();
2268 my ($self, $dbh, $key) = @_;
2270 $key = "all_currencies" unless ($key);
2272 my $query = qq|SELECT curr AS currency FROM defaults|;
2274 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2276 $main::lxdebug->leave_sub();
2280 $main::lxdebug->enter_sub();
2282 my ($self, $dbh, $key) = @_;
2284 $key = "all_payments" unless ($key);
2286 my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2288 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2290 $main::lxdebug->leave_sub();
2293 sub _get_customers {
2294 $main::lxdebug->enter_sub();
2296 my ($self, $dbh, $key, $limit) = @_;
2298 $key = "all_customers" unless ($key);
2299 my $limit_clause = "LIMIT $limit" if $limit;
2301 my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2303 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2305 $main::lxdebug->leave_sub();
2309 $main::lxdebug->enter_sub();
2311 my ($self, $dbh, $key) = @_;
2313 $key = "all_vendors" unless ($key);
2315 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2317 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2319 $main::lxdebug->leave_sub();
2322 sub _get_departments {
2323 $main::lxdebug->enter_sub();
2325 my ($self, $dbh, $key) = @_;
2327 $key = "all_departments" unless ($key);
2329 my $query = qq|SELECT * FROM department ORDER BY description|;
2331 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2333 $main::lxdebug->leave_sub();
2336 sub _get_warehouses {
2337 $main::lxdebug->enter_sub();
2339 my ($self, $dbh, $param) = @_;
2341 my ($key, $bins_key);
2343 if ('' eq ref $param) {
2347 $key = $param->{key};
2348 $bins_key = $param->{bins};
2351 my $query = qq|SELECT w.* FROM warehouse w
2352 WHERE (NOT w.invalid) AND
2353 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2354 ORDER BY w.sortkey|;
2356 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2359 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2360 my $sth = prepare_query($self, $dbh, $query);
2362 foreach my $warehouse (@{ $self->{$key} }) {
2363 do_statement($self, $sth, $query, $warehouse->{id});
2364 $warehouse->{$bins_key} = [];
2366 while (my $ref = $sth->fetchrow_hashref()) {
2367 push @{ $warehouse->{$bins_key} }, $ref;
2373 $main::lxdebug->leave_sub();
2377 $main::lxdebug->enter_sub();
2379 my ($self, $dbh, $table, $key, $sortkey) = @_;
2381 my $query = qq|SELECT * FROM $table|;
2382 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2384 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2386 $main::lxdebug->leave_sub();
2390 # $main::lxdebug->enter_sub();
2392 # my ($self, $dbh, $key) = @_;
2394 # $key ||= "all_groups";
2396 # my $groups = $main::auth->read_groups();
2398 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2400 # $main::lxdebug->leave_sub();
2404 $main::lxdebug->enter_sub();
2409 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2410 my ($sth, $query, $ref);
2412 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2413 my $vc_id = $self->{"${vc}_id"};
2415 if ($params{"contacts"}) {
2416 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2419 if ($params{"shipto"}) {
2420 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2423 if ($params{"projects"} || $params{"all_projects"}) {
2424 $self->_get_projects($dbh, $params{"all_projects"} ?
2425 $params{"all_projects"} : $params{"projects"},
2426 $params{"all_projects"} ? 1 : 0);
2429 if ($params{"printers"}) {
2430 $self->_get_printers($dbh, $params{"printers"});
2433 if ($params{"languages"}) {
2434 $self->_get_languages($dbh, $params{"languages"});
2437 if ($params{"charts"}) {
2438 $self->_get_charts($dbh, $params{"charts"});
2441 if ($params{"taxcharts"}) {
2442 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2445 if ($params{"taxzones"}) {
2446 $self->_get_taxzones($dbh, $params{"taxzones"});
2449 if ($params{"employees"}) {
2450 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2453 if ($params{"salesmen"}) {
2454 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2457 if ($params{"business_types"}) {
2458 $self->_get_business_types($dbh, $params{"business_types"});
2461 if ($params{"dunning_configs"}) {
2462 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2465 if($params{"currencies"}) {
2466 $self->_get_currencies($dbh, $params{"currencies"});
2469 if($params{"customers"}) {
2470 if (ref $params{"customers"} eq 'HASH') {
2471 $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2473 $self->_get_customers($dbh, $params{"customers"});
2477 if($params{"vendors"}) {
2478 if (ref $params{"vendors"} eq 'HASH') {
2479 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2481 $self->_get_vendors($dbh, $params{"vendors"});
2485 if($params{"payments"}) {
2486 $self->_get_payments($dbh, $params{"payments"});
2489 if($params{"departments"}) {
2490 $self->_get_departments($dbh, $params{"departments"});
2493 if ($params{price_factors}) {
2494 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2497 if ($params{warehouses}) {
2498 $self->_get_warehouses($dbh, $params{warehouses});
2501 # if ($params{groups}) {
2502 # $self->_get_groups($dbh, $params{groups});
2505 if ($params{partsgroup}) {
2506 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2509 $main::lxdebug->leave_sub();
2512 # this sub gets the id and name from $table
2514 $main::lxdebug->enter_sub();
2516 my ($self, $myconfig, $table) = @_;
2518 # connect to database
2519 my $dbh = $self->get_standard_dbh($myconfig);
2521 $table = $table eq "customer" ? "customer" : "vendor";
2522 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2524 my ($query, @values);
2526 if (!$self->{openinvoices}) {
2528 if ($self->{customernumber} ne "") {
2529 $where = qq|(vc.customernumber ILIKE ?)|;
2530 push(@values, '%' . $self->{customernumber} . '%');
2532 $where = qq|(vc.name ILIKE ?)|;
2533 push(@values, '%' . $self->{$table} . '%');
2537 qq~SELECT vc.id, vc.name,
2538 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2540 WHERE $where AND (NOT vc.obsolete)
2544 qq~SELECT DISTINCT vc.id, vc.name,
2545 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2547 JOIN $table vc ON (a.${table}_id = vc.id)
2548 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2550 push(@values, '%' . $self->{$table} . '%');
2553 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2555 $main::lxdebug->leave_sub();
2557 return scalar(@{ $self->{name_list} });
2560 # the selection sub is used in the AR, AP, IS, IR and OE module
2563 $main::lxdebug->enter_sub();
2565 my ($self, $myconfig, $table, $module) = @_;
2568 my $dbh = $self->get_standard_dbh($myconfig);
2570 $table = $table eq "customer" ? "customer" : "vendor";
2572 my $query = qq|SELECT count(*) FROM $table|;
2573 my ($count) = selectrow_query($self, $dbh, $query);
2575 # build selection list
2576 if ($count < $myconfig->{vclimit}) {
2577 $query = qq|SELECT id, name, salesman_id
2578 FROM $table WHERE NOT obsolete
2580 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2584 $self->get_employee($dbh);
2586 # setup sales contacts
2587 $query = qq|SELECT e.id, e.name
2589 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2590 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2593 push(@{ $self->{all_employees} },
2594 { id => $self->{employee_id},
2595 name => $self->{employee} });
2597 # sort the whole thing
2598 @{ $self->{all_employees} } =
2599 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2601 if ($module eq 'AR') {
2603 # prepare query for departments
2604 $query = qq|SELECT id, description
2607 ORDER BY description|;
2610 $query = qq|SELECT id, description
2612 ORDER BY description|;
2615 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2618 $query = qq|SELECT id, description
2622 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2625 $query = qq|SELECT printer_description, id
2627 ORDER BY printer_description|;
2629 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2632 $query = qq|SELECT id, description
2636 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2638 $main::lxdebug->leave_sub();
2641 sub language_payment {
2642 $main::lxdebug->enter_sub();
2644 my ($self, $myconfig) = @_;
2646 my $dbh = $self->get_standard_dbh($myconfig);
2648 my $query = qq|SELECT id, description
2652 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2655 $query = qq|SELECT printer_description, id
2657 ORDER BY printer_description|;
2659 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2662 $query = qq|SELECT id, description
2666 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2668 # get buchungsgruppen
2669 $query = qq|SELECT id, description
2670 FROM buchungsgruppen|;
2672 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2674 $main::lxdebug->leave_sub();
2677 # this is only used for reports
2678 sub all_departments {
2679 $main::lxdebug->enter_sub();
2681 my ($self, $myconfig, $table) = @_;
2683 my $dbh = $self->get_standard_dbh($myconfig);
2686 if ($table eq 'customer') {
2687 $where = "WHERE role = 'P' ";
2690 my $query = qq|SELECT id, description
2693 ORDER BY description|;
2694 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2696 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2698 $main::lxdebug->leave_sub();
2702 $main::lxdebug->enter_sub();
2704 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2707 if ($table eq "customer") {
2716 $self->all_vc($myconfig, $table, $module);
2718 # get last customers or vendors
2719 my ($query, $sth, $ref);
2721 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2726 my $transdate = "current_date";
2727 if ($self->{transdate}) {
2728 $transdate = $dbh->quote($self->{transdate});
2731 # now get the account numbers
2732 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2733 FROM chart c, taxkeys tk
2734 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2735 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2738 $sth = $dbh->prepare($query);
2740 do_statement($self, $sth, $query, '%' . $module . '%');
2742 $self->{accounts} = "";
2743 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2745 foreach my $key (split(/:/, $ref->{link})) {
2746 if ($key =~ /\Q$module\E/) {
2748 # cross reference for keys
2749 $xkeyref{ $ref->{accno} } = $key;
2751 push @{ $self->{"${module}_links"}{$key} },
2752 { accno => $ref->{accno},
2753 description => $ref->{description},
2754 taxkey => $ref->{taxkey_id},
2755 tax_id => $ref->{tax_id} };
2757 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2763 # get taxkeys and description
2764 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2765 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2767 if (($module eq "AP") || ($module eq "AR")) {
2768 # get tax rates and description
2769 $query = qq|SELECT * FROM tax|;
2770 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2776 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2777 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2778 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2779 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2781 d.description AS department,
2784 JOIN $table c ON (a.${table}_id = c.id)
2785 LEFT JOIN employee e ON (e.id = a.employee_id)
2786 LEFT JOIN department d ON (d.id = a.department_id)
2788 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2790 foreach my $key (keys %$ref) {
2791 $self->{$key} = $ref->{$key};
2794 my $transdate = "current_date";
2795 if ($self->{transdate}) {
2796 $transdate = $dbh->quote($self->{transdate});
2799 # now get the account numbers
2800 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2802 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2804 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2805 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2808 $sth = $dbh->prepare($query);
2809 do_statement($self, $sth, $query, "%$module%");
2811 $self->{accounts} = "";
2812 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2814 foreach my $key (split(/:/, $ref->{link})) {
2815 if ($key =~ /\Q$module\E/) {
2817 # cross reference for keys
2818 $xkeyref{ $ref->{accno} } = $key;
2820 push @{ $self->{"${module}_links"}{$key} },
2821 { accno => $ref->{accno},
2822 description => $ref->{description},
2823 taxkey => $ref->{taxkey_id},
2824 tax_id => $ref->{tax_id} };
2826 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2832 # get amounts from individual entries
2835 c.accno, c.description,
2836 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2840 LEFT JOIN chart c ON (c.id = a.chart_id)
2841 LEFT JOIN project p ON (p.id = a.project_id)
2842 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2843 WHERE (tk.taxkey_id=a.taxkey) AND
2844 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2845 THEN tk.chart_id = a.chart_id
2848 OR (c.link='%tax%')) AND
2849 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2850 WHERE a.trans_id = ?
2851 AND a.fx_transaction = '0'
2852 ORDER BY a.acc_trans_id, a.transdate|;
2853 $sth = $dbh->prepare($query);
2854 do_statement($self, $sth, $query, $self->{id});
2856 # get exchangerate for currency
2857 $self->{exchangerate} =
2858 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2861 # store amounts in {acc_trans}{$key} for multiple accounts
2862 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2863 $ref->{exchangerate} =
2864 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2865 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2868 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2869 $ref->{amount} *= -1;
2871 $ref->{index} = $index;
2873 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2879 d.curr AS currencies, d.closedto, d.revtrans,
2880 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2881 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2883 $ref = selectfirst_hashref_query($self, $dbh, $query);
2884 map { $self->{$_} = $ref->{$_} } keys %$ref;
2891 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2892 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2893 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2895 $ref = selectfirst_hashref_query($self, $dbh, $query);
2896 map { $self->{$_} = $ref->{$_} } keys %$ref;
2898 if ($self->{"$self->{vc}_id"}) {
2900 # only setup currency
2901 ($self->{currency}) = split(/:/, $self->{currencies});
2905 $self->lastname_used($dbh, $myconfig, $table, $module);
2907 # get exchangerate for currency
2908 $self->{exchangerate} =
2909 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2915 $main::lxdebug->leave_sub();
2919 $main::lxdebug->enter_sub();
2921 my ($self, $dbh, $myconfig, $table, $module) = @_;
2925 $table = $table eq "customer" ? "customer" : "vendor";
2926 my %column_map = ("a.curr" => "currency",
2927 "a.${table}_id" => "${table}_id",
2928 "a.department_id" => "department_id",
2929 "d.description" => "department",
2930 "ct.name" => $table,
2931 "current_date + ct.terms" => "duedate",
2934 if ($self->{type} =~ /delivery_order/) {
2935 $arap = 'delivery_orders';
2936 delete $column_map{"a.curr"};
2938 } elsif ($self->{type} =~ /_order/) {
2940 $where = "quotation = '0'";
2942 } elsif ($self->{type} =~ /_quotation/) {
2944 $where = "quotation = '1'";
2946 } elsif ($table eq 'customer') {
2954 $where = "($where) AND" if ($where);
2955 my $query = qq|SELECT MAX(id) FROM $arap
2956 WHERE $where ${table}_id > 0|;
2957 my ($trans_id) = selectrow_query($self, $dbh, $query);
2960 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2961 $query = qq|SELECT $column_spec
2963 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2964 LEFT JOIN department d ON (a.department_id = d.id)
2966 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2968 map { $self->{$_} = $ref->{$_} } values %column_map;
2970 $main::lxdebug->leave_sub();
2974 $main::lxdebug->enter_sub();
2976 my ($self, $myconfig, $thisdate, $days) = @_;
2978 my $dbh = $self->get_standard_dbh($myconfig);
2983 my $dateformat = $myconfig->{dateformat};
2984 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2985 $thisdate = $dbh->quote($thisdate);
2986 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2988 $query = qq|SELECT current_date AS thisdate|;
2991 ($thisdate) = selectrow_query($self, $dbh, $query);
2993 $main::lxdebug->leave_sub();
2999 $main::lxdebug->enter_sub();
3001 my ($self, $string) = @_;
3003 if ($string !~ /%/) {
3004 $string = "%$string%";
3007 $string =~ s/\'/\'\'/g;
3009 $main::lxdebug->leave_sub();
3015 $main::lxdebug->enter_sub();
3017 my ($self, $flds, $new, $count, $numrows) = @_;
3021 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3026 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3028 my $j = $item->{ndx} - 1;
3029 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3033 for $i ($count + 1 .. $numrows) {
3034 map { delete $self->{"${_}_$i"} } @{$flds};
3037 $main::lxdebug->leave_sub();
3041 $main::lxdebug->enter_sub();
3043 my ($self, $myconfig) = @_;
3047 my $dbh = $self->dbconnect_noauto($myconfig);
3049 my $query = qq|DELETE FROM status
3050 WHERE (formname = ?) AND (trans_id = ?)|;
3051 my $sth = prepare_query($self, $dbh, $query);
3053 if ($self->{formname} =~ /(check|receipt)/) {
3054 for $i (1 .. $self->{rowcount}) {
3055 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3058 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3062 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3063 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3065 my %queued = split / /, $self->{queued};
3068 if ($self->{formname} =~ /(check|receipt)/) {
3070 # this is a check or receipt, add one entry for each lineitem
3071 my ($accno) = split /--/, $self->{account};
3072 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3073 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3074 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3075 $sth = prepare_query($self, $dbh, $query);
3077 for $i (1 .. $self->{rowcount}) {
3078 if ($self->{"checked_$i"}) {
3079 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3085 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3086 VALUES (?, ?, ?, ?, ?)|;
3087 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3088 $queued{$self->{formname}}, $self->{formname});
3094 $main::lxdebug->leave_sub();
3098 $main::lxdebug->enter_sub();
3100 my ($self, $dbh) = @_;
3102 my ($query, $printed, $emailed);
3104 my $formnames = $self->{printed};
3105 my $emailforms = $self->{emailed};
3107 $query = qq|DELETE FROM status
3108 WHERE (formname = ?) AND (trans_id = ?)|;
3109 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3111 # this only applies to the forms
3112 # checks and receipts are posted when printed or queued
3114 if ($self->{queued}) {
3115 my %queued = split / /, $self->{queued};
3117 foreach my $formname (keys %queued) {
3118 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3119 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3121 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3122 VALUES (?, ?, ?, ?, ?)|;
3123 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3125 $formnames =~ s/\Q$self->{formname}\E//;
3126 $emailforms =~ s/\Q$self->{formname}\E//;
3131 # save printed, emailed info
3132 $formnames =~ s/^ +//g;
3133 $emailforms =~ s/^ +//g;
3136 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3137 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3139 foreach my $formname (keys %status) {
3140 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3141 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3143 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3144 VALUES (?, ?, ?, ?)|;
3145 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3148 $main::lxdebug->leave_sub();
3152 # $main::locale->text('SAVED')
3153 # $main::locale->text('DELETED')
3154 # $main::locale->text('ADDED')
3155 # $main::locale->text('PAYMENT POSTED')
3156 # $main::locale->text('POSTED')
3157 # $main::locale->text('POSTED AS NEW')
3158 # $main::locale->text('ELSE')
3159 # $main::locale->text('SAVED FOR DUNNING')
3160 # $main::locale->text('DUNNING STARTED')
3161 # $main::locale->text('PRINTED')
3162 # $main::locale->text('MAILED')
3163 # $main::locale->text('SCREENED')
3164 # $main::locale->text('CANCELED')
3165 # $main::locale->text('invoice')
3166 # $main::locale->text('proforma')
3167 # $main::locale->text('sales_order')
3168 # $main::locale->text('packing_list')
3169 # $main::locale->text('pick_list')
3170 # $main::locale->text('purchase_order')
3171 # $main::locale->text('bin_list')
3172 # $main::locale->text('sales_quotation')
3173 # $main::locale->text('request_quotation')
3176 $main::lxdebug->enter_sub();
3181 if(!exists $self->{employee_id}) {
3182 &get_employee($self, $dbh);
3186 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3187 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3188 my @values = (conv_i($self->{id}), $self->{login},
3189 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3190 do_query($self, $dbh, $query, @values);
3192 $main::lxdebug->leave_sub();
3196 $main::lxdebug->enter_sub();
3198 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3199 my ($orderBy, $desc) = split(/\-\-/, $order);
3200 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3203 if ($trans_id ne "") {
3205 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 | .
3206 qq|FROM history_erp h | .
3207 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3208 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3211 my $sth = $dbh->prepare($query) || $self->dberror($query);
3213 $sth->execute() || $self->dberror("$query");
3215 while(my $hash_ref = $sth->fetchrow_hashref()) {
3216 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3217 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3218 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3219 $tempArray[$i++] = $hash_ref;
3221 $main::lxdebug->leave_sub() and return \@tempArray
3222 if ($i > 0 && $tempArray[0] ne "");
3224 $main::lxdebug->leave_sub();
3228 sub update_defaults {
3229 $main::lxdebug->enter_sub();
3231 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3234 if ($provided_dbh) {
3235 $dbh = $provided_dbh;
3237 $dbh = $self->dbconnect_noauto($myconfig);
3239 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3240 my $sth = $dbh->prepare($query);
3242 $sth->execute || $self->dberror($query);
3243 my ($var) = $sth->fetchrow_array;
3246 if ($var =~ m/\d+$/) {
3247 my $new_var = (substr $var, $-[0]) * 1 + 1;
3248 my $len_diff = length($var) - $-[0] - length($new_var);
3249 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3255 $query = qq|UPDATE defaults SET $fld = ?|;
3256 do_query($self, $dbh, $query, $var);
3258 if (!$provided_dbh) {
3263 $main::lxdebug->leave_sub();
3268 sub update_business {
3269 $main::lxdebug->enter_sub();
3271 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3274 if ($provided_dbh) {
3275 $dbh = $provided_dbh;
3277 $dbh = $self->dbconnect_noauto($myconfig);
3280 qq|SELECT customernumberinit FROM business
3281 WHERE id = ? FOR UPDATE|;
3282 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3284 return undef unless $var;
3286 if ($var =~ m/\d+$/) {
3287 my $new_var = (substr $var, $-[0]) * 1 + 1;
3288 my $len_diff = length($var) - $-[0] - length($new_var);
3289 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3295 $query = qq|UPDATE business
3296 SET customernumberinit = ?
3298 do_query($self, $dbh, $query, $var, $business_id);
3300 if (!$provided_dbh) {
3305 $main::lxdebug->leave_sub();
3310 sub get_partsgroup {
3311 $main::lxdebug->enter_sub();
3313 my ($self, $myconfig, $p) = @_;
3314 my $target = $p->{target} || 'all_partsgroup';
3316 my $dbh = $self->get_standard_dbh($myconfig);
3318 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3320 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3323 if ($p->{searchitems} eq 'part') {
3324 $query .= qq|WHERE p.inventory_accno_id > 0|;
3326 if ($p->{searchitems} eq 'service') {
3327 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3329 if ($p->{searchitems} eq 'assembly') {
3330 $query .= qq|WHERE p.assembly = '1'|;
3332 if ($p->{searchitems} eq 'labor') {
3333 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3336 $query .= qq|ORDER BY partsgroup|;
3339 $query = qq|SELECT id, partsgroup FROM partsgroup
3340 ORDER BY partsgroup|;
3343 if ($p->{language_code}) {
3344 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3345 t.description AS translation
3347 JOIN parts p ON (p.partsgroup_id = pg.id)
3348 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3349 ORDER BY translation|;
3350 @values = ($p->{language_code});
3353 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3355 $main::lxdebug->leave_sub();
3358 sub get_pricegroup {
3359 $main::lxdebug->enter_sub();
3361 my ($self, $myconfig, $p) = @_;
3363 my $dbh = $self->get_standard_dbh($myconfig);
3365 my $query = qq|SELECT p.id, p.pricegroup
3368 $query .= qq| ORDER BY pricegroup|;
3371 $query = qq|SELECT id, pricegroup FROM pricegroup
3372 ORDER BY pricegroup|;
3375 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3377 $main::lxdebug->leave_sub();
3381 # usage $form->all_years($myconfig, [$dbh])
3382 # return list of all years where bookings found
3385 $main::lxdebug->enter_sub();
3387 my ($self, $myconfig, $dbh) = @_;
3389 $dbh ||= $self->get_standard_dbh($myconfig);
3392 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3393 (SELECT MAX(transdate) FROM acc_trans)|;
3394 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3396 if ($myconfig->{dateformat} =~ /^yy/) {
3397 ($startdate) = split /\W/, $startdate;
3398 ($enddate) = split /\W/, $enddate;
3400 (@_) = split /\W/, $startdate;
3402 (@_) = split /\W/, $enddate;
3407 $startdate = substr($startdate,0,4);
3408 $enddate = substr($enddate,0,4);
3410 while ($enddate >= $startdate) {
3411 push @all_years, $enddate--;
3416 $main::lxdebug->leave_sub();
3420 $main::lxdebug->enter_sub();
3424 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3426 $main::lxdebug->leave_sub();
3430 $main::lxdebug->enter_sub();
3435 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3437 $main::lxdebug->leave_sub();
3446 SL::Form.pm - main data object.
3450 This is the main data object of Lx-Office.
3451 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3452 Points of interest for a beginner are:
3454 - $form->error - renders a generic error in html. accepts an error message
3455 - $form->get_standard_dbh - returns a database connection for the
3457 =head1 SPECIAL FUNCTIONS
3461 =item _store_value()
3463 parses a complex var name, and stores it in the form.
3466 $form->_store_value($key, $value);
3468 keys must start with a string, and can contain various tokens.
3469 supported key structures are:
3472 simple key strings work as expected
3477 separating two keys by a dot (.) will result in a hash lookup for the inner value
3478 this is similar to the behaviour of java and templating mechanisms.
3480 filter.description => $form->{filter}->{description}
3482 3. array+hashref access
3484 adding brackets ([]) before the dot will cause the next hash to be put into an array.
3485 using [+] instead of [] will force a new array index. this is useful for recurring
3486 data structures like part lists. put a [+] into the first varname, and use [] on the
3489 repeating these names in your template:
3492 invoice.items[].parts_id
3496 $form->{invoice}->{items}->[
3510 using brackets at the end of a name will result in a pure array to be created.
3511 note that you mustn't use [+], which is reserved for array+hash access and will
3512 result in undefined behaviour in array context.
3514 filter.status[] => $form->{status}->[ val1, val2, ... ]
3516 =item update_business PARAMS
3519 \%config, - config hashref
3520 $business_id, - business id
3521 $dbh - optional database handle
3523 handles business (thats customer/vendor types) sequences.
3525 special behaviour for empty strings in customerinitnumber field:
3526 will in this case not increase the value, and return undef.