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/jquery.autocomplete.js'></script>
640 <script type="text/javascript" src="js/common.js"></script>
641 <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
642 <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
643 <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
644 <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
651 ? "$self->{title} - $self->{titlebar}"
654 foreach my $item (@ { $self->{AJAX} }) {
655 $ajax .= $item->show_javascript();
658 print $self->create_http_response('content_type' => 'text/html',
659 'charset' => $db_charset,);
660 print qq|${doctype}<html>
662 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
663 <title>$self->{titlebar}</title>
672 <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
674 <meta name="robots" content="noindex,nofollow" />
675 <script type="text/javascript" src="js/highlight_input.js"></script>
677 <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
678 <script type="text/javascript" src="js/tabcontent.js">
680 /***********************************************
681 * Tab Content script v2.2- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
682 * This notice MUST stay intact for legal use
683 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
684 ***********************************************/
695 $main::lxdebug->leave_sub();
698 sub ajax_response_header {
699 $main::lxdebug->enter_sub();
703 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
704 my $cgi = $main::cgi || CGI->new('');
705 my $output = $cgi->header('-charset' => $db_charset);
707 $main::lxdebug->leave_sub();
712 sub _prepare_html_template {
713 $main::lxdebug->enter_sub();
715 my ($self, $file, $additional_params) = @_;
718 if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
719 $language = $main::language;
721 $language = $main::myconfig{"countrycode"};
723 $language = "de" unless ($language);
725 if (-f "templates/webpages/${file}_${language}.html") {
726 if ((-f ".developer") &&
727 (-f "templates/webpages/${file}_master.html") &&
728 ((stat("templates/webpages/${file}_master.html"))[9] >
729 (stat("templates/webpages/${file}_${language}.html"))[9])) {
730 my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
731 "Please re-run 'locales.pl' in 'locale/${language}'.";
732 print(qq|<pre>$info</pre>|);
736 $file = "templates/webpages/${file}_${language}.html";
737 } elsif (-f "templates/webpages/${file}.html") {
738 $file = "templates/webpages/${file}.html";
740 my $info = "Web page template '${file}' not found.\n" .
741 "Please re-run 'locales.pl' in 'locale/${language}'.";
742 print(qq|<pre>$info</pre>|);
746 if ($self->{"DEBUG"}) {
747 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
750 if ($additional_params->{"DEBUG"}) {
751 $additional_params->{"DEBUG"} =
752 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
755 if (%main::myconfig) {
756 map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
757 my $jsc_dateformat = $main::myconfig{"dateformat"};
758 $jsc_dateformat =~ s/d+/\%d/gi;
759 $jsc_dateformat =~ s/m+/\%m/gi;
760 $jsc_dateformat =~ s/y+/\%Y/gi;
761 $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
764 $additional_params->{"conf_dbcharset"} = $main::dbcharset;
765 $additional_params->{"conf_webdav"} = $main::webdav;
766 $additional_params->{"conf_lizenzen"} = $main::lizenzen;
767 $additional_params->{"conf_latex_templates"} = $main::latex;
768 $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
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 $key = "all_business_types" unless ($key);
2226 selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2228 $main::lxdebug->leave_sub();
2231 sub _get_languages {
2232 $main::lxdebug->enter_sub();
2234 my ($self, $dbh, $key) = @_;
2236 $key = "all_languages" unless ($key);
2238 my $query = qq|SELECT * FROM language ORDER BY id|;
2240 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2242 $main::lxdebug->leave_sub();
2245 sub _get_dunning_configs {
2246 $main::lxdebug->enter_sub();
2248 my ($self, $dbh, $key) = @_;
2250 $key = "all_dunning_configs" unless ($key);
2252 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2254 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2256 $main::lxdebug->leave_sub();
2259 sub _get_currencies {
2260 $main::lxdebug->enter_sub();
2262 my ($self, $dbh, $key) = @_;
2264 $key = "all_currencies" unless ($key);
2266 my $query = qq|SELECT curr AS currency FROM defaults|;
2268 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2270 $main::lxdebug->leave_sub();
2274 $main::lxdebug->enter_sub();
2276 my ($self, $dbh, $key) = @_;
2278 $key = "all_payments" unless ($key);
2280 my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2282 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2284 $main::lxdebug->leave_sub();
2287 sub _get_customers {
2288 $main::lxdebug->enter_sub();
2290 my ($self, $dbh, $key, $limit) = @_;
2292 $key = "all_customers" unless ($key);
2293 my $limit_clause = "LIMIT $limit" if $limit;
2295 my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2297 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2299 $main::lxdebug->leave_sub();
2303 $main::lxdebug->enter_sub();
2305 my ($self, $dbh, $key) = @_;
2307 $key = "all_vendors" unless ($key);
2309 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2311 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2313 $main::lxdebug->leave_sub();
2316 sub _get_departments {
2317 $main::lxdebug->enter_sub();
2319 my ($self, $dbh, $key) = @_;
2321 $key = "all_departments" unless ($key);
2323 my $query = qq|SELECT * FROM department ORDER BY description|;
2325 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2327 $main::lxdebug->leave_sub();
2330 sub _get_warehouses {
2331 $main::lxdebug->enter_sub();
2333 my ($self, $dbh, $param) = @_;
2335 my ($key, $bins_key);
2337 if ('' eq ref $param) {
2341 $key = $param->{key};
2342 $bins_key = $param->{bins};
2345 my $query = qq|SELECT w.* FROM warehouse w
2346 WHERE (NOT w.invalid) AND
2347 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2348 ORDER BY w.sortkey|;
2350 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2353 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2354 my $sth = prepare_query($self, $dbh, $query);
2356 foreach my $warehouse (@{ $self->{$key} }) {
2357 do_statement($self, $sth, $query, $warehouse->{id});
2358 $warehouse->{$bins_key} = [];
2360 while (my $ref = $sth->fetchrow_hashref()) {
2361 push @{ $warehouse->{$bins_key} }, $ref;
2367 $main::lxdebug->leave_sub();
2371 $main::lxdebug->enter_sub();
2373 my ($self, $dbh, $table, $key, $sortkey) = @_;
2375 my $query = qq|SELECT * FROM $table|;
2376 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2378 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2380 $main::lxdebug->leave_sub();
2384 # $main::lxdebug->enter_sub();
2386 # my ($self, $dbh, $key) = @_;
2388 # $key ||= "all_groups";
2390 # my $groups = $main::auth->read_groups();
2392 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2394 # $main::lxdebug->leave_sub();
2398 $main::lxdebug->enter_sub();
2403 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2404 my ($sth, $query, $ref);
2406 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2407 my $vc_id = $self->{"${vc}_id"};
2409 if ($params{"contacts"}) {
2410 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2413 if ($params{"shipto"}) {
2414 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2417 if ($params{"projects"} || $params{"all_projects"}) {
2418 $self->_get_projects($dbh, $params{"all_projects"} ?
2419 $params{"all_projects"} : $params{"projects"},
2420 $params{"all_projects"} ? 1 : 0);
2423 if ($params{"printers"}) {
2424 $self->_get_printers($dbh, $params{"printers"});
2427 if ($params{"languages"}) {
2428 $self->_get_languages($dbh, $params{"languages"});
2431 if ($params{"charts"}) {
2432 $self->_get_charts($dbh, $params{"charts"});
2435 if ($params{"taxcharts"}) {
2436 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2439 if ($params{"taxzones"}) {
2440 $self->_get_taxzones($dbh, $params{"taxzones"});
2443 if ($params{"employees"}) {
2444 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2447 if ($params{"salesmen"}) {
2448 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2451 if ($params{"business_types"}) {
2452 $self->_get_business_types($dbh, $params{"business_types"});
2455 if ($params{"dunning_configs"}) {
2456 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2459 if($params{"currencies"}) {
2460 $self->_get_currencies($dbh, $params{"currencies"});
2463 if($params{"customers"}) {
2464 if (ref $params{"customers"} eq 'HASH') {
2465 $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2467 $self->_get_customers($dbh, $params{"customers"});
2471 if($params{"vendors"}) {
2472 if (ref $params{"vendors"} eq 'HASH') {
2473 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2475 $self->_get_vendors($dbh, $params{"vendors"});
2479 if($params{"payments"}) {
2480 $self->_get_payments($dbh, $params{"payments"});
2483 if($params{"departments"}) {
2484 $self->_get_departments($dbh, $params{"departments"});
2487 if ($params{price_factors}) {
2488 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2491 if ($params{warehouses}) {
2492 $self->_get_warehouses($dbh, $params{warehouses});
2495 # if ($params{groups}) {
2496 # $self->_get_groups($dbh, $params{groups});
2499 if ($params{partsgroup}) {
2500 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2503 $main::lxdebug->leave_sub();
2506 # this sub gets the id and name from $table
2508 $main::lxdebug->enter_sub();
2510 my ($self, $myconfig, $table) = @_;
2512 # connect to database
2513 my $dbh = $self->get_standard_dbh($myconfig);
2515 $table = $table eq "customer" ? "customer" : "vendor";
2516 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2518 my ($query, @values);
2520 if (!$self->{openinvoices}) {
2522 if ($self->{customernumber} ne "") {
2523 $where = qq|(vc.customernumber ILIKE ?)|;
2524 push(@values, '%' . $self->{customernumber} . '%');
2526 $where = qq|(vc.name ILIKE ?)|;
2527 push(@values, '%' . $self->{$table} . '%');
2531 qq~SELECT vc.id, vc.name,
2532 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2534 WHERE $where AND (NOT vc.obsolete)
2538 qq~SELECT DISTINCT vc.id, vc.name,
2539 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2541 JOIN $table vc ON (a.${table}_id = vc.id)
2542 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2544 push(@values, '%' . $self->{$table} . '%');
2547 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2549 $main::lxdebug->leave_sub();
2551 return scalar(@{ $self->{name_list} });
2554 # the selection sub is used in the AR, AP, IS, IR and OE module
2557 $main::lxdebug->enter_sub();
2559 my ($self, $myconfig, $table, $module) = @_;
2562 my $dbh = $self->get_standard_dbh($myconfig);
2564 $table = $table eq "customer" ? "customer" : "vendor";
2566 my $query = qq|SELECT count(*) FROM $table|;
2567 my ($count) = selectrow_query($self, $dbh, $query);
2569 # build selection list
2570 if ($count < $myconfig->{vclimit}) {
2571 $query = qq|SELECT id, name, salesman_id
2572 FROM $table WHERE NOT obsolete
2574 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2578 $self->get_employee($dbh);
2580 # setup sales contacts
2581 $query = qq|SELECT e.id, e.name
2583 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2584 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2587 push(@{ $self->{all_employees} },
2588 { id => $self->{employee_id},
2589 name => $self->{employee} });
2591 # sort the whole thing
2592 @{ $self->{all_employees} } =
2593 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2595 if ($module eq 'AR') {
2597 # prepare query for departments
2598 $query = qq|SELECT id, description
2601 ORDER BY description|;
2604 $query = qq|SELECT id, description
2606 ORDER BY description|;
2609 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2612 $query = qq|SELECT id, description
2616 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2619 $query = qq|SELECT printer_description, id
2621 ORDER BY printer_description|;
2623 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2626 $query = qq|SELECT id, description
2630 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2632 $main::lxdebug->leave_sub();
2635 sub language_payment {
2636 $main::lxdebug->enter_sub();
2638 my ($self, $myconfig) = @_;
2640 my $dbh = $self->get_standard_dbh($myconfig);
2642 my $query = qq|SELECT id, description
2646 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2649 $query = qq|SELECT printer_description, id
2651 ORDER BY printer_description|;
2653 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2656 $query = qq|SELECT id, description
2660 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2662 # get buchungsgruppen
2663 $query = qq|SELECT id, description
2664 FROM buchungsgruppen|;
2666 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2668 $main::lxdebug->leave_sub();
2671 # this is only used for reports
2672 sub all_departments {
2673 $main::lxdebug->enter_sub();
2675 my ($self, $myconfig, $table) = @_;
2677 my $dbh = $self->get_standard_dbh($myconfig);
2680 if ($table eq 'customer') {
2681 $where = "WHERE role = 'P' ";
2684 my $query = qq|SELECT id, description
2687 ORDER BY description|;
2688 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2690 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2692 $main::lxdebug->leave_sub();
2696 $main::lxdebug->enter_sub();
2698 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2701 if ($table eq "customer") {
2710 $self->all_vc($myconfig, $table, $module);
2712 # get last customers or vendors
2713 my ($query, $sth, $ref);
2715 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2720 my $transdate = "current_date";
2721 if ($self->{transdate}) {
2722 $transdate = $dbh->quote($self->{transdate});
2725 # now get the account numbers
2726 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2727 FROM chart c, taxkeys tk
2728 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2729 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2732 $sth = $dbh->prepare($query);
2734 do_statement($self, $sth, $query, '%' . $module . '%');
2736 $self->{accounts} = "";
2737 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2739 foreach my $key (split(/:/, $ref->{link})) {
2740 if ($key =~ /\Q$module\E/) {
2742 # cross reference for keys
2743 $xkeyref{ $ref->{accno} } = $key;
2745 push @{ $self->{"${module}_links"}{$key} },
2746 { accno => $ref->{accno},
2747 description => $ref->{description},
2748 taxkey => $ref->{taxkey_id},
2749 tax_id => $ref->{tax_id} };
2751 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2757 # get taxkeys and description
2758 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2759 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2761 if (($module eq "AP") || ($module eq "AR")) {
2762 # get tax rates and description
2763 $query = qq|SELECT * FROM tax|;
2764 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2770 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2771 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2772 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2773 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2775 d.description AS department,
2778 JOIN $table c ON (a.${table}_id = c.id)
2779 LEFT JOIN employee e ON (e.id = a.employee_id)
2780 LEFT JOIN department d ON (d.id = a.department_id)
2782 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2784 foreach my $key (keys %$ref) {
2785 $self->{$key} = $ref->{$key};
2788 my $transdate = "current_date";
2789 if ($self->{transdate}) {
2790 $transdate = $dbh->quote($self->{transdate});
2793 # now get the account numbers
2794 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2796 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2798 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2799 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2802 $sth = $dbh->prepare($query);
2803 do_statement($self, $sth, $query, "%$module%");
2805 $self->{accounts} = "";
2806 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2808 foreach my $key (split(/:/, $ref->{link})) {
2809 if ($key =~ /\Q$module\E/) {
2811 # cross reference for keys
2812 $xkeyref{ $ref->{accno} } = $key;
2814 push @{ $self->{"${module}_links"}{$key} },
2815 { accno => $ref->{accno},
2816 description => $ref->{description},
2817 taxkey => $ref->{taxkey_id},
2818 tax_id => $ref->{tax_id} };
2820 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2826 # get amounts from individual entries
2829 c.accno, c.description,
2830 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2834 LEFT JOIN chart c ON (c.id = a.chart_id)
2835 LEFT JOIN project p ON (p.id = a.project_id)
2836 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2837 WHERE (tk.taxkey_id=a.taxkey) AND
2838 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2839 THEN tk.chart_id = a.chart_id
2842 OR (c.link='%tax%')) AND
2843 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2844 WHERE a.trans_id = ?
2845 AND a.fx_transaction = '0'
2846 ORDER BY a.acc_trans_id, a.transdate|;
2847 $sth = $dbh->prepare($query);
2848 do_statement($self, $sth, $query, $self->{id});
2850 # get exchangerate for currency
2851 $self->{exchangerate} =
2852 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2855 # store amounts in {acc_trans}{$key} for multiple accounts
2856 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2857 $ref->{exchangerate} =
2858 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2859 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2862 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2863 $ref->{amount} *= -1;
2865 $ref->{index} = $index;
2867 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2873 d.curr AS currencies, d.closedto, d.revtrans,
2874 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2875 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2877 $ref = selectfirst_hashref_query($self, $dbh, $query);
2878 map { $self->{$_} = $ref->{$_} } keys %$ref;
2885 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2886 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2887 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2889 $ref = selectfirst_hashref_query($self, $dbh, $query);
2890 map { $self->{$_} = $ref->{$_} } keys %$ref;
2892 if ($self->{"$self->{vc}_id"}) {
2894 # only setup currency
2895 ($self->{currency}) = split(/:/, $self->{currencies});
2899 $self->lastname_used($dbh, $myconfig, $table, $module);
2901 # get exchangerate for currency
2902 $self->{exchangerate} =
2903 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2909 $main::lxdebug->leave_sub();
2913 $main::lxdebug->enter_sub();
2915 my ($self, $dbh, $myconfig, $table, $module) = @_;
2919 $table = $table eq "customer" ? "customer" : "vendor";
2920 my %column_map = ("a.curr" => "currency",
2921 "a.${table}_id" => "${table}_id",
2922 "a.department_id" => "department_id",
2923 "d.description" => "department",
2924 "ct.name" => $table,
2925 "current_date + ct.terms" => "duedate",
2928 if ($self->{type} =~ /delivery_order/) {
2929 $arap = 'delivery_orders';
2930 delete $column_map{"a.curr"};
2932 } elsif ($self->{type} =~ /_order/) {
2934 $where = "quotation = '0'";
2936 } elsif ($self->{type} =~ /_quotation/) {
2938 $where = "quotation = '1'";
2940 } elsif ($table eq 'customer') {
2948 $where = "($where) AND" if ($where);
2949 my $query = qq|SELECT MAX(id) FROM $arap
2950 WHERE $where ${table}_id > 0|;
2951 my ($trans_id) = selectrow_query($self, $dbh, $query);
2954 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2955 $query = qq|SELECT $column_spec
2957 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2958 LEFT JOIN department d ON (a.department_id = d.id)
2960 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2962 map { $self->{$_} = $ref->{$_} } values %column_map;
2964 $main::lxdebug->leave_sub();
2968 $main::lxdebug->enter_sub();
2970 my ($self, $myconfig, $thisdate, $days) = @_;
2972 my $dbh = $self->get_standard_dbh($myconfig);
2977 my $dateformat = $myconfig->{dateformat};
2978 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2979 $thisdate = $dbh->quote($thisdate);
2980 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2982 $query = qq|SELECT current_date AS thisdate|;
2985 ($thisdate) = selectrow_query($self, $dbh, $query);
2987 $main::lxdebug->leave_sub();
2993 $main::lxdebug->enter_sub();
2995 my ($self, $string) = @_;
2997 if ($string !~ /%/) {
2998 $string = "%$string%";
3001 $string =~ s/\'/\'\'/g;
3003 $main::lxdebug->leave_sub();
3009 $main::lxdebug->enter_sub();
3011 my ($self, $flds, $new, $count, $numrows) = @_;
3015 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3020 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3022 my $j = $item->{ndx} - 1;
3023 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3027 for $i ($count + 1 .. $numrows) {
3028 map { delete $self->{"${_}_$i"} } @{$flds};
3031 $main::lxdebug->leave_sub();
3035 $main::lxdebug->enter_sub();
3037 my ($self, $myconfig) = @_;
3041 my $dbh = $self->dbconnect_noauto($myconfig);
3043 my $query = qq|DELETE FROM status
3044 WHERE (formname = ?) AND (trans_id = ?)|;
3045 my $sth = prepare_query($self, $dbh, $query);
3047 if ($self->{formname} =~ /(check|receipt)/) {
3048 for $i (1 .. $self->{rowcount}) {
3049 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3052 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3056 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3057 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3059 my %queued = split / /, $self->{queued};
3062 if ($self->{formname} =~ /(check|receipt)/) {
3064 # this is a check or receipt, add one entry for each lineitem
3065 my ($accno) = split /--/, $self->{account};
3066 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3067 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3068 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3069 $sth = prepare_query($self, $dbh, $query);
3071 for $i (1 .. $self->{rowcount}) {
3072 if ($self->{"checked_$i"}) {
3073 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3079 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3080 VALUES (?, ?, ?, ?, ?)|;
3081 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3082 $queued{$self->{formname}}, $self->{formname});
3088 $main::lxdebug->leave_sub();
3092 $main::lxdebug->enter_sub();
3094 my ($self, $dbh) = @_;
3096 my ($query, $printed, $emailed);
3098 my $formnames = $self->{printed};
3099 my $emailforms = $self->{emailed};
3101 $query = qq|DELETE FROM status
3102 WHERE (formname = ?) AND (trans_id = ?)|;
3103 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3105 # this only applies to the forms
3106 # checks and receipts are posted when printed or queued
3108 if ($self->{queued}) {
3109 my %queued = split / /, $self->{queued};
3111 foreach my $formname (keys %queued) {
3112 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3113 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3115 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3116 VALUES (?, ?, ?, ?, ?)|;
3117 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3119 $formnames =~ s/\Q$self->{formname}\E//;
3120 $emailforms =~ s/\Q$self->{formname}\E//;
3125 # save printed, emailed info
3126 $formnames =~ s/^ +//g;
3127 $emailforms =~ s/^ +//g;
3130 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3131 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3133 foreach my $formname (keys %status) {
3134 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3135 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3137 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3138 VALUES (?, ?, ?, ?)|;
3139 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3142 $main::lxdebug->leave_sub();
3146 # $main::locale->text('SAVED')
3147 # $main::locale->text('DELETED')
3148 # $main::locale->text('ADDED')
3149 # $main::locale->text('PAYMENT POSTED')
3150 # $main::locale->text('POSTED')
3151 # $main::locale->text('POSTED AS NEW')
3152 # $main::locale->text('ELSE')
3153 # $main::locale->text('SAVED FOR DUNNING')
3154 # $main::locale->text('DUNNING STARTED')
3155 # $main::locale->text('PRINTED')
3156 # $main::locale->text('MAILED')
3157 # $main::locale->text('SCREENED')
3158 # $main::locale->text('CANCELED')
3159 # $main::locale->text('invoice')
3160 # $main::locale->text('proforma')
3161 # $main::locale->text('sales_order')
3162 # $main::locale->text('packing_list')
3163 # $main::locale->text('pick_list')
3164 # $main::locale->text('purchase_order')
3165 # $main::locale->text('bin_list')
3166 # $main::locale->text('sales_quotation')
3167 # $main::locale->text('request_quotation')
3170 $main::lxdebug->enter_sub();
3175 if(!exists $self->{employee_id}) {
3176 &get_employee($self, $dbh);
3180 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3181 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3182 my @values = (conv_i($self->{id}), $self->{login},
3183 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3184 do_query($self, $dbh, $query, @values);
3186 $main::lxdebug->leave_sub();
3190 $main::lxdebug->enter_sub();
3192 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3193 my ($orderBy, $desc) = split(/\-\-/, $order);
3194 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3197 if ($trans_id ne "") {
3199 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 | .
3200 qq|FROM history_erp h | .
3201 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3202 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3205 my $sth = $dbh->prepare($query) || $self->dberror($query);
3207 $sth->execute() || $self->dberror("$query");
3209 while(my $hash_ref = $sth->fetchrow_hashref()) {
3210 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3211 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3212 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3213 $tempArray[$i++] = $hash_ref;
3215 $main::lxdebug->leave_sub() and return \@tempArray
3216 if ($i > 0 && $tempArray[0] ne "");
3218 $main::lxdebug->leave_sub();
3222 sub update_defaults {
3223 $main::lxdebug->enter_sub();
3225 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3228 if ($provided_dbh) {
3229 $dbh = $provided_dbh;
3231 $dbh = $self->dbconnect_noauto($myconfig);
3233 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3234 my $sth = $dbh->prepare($query);
3236 $sth->execute || $self->dberror($query);
3237 my ($var) = $sth->fetchrow_array;
3240 if ($var =~ m/\d+$/) {
3241 my $new_var = (substr $var, $-[0]) * 1 + 1;
3242 my $len_diff = length($var) - $-[0] - length($new_var);
3243 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3249 $query = qq|UPDATE defaults SET $fld = ?|;
3250 do_query($self, $dbh, $query, $var);
3252 if (!$provided_dbh) {
3257 $main::lxdebug->leave_sub();
3262 sub update_business {
3263 $main::lxdebug->enter_sub();
3265 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3268 if ($provided_dbh) {
3269 $dbh = $provided_dbh;
3271 $dbh = $self->dbconnect_noauto($myconfig);
3274 qq|SELECT customernumberinit FROM business
3275 WHERE id = ? FOR UPDATE|;
3276 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3278 return undef unless $var;
3280 if ($var =~ m/\d+$/) {
3281 my $new_var = (substr $var, $-[0]) * 1 + 1;
3282 my $len_diff = length($var) - $-[0] - length($new_var);
3283 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3289 $query = qq|UPDATE business
3290 SET customernumberinit = ?
3292 do_query($self, $dbh, $query, $var, $business_id);
3294 if (!$provided_dbh) {
3299 $main::lxdebug->leave_sub();
3304 sub get_partsgroup {
3305 $main::lxdebug->enter_sub();
3307 my ($self, $myconfig, $p) = @_;
3308 my $target = $p->{target} || 'all_partsgroup';
3310 my $dbh = $self->get_standard_dbh($myconfig);
3312 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3314 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3317 if ($p->{searchitems} eq 'part') {
3318 $query .= qq|WHERE p.inventory_accno_id > 0|;
3320 if ($p->{searchitems} eq 'service') {
3321 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3323 if ($p->{searchitems} eq 'assembly') {
3324 $query .= qq|WHERE p.assembly = '1'|;
3326 if ($p->{searchitems} eq 'labor') {
3327 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3330 $query .= qq|ORDER BY partsgroup|;
3333 $query = qq|SELECT id, partsgroup FROM partsgroup
3334 ORDER BY partsgroup|;
3337 if ($p->{language_code}) {
3338 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3339 t.description AS translation
3341 JOIN parts p ON (p.partsgroup_id = pg.id)
3342 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3343 ORDER BY translation|;
3344 @values = ($p->{language_code});
3347 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3349 $main::lxdebug->leave_sub();
3352 sub get_pricegroup {
3353 $main::lxdebug->enter_sub();
3355 my ($self, $myconfig, $p) = @_;
3357 my $dbh = $self->get_standard_dbh($myconfig);
3359 my $query = qq|SELECT p.id, p.pricegroup
3362 $query .= qq| ORDER BY pricegroup|;
3365 $query = qq|SELECT id, pricegroup FROM pricegroup
3366 ORDER BY pricegroup|;
3369 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3371 $main::lxdebug->leave_sub();
3375 # usage $form->all_years($myconfig, [$dbh])
3376 # return list of all years where bookings found
3379 $main::lxdebug->enter_sub();
3381 my ($self, $myconfig, $dbh) = @_;
3383 $dbh ||= $self->get_standard_dbh($myconfig);
3386 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3387 (SELECT MAX(transdate) FROM acc_trans)|;
3388 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3390 if ($myconfig->{dateformat} =~ /^yy/) {
3391 ($startdate) = split /\W/, $startdate;
3392 ($enddate) = split /\W/, $enddate;
3394 (@_) = split /\W/, $startdate;
3396 (@_) = split /\W/, $enddate;
3401 $startdate = substr($startdate,0,4);
3402 $enddate = substr($enddate,0,4);
3404 while ($enddate >= $startdate) {
3405 push @all_years, $enddate--;
3410 $main::lxdebug->leave_sub();
3414 $main::lxdebug->enter_sub();
3418 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3420 $main::lxdebug->leave_sub();
3424 $main::lxdebug->enter_sub();
3429 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3431 $main::lxdebug->leave_sub();
3440 SL::Form.pm - main data object.
3444 This is the main data object of Lx-Office.
3445 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3446 Points of interest for a beginner are:
3448 - $form->error - renders a generic error in html. accepts an error message
3449 - $form->get_standard_dbh - returns a database connection for the
3451 =head1 SPECIAL FUNCTIONS
3455 =item _store_value()
3457 parses a complex var name, and stores it in the form.
3460 $form->_store_value($key, $value);
3462 keys must start with a string, and can contain various tokens.
3463 supported key structures are:
3466 simple key strings work as expected
3471 separating two keys by a dot (.) will result in a hash lookup for the inner value
3472 this is similar to the behaviour of java and templating mechanisms.
3474 filter.description => $form->{filter}->{description}
3476 3. array+hashref access
3478 adding brackets ([]) before the dot will cause the next hash to be put into an array.
3479 using [+] instead of [] will force a new array index. this is useful for recurring
3480 data structures like part lists. put a [+] into the first varname, and use [] on the
3483 repeating these names in your template:
3486 invoice.items[].parts_id
3490 $form->{invoice}->{items}->[
3504 using brackets at the end of a name will result in a pure array to be created.
3505 note that you mustn't use [+], which is reserved for array+hash access and will
3506 result in undefined behaviour in array context.
3508 filter.status[] => $form->{status}->[ val1, val2, ... ]
3510 =item update_business PARAMS
3513 \%config, - config hashref
3514 $business_id, - business id
3515 $dbh - optional database handle
3517 handles business (thats customer/vendor types) sequences.
3519 special behaviour for empty strings in customerinitnumber field:
3520 will in this case not increase the value, and return undef.