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();
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}) {
310 if (lc $self->{INPUT_ENCODING} ne lc $db_charset) {
312 my $iconv = Text::Iconv->new($self->{INPUT_ENCODING}, $db_charset);
314 _recode_recursively($iconv, $self);
317 delete $self->{INPUT_ENCODING};
320 $self->{action} = lc $self->{action};
321 $self->{action} =~ s/( |-|,|\#)/_/g;
323 $self->{version} = "2.6.0";
325 $main::lxdebug->leave_sub();
330 sub _flatten_variables_rec {
331 $main::lxdebug->enter_sub(2);
340 if ('' eq ref $curr->{$key}) {
341 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
343 } elsif ('HASH' eq ref $curr->{$key}) {
344 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
345 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
349 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
350 my $first_array_entry = 1;
352 foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
353 push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
354 $first_array_entry = 0;
359 $main::lxdebug->leave_sub(2);
364 sub flatten_variables {
365 $main::lxdebug->enter_sub(2);
373 push @variables, $self->_flatten_variables_rec($self, '', $_);
376 $main::lxdebug->leave_sub(2);
381 sub flatten_standard_variables {
382 $main::lxdebug->enter_sub(2);
385 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
389 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
390 push @variables, $self->_flatten_variables_rec($self, '', $_);
393 $main::lxdebug->leave_sub(2);
399 $main::lxdebug->enter_sub();
405 map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
407 $main::lxdebug->leave_sub();
411 $main::lxdebug->enter_sub(2);
414 my $password = $self->{password};
416 $self->{password} = 'X' x 8;
418 local $Data::Dumper::Sortkeys = 1;
419 my $output = Dumper($self);
421 $self->{password} = $password;
423 $main::lxdebug->leave_sub(2);
429 $main::lxdebug->enter_sub(2);
431 my ($self, $str) = @_;
433 $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
435 $main::lxdebug->leave_sub(2);
441 $main::lxdebug->enter_sub(2);
443 my ($self, $str) = @_;
448 $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
450 $main::lxdebug->leave_sub(2);
456 $main::lxdebug->enter_sub();
457 my ($self, $str) = @_;
459 if ($str && !ref($str)) {
460 $str =~ s/\"/"/g;
463 $main::lxdebug->leave_sub();
469 $main::lxdebug->enter_sub();
470 my ($self, $str) = @_;
472 if ($str && !ref($str)) {
473 $str =~ s/"/\"/g;
476 $main::lxdebug->leave_sub();
482 $main::lxdebug->enter_sub();
486 map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
488 for (sort keys %$self) {
489 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
490 print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
493 $main::lxdebug->leave_sub();
497 $main::lxdebug->enter_sub();
499 $main::lxdebug->show_backtrace();
501 my ($self, $msg) = @_;
502 if ($ENV{HTTP_USER_AGENT}) {
504 $self->show_generic_error($msg);
511 $main::lxdebug->leave_sub();
515 $main::lxdebug->enter_sub();
517 my ($self, $msg) = @_;
519 if ($ENV{HTTP_USER_AGENT}) {
522 if (!$self->{header}) {
535 if ($self->{info_function}) {
536 &{ $self->{info_function} }($msg);
542 $main::lxdebug->leave_sub();
545 # calculates the number of rows in a textarea based on the content and column number
546 # can be capped with maxrows
548 $main::lxdebug->enter_sub();
549 my ($self, $str, $cols, $maxrows, $minrows) = @_;
553 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
556 $main::lxdebug->leave_sub();
558 return max(min($rows, $maxrows), $minrows);
562 $main::lxdebug->enter_sub();
564 my ($self, $msg) = @_;
566 $self->error("$msg\n" . $DBI::errstr);
568 $main::lxdebug->leave_sub();
572 $main::lxdebug->enter_sub();
574 my ($self, $name, $msg) = @_;
577 foreach my $part (split m/\./, $name) {
578 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
581 $curr = $curr->{$part};
584 $main::lxdebug->leave_sub();
587 sub create_http_response {
588 $main::lxdebug->enter_sub();
593 my $cgi = $main::cgi;
594 $cgi ||= CGI->new('');
598 if ($ENV{HTTP_X_FORWARDED_FOR}) {
599 $base_path = $ENV{HTTP_REFERER};
600 $base_path =~ s|^.*?://.*?/|/|;
602 $base_path = $ENV{REQUEST_URI};
604 $base_path =~ s|[^/]+$||;
605 $base_path =~ s|/$||;
608 if (defined $main::auth) {
609 my $session_cookie_value = $main::auth->get_session_id();
610 $session_cookie_value ||= 'NO_SESSION';
612 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
613 '-value' => $session_cookie_value,
614 '-path' => $base_path,
615 '-secure' => $ENV{HTTPS});
618 my %cgi_params = ('-type' => $params{content_type});
619 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
621 my $output = $cgi->header('-cookie' => $session_cookie,
624 $main::lxdebug->leave_sub();
631 $main::lxdebug->enter_sub();
633 # extra code ist currently only used by menuv3 and menuv4 to set their css.
634 # it is strongly deprecated, and will be changed in a future version.
635 my ($self, $extra_code) = @_;
637 if ($self->{header}) {
638 $main::lxdebug->leave_sub();
642 my ($stylesheet, $favicon, $pagelayout);
644 if ($ENV{HTTP_USER_AGENT}) {
647 if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
648 # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
649 $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
652 my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
654 $stylesheets =~ s|^\s*||;
655 $stylesheets =~ s|\s*$||;
656 foreach my $file (split m/\s+/, $stylesheets) {
658 next if (! -f "css/$file");
660 $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
663 $self->{favicon} = "favicon.ico" unless $self->{favicon};
665 if ($self->{favicon} && (-f "$self->{favicon}")) {
667 qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
671 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
673 if ($self->{landscape}) {
674 $pagelayout = qq|<style type="text/css">
675 \@page { size:landscape; }
680 <script type="text/javascript">
683 document.$self->{fokus}.focus();
687 | if $self->{"fokus"};
691 if ($self->{jsscript} == 1) {
694 <script type="text/javascript" src="js/jquery.js"></script>
695 <script type="text/javascript" src="js/common.js"></script>
696 <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
697 <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
698 <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
699 <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
706 ? "$self->{title} - $self->{titlebar}"
709 foreach my $item (@ { $self->{AJAX} }) {
710 $ajax .= $item->show_javascript();
713 print $self->create_http_response('content_type' => 'text/html',
714 'charset' => $db_charset,);
715 print qq|${doctype}<html>
717 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
718 <title>$self->{titlebar}</title>
727 <meta name="robots" content="noindex,nofollow" />
728 <script type="text/javascript" src="js/highlight_input.js"></script>
730 <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
731 <script type="text/javascript" src="js/tabcontent.js">
733 /***********************************************
734 * Tab Content script v2.2- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
735 * This notice MUST stay intact for legal use
736 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
737 ***********************************************/
748 $main::lxdebug->leave_sub();
751 sub ajax_response_header {
752 $main::lxdebug->enter_sub();
756 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
757 my $cgi = $main::cgi || CGI->new('');
758 my $output = $cgi->header('-charset' => $db_charset);
760 $main::lxdebug->leave_sub();
765 sub _prepare_html_template {
766 $main::lxdebug->enter_sub();
768 my ($self, $file, $additional_params) = @_;
771 if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
772 $language = $main::language;
774 $language = $main::myconfig{"countrycode"};
776 $language = "de" unless ($language);
778 if (-f "templates/webpages/${file}_${language}.html") {
779 if ((-f ".developer") &&
780 (-f "templates/webpages/${file}_master.html") &&
781 ((stat("templates/webpages/${file}_master.html"))[9] >
782 (stat("templates/webpages/${file}_${language}.html"))[9])) {
783 my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
784 "Please re-run 'locales.pl' in 'locale/${language}'.";
785 print(qq|<pre>$info</pre>|);
789 $file = "templates/webpages/${file}_${language}.html";
790 } elsif (-f "templates/webpages/${file}.html") {
791 $file = "templates/webpages/${file}.html";
793 my $info = "Web page template '${file}' not found.\n" .
794 "Please re-run 'locales.pl' in 'locale/${language}'.";
795 print(qq|<pre>$info</pre>|);
799 if ($self->{"DEBUG"}) {
800 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
803 if ($additional_params->{"DEBUG"}) {
804 $additional_params->{"DEBUG"} =
805 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
808 if (%main::myconfig) {
809 map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
810 my $jsc_dateformat = $main::myconfig{"dateformat"};
811 $jsc_dateformat =~ s/d+/\%d/gi;
812 $jsc_dateformat =~ s/m+/\%m/gi;
813 $jsc_dateformat =~ s/y+/\%Y/gi;
814 $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
817 $additional_params->{"conf_dbcharset"} = $main::dbcharset;
818 $additional_params->{"conf_webdav"} = $main::webdav;
819 $additional_params->{"conf_lizenzen"} = $main::lizenzen;
820 $additional_params->{"conf_latex_templates"} = $main::latex;
821 $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
823 if (%main::debug_options) {
824 map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
827 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
828 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
829 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
833 $main::lxdebug->leave_sub();
838 sub parse_html_template {
839 $main::lxdebug->enter_sub();
841 my ($self, $file, $additional_params) = @_;
843 $additional_params ||= { };
845 $file = $self->_prepare_html_template($file, $additional_params);
847 my $template = Template->new({ 'INTERPOLATE' => 0,
851 'PLUGIN_BASE' => 'SL::Template::Plugin',
852 'INCLUDE_PATH' => '.:templates/webpages',
855 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
857 my $in = IO::File->new($file, 'r');
860 print STDERR "Error opening template file: $!";
861 $main::lxdebug->leave_sub();
865 my $input = join('', <$in>);
869 $input = $main::locale->{iconv}->convert($input);
873 if (!$template->process(\$input, $additional_params, \$output)) {
874 print STDERR $template->error();
877 $main::lxdebug->leave_sub();
882 sub show_generic_error {
883 $main::lxdebug->enter_sub();
885 my ($self, $error, %params) = @_;
888 'title_error' => $params{title},
889 'label_error' => $error,
892 if ($params{action}) {
895 map { delete($self->{$_}); } qw(action);
896 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
898 $add_params->{SHOW_BUTTON} = 1;
899 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
900 $add_params->{VARIABLES} = \@vars;
902 } elsif ($params{back_button}) {
903 $add_params->{SHOW_BACK_BUTTON} = 1;
906 $self->{title} = $params{title} if $params{title};
909 print $self->parse_html_template("generic/error", $add_params);
911 $main::lxdebug->leave_sub();
913 die("Error: $error\n");
916 sub show_generic_information {
917 $main::lxdebug->enter_sub();
919 my ($self, $text, $title) = @_;
922 'title_information' => $title,
923 'label_information' => $text,
926 $self->{title} = $title if ($title);
929 print $self->parse_html_template("generic/information", $add_params);
931 $main::lxdebug->leave_sub();
933 die("Information: $text\n");
936 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
937 # changed it to accept an arbitrary number of triggers - sschoeling
939 $main::lxdebug->enter_sub();
942 my $myconfig = shift;
945 # set dateform for jsscript
948 "dd.mm.yy" => "%d.%m.%Y",
949 "dd-mm-yy" => "%d-%m-%Y",
950 "dd/mm/yy" => "%d/%m/%Y",
951 "mm/dd/yy" => "%m/%d/%Y",
952 "mm-dd-yy" => "%m-%d-%Y",
953 "yyyy-mm-dd" => "%Y-%m-%d",
956 my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
957 $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
964 inputField : "| . (shift) . qq|",
965 ifFormat :"$ifFormat",
966 align : "| . (shift) . qq|",
967 button : "| . (shift) . qq|"
973 <script type="text/javascript">
974 <!--| . join("", @triggers) . qq|//-->
978 $main::lxdebug->leave_sub();
981 } #end sub write_trigger
984 $main::lxdebug->enter_sub();
986 my ($self, $msg) = @_;
988 if ($self->{callback}) {
990 my ($script, $argv) = split(/\?/, $self->{callback}, 2);
992 $script =~ s|[^a-zA-Z0-9_\.]||g;
993 exec("perl", "$script", $argv);
1001 $main::lxdebug->leave_sub();
1004 # sort of columns removed - empty sub
1006 $main::lxdebug->enter_sub();
1008 my ($self, @columns) = @_;
1010 $main::lxdebug->leave_sub();
1016 $main::lxdebug->enter_sub(2);
1018 my ($self, $myconfig, $amount, $places, $dash) = @_;
1020 if ($amount eq "") {
1024 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
1026 my $neg = ($amount =~ s/^-//);
1027 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
1029 if (defined($places) && ($places ne '')) {
1035 my ($actual_places) = ($amount =~ /\.(\d+)/);
1036 $actual_places = length($actual_places);
1037 $places = $actual_places > $places ? $actual_places : $places;
1040 $amount = $self->round_amount($amount, $places);
1043 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
1044 my @p = split(/\./, $amount); # split amount at decimal point
1046 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
1049 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
1052 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
1053 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1054 ($neg ? "-$amount" : "$amount" ) ;
1058 $main::lxdebug->leave_sub(2);
1062 sub format_amount_units {
1063 $main::lxdebug->enter_sub();
1068 my $myconfig = \%main::myconfig;
1069 my $amount = $params{amount} * 1;
1070 my $places = $params{places};
1071 my $part_unit_name = $params{part_unit};
1072 my $amount_unit_name = $params{amount_unit};
1073 my $conv_units = $params{conv_units};
1074 my $max_places = $params{max_places};
1076 if (!$part_unit_name) {
1077 $main::lxdebug->leave_sub();
1081 AM->retrieve_all_units();
1082 my $all_units = $main::all_units;
1084 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1085 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1088 if (!scalar @{ $conv_units }) {
1089 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1090 $main::lxdebug->leave_sub();
1094 my $part_unit = $all_units->{$part_unit_name};
1095 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1097 $amount *= $conv_unit->{factor};
1102 foreach my $unit (@$conv_units) {
1103 my $last = $unit->{name} eq $part_unit->{name};
1105 $num = int($amount / $unit->{factor});
1106 $amount -= $num * $unit->{factor};
1109 if ($last ? $amount : $num) {
1110 push @values, { "unit" => $unit->{name},
1111 "amount" => $last ? $amount / $unit->{factor} : $num,
1112 "places" => $last ? $places : 0 };
1119 push @values, { "unit" => $part_unit_name,
1124 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1126 $main::lxdebug->leave_sub();
1132 $main::lxdebug->enter_sub(2);
1137 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1138 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1139 $input =~ s/\#\#/\#/g;
1141 $main::lxdebug->leave_sub(2);
1149 $main::lxdebug->enter_sub(2);
1151 my ($self, $myconfig, $amount) = @_;
1153 if ( ($myconfig->{numberformat} eq '1.000,00')
1154 || ($myconfig->{numberformat} eq '1000,00')) {
1159 if ($myconfig->{numberformat} eq "1'000.00") {
1165 $main::lxdebug->leave_sub(2);
1167 return ($amount * 1);
1171 $main::lxdebug->enter_sub(2);
1173 my ($self, $amount, $places) = @_;
1176 # Rounding like "Kaufmannsrunden"
1177 # Descr. http://de.wikipedia.org/wiki/Rundung
1179 # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
1182 $amount = $amount * (10**($places));
1183 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1185 $main::lxdebug->leave_sub(2);
1187 return $round_amount;
1191 sub parse_template {
1192 $main::lxdebug->enter_sub();
1194 my ($self, $myconfig, $userspath) = @_;
1195 my ($template, $out);
1199 $self->{"cwd"} = getcwd();
1200 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1204 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1205 $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1206 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
1208 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1209 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1210 $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1211 $ext_for_format = 'pdf';
1213 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1214 $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1215 $ext_for_format = 'html';
1217 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1218 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1219 $ext_for_format = 'xml';
1221 } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1222 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1224 } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1225 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1227 } elsif ( defined $self->{'format'}) {
1228 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1230 } elsif ( $self->{'format'} eq '' ) {
1231 $self->error("No Outputformat given: $self->{'format'}");
1233 } else { #Catch the rest
1234 $self->error("Outputformat not defined: $self->{'format'}");
1237 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1238 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1240 if (!$self->{employee_id}) {
1241 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1244 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1246 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1248 # OUT is used for the media, screen, printer, email
1249 # for postscript we store a copy in a temporary file
1251 my $prepend_userspath;
1253 if (!$self->{tmpfile}) {
1254 $self->{tmpfile} = "${fileid}.$self->{IN}";
1255 $prepend_userspath = 1;
1258 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1260 $self->{tmpfile} =~ s|.*/||;
1261 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1262 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1264 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1265 $out = $self->{OUT};
1266 $self->{OUT} = ">$self->{tmpfile}";
1270 open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1272 open(OUT, ">-") or $self->error("STDOUT : $!");
1276 if (!$template->parse(*OUT)) {
1278 $self->error("$self->{IN} : " . $template->get_error());
1283 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1285 if ($self->{media} eq 'email') {
1287 my $mail = new Mailer;
1289 map { $mail->{$_} = $self->{$_} }
1290 qw(cc bcc subject message version format);
1291 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1292 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1293 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1294 $mail->{fileid} = "$fileid.";
1295 $myconfig->{signature} =~ s/\r//g;
1297 # if we send html or plain text inline
1298 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1299 $mail->{contenttype} = "text/html";
1301 $mail->{message} =~ s/\r//g;
1302 $mail->{message} =~ s/\n/<br>\n/g;
1303 $myconfig->{signature} =~ s/\n/<br>\n/g;
1304 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1306 open(IN, $self->{tmpfile})
1307 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1309 $mail->{message} .= $_;
1316 if (!$self->{"do_not_attach"}) {
1317 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1318 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1319 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1320 "name" => $attachment_name }];
1323 $mail->{message} =~ s/\r//g;
1324 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1328 my $err = $mail->send();
1329 $self->error($self->cleanup . "$err") if ($err);
1333 $self->{OUT} = $out;
1335 my $numbytes = (-s $self->{tmpfile});
1336 open(IN, $self->{tmpfile})
1337 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1339 $self->{copies} = 1 unless $self->{media} eq 'printer';
1341 chdir("$self->{cwd}");
1342 #print(STDERR "Kopien $self->{copies}\n");
1343 #print(STDERR "OUT $self->{OUT}\n");
1344 for my $i (1 .. $self->{copies}) {
1346 open(OUT, $self->{OUT})
1347 or $self->error($self->cleanup . "$self->{OUT} : $!");
1349 $self->{attachment_filename} = ($self->{attachment_filename})
1350 ? $self->{attachment_filename}
1351 : $self->generate_attachment_filename();
1353 # launch application
1354 print qq|Content-Type: | . $template->get_mime_type() . qq|
1355 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1356 Content-Length: $numbytes
1360 open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1381 chdir("$self->{cwd}");
1382 $main::lxdebug->leave_sub();
1385 sub get_formname_translation {
1386 $main::lxdebug->enter_sub();
1387 my ($self, $formname) = @_;
1389 $formname ||= $self->{formname};
1391 my %formname_translations = (
1392 bin_list => $main::locale->text('Bin List'),
1393 credit_note => $main::locale->text('Credit Note'),
1394 invoice => $main::locale->text('Invoice'),
1395 packing_list => $main::locale->text('Packing List'),
1396 pick_list => $main::locale->text('Pick List'),
1397 proforma => $main::locale->text('Proforma Invoice'),
1398 purchase_order => $main::locale->text('Purchase Order'),
1399 request_quotation => $main::locale->text('RFQ'),
1400 sales_order => $main::locale->text('Confirmation'),
1401 sales_quotation => $main::locale->text('Quotation'),
1402 storno_invoice => $main::locale->text('Storno Invoice'),
1403 storno_packing_list => $main::locale->text('Storno Packing List'),
1404 sales_delivery_order => $main::locale->text('Delivery Order'),
1405 purchase_delivery_order => $main::locale->text('Delivery Order'),
1406 dunning => $main::locale->text('Dunning'),
1409 $main::lxdebug->leave_sub();
1410 return $formname_translations{$formname}
1413 sub get_number_prefix_for_type {
1414 $main::lxdebug->enter_sub();
1418 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1419 : ($self->{type} =~ /_quotation$/) ? 'quo'
1420 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1423 $main::lxdebug->leave_sub();
1427 sub get_extension_for_format {
1428 $main::lxdebug->enter_sub();
1431 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1432 : $self->{format} =~ /postscript/i ? ".ps"
1433 : $self->{format} =~ /opendocument/i ? ".odt"
1434 : $self->{format} =~ /html/i ? ".html"
1437 $main::lxdebug->leave_sub();
1441 sub generate_attachment_filename {
1442 $main::lxdebug->enter_sub();
1445 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1446 my $prefix = $self->get_number_prefix_for_type();
1448 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1449 $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1451 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1452 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1455 $attachment_filename = "";
1458 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1459 $attachment_filename =~ s|[\s/\\]+|_|g;
1461 $main::lxdebug->leave_sub();
1462 return $attachment_filename;
1465 sub generate_email_subject {
1466 $main::lxdebug->enter_sub();
1469 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1470 my $prefix = $self->get_number_prefix_for_type();
1472 if ($subject && $self->{"${prefix}number"}) {
1473 $subject .= " " . $self->{"${prefix}number"}
1476 $main::lxdebug->leave_sub();
1481 $main::lxdebug->enter_sub();
1485 chdir("$self->{tmpdir}");
1488 if (-f "$self->{tmpfile}.err") {
1489 open(FH, "$self->{tmpfile}.err");
1494 if ($self->{tmpfile}) {
1495 $self->{tmpfile} =~ s|.*/||g;
1497 $self->{tmpfile} =~ s/\.\w+$//g;
1498 my $tmpfile = $self->{tmpfile};
1499 unlink(<$tmpfile.*>);
1502 chdir("$self->{cwd}");
1504 $main::lxdebug->leave_sub();
1510 $main::lxdebug->enter_sub();
1512 my ($self, $date, $myconfig) = @_;
1515 if ($date && $date =~ /\D/) {
1517 if ($myconfig->{dateformat} =~ /^yy/) {
1518 ($yy, $mm, $dd) = split /\D/, $date;
1520 if ($myconfig->{dateformat} =~ /^mm/) {
1521 ($mm, $dd, $yy) = split /\D/, $date;
1523 if ($myconfig->{dateformat} =~ /^dd/) {
1524 ($dd, $mm, $yy) = split /\D/, $date;
1529 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1530 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1532 $dd = "0$dd" if ($dd < 10);
1533 $mm = "0$mm" if ($mm < 10);
1535 $date = "$yy$mm$dd";
1538 $main::lxdebug->leave_sub();
1543 # Database routines used throughout
1546 $main::lxdebug->enter_sub(2);
1548 my ($self, $myconfig) = @_;
1550 # connect to database
1552 DBI->connect($myconfig->{dbconnect},
1553 $myconfig->{dbuser}, $myconfig->{dbpasswd})
1557 if ($myconfig->{dboptions}) {
1558 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1561 $main::lxdebug->leave_sub(2);
1566 sub dbconnect_noauto {
1567 $main::lxdebug->enter_sub();
1569 my ($self, $myconfig) = @_;
1571 # connect to database
1573 DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1574 $myconfig->{dbpasswd}, { AutoCommit => 0 })
1578 if ($myconfig->{dboptions}) {
1579 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1582 $main::lxdebug->leave_sub();
1587 sub get_standard_dbh {
1588 $main::lxdebug->enter_sub(2);
1590 my ($self, $myconfig) = @_;
1592 if ($standard_dbh && !$standard_dbh->{Active}) {
1593 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1594 undef $standard_dbh;
1597 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1599 $main::lxdebug->leave_sub(2);
1601 return $standard_dbh;
1605 $main::lxdebug->enter_sub();
1607 my ($self, $date, $myconfig) = @_;
1608 my $dbh = $self->dbconnect($myconfig);
1610 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1611 my $sth = prepare_execute_query($self, $dbh, $query, $date);
1612 my ($closed) = $sth->fetchrow_array;
1614 $main::lxdebug->leave_sub();
1619 sub update_balance {
1620 $main::lxdebug->enter_sub();
1622 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1624 # if we have a value, go do it
1627 # retrieve balance from table
1628 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1629 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1630 my ($balance) = $sth->fetchrow_array;
1636 $query = "UPDATE $table SET $field = $balance WHERE $where";
1637 do_query($self, $dbh, $query, @values);
1639 $main::lxdebug->leave_sub();
1642 sub update_exchangerate {
1643 $main::lxdebug->enter_sub();
1645 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1647 # some sanity check for currency
1649 $main::lxdebug->leave_sub();
1652 $query = qq|SELECT curr FROM defaults|;
1654 my ($currency) = selectrow_query($self, $dbh, $query);
1655 my ($defaultcurrency) = split m/:/, $currency;
1658 if ($curr eq $defaultcurrency) {
1659 $main::lxdebug->leave_sub();
1663 $query = qq|SELECT e.curr FROM exchangerate e
1664 WHERE e.curr = ? AND e.transdate = ?
1666 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1675 $buy = conv_i($buy, "NULL");
1676 $sell = conv_i($sell, "NULL");
1679 if ($buy != 0 && $sell != 0) {
1680 $set = "buy = $buy, sell = $sell";
1681 } elsif ($buy != 0) {
1682 $set = "buy = $buy";
1683 } elsif ($sell != 0) {
1684 $set = "sell = $sell";
1687 if ($sth->fetchrow_array) {
1688 $query = qq|UPDATE exchangerate
1694 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1695 VALUES (?, $buy, $sell, ?)|;
1698 do_query($self, $dbh, $query, $curr, $transdate);
1700 $main::lxdebug->leave_sub();
1703 sub save_exchangerate {
1704 $main::lxdebug->enter_sub();
1706 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1708 my $dbh = $self->dbconnect($myconfig);
1712 $buy = $rate if $fld eq 'buy';
1713 $sell = $rate if $fld eq 'sell';
1716 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1721 $main::lxdebug->leave_sub();
1724 sub get_exchangerate {
1725 $main::lxdebug->enter_sub();
1727 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1730 unless ($transdate) {
1731 $main::lxdebug->leave_sub();
1735 $query = qq|SELECT curr FROM defaults|;
1737 my ($currency) = selectrow_query($self, $dbh, $query);
1738 my ($defaultcurrency) = split m/:/, $currency;
1740 if ($currency eq $defaultcurrency) {
1741 $main::lxdebug->leave_sub();
1745 $query = qq|SELECT e.$fld FROM exchangerate e
1746 WHERE e.curr = ? AND e.transdate = ?|;
1747 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1751 $main::lxdebug->leave_sub();
1753 return $exchangerate;
1756 sub check_exchangerate {
1757 $main::lxdebug->enter_sub();
1759 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1761 if ($fld !~/^buy|sell$/) {
1762 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1765 unless ($transdate) {
1766 $main::lxdebug->leave_sub();
1770 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1772 if ($currency eq $defaultcurrency) {
1773 $main::lxdebug->leave_sub();
1777 my $dbh = $self->get_standard_dbh($myconfig);
1778 my $query = qq|SELECT e.$fld FROM exchangerate e
1779 WHERE e.curr = ? AND e.transdate = ?|;
1781 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1783 $main::lxdebug->leave_sub();
1785 return $exchangerate;
1788 sub get_default_currency {
1789 $main::lxdebug->enter_sub();
1791 my ($self, $myconfig) = @_;
1792 my $dbh = $self->get_standard_dbh($myconfig);
1794 my $query = qq|SELECT curr FROM defaults|;
1796 my ($curr) = selectrow_query($self, $dbh, $query);
1797 my ($defaultcurrency) = split m/:/, $curr;
1799 $main::lxdebug->leave_sub();
1801 return $defaultcurrency;
1805 sub set_payment_options {
1806 $main::lxdebug->enter_sub();
1808 my ($self, $myconfig, $transdate) = @_;
1810 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1812 my $dbh = $self->get_standard_dbh($myconfig);
1815 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1816 qq|FROM payment_terms p | .
1819 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1820 $self->{payment_terms}) =
1821 selectrow_query($self, $dbh, $query, $self->{payment_id});
1823 if ($transdate eq "") {
1824 if ($self->{invdate}) {
1825 $transdate = $self->{invdate};
1827 $transdate = $self->{transdate};
1832 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1833 qq|FROM payment_terms|;
1834 ($self->{netto_date}, $self->{skonto_date}) =
1835 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1837 my ($invtotal, $total);
1838 my (%amounts, %formatted_amounts);
1840 if ($self->{type} =~ /_order$/) {
1841 $amounts{invtotal} = $self->{ordtotal};
1842 $amounts{total} = $self->{ordtotal};
1844 } elsif ($self->{type} =~ /_quotation$/) {
1845 $amounts{invtotal} = $self->{quototal};
1846 $amounts{total} = $self->{quototal};
1849 $amounts{invtotal} = $self->{invtotal};
1850 $amounts{total} = $self->{total};
1853 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1855 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1856 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1857 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1859 foreach (keys %amounts) {
1860 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1861 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1864 if ($self->{"language_id"}) {
1866 qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1867 qq|FROM translation_payment_terms t | .
1868 qq|LEFT JOIN language l ON t.language_id = l.id | .
1869 qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1870 my ($description_long, $output_numberformat, $output_dateformat,
1871 $output_longdates) =
1872 selectrow_query($self, $dbh, $query,
1873 $self->{"language_id"}, $self->{"payment_id"});
1875 $self->{payment_terms} = $description_long if ($description_long);
1877 if ($output_dateformat) {
1878 foreach my $key (qw(netto_date skonto_date)) {
1880 $main::locale->reformat_date($myconfig, $self->{$key},
1886 if ($output_numberformat &&
1887 ($output_numberformat ne $myconfig->{"numberformat"})) {
1888 my $saved_numberformat = $myconfig->{"numberformat"};
1889 $myconfig->{"numberformat"} = $output_numberformat;
1890 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1891 $myconfig->{"numberformat"} = $saved_numberformat;
1895 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1896 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1897 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1898 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1899 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1900 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1901 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1903 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1905 $main::lxdebug->leave_sub();
1909 sub get_template_language {
1910 $main::lxdebug->enter_sub();
1912 my ($self, $myconfig) = @_;
1914 my $template_code = "";
1916 if ($self->{language_id}) {
1917 my $dbh = $self->get_standard_dbh($myconfig);
1918 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1919 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1922 $main::lxdebug->leave_sub();
1924 return $template_code;
1927 sub get_printer_code {
1928 $main::lxdebug->enter_sub();
1930 my ($self, $myconfig) = @_;
1932 my $template_code = "";
1934 if ($self->{printer_id}) {
1935 my $dbh = $self->get_standard_dbh($myconfig);
1936 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1937 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1940 $main::lxdebug->leave_sub();
1942 return $template_code;
1946 $main::lxdebug->enter_sub();
1948 my ($self, $myconfig) = @_;
1950 my $template_code = "";
1952 if ($self->{shipto_id}) {
1953 my $dbh = $self->get_standard_dbh($myconfig);
1954 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1955 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1956 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1959 $main::lxdebug->leave_sub();
1963 $main::lxdebug->enter_sub();
1965 my ($self, $dbh, $id, $module) = @_;
1970 foreach my $item (qw(name department_1 department_2 street zipcode city country
1971 contact phone fax email)) {
1972 if ($self->{"shipto$item"}) {
1973 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1975 push(@values, $self->{"shipto${item}"});
1979 if ($self->{shipto_id}) {
1980 my $query = qq|UPDATE shipto set
1982 shiptodepartment_1 = ?,
1983 shiptodepartment_2 = ?,
1992 WHERE shipto_id = ?|;
1993 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1995 my $query = qq|SELECT * FROM shipto
1996 WHERE shiptoname = ? AND
1997 shiptodepartment_1 = ? AND
1998 shiptodepartment_2 = ? AND
1999 shiptostreet = ? AND
2000 shiptozipcode = ? AND
2002 shiptocountry = ? AND
2003 shiptocontact = ? AND
2009 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
2012 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
2013 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
2014 shiptocontact, shiptophone, shiptofax, shiptoemail, module)
2015 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
2016 do_query($self, $dbh, $query, $id, @values, $module);
2021 $main::lxdebug->leave_sub();
2025 $main::lxdebug->enter_sub();
2027 my ($self, $dbh) = @_;
2029 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
2031 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2032 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2033 $self->{"employee_id"} *= 1;
2035 $main::lxdebug->leave_sub();
2038 sub get_employee_data {
2039 $main::lxdebug->enter_sub();
2044 Common::check_params(\%params, qw(prefix));
2045 Common::check_params_x(\%params, qw(id));
2048 $main::lxdebug->leave_sub();
2052 my $myconfig = \%main::myconfig;
2053 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
2055 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2058 my $user = User->new($login);
2059 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2061 $self->{$params{prefix} . '_login'} = $login;
2062 $self->{$params{prefix} . '_name'} ||= $login;
2065 $main::lxdebug->leave_sub();
2069 $main::lxdebug->enter_sub();
2071 my ($self, $myconfig, $reference_date) = @_;
2073 $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2075 my $dbh = $self->get_standard_dbh($myconfig);
2076 my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2077 my ($duedate) = selectrow_query($self, $dbh, $query, $self->{payment_id});
2079 $main::lxdebug->leave_sub();
2085 $main::lxdebug->enter_sub();
2087 my ($self, $dbh, $id, $key) = @_;
2089 $key = "all_contacts" unless ($key);
2093 $main::lxdebug->leave_sub();
2098 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2099 qq|FROM contacts | .
2100 qq|WHERE cp_cv_id = ? | .
2101 qq|ORDER BY lower(cp_name)|;
2103 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2105 $main::lxdebug->leave_sub();
2109 $main::lxdebug->enter_sub();
2111 my ($self, $dbh, $key) = @_;
2113 my ($all, $old_id, $where, @values);
2115 if (ref($key) eq "HASH") {
2118 $key = "ALL_PROJECTS";
2120 foreach my $p (keys(%{$params})) {
2122 $all = $params->{$p};
2123 } elsif ($p eq "old_id") {
2124 $old_id = $params->{$p};
2125 } elsif ($p eq "key") {
2126 $key = $params->{$p};
2132 $where = "WHERE active ";
2134 if (ref($old_id) eq "ARRAY") {
2135 my @ids = grep({ $_ } @{$old_id});
2137 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2138 push(@values, @ids);
2141 $where .= " OR (id = ?) ";
2142 push(@values, $old_id);
2148 qq|SELECT id, projectnumber, description, active | .
2151 qq|ORDER BY lower(projectnumber)|;
2153 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2155 $main::lxdebug->leave_sub();
2159 $main::lxdebug->enter_sub();
2161 my ($self, $dbh, $vc_id, $key) = @_;
2163 $key = "all_shipto" unless ($key);
2166 # get shipping addresses
2167 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2169 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2175 $main::lxdebug->leave_sub();
2179 $main::lxdebug->enter_sub();
2181 my ($self, $dbh, $key) = @_;
2183 $key = "all_printers" unless ($key);
2185 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2187 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2189 $main::lxdebug->leave_sub();
2193 $main::lxdebug->enter_sub();
2195 my ($self, $dbh, $params) = @_;
2198 $key = $params->{key};
2199 $key = "all_charts" unless ($key);
2201 my $transdate = quote_db_date($params->{transdate});
2204 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2206 qq|LEFT JOIN taxkeys tk ON | .
2207 qq|(tk.id = (SELECT id FROM taxkeys | .
2208 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2209 qq| ORDER BY startdate DESC LIMIT 1)) | .
2210 qq|ORDER BY c.accno|;
2212 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2214 $main::lxdebug->leave_sub();
2217 sub _get_taxcharts {
2218 $main::lxdebug->enter_sub();
2220 my ($self, $dbh, $params) = @_;
2222 my $key = "all_taxcharts";
2225 if (ref $params eq 'HASH') {
2226 $key = $params->{key} if ($params->{key});
2227 if ($params->{module} eq 'AR') {
2228 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2230 } elsif ($params->{module} eq 'AP') {
2231 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2238 my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2240 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2242 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2244 $main::lxdebug->leave_sub();
2248 $main::lxdebug->enter_sub();
2250 my ($self, $dbh, $key) = @_;
2252 $key = "all_taxzones" unless ($key);
2254 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2256 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2258 $main::lxdebug->leave_sub();
2261 sub _get_employees {
2262 $main::lxdebug->enter_sub();
2264 my ($self, $dbh, $default_key, $key) = @_;
2266 $key = $default_key unless ($key);
2267 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2269 $main::lxdebug->leave_sub();
2272 sub _get_business_types {
2273 $main::lxdebug->enter_sub();
2275 my ($self, $dbh, $key) = @_;
2277 $key = "all_business_types" unless ($key);
2279 selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2281 $main::lxdebug->leave_sub();
2284 sub _get_languages {
2285 $main::lxdebug->enter_sub();
2287 my ($self, $dbh, $key) = @_;
2289 $key = "all_languages" unless ($key);
2291 my $query = qq|SELECT * FROM language ORDER BY id|;
2293 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2295 $main::lxdebug->leave_sub();
2298 sub _get_dunning_configs {
2299 $main::lxdebug->enter_sub();
2301 my ($self, $dbh, $key) = @_;
2303 $key = "all_dunning_configs" unless ($key);
2305 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2307 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2309 $main::lxdebug->leave_sub();
2312 sub _get_currencies {
2313 $main::lxdebug->enter_sub();
2315 my ($self, $dbh, $key) = @_;
2317 $key = "all_currencies" unless ($key);
2319 my $query = qq|SELECT curr AS currency FROM defaults|;
2321 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2323 $main::lxdebug->leave_sub();
2327 $main::lxdebug->enter_sub();
2329 my ($self, $dbh, $key) = @_;
2331 $key = "all_payments" unless ($key);
2333 my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2335 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2337 $main::lxdebug->leave_sub();
2340 sub _get_customers {
2341 $main::lxdebug->enter_sub();
2343 my ($self, $dbh, $key, $limit) = @_;
2345 $key = "all_customers" unless ($key);
2346 my $limit_clause = "LIMIT $limit" if $limit;
2348 my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2350 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2352 $main::lxdebug->leave_sub();
2356 $main::lxdebug->enter_sub();
2358 my ($self, $dbh, $key) = @_;
2360 $key = "all_vendors" unless ($key);
2362 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2364 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2366 $main::lxdebug->leave_sub();
2369 sub _get_departments {
2370 $main::lxdebug->enter_sub();
2372 my ($self, $dbh, $key) = @_;
2374 $key = "all_departments" unless ($key);
2376 my $query = qq|SELECT * FROM department ORDER BY description|;
2378 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2380 $main::lxdebug->leave_sub();
2383 sub _get_warehouses {
2384 $main::lxdebug->enter_sub();
2386 my ($self, $dbh, $param) = @_;
2388 my ($key, $bins_key);
2390 if ('' eq ref $param) {
2394 $key = $param->{key};
2395 $bins_key = $param->{bins};
2398 my $query = qq|SELECT w.* FROM warehouse w
2399 WHERE (NOT w.invalid) AND
2400 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2401 ORDER BY w.sortkey|;
2403 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2406 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2407 my $sth = prepare_query($self, $dbh, $query);
2409 foreach my $warehouse (@{ $self->{$key} }) {
2410 do_statement($self, $sth, $query, $warehouse->{id});
2411 $warehouse->{$bins_key} = [];
2413 while (my $ref = $sth->fetchrow_hashref()) {
2414 push @{ $warehouse->{$bins_key} }, $ref;
2420 $main::lxdebug->leave_sub();
2424 $main::lxdebug->enter_sub();
2426 my ($self, $dbh, $table, $key, $sortkey) = @_;
2428 my $query = qq|SELECT * FROM $table|;
2429 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2431 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2433 $main::lxdebug->leave_sub();
2437 # $main::lxdebug->enter_sub();
2439 # my ($self, $dbh, $key) = @_;
2441 # $key ||= "all_groups";
2443 # my $groups = $main::auth->read_groups();
2445 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2447 # $main::lxdebug->leave_sub();
2451 $main::lxdebug->enter_sub();
2456 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2457 my ($sth, $query, $ref);
2459 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2460 my $vc_id = $self->{"${vc}_id"};
2462 if ($params{"contacts"}) {
2463 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2466 if ($params{"shipto"}) {
2467 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2470 if ($params{"projects"} || $params{"all_projects"}) {
2471 $self->_get_projects($dbh, $params{"all_projects"} ?
2472 $params{"all_projects"} : $params{"projects"},
2473 $params{"all_projects"} ? 1 : 0);
2476 if ($params{"printers"}) {
2477 $self->_get_printers($dbh, $params{"printers"});
2480 if ($params{"languages"}) {
2481 $self->_get_languages($dbh, $params{"languages"});
2484 if ($params{"charts"}) {
2485 $self->_get_charts($dbh, $params{"charts"});
2488 if ($params{"taxcharts"}) {
2489 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2492 if ($params{"taxzones"}) {
2493 $self->_get_taxzones($dbh, $params{"taxzones"});
2496 if ($params{"employees"}) {
2497 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2500 if ($params{"salesmen"}) {
2501 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2504 if ($params{"business_types"}) {
2505 $self->_get_business_types($dbh, $params{"business_types"});
2508 if ($params{"dunning_configs"}) {
2509 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2512 if($params{"currencies"}) {
2513 $self->_get_currencies($dbh, $params{"currencies"});
2516 if($params{"customers"}) {
2517 if (ref $params{"customers"} eq 'HASH') {
2518 $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2520 $self->_get_customers($dbh, $params{"customers"});
2524 if($params{"vendors"}) {
2525 if (ref $params{"vendors"} eq 'HASH') {
2526 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2528 $self->_get_vendors($dbh, $params{"vendors"});
2532 if($params{"payments"}) {
2533 $self->_get_payments($dbh, $params{"payments"});
2536 if($params{"departments"}) {
2537 $self->_get_departments($dbh, $params{"departments"});
2540 if ($params{price_factors}) {
2541 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2544 if ($params{warehouses}) {
2545 $self->_get_warehouses($dbh, $params{warehouses});
2548 # if ($params{groups}) {
2549 # $self->_get_groups($dbh, $params{groups});
2552 if ($params{partsgroup}) {
2553 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2556 $main::lxdebug->leave_sub();
2559 # this sub gets the id and name from $table
2561 $main::lxdebug->enter_sub();
2563 my ($self, $myconfig, $table) = @_;
2565 # connect to database
2566 my $dbh = $self->get_standard_dbh($myconfig);
2568 $table = $table eq "customer" ? "customer" : "vendor";
2569 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2571 my ($query, @values);
2573 if (!$self->{openinvoices}) {
2575 if ($self->{customernumber} ne "") {
2576 $where = qq|(vc.customernumber ILIKE ?)|;
2577 push(@values, '%' . $self->{customernumber} . '%');
2579 $where = qq|(vc.name ILIKE ?)|;
2580 push(@values, '%' . $self->{$table} . '%');
2584 qq~SELECT vc.id, vc.name,
2585 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2587 WHERE $where AND (NOT vc.obsolete)
2591 qq~SELECT DISTINCT vc.id, vc.name,
2592 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2594 JOIN $table vc ON (a.${table}_id = vc.id)
2595 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2597 push(@values, '%' . $self->{$table} . '%');
2600 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2602 $main::lxdebug->leave_sub();
2604 return scalar(@{ $self->{name_list} });
2607 # the selection sub is used in the AR, AP, IS, IR and OE module
2610 $main::lxdebug->enter_sub();
2612 my ($self, $myconfig, $table, $module) = @_;
2615 my $dbh = $self->get_standard_dbh($myconfig);
2617 $table = $table eq "customer" ? "customer" : "vendor";
2619 my $query = qq|SELECT count(*) FROM $table|;
2620 my ($count) = selectrow_query($self, $dbh, $query);
2622 # build selection list
2623 if ($count < $myconfig->{vclimit}) {
2624 $query = qq|SELECT id, name, salesman_id
2625 FROM $table WHERE NOT obsolete
2627 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2631 $self->get_employee($dbh);
2633 # setup sales contacts
2634 $query = qq|SELECT e.id, e.name
2636 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2637 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2640 push(@{ $self->{all_employees} },
2641 { id => $self->{employee_id},
2642 name => $self->{employee} });
2644 # sort the whole thing
2645 @{ $self->{all_employees} } =
2646 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2648 if ($module eq 'AR') {
2650 # prepare query for departments
2651 $query = qq|SELECT id, description
2654 ORDER BY description|;
2657 $query = qq|SELECT id, description
2659 ORDER BY description|;
2662 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2665 $query = qq|SELECT id, description
2669 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2672 $query = qq|SELECT printer_description, id
2674 ORDER BY printer_description|;
2676 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2679 $query = qq|SELECT id, description
2683 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2685 $main::lxdebug->leave_sub();
2688 sub language_payment {
2689 $main::lxdebug->enter_sub();
2691 my ($self, $myconfig) = @_;
2693 my $dbh = $self->get_standard_dbh($myconfig);
2695 my $query = qq|SELECT id, description
2699 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2702 $query = qq|SELECT printer_description, id
2704 ORDER BY printer_description|;
2706 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2709 $query = qq|SELECT id, description
2713 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2715 # get buchungsgruppen
2716 $query = qq|SELECT id, description
2717 FROM buchungsgruppen|;
2719 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2721 $main::lxdebug->leave_sub();
2724 # this is only used for reports
2725 sub all_departments {
2726 $main::lxdebug->enter_sub();
2728 my ($self, $myconfig, $table) = @_;
2730 my $dbh = $self->get_standard_dbh($myconfig);
2733 if ($table eq 'customer') {
2734 $where = "WHERE role = 'P' ";
2737 my $query = qq|SELECT id, description
2740 ORDER BY description|;
2741 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2743 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2745 $main::lxdebug->leave_sub();
2749 $main::lxdebug->enter_sub();
2751 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2754 if ($table eq "customer") {
2763 $self->all_vc($myconfig, $table, $module);
2765 # get last customers or vendors
2766 my ($query, $sth, $ref);
2768 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2773 my $transdate = "current_date";
2774 if ($self->{transdate}) {
2775 $transdate = $dbh->quote($self->{transdate});
2778 # now get the account numbers
2779 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2780 FROM chart c, taxkeys tk
2781 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2782 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2785 $sth = $dbh->prepare($query);
2787 do_statement($self, $sth, $query, '%' . $module . '%');
2789 $self->{accounts} = "";
2790 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2792 foreach my $key (split(/:/, $ref->{link})) {
2793 if ($key =~ /\Q$module\E/) {
2795 # cross reference for keys
2796 $xkeyref{ $ref->{accno} } = $key;
2798 push @{ $self->{"${module}_links"}{$key} },
2799 { accno => $ref->{accno},
2800 description => $ref->{description},
2801 taxkey => $ref->{taxkey_id},
2802 tax_id => $ref->{tax_id} };
2804 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2810 # get taxkeys and description
2811 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2812 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2814 if (($module eq "AP") || ($module eq "AR")) {
2815 # get tax rates and description
2816 $query = qq|SELECT * FROM tax|;
2817 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2823 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2824 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2825 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2826 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2828 d.description AS department,
2831 JOIN $table c ON (a.${table}_id = c.id)
2832 LEFT JOIN employee e ON (e.id = a.employee_id)
2833 LEFT JOIN department d ON (d.id = a.department_id)
2835 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2837 foreach my $key (keys %$ref) {
2838 $self->{$key} = $ref->{$key};
2841 my $transdate = "current_date";
2842 if ($self->{transdate}) {
2843 $transdate = $dbh->quote($self->{transdate});
2846 # now get the account numbers
2847 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2849 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2851 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2852 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2855 $sth = $dbh->prepare($query);
2856 do_statement($self, $sth, $query, "%$module%");
2858 $self->{accounts} = "";
2859 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2861 foreach my $key (split(/:/, $ref->{link})) {
2862 if ($key =~ /\Q$module\E/) {
2864 # cross reference for keys
2865 $xkeyref{ $ref->{accno} } = $key;
2867 push @{ $self->{"${module}_links"}{$key} },
2868 { accno => $ref->{accno},
2869 description => $ref->{description},
2870 taxkey => $ref->{taxkey_id},
2871 tax_id => $ref->{tax_id} };
2873 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2879 # get amounts from individual entries
2882 c.accno, c.description,
2883 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2887 LEFT JOIN chart c ON (c.id = a.chart_id)
2888 LEFT JOIN project p ON (p.id = a.project_id)
2889 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2890 WHERE (tk.taxkey_id=a.taxkey) AND
2891 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2892 THEN tk.chart_id = a.chart_id
2895 OR (c.link='%tax%')) AND
2896 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2897 WHERE a.trans_id = ?
2898 AND a.fx_transaction = '0'
2899 ORDER BY a.acc_trans_id, a.transdate|;
2900 $sth = $dbh->prepare($query);
2901 do_statement($self, $sth, $query, $self->{id});
2903 # get exchangerate for currency
2904 $self->{exchangerate} =
2905 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2908 # store amounts in {acc_trans}{$key} for multiple accounts
2909 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2910 $ref->{exchangerate} =
2911 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2912 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2915 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2916 $ref->{amount} *= -1;
2918 $ref->{index} = $index;
2920 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2926 d.curr AS currencies, d.closedto, d.revtrans,
2927 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2928 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2930 $ref = selectfirst_hashref_query($self, $dbh, $query);
2931 map { $self->{$_} = $ref->{$_} } keys %$ref;
2938 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2939 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2940 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2942 $ref = selectfirst_hashref_query($self, $dbh, $query);
2943 map { $self->{$_} = $ref->{$_} } keys %$ref;
2945 if ($self->{"$self->{vc}_id"}) {
2947 # only setup currency
2948 ($self->{currency}) = split(/:/, $self->{currencies});
2952 $self->lastname_used($dbh, $myconfig, $table, $module);
2954 # get exchangerate for currency
2955 $self->{exchangerate} =
2956 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2962 $main::lxdebug->leave_sub();
2966 $main::lxdebug->enter_sub();
2968 my ($self, $dbh, $myconfig, $table, $module) = @_;
2972 $table = $table eq "customer" ? "customer" : "vendor";
2973 my %column_map = ("a.curr" => "currency",
2974 "a.${table}_id" => "${table}_id",
2975 "a.department_id" => "department_id",
2976 "d.description" => "department",
2977 "ct.name" => $table,
2978 "current_date + ct.terms" => "duedate",
2981 if ($self->{type} =~ /delivery_order/) {
2982 $arap = 'delivery_orders';
2983 delete $column_map{"a.curr"};
2985 } elsif ($self->{type} =~ /_order/) {
2987 $where = "quotation = '0'";
2989 } elsif ($self->{type} =~ /_quotation/) {
2991 $where = "quotation = '1'";
2993 } elsif ($table eq 'customer') {
3001 $where = "($where) AND" if ($where);
3002 my $query = qq|SELECT MAX(id) FROM $arap
3003 WHERE $where ${table}_id > 0|;
3004 my ($trans_id) = selectrow_query($self, $dbh, $query);
3007 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
3008 $query = qq|SELECT $column_spec
3010 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
3011 LEFT JOIN department d ON (a.department_id = d.id)
3013 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3015 map { $self->{$_} = $ref->{$_} } values %column_map;
3017 $main::lxdebug->leave_sub();
3021 $main::lxdebug->enter_sub();
3023 my ($self, $myconfig, $thisdate, $days) = @_;
3025 my $dbh = $self->get_standard_dbh($myconfig);
3030 my $dateformat = $myconfig->{dateformat};
3031 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3032 $thisdate = $dbh->quote($thisdate);
3033 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3035 $query = qq|SELECT current_date AS thisdate|;
3038 ($thisdate) = selectrow_query($self, $dbh, $query);
3040 $main::lxdebug->leave_sub();
3046 $main::lxdebug->enter_sub();
3048 my ($self, $string) = @_;
3050 if ($string !~ /%/) {
3051 $string = "%$string%";
3054 $string =~ s/\'/\'\'/g;
3056 $main::lxdebug->leave_sub();
3062 $main::lxdebug->enter_sub();
3064 my ($self, $flds, $new, $count, $numrows) = @_;
3068 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3073 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3075 my $j = $item->{ndx} - 1;
3076 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3080 for $i ($count + 1 .. $numrows) {
3081 map { delete $self->{"${_}_$i"} } @{$flds};
3084 $main::lxdebug->leave_sub();
3088 $main::lxdebug->enter_sub();
3090 my ($self, $myconfig) = @_;
3094 my $dbh = $self->dbconnect_noauto($myconfig);
3096 my $query = qq|DELETE FROM status
3097 WHERE (formname = ?) AND (trans_id = ?)|;
3098 my $sth = prepare_query($self, $dbh, $query);
3100 if ($self->{formname} =~ /(check|receipt)/) {
3101 for $i (1 .. $self->{rowcount}) {
3102 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3105 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3109 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3110 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3112 my %queued = split / /, $self->{queued};
3115 if ($self->{formname} =~ /(check|receipt)/) {
3117 # this is a check or receipt, add one entry for each lineitem
3118 my ($accno) = split /--/, $self->{account};
3119 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3120 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3121 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3122 $sth = prepare_query($self, $dbh, $query);
3124 for $i (1 .. $self->{rowcount}) {
3125 if ($self->{"checked_$i"}) {
3126 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3132 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3133 VALUES (?, ?, ?, ?, ?)|;
3134 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3135 $queued{$self->{formname}}, $self->{formname});
3141 $main::lxdebug->leave_sub();
3145 $main::lxdebug->enter_sub();
3147 my ($self, $dbh) = @_;
3149 my ($query, $printed, $emailed);
3151 my $formnames = $self->{printed};
3152 my $emailforms = $self->{emailed};
3154 $query = qq|DELETE FROM status
3155 WHERE (formname = ?) AND (trans_id = ?)|;
3156 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3158 # this only applies to the forms
3159 # checks and receipts are posted when printed or queued
3161 if ($self->{queued}) {
3162 my %queued = split / /, $self->{queued};
3164 foreach my $formname (keys %queued) {
3165 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3166 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3168 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3169 VALUES (?, ?, ?, ?, ?)|;
3170 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3172 $formnames =~ s/\Q$self->{formname}\E//;
3173 $emailforms =~ s/\Q$self->{formname}\E//;
3178 # save printed, emailed info
3179 $formnames =~ s/^ +//g;
3180 $emailforms =~ s/^ +//g;
3183 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3184 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3186 foreach my $formname (keys %status) {
3187 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3188 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3190 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3191 VALUES (?, ?, ?, ?)|;
3192 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3195 $main::lxdebug->leave_sub();
3199 # $main::locale->text('SAVED')
3200 # $main::locale->text('DELETED')
3201 # $main::locale->text('ADDED')
3202 # $main::locale->text('PAYMENT POSTED')
3203 # $main::locale->text('POSTED')
3204 # $main::locale->text('POSTED AS NEW')
3205 # $main::locale->text('ELSE')
3206 # $main::locale->text('SAVED FOR DUNNING')
3207 # $main::locale->text('DUNNING STARTED')
3208 # $main::locale->text('PRINTED')
3209 # $main::locale->text('MAILED')
3210 # $main::locale->text('SCREENED')
3211 # $main::locale->text('CANCELED')
3212 # $main::locale->text('invoice')
3213 # $main::locale->text('proforma')
3214 # $main::locale->text('sales_order')
3215 # $main::locale->text('packing_list')
3216 # $main::locale->text('pick_list')
3217 # $main::locale->text('purchase_order')
3218 # $main::locale->text('bin_list')
3219 # $main::locale->text('sales_quotation')
3220 # $main::locale->text('request_quotation')
3223 $main::lxdebug->enter_sub();
3228 if(!exists $self->{employee_id}) {
3229 &get_employee($self, $dbh);
3233 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3234 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3235 my @values = (conv_i($self->{id}), $self->{login},
3236 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3237 do_query($self, $dbh, $query, @values);
3239 $main::lxdebug->leave_sub();
3243 $main::lxdebug->enter_sub();
3245 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3246 my ($orderBy, $desc) = split(/\-\-/, $order);
3247 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3250 if ($trans_id ne "") {
3252 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 | .
3253 qq|FROM history_erp h | .
3254 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3255 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3258 my $sth = $dbh->prepare($query) || $self->dberror($query);
3260 $sth->execute() || $self->dberror("$query");
3262 while(my $hash_ref = $sth->fetchrow_hashref()) {
3263 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3264 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3265 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3266 $tempArray[$i++] = $hash_ref;
3268 $main::lxdebug->leave_sub() and return \@tempArray
3269 if ($i > 0 && $tempArray[0] ne "");
3271 $main::lxdebug->leave_sub();
3275 sub update_defaults {
3276 $main::lxdebug->enter_sub();
3278 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3281 if ($provided_dbh) {
3282 $dbh = $provided_dbh;
3284 $dbh = $self->dbconnect_noauto($myconfig);
3286 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3287 my $sth = $dbh->prepare($query);
3289 $sth->execute || $self->dberror($query);
3290 my ($var) = $sth->fetchrow_array;
3293 if ($var =~ m/\d+$/) {
3294 my $new_var = (substr $var, $-[0]) * 1 + 1;
3295 my $len_diff = length($var) - $-[0] - length($new_var);
3296 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3302 $query = qq|UPDATE defaults SET $fld = ?|;
3303 do_query($self, $dbh, $query, $var);
3305 if (!$provided_dbh) {
3310 $main::lxdebug->leave_sub();
3315 =item update_business
3318 \%config, - config hashref
3319 $business_id, - business id
3320 $dbh - optional database handle
3322 handles business (thats customer/vendor types) sequences.
3324 special behaviour for empty strings in customerinitnumber field:
3325 will in this case not increase the value, and return undef.
3328 sub update_business {
3329 $main::lxdebug->enter_sub();
3331 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3334 if ($provided_dbh) {
3335 $dbh = $provided_dbh;
3337 $dbh = $self->dbconnect_noauto($myconfig);
3340 qq|SELECT customernumberinit FROM business
3341 WHERE id = ? FOR UPDATE|;
3342 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3344 return undef unless $var;
3346 if ($var =~ m/\d+$/) {
3347 my $new_var = (substr $var, $-[0]) * 1 + 1;
3348 my $len_diff = length($var) - $-[0] - length($new_var);
3349 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3355 $query = qq|UPDATE business
3356 SET customernumberinit = ?
3358 do_query($self, $dbh, $query, $var, $business_id);
3360 if (!$provided_dbh) {
3365 $main::lxdebug->leave_sub();
3370 sub get_partsgroup {
3371 $main::lxdebug->enter_sub();
3373 my ($self, $myconfig, $p) = @_;
3374 my $target = $p->{target} || 'all_partsgroup';
3376 my $dbh = $self->get_standard_dbh($myconfig);
3378 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3380 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3383 if ($p->{searchitems} eq 'part') {
3384 $query .= qq|WHERE p.inventory_accno_id > 0|;
3386 if ($p->{searchitems} eq 'service') {
3387 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3389 if ($p->{searchitems} eq 'assembly') {
3390 $query .= qq|WHERE p.assembly = '1'|;
3392 if ($p->{searchitems} eq 'labor') {
3393 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3396 $query .= qq|ORDER BY partsgroup|;
3399 $query = qq|SELECT id, partsgroup FROM partsgroup
3400 ORDER BY partsgroup|;
3403 if ($p->{language_code}) {
3404 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3405 t.description AS translation
3407 JOIN parts p ON (p.partsgroup_id = pg.id)
3408 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3409 ORDER BY translation|;
3410 @values = ($p->{language_code});
3413 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3415 $main::lxdebug->leave_sub();
3418 sub get_pricegroup {
3419 $main::lxdebug->enter_sub();
3421 my ($self, $myconfig, $p) = @_;
3423 my $dbh = $self->get_standard_dbh($myconfig);
3425 my $query = qq|SELECT p.id, p.pricegroup
3428 $query .= qq| ORDER BY pricegroup|;
3431 $query = qq|SELECT id, pricegroup FROM pricegroup
3432 ORDER BY pricegroup|;
3435 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3437 $main::lxdebug->leave_sub();
3441 # usage $form->all_years($myconfig, [$dbh])
3442 # return list of all years where bookings found
3445 $main::lxdebug->enter_sub();
3447 my ($self, $myconfig, $dbh) = @_;
3449 $dbh ||= $self->get_standard_dbh($myconfig);
3452 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3453 (SELECT MAX(transdate) FROM acc_trans)|;
3454 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3456 if ($myconfig->{dateformat} =~ /^yy/) {
3457 ($startdate) = split /\W/, $startdate;
3458 ($enddate) = split /\W/, $enddate;
3460 (@_) = split /\W/, $startdate;
3462 (@_) = split /\W/, $enddate;
3467 $startdate = substr($startdate,0,4);
3468 $enddate = substr($enddate,0,4);
3470 while ($enddate >= $startdate) {
3471 push @all_years, $enddate--;
3476 $main::lxdebug->leave_sub();
3480 $main::lxdebug->enter_sub();
3484 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3486 $main::lxdebug->leave_sub();
3490 $main::lxdebug->enter_sub();
3495 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3497 $main::lxdebug->leave_sub();