1 #====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
15 # Contributors: Thomas Bayen <bayen@gmx.de>
16 # Antti Kaihola <akaihola@siba.fi>
17 # Moritz Bunkus (tex code)
19 # This program is free software; you can redistribute it and/or modify
20 # it under the terms of the GNU General Public License as published by
21 # the Free Software Foundation; either version 2 of the License, or
22 # (at your option) any later version.
24 # This program is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 # GNU General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, write to the Free Software
30 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #======================================================================
32 # Utilities for parsing forms
33 # and supporting routines for linking account numbers
34 # used in AR, AP and IS, IR modules
36 #======================================================================
59 use List::Util qw(first max min sum);
60 use List::MoreUtils qw(any);
66 $standard_dbh->disconnect();
73 parses a complex var name, and stores it in the form.
76 $form->_store_value($key, $value);
78 keys must start with a string, and can contain various tokens.
79 supported key structures are:
82 simple key strings work as expected
87 separating two keys by a dot (.) will result in a hash lookup for the inner value
88 this is similar to the behaviour of java and templating mechanisms.
90 filter.description => $form->{filter}->{description}
92 3. array+hashref access
94 adding brackets ([]) before the dot will cause the next hash to be put into an array.
95 using [+] instead of [] will force a new array index. this is useful for recurring
96 data structures like part lists. put a [+] into the first varname, and use [] on the
99 repeating these names in your template:
102 invoice.items[].parts_id
106 $form->{invoice}->{items}->[
120 using brackets at the end of a name will result in a pure array to be created.
121 note that you mustn't use [+], which is reserved for array+hash access and will
122 result in undefined behaviour in array context.
124 filter.status[] => $form->{status}->[ val1, val2, ... ]
128 $main::lxdebug->enter_sub(2);
134 my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key;
138 if (scalar @tokens) {
139 $curr = \ $self->{ shift @tokens };
143 my $sep = shift @tokens;
144 my $key = shift @tokens;
146 $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]';
147 $curr = \ $$curr->[max 0, $#$$curr] if $sep eq '[].';
148 $curr = \ $$curr->[++$#$$curr] if $sep eq '[+].';
149 $curr = \ $$curr->{$key}
154 $main::lxdebug->leave_sub(2);
160 $main::lxdebug->enter_sub(2);
165 my @pairs = split(/&/, $input);
168 my ($key, $value) = split(/=/, $_, 2);
169 $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key);
172 $main::lxdebug->leave_sub(2);
175 sub _request_to_hash {
176 $main::lxdebug->enter_sub(2);
181 if (!$ENV{'CONTENT_TYPE'}
182 || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
184 $self->_input_to_hash($input);
186 $main::lxdebug->leave_sub(2);
190 my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
192 my $boundary = '--' . $1;
194 foreach my $line (split m/\n/, $input) {
195 last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
197 if (($line eq $boundary) || ($line eq "$boundary\r")) {
198 ${ $previous } =~ s|\r?\n$|| if $previous;
204 $content_type = "text/plain";
211 next unless $boundary_found;
213 if (!$headers_done) {
214 $line =~ s/[\r\n]*$//;
221 if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
222 if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
224 substr $line, $-[0], $+[0] - $-[0], "";
227 if ($line =~ m|name\s*=\s*"(.*?)"|i) {
229 substr $line, $-[0], $+[0] - $-[0], "";
232 $previous = $self->_store_value($name, '') if ($name);
233 $self->{FILENAME} = $filename if ($filename);
238 if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
245 next unless $previous;
247 ${ $previous } .= "${line}\n";
250 ${ $previous } =~ s|\r?\n$|| if $previous;
252 $main::lxdebug->leave_sub(2);
255 sub _recode_recursively {
256 $main::lxdebug->enter_sub();
257 my ($iconv, $param) = @_;
259 if (any { ref $param eq $_ } qw(Form HASH)) {
260 foreach my $key (keys %{ $param }) {
261 if (!ref $param->{$key}) {
262 $param->{$key} = $iconv->convert($param->{$key});
264 _recode_recursively($iconv, $param->{$key});
268 } elsif (ref $param eq 'ARRAY') {
269 foreach my $idx (0 .. scalar(@{ $param }) - 1) {
270 if (!ref $param->[$idx]) {
271 $param->[$idx] = $iconv->convert($param->[$idx]);
273 _recode_recursively($iconv, $param->[$idx]);
277 $main::lxdebug->leave_sub();
281 $main::lxdebug->enter_sub();
287 if ($LXDebug::watch_form) {
288 require SL::Watchdog;
289 tie %{ $self }, 'SL::Watchdog';
292 read(STDIN, $_, $ENV{CONTENT_LENGTH});
294 if ($ENV{QUERY_STRING}) {
295 $_ = $ENV{QUERY_STRING};
304 $self->_request_to_hash($_);
306 my $db_charset = $main::dbcharset;
307 $db_charset ||= Common::DEFAULT_CHARSET;
309 if ($self->{INPUT_ENCODING} && (lc $self->{INPUT_ENCODING} ne $db_charset)) {
311 my $iconv = Text::Iconv->new($self->{INPUT_ENCODING}, $db_charset);
313 _recode_recursively($iconv, $self);
315 delete $self{INPUT_ENCODING};
318 $self->{action} = lc $self->{action};
319 $self->{action} =~ s/( |-|,|\#)/_/g;
321 $self->{version} = "2.6.0";
323 $main::lxdebug->leave_sub();
328 sub _flatten_variables_rec {
329 $main::lxdebug->enter_sub(2);
338 if ('' eq ref $curr->{$key}) {
339 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
341 } elsif ('HASH' eq ref $curr->{$key}) {
342 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
343 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
347 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
348 my $first_array_entry = 1;
350 foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
351 push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
352 $first_array_entry = 0;
357 $main::lxdebug->leave_sub(2);
362 sub flatten_variables {
363 $main::lxdebug->enter_sub(2);
371 push @variables, $self->_flatten_variables_rec($self, '', $_);
374 $main::lxdebug->leave_sub(2);
379 sub flatten_standard_variables {
380 $main::lxdebug->enter_sub(2);
383 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
387 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
388 push @variables, $self->_flatten_variables_rec($self, '', $_);
391 $main::lxdebug->leave_sub(2);
397 $main::lxdebug->enter_sub();
403 map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
405 $main::lxdebug->leave_sub();
409 $main::lxdebug->enter_sub(2);
412 my $password = $self->{password};
414 $self->{password} = 'X' x 8;
416 local $Data::Dumper::Sortkeys = 1;
417 my $output = Dumper($self);
419 $self->{password} = $password;
421 $main::lxdebug->leave_sub(2);
427 $main::lxdebug->enter_sub(2);
429 my ($self, $str) = @_;
431 $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
433 $main::lxdebug->leave_sub(2);
439 $main::lxdebug->enter_sub(2);
441 my ($self, $str) = @_;
446 $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
448 $main::lxdebug->leave_sub(2);
454 $main::lxdebug->enter_sub();
455 my ($self, $str) = @_;
457 if ($str && !ref($str)) {
458 $str =~ s/\"/"/g;
461 $main::lxdebug->leave_sub();
467 $main::lxdebug->enter_sub();
468 my ($self, $str) = @_;
470 if ($str && !ref($str)) {
471 $str =~ s/"/\"/g;
474 $main::lxdebug->leave_sub();
480 $main::lxdebug->enter_sub();
484 map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
486 for (sort keys %$self) {
487 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
488 print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
491 $main::lxdebug->leave_sub();
495 $main::lxdebug->enter_sub();
497 $main::lxdebug->show_backtrace();
499 my ($self, $msg) = @_;
500 if ($ENV{HTTP_USER_AGENT}) {
502 $self->show_generic_error($msg);
509 $main::lxdebug->leave_sub();
513 $main::lxdebug->enter_sub();
515 my ($self, $msg) = @_;
517 if ($ENV{HTTP_USER_AGENT}) {
520 if (!$self->{header}) {
533 if ($self->{info_function}) {
534 &{ $self->{info_function} }($msg);
540 $main::lxdebug->leave_sub();
543 # calculates the number of rows in a textarea based on the content and column number
544 # can be capped with maxrows
546 $main::lxdebug->enter_sub();
547 my ($self, $str, $cols, $maxrows, $minrows) = @_;
551 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
554 $main::lxdebug->leave_sub();
556 return max(min($rows, $maxrows), $minrows);
560 $main::lxdebug->enter_sub();
562 my ($self, $msg) = @_;
564 $self->error("$msg\n" . $DBI::errstr);
566 $main::lxdebug->leave_sub();
570 $main::lxdebug->enter_sub();
572 my ($self, $name, $msg) = @_;
575 foreach my $part (split m/\./, $name) {
576 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
579 $curr = $curr->{$part};
582 $main::lxdebug->leave_sub();
585 sub create_http_response {
586 $main::lxdebug->enter_sub();
591 my $cgi = $main::cgi;
592 $cgi ||= CGI->new('');
596 if ($ENV{HTTP_X_FORWARDED_FOR}) {
597 $base_path = $ENV{HTTP_REFERER};
598 $base_path =~ s|^.*?://.*?/|/|;
600 $base_path = $ENV{REQUEST_URI};
602 $base_path =~ s|[^/]+$||;
603 $base_path =~ s|/$||;
606 if (defined $main::auth) {
607 my $session_cookie_value = $main::auth->get_session_id();
608 $session_cookie_value ||= 'NO_SESSION';
610 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
611 '-value' => $session_cookie_value,
612 '-path' => $base_path,
613 '-secure' => $ENV{HTTPS});
616 my %cgi_params = ('-type' => $params{content_type});
617 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
619 my $output = $cgi->header('-cookie' => $session_cookie,
622 $main::lxdebug->leave_sub();
629 $main::lxdebug->enter_sub();
631 my ($self, $extra_code) = @_;
633 if ($self->{header}) {
634 $main::lxdebug->leave_sub();
638 my ($stylesheet, $favicon, $pagelayout);
640 if ($ENV{HTTP_USER_AGENT}) {
643 if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
644 # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
645 $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
648 my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
650 $stylesheets =~ s|^\s*||;
651 $stylesheets =~ s|\s*$||;
652 foreach my $file (split m/\s+/, $stylesheets) {
654 next if (! -f "css/$file");
656 $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
659 $self->{favicon} = "favicon.ico" unless $self->{favicon};
661 if ($self->{favicon} && (-f "$self->{favicon}")) {
663 qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
667 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
669 if ($self->{landscape}) {
670 $pagelayout = qq|<style type="text/css">
671 \@page { size:landscape; }
675 my $fokus = qq| document.$self->{fokus}.focus();| if ($self->{"fokus"});
679 if ($self->{jsscript} == 1) {
682 <script type="text/javascript" src="js/common.js"></script>
683 <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
684 <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
685 <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
686 <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
693 ? "$self->{title} - $self->{titlebar}"
696 foreach my $item (@ { $self->{AJAX} }) {
697 $ajax .= $item->show_javascript();
700 print $self->create_http_response('content_type' => 'text/html',
701 'charset' => $db_charset,);
702 print qq|${doctype}<html>
704 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
705 <title>$self->{titlebar}</title>
712 <script type="text/javascript">
720 <meta name="robots" content="noindex,nofollow" />
721 <script type="text/javascript" src="js/highlight_input.js"></script>
723 <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
724 <script type="text/javascript" src="js/tabcontent.js">
726 /***********************************************
727 * Tab Content script v2.2- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
728 * This notice MUST stay intact for legal use
729 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
730 ***********************************************/
741 $main::lxdebug->leave_sub();
744 sub ajax_response_header {
745 $main::lxdebug->enter_sub();
749 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
750 my $cgi = $main::cgi || CGI->new('');
751 my $output = $cgi->header('-charset' => $db_charset);
753 $main::lxdebug->leave_sub();
758 sub _prepare_html_template {
759 $main::lxdebug->enter_sub();
761 my ($self, $file, $additional_params) = @_;
764 if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
765 $language = $main::language;
767 $language = $main::myconfig{"countrycode"};
769 $language = "de" unless ($language);
771 if (-f "templates/webpages/${file}_${language}.html") {
772 if ((-f ".developer") &&
773 (-f "templates/webpages/${file}_master.html") &&
774 ((stat("templates/webpages/${file}_master.html"))[9] >
775 (stat("templates/webpages/${file}_${language}.html"))[9])) {
776 my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
777 "Please re-run 'locales.pl' in 'locale/${language}'.";
778 print(qq|<pre>$info</pre>|);
782 $file = "templates/webpages/${file}_${language}.html";
783 } elsif (-f "templates/webpages/${file}.html") {
784 $file = "templates/webpages/${file}.html";
786 my $info = "Web page template '${file}' not found.\n" .
787 "Please re-run 'locales.pl' in 'locale/${language}'.";
788 print(qq|<pre>$info</pre>|);
792 if ($self->{"DEBUG"}) {
793 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
796 if ($additional_params->{"DEBUG"}) {
797 $additional_params->{"DEBUG"} =
798 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
801 if (%main::myconfig) {
802 map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
803 my $jsc_dateformat = $main::myconfig{"dateformat"};
804 $jsc_dateformat =~ s/d+/\%d/gi;
805 $jsc_dateformat =~ s/m+/\%m/gi;
806 $jsc_dateformat =~ s/y+/\%Y/gi;
807 $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
810 $additional_params->{"conf_dbcharset"} = $main::dbcharset;
811 $additional_params->{"conf_webdav"} = $main::webdav;
812 $additional_params->{"conf_lizenzen"} = $main::lizenzen;
813 $additional_params->{"conf_latex_templates"} = $main::latex;
814 $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
816 if (%main::debug_options) {
817 map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
820 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
821 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
822 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
826 $main::lxdebug->leave_sub();
831 sub parse_html_template {
832 $main::lxdebug->enter_sub();
834 my ($self, $file, $additional_params) = @_;
836 $additional_params ||= { };
838 $file = $self->_prepare_html_template($file, $additional_params);
840 my $template = Template->new({ 'INTERPOLATE' => 0,
844 'PLUGIN_BASE' => 'SL::Template::Plugin',
845 'INCLUDE_PATH' => '.:templates/webpages',
848 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
850 my $in = IO::File->new($file, 'r');
853 print STDERR "Error opening template file: $!";
854 $main::lxdebug->leave_sub();
858 my $input = join('', <$in>);
862 $input = $main::locale->{iconv}->convert($input);
866 if (!$template->process(\$input, $additional_params, \$output)) {
867 print STDERR $template->error();
870 $main::lxdebug->leave_sub();
875 sub show_generic_error {
876 $main::lxdebug->enter_sub();
878 my ($self, $error, %params) = @_;
881 'title_error' => $params{title},
882 'label_error' => $error,
885 if ($params{action}) {
888 map { delete($self->{$_}); } qw(action);
889 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
891 $add_params->{SHOW_BUTTON} = 1;
892 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
893 $add_params->{VARIABLES} = \@vars;
895 } elsif ($params{back_button}) {
896 $add_params->{SHOW_BACK_BUTTON} = 1;
899 $self->{title} = $params{title} if $params{title};
902 print $self->parse_html_template("generic/error", $add_params);
904 $main::lxdebug->leave_sub();
906 die("Error: $error\n");
909 sub show_generic_information {
910 $main::lxdebug->enter_sub();
912 my ($self, $text, $title) = @_;
915 'title_information' => $title,
916 'label_information' => $text,
919 $self->{title} = $title if ($title);
922 print $self->parse_html_template("generic/information", $add_params);
924 $main::lxdebug->leave_sub();
926 die("Information: $text\n");
929 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
930 # changed it to accept an arbitrary number of triggers - sschoeling
932 $main::lxdebug->enter_sub();
935 my $myconfig = shift;
938 # set dateform for jsscript
941 "dd.mm.yy" => "%d.%m.%Y",
942 "dd-mm-yy" => "%d-%m-%Y",
943 "dd/mm/yy" => "%d/%m/%Y",
944 "mm/dd/yy" => "%m/%d/%Y",
945 "mm-dd-yy" => "%m-%d-%Y",
946 "yyyy-mm-dd" => "%Y-%m-%d",
949 my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
950 $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
957 inputField : "| . (shift) . qq|",
958 ifFormat :"$ifFormat",
959 align : "| . (shift) . qq|",
960 button : "| . (shift) . qq|"
966 <script type="text/javascript">
967 <!--| . join("", @triggers) . qq|//-->
971 $main::lxdebug->leave_sub();
974 } #end sub write_trigger
977 $main::lxdebug->enter_sub();
979 my ($self, $msg) = @_;
981 if ($self->{callback}) {
983 my ($script, $argv) = split(/\?/, $self->{callback}, 2);
985 $script =~ s|[^a-zA-Z0-9_\.]||g;
986 exec("perl", "$script", $argv);
994 $main::lxdebug->leave_sub();
997 # sort of columns removed - empty sub
999 $main::lxdebug->enter_sub();
1001 my ($self, @columns) = @_;
1003 $main::lxdebug->leave_sub();
1009 $main::lxdebug->enter_sub(2);
1011 my ($self, $myconfig, $amount, $places, $dash) = @_;
1013 if ($amount eq "") {
1017 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
1019 my $neg = ($amount =~ s/^-//);
1020 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
1022 if (defined($places) && ($places ne '')) {
1028 my ($actual_places) = ($amount =~ /\.(\d+)/);
1029 $actual_places = length($actual_places);
1030 $places = $actual_places > $places ? $actual_places : $places;
1033 $amount = $self->round_amount($amount, $places);
1036 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
1037 my @p = split(/\./, $amount); # split amount at decimal point
1039 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
1042 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
1045 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
1046 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1047 ($neg ? "-$amount" : "$amount" ) ;
1051 $main::lxdebug->leave_sub(2);
1055 sub format_amount_units {
1056 $main::lxdebug->enter_sub();
1061 my $myconfig = \%main::myconfig;
1062 my $amount = $params{amount} * 1;
1063 my $places = $params{places};
1064 my $part_unit_name = $params{part_unit};
1065 my $amount_unit_name = $params{amount_unit};
1066 my $conv_units = $params{conv_units};
1067 my $max_places = $params{max_places};
1069 if (!$part_unit_name) {
1070 $main::lxdebug->leave_sub();
1074 AM->retrieve_all_units();
1075 my $all_units = $main::all_units;
1077 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1078 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1081 if (!scalar @{ $conv_units }) {
1082 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1083 $main::lxdebug->leave_sub();
1087 my $part_unit = $all_units->{$part_unit_name};
1088 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1090 $amount *= $conv_unit->{factor};
1095 foreach my $unit (@$conv_units) {
1096 my $last = $unit->{name} eq $part_unit->{name};
1098 $num = int($amount / $unit->{factor});
1099 $amount -= $num * $unit->{factor};
1102 if ($last ? $amount : $num) {
1103 push @values, { "unit" => $unit->{name},
1104 "amount" => $last ? $amount / $unit->{factor} : $num,
1105 "places" => $last ? $places : 0 };
1112 push @values, { "unit" => $part_unit_name,
1117 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1119 $main::lxdebug->leave_sub();
1125 $main::lxdebug->enter_sub(2);
1130 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1131 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1132 $input =~ s/\#\#/\#/g;
1134 $main::lxdebug->leave_sub(2);
1142 $main::lxdebug->enter_sub(2);
1144 my ($self, $myconfig, $amount) = @_;
1146 if ( ($myconfig->{numberformat} eq '1.000,00')
1147 || ($myconfig->{numberformat} eq '1000,00')) {
1152 if ($myconfig->{numberformat} eq "1'000.00") {
1158 $main::lxdebug->leave_sub(2);
1160 return ($amount * 1);
1164 $main::lxdebug->enter_sub(2);
1166 my ($self, $amount, $places) = @_;
1169 # Rounding like "Kaufmannsrunden"
1170 # Descr. http://de.wikipedia.org/wiki/Rundung
1172 # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
1175 $amount = $amount * (10**($places));
1176 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1178 $main::lxdebug->leave_sub(2);
1180 return $round_amount;
1184 sub parse_template {
1185 $main::lxdebug->enter_sub();
1187 my ($self, $myconfig, $userspath) = @_;
1188 my ($template, $out);
1192 $self->{"cwd"} = getcwd();
1193 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1197 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1198 $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1199 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
1201 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1202 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1203 $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1204 $ext_for_format = 'pdf';
1206 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1207 $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1208 $ext_for_format = 'html';
1210 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1211 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1212 $ext_for_format = 'xml';
1214 } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1215 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1217 } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1218 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1220 } elsif ( defined $self->{'format'}) {
1221 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1223 } elsif ( $self->{'format'} eq '' ) {
1224 $self->error("No Outputformat given: $self->{'format'}");
1226 } else { #Catch the rest
1227 $self->error("Outputformat not defined: $self->{'format'}");
1230 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1231 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1233 if (!$self->{employee_id}) {
1234 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1237 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1239 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1241 # OUT is used for the media, screen, printer, email
1242 # for postscript we store a copy in a temporary file
1244 my $prepend_userspath;
1246 if (!$self->{tmpfile}) {
1247 $self->{tmpfile} = "${fileid}.$self->{IN}";
1248 $prepend_userspath = 1;
1251 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1253 $self->{tmpfile} =~ s|.*/||;
1254 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1255 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1257 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1258 $out = $self->{OUT};
1259 $self->{OUT} = ">$self->{tmpfile}";
1263 open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1265 open(OUT, ">-") or $self->error("STDOUT : $!");
1269 if (!$template->parse(*OUT)) {
1271 $self->error("$self->{IN} : " . $template->get_error());
1276 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1278 if ($self->{media} eq 'email') {
1280 my $mail = new Mailer;
1282 map { $mail->{$_} = $self->{$_} }
1283 qw(cc bcc subject message version format);
1284 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1285 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1286 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1287 $mail->{fileid} = "$fileid.";
1288 $myconfig->{signature} =~ s/\r//g;
1290 # if we send html or plain text inline
1291 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1292 $mail->{contenttype} = "text/html";
1294 $mail->{message} =~ s/\r//g;
1295 $mail->{message} =~ s/\n/<br>\n/g;
1296 $myconfig->{signature} =~ s/\n/<br>\n/g;
1297 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1299 open(IN, $self->{tmpfile})
1300 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1302 $mail->{message} .= $_;
1309 if (!$self->{"do_not_attach"}) {
1310 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1311 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1312 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1313 "name" => $attachment_name }];
1316 $mail->{message} =~ s/\r//g;
1317 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1321 my $err = $mail->send();
1322 $self->error($self->cleanup . "$err") if ($err);
1326 $self->{OUT} = $out;
1328 my $numbytes = (-s $self->{tmpfile});
1329 open(IN, $self->{tmpfile})
1330 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1332 $self->{copies} = 1 unless $self->{media} eq 'printer';
1334 chdir("$self->{cwd}");
1335 #print(STDERR "Kopien $self->{copies}\n");
1336 #print(STDERR "OUT $self->{OUT}\n");
1337 for my $i (1 .. $self->{copies}) {
1339 open(OUT, $self->{OUT})
1340 or $self->error($self->cleanup . "$self->{OUT} : $!");
1342 $self->{attachment_filename} = ($self->{attachment_filename})
1343 ? $self->{attachment_filename}
1344 : $self->generate_attachment_filename();
1346 # launch application
1347 print qq|Content-Type: | . $template->get_mime_type() . qq|
1348 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1349 Content-Length: $numbytes
1353 open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1374 chdir("$self->{cwd}");
1375 $main::lxdebug->leave_sub();
1378 sub get_formname_translation {
1379 $main::lxdebug->enter_sub();
1380 my ($self, $formname) = @_;
1382 $formname ||= $self->{formname};
1384 my %formname_translations = (
1385 bin_list => $main::locale->text('Bin List'),
1386 credit_note => $main::locale->text('Credit Note'),
1387 invoice => $main::locale->text('Invoice'),
1388 packing_list => $main::locale->text('Packing List'),
1389 pick_list => $main::locale->text('Pick List'),
1390 proforma => $main::locale->text('Proforma Invoice'),
1391 purchase_order => $main::locale->text('Purchase Order'),
1392 request_quotation => $main::locale->text('RFQ'),
1393 sales_order => $main::locale->text('Confirmation'),
1394 sales_quotation => $main::locale->text('Quotation'),
1395 storno_invoice => $main::locale->text('Storno Invoice'),
1396 storno_packing_list => $main::locale->text('Storno Packing List'),
1397 sales_delivery_order => $main::locale->text('Delivery Order'),
1398 purchase_delivery_order => $main::locale->text('Delivery Order'),
1399 dunning => $main::locale->text('Dunning'),
1402 $main::lxdebug->leave_sub();
1403 return $formname_translations{$formname}
1406 sub get_number_prefix_for_type {
1407 $main::lxdebug->enter_sub();
1411 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1412 : ($self->{type} =~ /_quotation$/) ? 'quo'
1413 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1416 $main::lxdebug->leave_sub();
1420 sub get_extension_for_format {
1421 $main::lxdebug->enter_sub();
1424 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1425 : $self->{format} =~ /postscript/i ? ".ps"
1426 : $self->{format} =~ /opendocument/i ? ".odt"
1427 : $self->{format} =~ /html/i ? ".html"
1430 $main::lxdebug->leave_sub();
1434 sub generate_attachment_filename {
1435 $main::lxdebug->enter_sub();
1438 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1439 my $prefix = $self->get_number_prefix_for_type();
1441 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1442 $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1444 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1445 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1448 $attachment_filename = "";
1451 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1452 $attachment_filename =~ s|[\s/\\]+|_|g;
1454 $main::lxdebug->leave_sub();
1455 return $attachment_filename;
1458 sub generate_email_subject {
1459 $main::lxdebug->enter_sub();
1462 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1463 my $prefix = $self->get_number_prefix_for_type();
1465 if ($subject && $self->{"${prefix}number"}) {
1466 $subject .= " " . $self->{"${prefix}number"}
1469 $main::lxdebug->leave_sub();
1474 $main::lxdebug->enter_sub();
1478 chdir("$self->{tmpdir}");
1481 if (-f "$self->{tmpfile}.err") {
1482 open(FH, "$self->{tmpfile}.err");
1487 if ($self->{tmpfile}) {
1488 $self->{tmpfile} =~ s|.*/||g;
1490 $self->{tmpfile} =~ s/\.\w+$//g;
1491 my $tmpfile = $self->{tmpfile};
1492 unlink(<$tmpfile.*>);
1495 chdir("$self->{cwd}");
1497 $main::lxdebug->leave_sub();
1503 $main::lxdebug->enter_sub();
1505 my ($self, $date, $myconfig) = @_;
1508 if ($date && $date =~ /\D/) {
1510 if ($myconfig->{dateformat} =~ /^yy/) {
1511 ($yy, $mm, $dd) = split /\D/, $date;
1513 if ($myconfig->{dateformat} =~ /^mm/) {
1514 ($mm, $dd, $yy) = split /\D/, $date;
1516 if ($myconfig->{dateformat} =~ /^dd/) {
1517 ($dd, $mm, $yy) = split /\D/, $date;
1522 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1523 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1525 $dd = "0$dd" if ($dd < 10);
1526 $mm = "0$mm" if ($mm < 10);
1528 $date = "$yy$mm$dd";
1531 $main::lxdebug->leave_sub();
1536 # Database routines used throughout
1539 $main::lxdebug->enter_sub(2);
1541 my ($self, $myconfig) = @_;
1543 # connect to database
1545 DBI->connect($myconfig->{dbconnect},
1546 $myconfig->{dbuser}, $myconfig->{dbpasswd})
1550 if ($myconfig->{dboptions}) {
1551 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1554 $main::lxdebug->leave_sub(2);
1559 sub dbconnect_noauto {
1560 $main::lxdebug->enter_sub();
1562 my ($self, $myconfig) = @_;
1564 # connect to database
1566 DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1567 $myconfig->{dbpasswd}, { AutoCommit => 0 })
1571 if ($myconfig->{dboptions}) {
1572 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1575 $main::lxdebug->leave_sub();
1580 sub get_standard_dbh {
1581 $main::lxdebug->enter_sub(2);
1583 my ($self, $myconfig) = @_;
1585 if ($standard_dbh && !$standard_dbh->{Active}) {
1586 $main::lxdebug->message(LXDebug::INFO, "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1587 undef $standard_dbh;
1590 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1592 $main::lxdebug->leave_sub(2);
1594 return $standard_dbh;
1598 $main::lxdebug->enter_sub();
1600 my ($self, $date, $myconfig) = @_;
1601 my $dbh = $self->dbconnect($myconfig);
1603 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1604 my $sth = prepare_execute_query($self, $dbh, $query, $date);
1605 my ($closed) = $sth->fetchrow_array;
1607 $main::lxdebug->leave_sub();
1612 sub update_balance {
1613 $main::lxdebug->enter_sub();
1615 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1617 # if we have a value, go do it
1620 # retrieve balance from table
1621 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1622 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1623 my ($balance) = $sth->fetchrow_array;
1629 $query = "UPDATE $table SET $field = $balance WHERE $where";
1630 do_query($self, $dbh, $query, @values);
1632 $main::lxdebug->leave_sub();
1635 sub update_exchangerate {
1636 $main::lxdebug->enter_sub();
1638 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1640 # some sanity check for currency
1642 $main::lxdebug->leave_sub();
1645 $query = qq|SELECT curr FROM defaults|;
1647 my ($currency) = selectrow_query($self, $dbh, $query);
1648 my ($defaultcurrency) = split m/:/, $currency;
1651 if ($curr eq $defaultcurrency) {
1652 $main::lxdebug->leave_sub();
1656 $query = qq|SELECT e.curr FROM exchangerate e
1657 WHERE e.curr = ? AND e.transdate = ?
1659 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1668 $buy = conv_i($buy, "NULL");
1669 $sell = conv_i($sell, "NULL");
1672 if ($buy != 0 && $sell != 0) {
1673 $set = "buy = $buy, sell = $sell";
1674 } elsif ($buy != 0) {
1675 $set = "buy = $buy";
1676 } elsif ($sell != 0) {
1677 $set = "sell = $sell";
1680 if ($sth->fetchrow_array) {
1681 $query = qq|UPDATE exchangerate
1687 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1688 VALUES (?, $buy, $sell, ?)|;
1691 do_query($self, $dbh, $query, $curr, $transdate);
1693 $main::lxdebug->leave_sub();
1696 sub save_exchangerate {
1697 $main::lxdebug->enter_sub();
1699 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1701 my $dbh = $self->dbconnect($myconfig);
1705 $buy = $rate if $fld eq 'buy';
1706 $sell = $rate if $fld eq 'sell';
1709 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1714 $main::lxdebug->leave_sub();
1717 sub get_exchangerate {
1718 $main::lxdebug->enter_sub();
1720 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1723 unless ($transdate) {
1724 $main::lxdebug->leave_sub();
1728 $query = qq|SELECT curr FROM defaults|;
1730 my ($currency) = selectrow_query($self, $dbh, $query);
1731 my ($defaultcurrency) = split m/:/, $currency;
1733 if ($currency eq $defaultcurrency) {
1734 $main::lxdebug->leave_sub();
1738 $query = qq|SELECT e.$fld FROM exchangerate e
1739 WHERE e.curr = ? AND e.transdate = ?|;
1740 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1744 $main::lxdebug->leave_sub();
1746 return $exchangerate;
1749 sub check_exchangerate {
1750 $main::lxdebug->enter_sub();
1752 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1754 if ($fld !~/^buy|sell$/) {
1755 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1758 unless ($transdate) {
1759 $main::lxdebug->leave_sub();
1763 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1765 if ($currency eq $defaultcurrency) {
1766 $main::lxdebug->leave_sub();
1770 my $dbh = $self->get_standard_dbh($myconfig);
1771 my $query = qq|SELECT e.$fld FROM exchangerate e
1772 WHERE e.curr = ? AND e.transdate = ?|;
1774 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1776 $main::lxdebug->leave_sub();
1778 return $exchangerate;
1781 sub get_default_currency {
1782 $main::lxdebug->enter_sub();
1784 my ($self, $myconfig) = @_;
1785 my $dbh = $self->get_standard_dbh($myconfig);
1787 my $query = qq|SELECT curr FROM defaults|;
1789 my ($curr) = selectrow_query($self, $dbh, $query);
1790 my ($defaultcurrency) = split m/:/, $curr;
1792 $main::lxdebug->leave_sub();
1794 return $defaultcurrency;
1798 sub set_payment_options {
1799 $main::lxdebug->enter_sub();
1801 my ($self, $myconfig, $transdate) = @_;
1803 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1805 my $dbh = $self->get_standard_dbh($myconfig);
1808 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1809 qq|FROM payment_terms p | .
1812 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1813 $self->{payment_terms}) =
1814 selectrow_query($self, $dbh, $query, $self->{payment_id});
1816 if ($transdate eq "") {
1817 if ($self->{invdate}) {
1818 $transdate = $self->{invdate};
1820 $transdate = $self->{transdate};
1825 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1826 qq|FROM payment_terms|;
1827 ($self->{netto_date}, $self->{skonto_date}) =
1828 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1830 my ($invtotal, $total);
1831 my (%amounts, %formatted_amounts);
1833 if ($self->{type} =~ /_order$/) {
1834 $amounts{invtotal} = $self->{ordtotal};
1835 $amounts{total} = $self->{ordtotal};
1837 } elsif ($self->{type} =~ /_quotation$/) {
1838 $amounts{invtotal} = $self->{quototal};
1839 $amounts{total} = $self->{quototal};
1842 $amounts{invtotal} = $self->{invtotal};
1843 $amounts{total} = $self->{total};
1846 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1848 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1849 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1850 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1852 foreach (keys %amounts) {
1853 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1854 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1857 if ($self->{"language_id"}) {
1859 qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1860 qq|FROM translation_payment_terms t | .
1861 qq|LEFT JOIN language l ON t.language_id = l.id | .
1862 qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1863 my ($description_long, $output_numberformat, $output_dateformat,
1864 $output_longdates) =
1865 selectrow_query($self, $dbh, $query,
1866 $self->{"language_id"}, $self->{"payment_id"});
1868 $self->{payment_terms} = $description_long if ($description_long);
1870 if ($output_dateformat) {
1871 foreach my $key (qw(netto_date skonto_date)) {
1873 $main::locale->reformat_date($myconfig, $self->{$key},
1879 if ($output_numberformat &&
1880 ($output_numberformat ne $myconfig->{"numberformat"})) {
1881 my $saved_numberformat = $myconfig->{"numberformat"};
1882 $myconfig->{"numberformat"} = $output_numberformat;
1883 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1884 $myconfig->{"numberformat"} = $saved_numberformat;
1888 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1889 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1890 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1891 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1892 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1893 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1894 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1896 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1898 $main::lxdebug->leave_sub();
1902 sub get_template_language {
1903 $main::lxdebug->enter_sub();
1905 my ($self, $myconfig) = @_;
1907 my $template_code = "";
1909 if ($self->{language_id}) {
1910 my $dbh = $self->get_standard_dbh($myconfig);
1911 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1912 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1915 $main::lxdebug->leave_sub();
1917 return $template_code;
1920 sub get_printer_code {
1921 $main::lxdebug->enter_sub();
1923 my ($self, $myconfig) = @_;
1925 my $template_code = "";
1927 if ($self->{printer_id}) {
1928 my $dbh = $self->get_standard_dbh($myconfig);
1929 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1930 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1933 $main::lxdebug->leave_sub();
1935 return $template_code;
1939 $main::lxdebug->enter_sub();
1941 my ($self, $myconfig) = @_;
1943 my $template_code = "";
1945 if ($self->{shipto_id}) {
1946 my $dbh = $self->get_standard_dbh($myconfig);
1947 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1948 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1949 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1952 $main::lxdebug->leave_sub();
1956 $main::lxdebug->enter_sub();
1958 my ($self, $dbh, $id, $module) = @_;
1963 foreach my $item (qw(name department_1 department_2 street zipcode city country
1964 contact phone fax email)) {
1965 if ($self->{"shipto$item"}) {
1966 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1968 push(@values, $self->{"shipto${item}"});
1972 if ($self->{shipto_id}) {
1973 my $query = qq|UPDATE shipto set
1975 shiptodepartment_1 = ?,
1976 shiptodepartment_2 = ?,
1985 WHERE shipto_id = ?|;
1986 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1988 my $query = qq|SELECT * FROM shipto
1989 WHERE shiptoname = ? AND
1990 shiptodepartment_1 = ? AND
1991 shiptodepartment_2 = ? AND
1992 shiptostreet = ? AND
1993 shiptozipcode = ? AND
1995 shiptocountry = ? AND
1996 shiptocontact = ? AND
2002 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
2005 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
2006 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
2007 shiptocontact, shiptophone, shiptofax, shiptoemail, module)
2008 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
2009 do_query($self, $dbh, $query, $id, @values, $module);
2014 $main::lxdebug->leave_sub();
2018 $main::lxdebug->enter_sub();
2020 my ($self, $dbh) = @_;
2022 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2023 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2024 $self->{"employee_id"} *= 1;
2026 $main::lxdebug->leave_sub();
2029 sub get_employee_data {
2030 $main::lxdebug->enter_sub();
2035 Common::check_params(\%params, qw(prefix));
2036 Common::check_params_x(\%params, qw(id));
2039 $main::lxdebug->leave_sub();
2043 my $myconfig = \%main::myconfig;
2044 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
2046 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2049 my $user = User->new($login);
2050 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2052 $self->{$params{prefix} . '_login'} = $login;
2053 $self->{$params{prefix} . '_name'} ||= $login;
2056 $main::lxdebug->leave_sub();
2060 $main::lxdebug->enter_sub();
2062 my ($self, $myconfig, $reference_date) = @_;
2064 my $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2066 my $dbh = $self->get_standard_dbh($myconfig);
2067 my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2068 my ($duedate) = selectrow_query($self, $dbh, $query, $self->{payment_id});
2070 $main::lxdebug->leave_sub();
2076 $main::lxdebug->enter_sub();
2078 my ($self, $dbh, $id, $key) = @_;
2080 $key = "all_contacts" unless ($key);
2084 $main::lxdebug->leave_sub();
2089 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2090 qq|FROM contacts | .
2091 qq|WHERE cp_cv_id = ? | .
2092 qq|ORDER BY lower(cp_name)|;
2094 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2096 $main::lxdebug->leave_sub();
2100 $main::lxdebug->enter_sub();
2102 my ($self, $dbh, $key) = @_;
2104 my ($all, $old_id, $where, @values);
2106 if (ref($key) eq "HASH") {
2109 $key = "ALL_PROJECTS";
2111 foreach my $p (keys(%{$params})) {
2113 $all = $params->{$p};
2114 } elsif ($p eq "old_id") {
2115 $old_id = $params->{$p};
2116 } elsif ($p eq "key") {
2117 $key = $params->{$p};
2123 $where = "WHERE active ";
2125 if (ref($old_id) eq "ARRAY") {
2126 my @ids = grep({ $_ } @{$old_id});
2128 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2129 push(@values, @ids);
2132 $where .= " OR (id = ?) ";
2133 push(@values, $old_id);
2139 qq|SELECT id, projectnumber, description, active | .
2142 qq|ORDER BY lower(projectnumber)|;
2144 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2146 $main::lxdebug->leave_sub();
2150 $main::lxdebug->enter_sub();
2152 my ($self, $dbh, $vc_id, $key) = @_;
2154 $key = "all_shipto" unless ($key);
2157 # get shipping addresses
2158 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2160 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2166 $main::lxdebug->leave_sub();
2170 $main::lxdebug->enter_sub();
2172 my ($self, $dbh, $key) = @_;
2174 $key = "all_printers" unless ($key);
2176 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2178 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2180 $main::lxdebug->leave_sub();
2184 $main::lxdebug->enter_sub();
2186 my ($self, $dbh, $params) = @_;
2189 $key = $params->{key};
2190 $key = "all_charts" unless ($key);
2192 my $transdate = quote_db_date($params->{transdate});
2195 qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
2197 qq|LEFT JOIN taxkeys tk ON | .
2198 qq|(tk.id = (SELECT id FROM taxkeys | .
2199 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2200 qq| ORDER BY startdate DESC LIMIT 1)) | .
2201 qq|ORDER BY c.accno|;
2203 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2205 $main::lxdebug->leave_sub();
2208 sub _get_taxcharts {
2209 $main::lxdebug->enter_sub();
2211 my ($self, $dbh, $params) = @_;
2213 my $key = "all_taxcharts";
2216 if (ref $params eq 'HASH') {
2217 $key = $params->{key} if ($params->{key});
2218 if ($params->{module} eq 'AR') {
2219 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2221 } elsif ($params->{module} eq 'AP') {
2222 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2229 my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2231 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2233 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2235 $main::lxdebug->leave_sub();
2239 $main::lxdebug->enter_sub();
2241 my ($self, $dbh, $key) = @_;
2243 $key = "all_taxzones" unless ($key);
2245 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2247 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2249 $main::lxdebug->leave_sub();
2252 sub _get_employees {
2253 $main::lxdebug->enter_sub();
2255 my ($self, $dbh, $default_key, $key) = @_;
2257 $key = $default_key unless ($key);
2258 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2260 $main::lxdebug->leave_sub();
2263 sub _get_business_types {
2264 $main::lxdebug->enter_sub();
2266 my ($self, $dbh, $key) = @_;
2268 $key = "all_business_types" unless ($key);
2270 selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2272 $main::lxdebug->leave_sub();
2275 sub _get_languages {
2276 $main::lxdebug->enter_sub();
2278 my ($self, $dbh, $key) = @_;
2280 $key = "all_languages" unless ($key);
2282 my $query = qq|SELECT * FROM language ORDER BY id|;
2284 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2286 $main::lxdebug->leave_sub();
2289 sub _get_dunning_configs {
2290 $main::lxdebug->enter_sub();
2292 my ($self, $dbh, $key) = @_;
2294 $key = "all_dunning_configs" unless ($key);
2296 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2298 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2300 $main::lxdebug->leave_sub();
2303 sub _get_currencies {
2304 $main::lxdebug->enter_sub();
2306 my ($self, $dbh, $key) = @_;
2308 $key = "all_currencies" unless ($key);
2310 my $query = qq|SELECT curr AS currency FROM defaults|;
2312 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2314 $main::lxdebug->leave_sub();
2318 $main::lxdebug->enter_sub();
2320 my ($self, $dbh, $key) = @_;
2322 $key = "all_payments" unless ($key);
2324 my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2326 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2328 $main::lxdebug->leave_sub();
2331 sub _get_customers {
2332 $main::lxdebug->enter_sub();
2334 my ($self, $dbh, $key, $limit) = @_;
2336 $key = "all_customers" unless ($key);
2337 my $limit_clause = "LIMIT $limit" if $limit;
2339 my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2341 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2343 $main::lxdebug->leave_sub();
2347 $main::lxdebug->enter_sub();
2349 my ($self, $dbh, $key) = @_;
2351 $key = "all_vendors" unless ($key);
2353 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2355 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2357 $main::lxdebug->leave_sub();
2360 sub _get_departments {
2361 $main::lxdebug->enter_sub();
2363 my ($self, $dbh, $key) = @_;
2365 $key = "all_departments" unless ($key);
2367 my $query = qq|SELECT * FROM department ORDER BY description|;
2369 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2371 $main::lxdebug->leave_sub();
2374 sub _get_warehouses {
2375 $main::lxdebug->enter_sub();
2377 my ($self, $dbh, $param) = @_;
2379 my ($key, $bins_key);
2381 if ('' eq ref $param) {
2385 $key = $param->{key};
2386 $bins_key = $param->{bins};
2389 my $query = qq|SELECT w.* FROM warehouse w
2390 WHERE (NOT w.invalid) AND
2391 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2392 ORDER BY w.sortkey|;
2394 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2397 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2398 my $sth = prepare_query($self, $dbh, $query);
2400 foreach my $warehouse (@{ $self->{$key} }) {
2401 do_statement($self, $sth, $query, $warehouse->{id});
2402 $warehouse->{$bins_key} = [];
2404 while (my $ref = $sth->fetchrow_hashref()) {
2405 push @{ $warehouse->{$bins_key} }, $ref;
2411 $main::lxdebug->leave_sub();
2415 $main::lxdebug->enter_sub();
2417 my ($self, $dbh, $table, $key, $sortkey) = @_;
2419 my $query = qq|SELECT * FROM $table|;
2420 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2422 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2424 $main::lxdebug->leave_sub();
2428 # $main::lxdebug->enter_sub();
2430 # my ($self, $dbh, $key) = @_;
2432 # $key ||= "all_groups";
2434 # my $groups = $main::auth->read_groups();
2436 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2438 # $main::lxdebug->leave_sub();
2442 $main::lxdebug->enter_sub();
2447 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2448 my ($sth, $query, $ref);
2450 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2451 my $vc_id = $self->{"${vc}_id"};
2453 if ($params{"contacts"}) {
2454 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2457 if ($params{"shipto"}) {
2458 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2461 if ($params{"projects"} || $params{"all_projects"}) {
2462 $self->_get_projects($dbh, $params{"all_projects"} ?
2463 $params{"all_projects"} : $params{"projects"},
2464 $params{"all_projects"} ? 1 : 0);
2467 if ($params{"printers"}) {
2468 $self->_get_printers($dbh, $params{"printers"});
2471 if ($params{"languages"}) {
2472 $self->_get_languages($dbh, $params{"languages"});
2475 if ($params{"charts"}) {
2476 $self->_get_charts($dbh, $params{"charts"});
2479 if ($params{"taxcharts"}) {
2480 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2483 if ($params{"taxzones"}) {
2484 $self->_get_taxzones($dbh, $params{"taxzones"});
2487 if ($params{"employees"}) {
2488 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2491 if ($params{"salesmen"}) {
2492 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2495 if ($params{"business_types"}) {
2496 $self->_get_business_types($dbh, $params{"business_types"});
2499 if ($params{"dunning_configs"}) {
2500 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2503 if($params{"currencies"}) {
2504 $self->_get_currencies($dbh, $params{"currencies"});
2507 if($params{"customers"}) {
2508 if (ref $params{"customers"} eq 'HASH') {
2509 $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2511 $self->_get_customers($dbh, $params{"customers"});
2515 if($params{"vendors"}) {
2516 if (ref $params{"vendors"} eq 'HASH') {
2517 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2519 $self->_get_vendors($dbh, $params{"vendors"});
2523 if($params{"payments"}) {
2524 $self->_get_payments($dbh, $params{"payments"});
2527 if($params{"departments"}) {
2528 $self->_get_departments($dbh, $params{"departments"});
2531 if ($params{price_factors}) {
2532 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2535 if ($params{warehouses}) {
2536 $self->_get_warehouses($dbh, $params{warehouses});
2539 # if ($params{groups}) {
2540 # $self->_get_groups($dbh, $params{groups});
2543 if ($params{partsgroup}) {
2544 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2547 $main::lxdebug->leave_sub();
2550 # this sub gets the id and name from $table
2552 $main::lxdebug->enter_sub();
2554 my ($self, $myconfig, $table) = @_;
2556 # connect to database
2557 my $dbh = $self->get_standard_dbh($myconfig);
2559 $table = $table eq "customer" ? "customer" : "vendor";
2560 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2562 my ($query, @values);
2564 if (!$self->{openinvoices}) {
2566 if ($self->{customernumber} ne "") {
2567 $where = qq|(vc.customernumber ILIKE ?)|;
2568 push(@values, '%' . $self->{customernumber} . '%');
2570 $where = qq|(vc.name ILIKE ?)|;
2571 push(@values, '%' . $self->{$table} . '%');
2575 qq~SELECT vc.id, vc.name,
2576 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2578 WHERE $where AND (NOT vc.obsolete)
2582 qq~SELECT DISTINCT vc.id, vc.name,
2583 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2585 JOIN $table vc ON (a.${table}_id = vc.id)
2586 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2588 push(@values, '%' . $self->{$table} . '%');
2591 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2593 $main::lxdebug->leave_sub();
2595 return scalar(@{ $self->{name_list} });
2598 # the selection sub is used in the AR, AP, IS, IR and OE module
2601 $main::lxdebug->enter_sub();
2603 my ($self, $myconfig, $table, $module) = @_;
2606 my $dbh = $self->get_standard_dbh($myconfig);
2608 $table = $table eq "customer" ? "customer" : "vendor";
2610 my $query = qq|SELECT count(*) FROM $table|;
2611 my ($count) = selectrow_query($self, $dbh, $query);
2613 # build selection list
2614 if ($count < $myconfig->{vclimit}) {
2615 $query = qq|SELECT id, name, salesman_id
2616 FROM $table WHERE NOT obsolete
2618 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2622 $self->get_employee($dbh);
2624 # setup sales contacts
2625 $query = qq|SELECT e.id, e.name
2627 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2628 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2631 push(@{ $self->{all_employees} },
2632 { id => $self->{employee_id},
2633 name => $self->{employee} });
2635 # sort the whole thing
2636 @{ $self->{all_employees} } =
2637 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2639 if ($module eq 'AR') {
2641 # prepare query for departments
2642 $query = qq|SELECT id, description
2645 ORDER BY description|;
2648 $query = qq|SELECT id, description
2650 ORDER BY description|;
2653 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2656 $query = qq|SELECT id, description
2660 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2663 $query = qq|SELECT printer_description, id
2665 ORDER BY printer_description|;
2667 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2670 $query = qq|SELECT id, description
2674 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2676 $main::lxdebug->leave_sub();
2679 sub language_payment {
2680 $main::lxdebug->enter_sub();
2682 my ($self, $myconfig) = @_;
2684 my $dbh = $self->get_standard_dbh($myconfig);
2686 my $query = qq|SELECT id, description
2690 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2693 $query = qq|SELECT printer_description, id
2695 ORDER BY printer_description|;
2697 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2700 $query = qq|SELECT id, description
2704 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2706 # get buchungsgruppen
2707 $query = qq|SELECT id, description
2708 FROM buchungsgruppen|;
2710 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2712 $main::lxdebug->leave_sub();
2715 # this is only used for reports
2716 sub all_departments {
2717 $main::lxdebug->enter_sub();
2719 my ($self, $myconfig, $table) = @_;
2721 my $dbh = $self->get_standard_dbh($myconfig);
2724 if ($table eq 'customer') {
2725 $where = "WHERE role = 'P' ";
2728 my $query = qq|SELECT id, description
2731 ORDER BY description|;
2732 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2734 delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2736 $main::lxdebug->leave_sub();
2740 $main::lxdebug->enter_sub();
2742 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2745 if ($table eq "customer") {
2754 $self->all_vc($myconfig, $table, $module);
2756 # get last customers or vendors
2757 my ($query, $sth, $ref);
2759 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2764 my $transdate = "current_date";
2765 if ($self->{transdate}) {
2766 $transdate = $dbh->quote($self->{transdate});
2769 # now get the account numbers
2770 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2771 FROM chart c, taxkeys tk
2772 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2773 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2776 $sth = $dbh->prepare($query);
2778 do_statement($self, $sth, $query, '%' . $module . '%');
2780 $self->{accounts} = "";
2781 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2783 foreach my $key (split(/:/, $ref->{link})) {
2784 if ($key =~ /\Q$module\E/) {
2786 # cross reference for keys
2787 $xkeyref{ $ref->{accno} } = $key;
2789 push @{ $self->{"${module}_links"}{$key} },
2790 { accno => $ref->{accno},
2791 description => $ref->{description},
2792 taxkey => $ref->{taxkey_id},
2793 tax_id => $ref->{tax_id} };
2795 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2801 # get taxkeys and description
2802 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2803 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2805 if (($module eq "AP") || ($module eq "AR")) {
2806 # get tax rates and description
2807 $query = qq|SELECT * FROM tax|;
2808 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2814 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2815 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2816 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2817 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2819 d.description AS department,
2822 JOIN $table c ON (a.${table}_id = c.id)
2823 LEFT JOIN employee e ON (e.id = a.employee_id)
2824 LEFT JOIN department d ON (d.id = a.department_id)
2826 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2828 foreach my $key (keys %$ref) {
2829 $self->{$key} = $ref->{$key};
2832 my $transdate = "current_date";
2833 if ($self->{transdate}) {
2834 $transdate = $dbh->quote($self->{transdate});
2837 # now get the account numbers
2838 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2840 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2842 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2843 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2846 $sth = $dbh->prepare($query);
2847 do_statement($self, $sth, $query, "%$module%");
2849 $self->{accounts} = "";
2850 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2852 foreach my $key (split(/:/, $ref->{link})) {
2853 if ($key =~ /\Q$module\E/) {
2855 # cross reference for keys
2856 $xkeyref{ $ref->{accno} } = $key;
2858 push @{ $self->{"${module}_links"}{$key} },
2859 { accno => $ref->{accno},
2860 description => $ref->{description},
2861 taxkey => $ref->{taxkey_id},
2862 tax_id => $ref->{tax_id} };
2864 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2870 # get amounts from individual entries
2873 c.accno, c.description,
2874 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2878 LEFT JOIN chart c ON (c.id = a.chart_id)
2879 LEFT JOIN project p ON (p.id = a.project_id)
2880 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2881 WHERE (tk.taxkey_id=a.taxkey) AND
2882 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2883 THEN tk.chart_id = a.chart_id
2886 OR (c.link='%tax%')) AND
2887 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2888 WHERE a.trans_id = ?
2889 AND a.fx_transaction = '0'
2890 ORDER BY a.acc_trans_id, a.transdate|;
2891 $sth = $dbh->prepare($query);
2892 do_statement($self, $sth, $query, $self->{id});
2894 # get exchangerate for currency
2895 $self->{exchangerate} =
2896 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2899 # store amounts in {acc_trans}{$key} for multiple accounts
2900 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2901 $ref->{exchangerate} =
2902 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2903 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2906 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2907 $ref->{amount} *= -1;
2909 $ref->{index} = $index;
2911 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2917 d.curr AS currencies, d.closedto, d.revtrans,
2918 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2919 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2921 $ref = selectfirst_hashref_query($self, $dbh, $query);
2922 map { $self->{$_} = $ref->{$_} } keys %$ref;
2929 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2930 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2931 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2933 $ref = selectfirst_hashref_query($self, $dbh, $query);
2934 map { $self->{$_} = $ref->{$_} } keys %$ref;
2936 if ($self->{"$self->{vc}_id"}) {
2938 # only setup currency
2939 ($self->{currency}) = split(/:/, $self->{currencies});
2943 $self->lastname_used($dbh, $myconfig, $table, $module);
2945 # get exchangerate for currency
2946 $self->{exchangerate} =
2947 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2953 $main::lxdebug->leave_sub();
2957 $main::lxdebug->enter_sub();
2959 my ($self, $dbh, $myconfig, $table, $module) = @_;
2963 $table = $table eq "customer" ? "customer" : "vendor";
2964 my %column_map = ("a.curr" => "currency",
2965 "a.${table}_id" => "${table}_id",
2966 "a.department_id" => "department_id",
2967 "d.description" => "department",
2968 "ct.name" => $table,
2969 "current_date + ct.terms" => "duedate",
2972 if ($self->{type} =~ /delivery_order/) {
2973 $arap = 'delivery_orders';
2974 delete $column_map{"a.curr"};
2976 } elsif ($self->{type} =~ /_order/) {
2978 $where = "quotation = '0'";
2980 } elsif ($self->{type} =~ /_quotation/) {
2982 $where = "quotation = '1'";
2984 } elsif ($table eq 'customer') {
2992 $where = "($where) AND" if ($where);
2993 my $query = qq|SELECT MAX(id) FROM $arap
2994 WHERE $where ${table}_id > 0|;
2995 my ($trans_id) = selectrow_query($self, $dbh, $query);
2998 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2999 $query = qq|SELECT $column_spec
3001 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
3002 LEFT JOIN department d ON (a.department_id = d.id)
3004 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3006 map { $self->{$_} = $ref->{$_} } values %column_map;
3008 $main::lxdebug->leave_sub();
3012 $main::lxdebug->enter_sub();
3014 my ($self, $myconfig, $thisdate, $days) = @_;
3016 my $dbh = $self->get_standard_dbh($myconfig);
3021 my $dateformat = $myconfig->{dateformat};
3022 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3023 $thisdate = $dbh->quote($thisdate);
3024 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3026 $query = qq|SELECT current_date AS thisdate|;
3029 ($thisdate) = selectrow_query($self, $dbh, $query);
3031 $main::lxdebug->leave_sub();
3037 $main::lxdebug->enter_sub();
3039 my ($self, $string) = @_;
3041 if ($string !~ /%/) {
3042 $string = "%$string%";
3045 $string =~ s/\'/\'\'/g;
3047 $main::lxdebug->leave_sub();
3053 $main::lxdebug->enter_sub();
3055 my ($self, $flds, $new, $count, $numrows) = @_;
3059 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3064 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3066 my $j = $item->{ndx} - 1;
3067 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3071 for $i ($count + 1 .. $numrows) {
3072 map { delete $self->{"${_}_$i"} } @{$flds};
3075 $main::lxdebug->leave_sub();
3079 $main::lxdebug->enter_sub();
3081 my ($self, $myconfig) = @_;
3085 my $dbh = $self->dbconnect_noauto($myconfig);
3087 my $query = qq|DELETE FROM status
3088 WHERE (formname = ?) AND (trans_id = ?)|;
3089 my $sth = prepare_query($self, $dbh, $query);
3091 if ($self->{formname} =~ /(check|receipt)/) {
3092 for $i (1 .. $self->{rowcount}) {
3093 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3096 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3100 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3101 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3103 my %queued = split / /, $self->{queued};
3106 if ($self->{formname} =~ /(check|receipt)/) {
3108 # this is a check or receipt, add one entry for each lineitem
3109 my ($accno) = split /--/, $self->{account};
3110 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3111 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3112 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3113 $sth = prepare_query($self, $dbh, $query);
3115 for $i (1 .. $self->{rowcount}) {
3116 if ($self->{"checked_$i"}) {
3117 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3123 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3124 VALUES (?, ?, ?, ?, ?)|;
3125 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3126 $queued{$self->{formname}}, $self->{formname});
3132 $main::lxdebug->leave_sub();
3136 $main::lxdebug->enter_sub();
3138 my ($self, $dbh) = @_;
3140 my ($query, $printed, $emailed);
3142 my $formnames = $self->{printed};
3143 my $emailforms = $self->{emailed};
3145 $query = qq|DELETE FROM status
3146 WHERE (formname = ?) AND (trans_id = ?)|;
3147 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3149 # this only applies to the forms
3150 # checks and receipts are posted when printed or queued
3152 if ($self->{queued}) {
3153 my %queued = split / /, $self->{queued};
3155 foreach my $formname (keys %queued) {
3156 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3157 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3159 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3160 VALUES (?, ?, ?, ?, ?)|;
3161 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3163 $formnames =~ s/\Q$self->{formname}\E//;
3164 $emailforms =~ s/\Q$self->{formname}\E//;
3169 # save printed, emailed info
3170 $formnames =~ s/^ +//g;
3171 $emailforms =~ s/^ +//g;
3174 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3175 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3177 foreach my $formname (keys %status) {
3178 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3179 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3181 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3182 VALUES (?, ?, ?, ?)|;
3183 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3186 $main::lxdebug->leave_sub();
3190 # $main::locale->text('SAVED')
3191 # $main::locale->text('DELETED')
3192 # $main::locale->text('ADDED')
3193 # $main::locale->text('PAYMENT POSTED')
3194 # $main::locale->text('POSTED')
3195 # $main::locale->text('POSTED AS NEW')
3196 # $main::locale->text('ELSE')
3197 # $main::locale->text('SAVED FOR DUNNING')
3198 # $main::locale->text('DUNNING STARTED')
3199 # $main::locale->text('PRINTED')
3200 # $main::locale->text('MAILED')
3201 # $main::locale->text('SCREENED')
3202 # $main::locale->text('CANCELED')
3203 # $main::locale->text('invoice')
3204 # $main::locale->text('proforma')
3205 # $main::locale->text('sales_order')
3206 # $main::locale->text('packing_list')
3207 # $main::locale->text('pick_list')
3208 # $main::locale->text('purchase_order')
3209 # $main::locale->text('bin_list')
3210 # $main::locale->text('sales_quotation')
3211 # $main::locale->text('request_quotation')
3214 $main::lxdebug->enter_sub();
3219 if(!exists $self->{employee_id}) {
3220 &get_employee($self, $dbh);
3224 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3225 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3226 my @values = (conv_i($self->{id}), $self->{login},
3227 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3228 do_query($self, $dbh, $query, @values);
3230 $main::lxdebug->leave_sub();
3234 $main::lxdebug->enter_sub();
3236 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3237 my ($orderBy, $desc) = split(/\-\-/, $order);
3238 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3241 if ($trans_id ne "") {
3243 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 | .
3244 qq|FROM history_erp h | .
3245 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3246 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3249 my $sth = $dbh->prepare($query) || $self->dberror($query);
3251 $sth->execute() || $self->dberror("$query");
3253 while(my $hash_ref = $sth->fetchrow_hashref()) {
3254 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3255 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3256 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3257 $tempArray[$i++] = $hash_ref;
3259 $main::lxdebug->leave_sub() and return \@tempArray
3260 if ($i > 0 && $tempArray[0] ne "");
3262 $main::lxdebug->leave_sub();
3266 sub update_defaults {
3267 $main::lxdebug->enter_sub();
3269 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3272 if ($provided_dbh) {
3273 $dbh = $provided_dbh;
3275 $dbh = $self->dbconnect_noauto($myconfig);
3277 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3278 my $sth = $dbh->prepare($query);
3280 $sth->execute || $self->dberror($query);
3281 my ($var) = $sth->fetchrow_array;
3284 if ($var =~ m/\d+$/) {
3285 my $new_var = (substr $var, $-[0]) * 1 + 1;
3286 my $len_diff = length($var) - $-[0] - length($new_var);
3287 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3293 $query = qq|UPDATE defaults SET $fld = ?|;
3294 do_query($self, $dbh, $query, $var);
3296 if (!$provided_dbh) {
3301 $main::lxdebug->leave_sub();
3306 =item update_business
3309 \%config, - config hashref
3310 $business_id, - business id
3311 $dbh - optional database handle
3313 handles business (thats customer/vendor types) sequences.
3315 special behaviour for empty strings in customerinitnumber field:
3316 will in this case not increase the value, and return undef.
3319 sub update_business {
3320 $main::lxdebug->enter_sub();
3322 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3325 if ($provided_dbh) {
3326 $dbh = $provided_dbh;
3328 $dbh = $self->dbconnect_noauto($myconfig);
3331 qq|SELECT customernumberinit FROM business
3332 WHERE id = ? FOR UPDATE|;
3333 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3335 return undef unless $var;
3337 if ($var =~ m/\d+$/) {
3338 my $new_var = (substr $var, $-[0]) * 1 + 1;
3339 my $len_diff = length($var) - $-[0] - length($new_var);
3340 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3346 $query = qq|UPDATE business
3347 SET customernumberinit = ?
3349 do_query($self, $dbh, $query, $var, $business_id);
3351 if (!$provided_dbh) {
3356 $main::lxdebug->leave_sub();
3361 sub get_partsgroup {
3362 $main::lxdebug->enter_sub();
3364 my ($self, $myconfig, $p) = @_;
3365 my $target = $p->{target} || 'all_partsgroup';
3367 my $dbh = $self->get_standard_dbh($myconfig);
3369 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3371 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3374 if ($p->{searchitems} eq 'part') {
3375 $query .= qq|WHERE p.inventory_accno_id > 0|;
3377 if ($p->{searchitems} eq 'service') {
3378 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3380 if ($p->{searchitems} eq 'assembly') {
3381 $query .= qq|WHERE p.assembly = '1'|;
3383 if ($p->{searchitems} eq 'labor') {
3384 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3387 $query .= qq|ORDER BY partsgroup|;
3390 $query = qq|SELECT id, partsgroup FROM partsgroup
3391 ORDER BY partsgroup|;
3394 if ($p->{language_code}) {
3395 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3396 t.description AS translation
3398 JOIN parts p ON (p.partsgroup_id = pg.id)
3399 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3400 ORDER BY translation|;
3401 @values = ($p->{language_code});
3404 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3406 $main::lxdebug->leave_sub();
3409 sub get_pricegroup {
3410 $main::lxdebug->enter_sub();
3412 my ($self, $myconfig, $p) = @_;
3414 my $dbh = $self->get_standard_dbh($myconfig);
3416 my $query = qq|SELECT p.id, p.pricegroup
3419 $query .= qq| ORDER BY pricegroup|;
3422 $query = qq|SELECT id, pricegroup FROM pricegroup
3423 ORDER BY pricegroup|;
3426 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3428 $main::lxdebug->leave_sub();
3432 # usage $form->all_years($myconfig, [$dbh])
3433 # return list of all years where bookings found
3436 $main::lxdebug->enter_sub();
3438 my ($self, $myconfig, $dbh) = @_;
3440 $dbh ||= $self->get_standard_dbh($myconfig);
3443 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3444 (SELECT MAX(transdate) FROM acc_trans)|;
3445 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3447 if ($myconfig->{dateformat} =~ /^yy/) {
3448 ($startdate) = split /\W/, $startdate;
3449 ($enddate) = split /\W/, $enddate;
3451 (@_) = split /\W/, $startdate;
3453 (@_) = split /\W/, $enddate;
3458 $startdate = substr($startdate,0,4);
3459 $enddate = substr($enddate,0,4);
3461 while ($enddate >= $startdate) {
3462 push @all_years, $enddate--;
3467 $main::lxdebug->leave_sub();
3471 $main::lxdebug->enter_sub();
3475 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3477 $main::lxdebug->leave_sub();
3481 $main::lxdebug->enter_sub();
3486 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3488 $main::lxdebug->leave_sub();