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);
615 my %cgi_params = ('-type' => $params{content_type});
616 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
618 my $output = $cgi->header('-cookie' => $session_cookie,
621 $main::lxdebug->leave_sub();
628 $main::lxdebug->enter_sub();
630 my ($self, $extra_code) = @_;
632 if ($self->{header}) {
633 $main::lxdebug->leave_sub();
637 my ($stylesheet, $favicon, $pagelayout);
639 if ($ENV{HTTP_USER_AGENT}) {
642 if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
643 # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
644 $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
647 my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
649 $stylesheets =~ s|^\s*||;
650 $stylesheets =~ s|\s*$||;
651 foreach my $file (split m/\s+/, $stylesheets) {
653 next if (! -f "css/$file");
655 $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
658 $self->{favicon} = "favicon.ico" unless $self->{favicon};
660 if ($self->{favicon} && (-f "$self->{favicon}")) {
662 qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
666 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
668 if ($self->{landscape}) {
669 $pagelayout = qq|<style type="text/css">
670 \@page { size:landscape; }
674 my $fokus = qq| document.$self->{fokus}.focus();| if ($self->{"fokus"});
678 if ($self->{jsscript} == 1) {
681 <script type="text/javascript" src="js/common.js"></script>
682 <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
683 <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
684 <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
685 <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
692 ? "$self->{title} - $self->{titlebar}"
695 foreach my $item (@ { $self->{AJAX} }) {
696 $ajax .= $item->show_javascript();
699 print $self->create_http_response('content_type' => 'text/html',
700 'charset' => $db_charset,);
701 print qq|${doctype}<html>
703 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
704 <title>$self->{titlebar}</title>
711 <script type="text/javascript">
719 <meta name="robots" content="noindex,nofollow" />
720 <script type="text/javascript" src="js/highlight_input.js"></script>
722 <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
723 <script type="text/javascript" src="js/tabcontent.js">
725 /***********************************************
726 * Tab Content script v2.2- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
727 * This notice MUST stay intact for legal use
728 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
729 ***********************************************/
740 $main::lxdebug->leave_sub();
743 sub ajax_response_header {
744 $main::lxdebug->enter_sub();
748 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
749 my $cgi = $main::cgi || CGI->new('');
750 my $output = $cgi->header('-charset' => $db_charset);
752 $main::lxdebug->leave_sub();
757 sub _prepare_html_template {
758 $main::lxdebug->enter_sub();
760 my ($self, $file, $additional_params) = @_;
763 if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
764 $language = $main::language;
766 $language = $main::myconfig{"countrycode"};
768 $language = "de" unless ($language);
770 if (-f "templates/webpages/${file}_${language}.html") {
771 if ((-f ".developer") &&
772 (-f "templates/webpages/${file}_master.html") &&
773 ((stat("templates/webpages/${file}_master.html"))[9] >
774 (stat("templates/webpages/${file}_${language}.html"))[9])) {
775 my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
776 "Please re-run 'locales.pl' in 'locale/${language}'.";
777 print(qq|<pre>$info</pre>|);
781 $file = "templates/webpages/${file}_${language}.html";
782 } elsif (-f "templates/webpages/${file}.html") {
783 $file = "templates/webpages/${file}.html";
785 my $info = "Web page template '${file}' not found.\n" .
786 "Please re-run 'locales.pl' in 'locale/${language}'.";
787 print(qq|<pre>$info</pre>|);
791 if ($self->{"DEBUG"}) {
792 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
795 if ($additional_params->{"DEBUG"}) {
796 $additional_params->{"DEBUG"} =
797 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
800 if (%main::myconfig) {
801 map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
802 my $jsc_dateformat = $main::myconfig{"dateformat"};
803 $jsc_dateformat =~ s/d+/\%d/gi;
804 $jsc_dateformat =~ s/m+/\%m/gi;
805 $jsc_dateformat =~ s/y+/\%Y/gi;
806 $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
809 $additional_params->{"conf_dbcharset"} = $main::dbcharset;
810 $additional_params->{"conf_webdav"} = $main::webdav;
811 $additional_params->{"conf_lizenzen"} = $main::lizenzen;
812 $additional_params->{"conf_latex_templates"} = $main::latex;
813 $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
815 if (%main::debug_options) {
816 map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
819 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
820 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
821 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
825 $main::lxdebug->leave_sub();
830 sub parse_html_template {
831 $main::lxdebug->enter_sub();
833 my ($self, $file, $additional_params) = @_;
835 $additional_params ||= { };
837 $file = $self->_prepare_html_template($file, $additional_params);
839 my $template = Template->new({ 'INTERPOLATE' => 0,
843 'PLUGIN_BASE' => 'SL::Template::Plugin',
844 'INCLUDE_PATH' => '.:templates/webpages',
847 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
849 my $in = IO::File->new($file, 'r');
852 print STDERR "Error opening template file: $!";
853 $main::lxdebug->leave_sub();
857 my $input = join('', <$in>);
861 $input = $main::locale->{iconv}->convert($input);
865 if (!$template->process(\$input, $additional_params, \$output)) {
866 print STDERR $template->error();
869 $main::lxdebug->leave_sub();
874 sub show_generic_error {
875 $main::lxdebug->enter_sub();
877 my ($self, $error, %params) = @_;
880 'title_error' => $params{title},
881 'label_error' => $error,
884 if ($params{action}) {
887 map { delete($self->{$_}); } qw(action);
888 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
890 $add_params->{SHOW_BUTTON} = 1;
891 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
892 $add_params->{VARIABLES} = \@vars;
894 } elsif ($params{back_button}) {
895 $add_params->{SHOW_BACK_BUTTON} = 1;
898 $self->{title} = $params{title} if $params{title};
901 print $self->parse_html_template("generic/error", $add_params);
903 $main::lxdebug->leave_sub();
905 die("Error: $error\n");
908 sub show_generic_information {
909 $main::lxdebug->enter_sub();
911 my ($self, $text, $title) = @_;
914 'title_information' => $title,
915 'label_information' => $text,
918 $self->{title} = $title if ($title);
921 print $self->parse_html_template("generic/information", $add_params);
923 $main::lxdebug->leave_sub();
925 die("Information: $text\n");
928 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
929 # changed it to accept an arbitrary number of triggers - sschoeling
931 $main::lxdebug->enter_sub();
934 my $myconfig = shift;
937 # set dateform for jsscript
940 "dd.mm.yy" => "%d.%m.%Y",
941 "dd-mm-yy" => "%d-%m-%Y",
942 "dd/mm/yy" => "%d/%m/%Y",
943 "mm/dd/yy" => "%m/%d/%Y",
944 "mm-dd-yy" => "%m-%d-%Y",
945 "yyyy-mm-dd" => "%Y-%m-%d",
948 my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
949 $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
956 inputField : "| . (shift) . qq|",
957 ifFormat :"$ifFormat",
958 align : "| . (shift) . qq|",
959 button : "| . (shift) . qq|"
965 <script type="text/javascript">
966 <!--| . join("", @triggers) . qq|//-->
970 $main::lxdebug->leave_sub();
973 } #end sub write_trigger
976 $main::lxdebug->enter_sub();
978 my ($self, $msg) = @_;
980 if ($self->{callback}) {
982 my ($script, $argv) = split(/\?/, $self->{callback}, 2);
984 $script =~ s|[^a-zA-Z0-9_\.]||g;
985 exec("perl", "$script", $argv);
993 $main::lxdebug->leave_sub();
996 # sort of columns removed - empty sub
998 $main::lxdebug->enter_sub();
1000 my ($self, @columns) = @_;
1002 $main::lxdebug->leave_sub();
1008 $main::lxdebug->enter_sub(2);
1010 my ($self, $myconfig, $amount, $places, $dash) = @_;
1012 if ($amount eq "") {
1016 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
1018 my $neg = ($amount =~ s/^-//);
1019 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
1021 if (defined($places) && ($places ne '')) {
1027 my ($actual_places) = ($amount =~ /\.(\d+)/);
1028 $actual_places = length($actual_places);
1029 $places = $actual_places > $places ? $actual_places : $places;
1032 $amount = $self->round_amount($amount, $places);
1035 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
1036 my @p = split(/\./, $amount); # split amount at decimal point
1038 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
1041 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
1044 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
1045 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1046 ($neg ? "-$amount" : "$amount" ) ;
1050 $main::lxdebug->leave_sub(2);
1054 sub format_amount_units {
1055 $main::lxdebug->enter_sub();
1060 my $myconfig = \%main::myconfig;
1061 my $amount = $params{amount} * 1;
1062 my $places = $params{places};
1063 my $part_unit_name = $params{part_unit};
1064 my $amount_unit_name = $params{amount_unit};
1065 my $conv_units = $params{conv_units};
1066 my $max_places = $params{max_places};
1068 if (!$part_unit_name) {
1069 $main::lxdebug->leave_sub();
1073 AM->retrieve_all_units();
1074 my $all_units = $main::all_units;
1076 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1077 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1080 if (!scalar @{ $conv_units }) {
1081 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1082 $main::lxdebug->leave_sub();
1086 my $part_unit = $all_units->{$part_unit_name};
1087 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1089 $amount *= $conv_unit->{factor};
1094 foreach my $unit (@$conv_units) {
1095 my $last = $unit->{name} eq $part_unit->{name};
1097 $num = int($amount / $unit->{factor});
1098 $amount -= $num * $unit->{factor};
1101 if ($last ? $amount : $num) {
1102 push @values, { "unit" => $unit->{name},
1103 "amount" => $last ? $amount / $unit->{factor} : $num,
1104 "places" => $last ? $places : 0 };
1111 push @values, { "unit" => $part_unit_name,
1116 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1118 $main::lxdebug->leave_sub();
1124 $main::lxdebug->enter_sub(2);
1129 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1130 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1131 $input =~ s/\#\#/\#/g;
1133 $main::lxdebug->leave_sub(2);
1141 $main::lxdebug->enter_sub(2);
1143 my ($self, $myconfig, $amount) = @_;
1145 if ( ($myconfig->{numberformat} eq '1.000,00')
1146 || ($myconfig->{numberformat} eq '1000,00')) {
1151 if ($myconfig->{numberformat} eq "1'000.00") {
1157 $main::lxdebug->leave_sub(2);
1159 return ($amount * 1);
1163 $main::lxdebug->enter_sub(2);
1165 my ($self, $amount, $places) = @_;
1168 # Rounding like "Kaufmannsrunden"
1169 # Descr. http://de.wikipedia.org/wiki/Rundung
1171 # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
1174 $amount = $amount * (10**($places));
1175 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1177 $main::lxdebug->leave_sub(2);
1179 return $round_amount;
1183 sub parse_template {
1184 $main::lxdebug->enter_sub();
1186 my ($self, $myconfig, $userspath) = @_;
1187 my ($template, $out);
1191 $self->{"cwd"} = getcwd();
1192 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1196 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1197 $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1198 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
1200 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1201 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1202 $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1203 $ext_for_format = 'pdf';
1205 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1206 $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1207 $ext_for_format = 'html';
1209 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1210 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1211 $ext_for_format = 'xml';
1213 } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1214 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1216 } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1217 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1219 } elsif ( defined $self->{'format'}) {
1220 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1222 } elsif ( $self->{'format'} eq '' ) {
1223 $self->error("No Outputformat given: $self->{'format'}");
1225 } else { #Catch the rest
1226 $self->error("Outputformat not defined: $self->{'format'}");
1229 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1230 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1232 if (!$self->{employee_id}) {
1233 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1236 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1238 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1240 # OUT is used for the media, screen, printer, email
1241 # for postscript we store a copy in a temporary file
1243 my $prepend_userspath;
1245 if (!$self->{tmpfile}) {
1246 $self->{tmpfile} = "${fileid}.$self->{IN}";
1247 $prepend_userspath = 1;
1250 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1252 $self->{tmpfile} =~ s|.*/||;
1253 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1254 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1256 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1257 $out = $self->{OUT};
1258 $self->{OUT} = ">$self->{tmpfile}";
1262 open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1264 open(OUT, ">-") or $self->error("STDOUT : $!");
1268 if (!$template->parse(*OUT)) {
1270 $self->error("$self->{IN} : " . $template->get_error());
1275 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1277 if ($self->{media} eq 'email') {
1279 my $mail = new Mailer;
1281 map { $mail->{$_} = $self->{$_} }
1282 qw(cc bcc subject message version format);
1283 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1284 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1285 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1286 $mail->{fileid} = "$fileid.";
1287 $myconfig->{signature} =~ s/\r//g;
1289 # if we send html or plain text inline
1290 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1291 $mail->{contenttype} = "text/html";
1293 $mail->{message} =~ s/\r//g;
1294 $mail->{message} =~ s/\n/<br>\n/g;
1295 $myconfig->{signature} =~ s/\n/<br>\n/g;
1296 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1298 open(IN, $self->{tmpfile})
1299 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1301 $mail->{message} .= $_;
1308 if (!$self->{"do_not_attach"}) {
1309 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1310 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1311 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1312 "name" => $attachment_name }];
1315 $mail->{message} =~ s/\r//g;
1316 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1320 my $err = $mail->send();
1321 $self->error($self->cleanup . "$err") if ($err);
1325 $self->{OUT} = $out;
1327 my $numbytes = (-s $self->{tmpfile});
1328 open(IN, $self->{tmpfile})
1329 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1331 $self->{copies} = 1 unless $self->{media} eq 'printer';
1333 chdir("$self->{cwd}");
1334 #print(STDERR "Kopien $self->{copies}\n");
1335 #print(STDERR "OUT $self->{OUT}\n");
1336 for my $i (1 .. $self->{copies}) {
1338 open(OUT, $self->{OUT})
1339 or $self->error($self->cleanup . "$self->{OUT} : $!");
1341 $self->{attachment_filename} = ($self->{attachment_filename})
1342 ? $self->{attachment_filename}
1343 : $self->generate_attachment_filename();
1345 # launch application
1346 print qq|Content-Type: | . $template->get_mime_type() . qq|
1347 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1348 Content-Length: $numbytes
1352 open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1372 chdir("$self->{cwd}");
1373 $main::lxdebug->leave_sub();
1376 sub get_formname_translation {
1377 $main::lxdebug->enter_sub();
1378 my ($self, $formname) = @_;
1380 $formname ||= $self->{formname};
1382 my %formname_translations = (
1383 bin_list => $main::locale->text('Bin List'),
1384 credit_note => $main::locale->text('Credit Note'),
1385 invoice => $main::locale->text('Invoice'),
1386 packing_list => $main::locale->text('Packing List'),
1387 pick_list => $main::locale->text('Pick List'),
1388 proforma => $main::locale->text('Proforma Invoice'),
1389 purchase_order => $main::locale->text('Purchase Order'),
1390 request_quotation => $main::locale->text('RFQ'),
1391 sales_order => $main::locale->text('Confirmation'),
1392 sales_quotation => $main::locale->text('Quotation'),
1393 storno_invoice => $main::locale->text('Storno Invoice'),
1394 storno_packing_list => $main::locale->text('Storno Packing List'),
1395 sales_delivery_order => $main::locale->text('Delivery Order'),
1396 purchase_delivery_order => $main::locale->text('Delivery Order'),
1399 $main::lxdebug->leave_sub();
1400 return $formname_translations{$formname}
1403 sub get_number_prefix_for_type {
1404 $main::lxdebug->enter_sub();
1408 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1409 : ($self->{type} =~ /_quotation$/) ? 'quo'
1410 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1413 $main::lxdebug->leave_sub();
1417 sub get_extension_for_format {
1418 $main::lxdebug->enter_sub();
1421 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1422 : $self->{format} =~ /postscript/i ? ".ps"
1423 : $self->{format} =~ /opendocument/i ? ".odt"
1424 : $self->{format} =~ /html/i ? ".html"
1427 $main::lxdebug->leave_sub();
1431 sub generate_attachment_filename {
1432 $main::lxdebug->enter_sub();
1435 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1436 my $prefix = $self->get_number_prefix_for_type();
1438 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1439 $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1441 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1442 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1445 $attachment_filename = "";
1448 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1449 $attachment_filename =~ s|[\s/\\]+|_|g;
1451 $main::lxdebug->leave_sub();
1452 return $attachment_filename;
1455 sub generate_email_subject {
1456 $main::lxdebug->enter_sub();
1459 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1460 my $prefix = $self->get_number_prefix_for_type();
1462 if ($subject && $self->{"${prefix}number"}) {
1463 $subject .= " " . $self->{"${prefix}number"}
1466 $main::lxdebug->leave_sub();
1471 $main::lxdebug->enter_sub();
1475 chdir("$self->{tmpdir}");
1478 if (-f "$self->{tmpfile}.err") {
1479 open(FH, "$self->{tmpfile}.err");
1484 if ($self->{tmpfile}) {
1485 $self->{tmpfile} =~ s|.*/||g;
1487 $self->{tmpfile} =~ s/\.\w+$//g;
1488 my $tmpfile = $self->{tmpfile};
1489 unlink(<$tmpfile.*>);
1492 chdir("$self->{cwd}");
1494 $main::lxdebug->leave_sub();
1500 $main::lxdebug->enter_sub();
1502 my ($self, $date, $myconfig) = @_;
1505 if ($date && $date =~ /\D/) {
1507 if ($myconfig->{dateformat} =~ /^yy/) {
1508 ($yy, $mm, $dd) = split /\D/, $date;
1510 if ($myconfig->{dateformat} =~ /^mm/) {
1511 ($mm, $dd, $yy) = split /\D/, $date;
1513 if ($myconfig->{dateformat} =~ /^dd/) {
1514 ($dd, $mm, $yy) = split /\D/, $date;
1519 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1520 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1522 $dd = "0$dd" if ($dd < 10);
1523 $mm = "0$mm" if ($mm < 10);
1525 $date = "$yy$mm$dd";
1528 $main::lxdebug->leave_sub();
1533 # Database routines used throughout
1536 $main::lxdebug->enter_sub(2);
1538 my ($self, $myconfig) = @_;
1540 # connect to database
1542 DBI->connect($myconfig->{dbconnect},
1543 $myconfig->{dbuser}, $myconfig->{dbpasswd})
1547 if ($myconfig->{dboptions}) {
1548 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1551 $main::lxdebug->leave_sub(2);
1556 sub dbconnect_noauto {
1557 $main::lxdebug->enter_sub();
1559 my ($self, $myconfig) = @_;
1561 # connect to database
1563 DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1564 $myconfig->{dbpasswd}, { AutoCommit => 0 })
1568 if ($myconfig->{dboptions}) {
1569 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1572 $main::lxdebug->leave_sub();
1577 sub get_standard_dbh {
1578 $main::lxdebug->enter_sub(2);
1580 my ($self, $myconfig) = @_;
1582 if ($standard_dbh && !$standard_dbh->{Active}) {
1583 $main::lxdebug->message(LXDebug::INFO, "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1584 undef $standard_dbh;
1587 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1589 $main::lxdebug->leave_sub(2);
1591 return $standard_dbh;
1595 $main::lxdebug->enter_sub();
1597 my ($self, $date, $myconfig) = @_;
1598 my $dbh = $self->dbconnect($myconfig);
1600 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1601 my $sth = prepare_execute_query($self, $dbh, $query, $date);
1602 my ($closed) = $sth->fetchrow_array;
1604 $main::lxdebug->leave_sub();
1609 sub update_balance {
1610 $main::lxdebug->enter_sub();
1612 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1614 # if we have a value, go do it
1617 # retrieve balance from table
1618 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1619 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1620 my ($balance) = $sth->fetchrow_array;
1626 $query = "UPDATE $table SET $field = $balance WHERE $where";
1627 do_query($self, $dbh, $query, @values);
1629 $main::lxdebug->leave_sub();
1632 sub update_exchangerate {
1633 $main::lxdebug->enter_sub();
1635 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1637 # some sanity check for currency
1639 $main::lxdebug->leave_sub();
1642 $query = qq|SELECT curr FROM defaults|;
1644 my ($currency) = selectrow_query($self, $dbh, $query);
1645 my ($defaultcurrency) = split m/:/, $currency;
1648 if ($curr eq $defaultcurrency) {
1649 $main::lxdebug->leave_sub();
1653 $query = qq|SELECT e.curr FROM exchangerate e
1654 WHERE e.curr = ? AND e.transdate = ?
1656 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1665 $buy = conv_i($buy, "NULL");
1666 $sell = conv_i($sell, "NULL");
1669 if ($buy != 0 && $sell != 0) {
1670 $set = "buy = $buy, sell = $sell";
1671 } elsif ($buy != 0) {
1672 $set = "buy = $buy";
1673 } elsif ($sell != 0) {
1674 $set = "sell = $sell";
1677 if ($sth->fetchrow_array) {
1678 $query = qq|UPDATE exchangerate
1684 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1685 VALUES (?, $buy, $sell, ?)|;
1688 do_query($self, $dbh, $query, $curr, $transdate);
1690 $main::lxdebug->leave_sub();
1693 sub save_exchangerate {
1694 $main::lxdebug->enter_sub();
1696 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1698 my $dbh = $self->dbconnect($myconfig);
1702 $buy = $rate if $fld eq 'buy';
1703 $sell = $rate if $fld eq 'sell';
1706 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1711 $main::lxdebug->leave_sub();
1714 sub get_exchangerate {
1715 $main::lxdebug->enter_sub();
1717 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1720 unless ($transdate) {
1721 $main::lxdebug->leave_sub();
1725 $query = qq|SELECT curr FROM defaults|;
1727 my ($currency) = selectrow_query($self, $dbh, $query);
1728 my ($defaultcurrency) = split m/:/, $currency;
1730 if ($currency eq $defaultcurrency) {
1731 $main::lxdebug->leave_sub();
1735 $query = qq|SELECT e.$fld FROM exchangerate e
1736 WHERE e.curr = ? AND e.transdate = ?|;
1737 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1741 $main::lxdebug->leave_sub();
1743 return $exchangerate;
1746 sub check_exchangerate {
1747 $main::lxdebug->enter_sub();
1749 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1751 if ($fld !~/^buy|sell$/) {
1752 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1755 unless ($transdate) {
1756 $main::lxdebug->leave_sub();
1760 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1762 if ($currency eq $defaultcurrency) {
1763 $main::lxdebug->leave_sub();
1767 my $dbh = $self->get_standard_dbh($myconfig);
1768 my $query = qq|SELECT e.$fld FROM exchangerate e
1769 WHERE e.curr = ? AND e.transdate = ?|;
1771 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1773 $main::lxdebug->leave_sub();
1775 return $exchangerate;
1778 sub get_default_currency {
1779 $main::lxdebug->enter_sub();
1781 my ($self, $myconfig) = @_;
1782 my $dbh = $self->get_standard_dbh($myconfig);
1784 my $query = qq|SELECT curr FROM defaults|;
1786 my ($curr) = selectrow_query($self, $dbh, $query);
1787 my ($defaultcurrency) = split m/:/, $curr;
1789 $main::lxdebug->leave_sub();
1791 return $defaultcurrency;
1795 sub set_payment_options {
1796 $main::lxdebug->enter_sub();
1798 my ($self, $myconfig, $transdate) = @_;
1800 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1802 my $dbh = $self->get_standard_dbh($myconfig);
1805 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1806 qq|FROM payment_terms p | .
1809 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1810 $self->{payment_terms}) =
1811 selectrow_query($self, $dbh, $query, $self->{payment_id});
1813 if ($transdate eq "") {
1814 if ($self->{invdate}) {
1815 $transdate = $self->{invdate};
1817 $transdate = $self->{transdate};
1822 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1823 qq|FROM payment_terms|;
1824 ($self->{netto_date}, $self->{skonto_date}) =
1825 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1827 my ($invtotal, $total);
1828 my (%amounts, %formatted_amounts);
1830 if ($self->{type} =~ /_order$/) {
1831 $amounts{invtotal} = $self->{ordtotal};
1832 $amounts{total} = $self->{ordtotal};
1834 } elsif ($self->{type} =~ /_quotation$/) {
1835 $amounts{invtotal} = $self->{quototal};
1836 $amounts{total} = $self->{quototal};
1839 $amounts{invtotal} = $self->{invtotal};
1840 $amounts{total} = $self->{total};
1843 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1845 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1846 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1847 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1849 foreach (keys %amounts) {
1850 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1851 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1854 if ($self->{"language_id"}) {
1856 qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1857 qq|FROM translation_payment_terms t | .
1858 qq|LEFT JOIN language l ON t.language_id = l.id | .
1859 qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1860 my ($description_long, $output_numberformat, $output_dateformat,
1861 $output_longdates) =
1862 selectrow_query($self, $dbh, $query,
1863 $self->{"language_id"}, $self->{"payment_id"});
1865 $self->{payment_terms} = $description_long if ($description_long);
1867 if ($output_dateformat) {
1868 foreach my $key (qw(netto_date skonto_date)) {
1870 $main::locale->reformat_date($myconfig, $self->{$key},
1876 if ($output_numberformat &&
1877 ($output_numberformat ne $myconfig->{"numberformat"})) {
1878 my $saved_numberformat = $myconfig->{"numberformat"};
1879 $myconfig->{"numberformat"} = $output_numberformat;
1880 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1881 $myconfig->{"numberformat"} = $saved_numberformat;
1885 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1886 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1887 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1888 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1889 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1890 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1891 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1893 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1895 $main::lxdebug->leave_sub();
1899 sub get_template_language {
1900 $main::lxdebug->enter_sub();
1902 my ($self, $myconfig) = @_;
1904 my $template_code = "";
1906 if ($self->{language_id}) {
1907 my $dbh = $self->get_standard_dbh($myconfig);
1908 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1909 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1912 $main::lxdebug->leave_sub();
1914 return $template_code;
1917 sub get_printer_code {
1918 $main::lxdebug->enter_sub();
1920 my ($self, $myconfig) = @_;
1922 my $template_code = "";
1924 if ($self->{printer_id}) {
1925 my $dbh = $self->get_standard_dbh($myconfig);
1926 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1927 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1930 $main::lxdebug->leave_sub();
1932 return $template_code;
1936 $main::lxdebug->enter_sub();
1938 my ($self, $myconfig) = @_;
1940 my $template_code = "";
1942 if ($self->{shipto_id}) {
1943 my $dbh = $self->get_standard_dbh($myconfig);
1944 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1945 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1946 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1949 $main::lxdebug->leave_sub();
1953 $main::lxdebug->enter_sub();
1955 my ($self, $dbh, $id, $module) = @_;
1960 foreach my $item (qw(name department_1 department_2 street zipcode city country
1961 contact phone fax email)) {
1962 if ($self->{"shipto$item"}) {
1963 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1965 push(@values, $self->{"shipto${item}"});
1969 if ($self->{shipto_id}) {
1970 my $query = qq|UPDATE shipto set
1972 shiptodepartment_1 = ?,
1973 shiptodepartment_2 = ?,
1982 WHERE shipto_id = ?|;
1983 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1985 my $query = qq|SELECT * FROM shipto
1986 WHERE shiptoname = ? AND
1987 shiptodepartment_1 = ? AND
1988 shiptodepartment_2 = ? AND
1989 shiptostreet = ? AND
1990 shiptozipcode = ? AND
1992 shiptocountry = ? AND
1993 shiptocontact = ? AND
1999 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
2002 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
2003 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
2004 shiptocontact, shiptophone, shiptofax, shiptoemail, module)
2005 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
2006 do_query($self, $dbh, $query, $id, @values, $module);
2011 $main::lxdebug->leave_sub();
2015 $main::lxdebug->enter_sub();
2017 my ($self, $dbh) = @_;
2019 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2020 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2021 $self->{"employee_id"} *= 1;
2023 $main::lxdebug->leave_sub();
2026 sub get_employee_data {
2027 $main::lxdebug->enter_sub();
2032 Common::check_params(\%params, qw(prefix));
2033 Common::check_params_x(\%params, qw(id));
2036 $main::lxdebug->leave_sub();
2040 my $myconfig = \%main::myconfig;
2041 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
2043 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2046 my $user = User->new($login);
2047 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2049 $self->{$params{prefix} . '_login'} = $login;
2050 $self->{$params{prefix} . '_name'} ||= $login;
2053 $main::lxdebug->leave_sub();
2057 $main::lxdebug->enter_sub();
2059 my ($self, $myconfig, $reference_date) = @_;
2061 my $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2063 my $dbh = $self->get_standard_dbh($myconfig);
2064 my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2065 my ($duedate) = selectrow_query($self, $dbh, $query, $self->{payment_id});
2067 $main::lxdebug->leave_sub();
2073 $main::lxdebug->enter_sub();
2075 my ($self, $dbh, $id, $key) = @_;
2077 $key = "all_contacts" unless ($key);
2081 $main::lxdebug->leave_sub();
2086 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2087 qq|FROM contacts | .
2088 qq|WHERE cp_cv_id = ? | .
2089 qq|ORDER BY lower(cp_name)|;
2091 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2093 $main::lxdebug->leave_sub();
2097 $main::lxdebug->enter_sub();
2099 my ($self, $dbh, $key) = @_;
2101 my ($all, $old_id, $where, @values);
2103 if (ref($key) eq "HASH") {
2106 $key = "ALL_PROJECTS";
2108 foreach my $p (keys(%{$params})) {
2110 $all = $params->{$p};
2111 } elsif ($p eq "old_id") {
2112 $old_id = $params->{$p};
2113 } elsif ($p eq "key") {
2114 $key = $params->{$p};
2120 $where = "WHERE active ";
2122 if (ref($old_id) eq "ARRAY") {
2123 my @ids = grep({ $_ } @{$old_id});
2125 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2126 push(@values, @ids);
2129 $where .= " OR (id = ?) ";
2130 push(@values, $old_id);
2136 qq|SELECT id, projectnumber, description, active | .
2139 qq|ORDER BY lower(projectnumber)|;
2141 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2143 $main::lxdebug->leave_sub();
2147 $main::lxdebug->enter_sub();
2149 my ($self, $dbh, $vc_id, $key) = @_;
2151 $key = "all_shipto" unless ($key);
2154 # get shipping addresses
2155 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2157 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2163 $main::lxdebug->leave_sub();
2167 $main::lxdebug->enter_sub();
2169 my ($self, $dbh, $key) = @_;
2171 $key = "all_printers" unless ($key);
2173 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2175 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2177 $main::lxdebug->leave_sub();
2181 $main::lxdebug->enter_sub();
2183 my ($self, $dbh, $params) = @_;
2186 $key = $params->{key};
2187 $key = "all_charts" unless ($key);
2189 my $transdate = quote_db_date($params->{transdate});
2192 qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
2194 qq|LEFT JOIN taxkeys tk ON | .
2195 qq|(tk.id = (SELECT id FROM taxkeys | .
2196 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2197 qq| ORDER BY startdate DESC LIMIT 1)) | .
2198 qq|ORDER BY c.accno|;
2200 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2202 $main::lxdebug->leave_sub();
2205 sub _get_taxcharts {
2206 $main::lxdebug->enter_sub();
2208 my ($self, $dbh, $params) = @_;
2210 my $key = "all_taxcharts";
2213 if (ref $params eq 'HASH') {
2214 $key = $params->{key} if ($params->{key});
2215 if ($params->{module} eq 'AR') {
2216 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2218 } elsif ($params->{module} eq 'AP') {
2219 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2226 my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2228 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2230 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2232 $main::lxdebug->leave_sub();
2236 $main::lxdebug->enter_sub();
2238 my ($self, $dbh, $key) = @_;
2240 $key = "all_taxzones" unless ($key);
2242 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2244 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2246 $main::lxdebug->leave_sub();
2249 sub _get_employees {
2250 $main::lxdebug->enter_sub();
2252 my ($self, $dbh, $default_key, $key) = @_;
2254 $key = $default_key unless ($key);
2255 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2257 $main::lxdebug->leave_sub();
2260 sub _get_business_types {
2261 $main::lxdebug->enter_sub();
2263 my ($self, $dbh, $key) = @_;
2265 $key = "all_business_types" unless ($key);
2267 selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2269 $main::lxdebug->leave_sub();
2272 sub _get_languages {
2273 $main::lxdebug->enter_sub();
2275 my ($self, $dbh, $key) = @_;
2277 $key = "all_languages" unless ($key);
2279 my $query = qq|SELECT * FROM language ORDER BY id|;
2281 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2283 $main::lxdebug->leave_sub();
2286 sub _get_dunning_configs {
2287 $main::lxdebug->enter_sub();
2289 my ($self, $dbh, $key) = @_;
2291 $key = "all_dunning_configs" unless ($key);
2293 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2295 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2297 $main::lxdebug->leave_sub();
2300 sub _get_currencies {
2301 $main::lxdebug->enter_sub();
2303 my ($self, $dbh, $key) = @_;
2305 $key = "all_currencies" unless ($key);
2307 my $query = qq|SELECT curr AS currency FROM defaults|;
2309 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2311 $main::lxdebug->leave_sub();
2315 $main::lxdebug->enter_sub();
2317 my ($self, $dbh, $key) = @_;
2319 $key = "all_payments" unless ($key);
2321 my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2323 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2325 $main::lxdebug->leave_sub();
2328 sub _get_customers {
2329 $main::lxdebug->enter_sub();
2331 my ($self, $dbh, $key, $limit) = @_;
2333 $key = "all_customers" unless ($key);
2334 my $limit_clause = "LIMIT $limit" if $limit;
2336 my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2338 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2340 $main::lxdebug->leave_sub();
2344 $main::lxdebug->enter_sub();
2346 my ($self, $dbh, $key) = @_;
2348 $key = "all_vendors" unless ($key);
2350 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2352 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2354 $main::lxdebug->leave_sub();
2357 sub _get_departments {
2358 $main::lxdebug->enter_sub();
2360 my ($self, $dbh, $key) = @_;
2362 $key = "all_departments" unless ($key);
2364 my $query = qq|SELECT * FROM department ORDER BY description|;
2366 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2368 $main::lxdebug->leave_sub();
2371 sub _get_warehouses {
2372 $main::lxdebug->enter_sub();
2374 my ($self, $dbh, $param) = @_;
2376 my ($key, $bins_key);
2378 if ('' eq ref $param) {
2382 $key = $param->{key};
2383 $bins_key = $param->{bins};
2386 my $query = qq|SELECT w.* FROM warehouse w
2387 WHERE (NOT w.invalid) AND
2388 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2389 ORDER BY w.sortkey|;
2391 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2394 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2395 my $sth = prepare_query($self, $dbh, $query);
2397 foreach my $warehouse (@{ $self->{$key} }) {
2398 do_statement($self, $sth, $query, $warehouse->{id});
2399 $warehouse->{$bins_key} = [];
2401 while (my $ref = $sth->fetchrow_hashref()) {
2402 push @{ $warehouse->{$bins_key} }, $ref;
2408 $main::lxdebug->leave_sub();
2412 $main::lxdebug->enter_sub();
2414 my ($self, $dbh, $table, $key, $sortkey) = @_;
2416 my $query = qq|SELECT * FROM $table|;
2417 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2419 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2421 $main::lxdebug->leave_sub();
2425 # $main::lxdebug->enter_sub();
2427 # my ($self, $dbh, $key) = @_;
2429 # $key ||= "all_groups";
2431 # my $groups = $main::auth->read_groups();
2433 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2435 # $main::lxdebug->leave_sub();
2439 $main::lxdebug->enter_sub();
2444 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2445 my ($sth, $query, $ref);
2447 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2448 my $vc_id = $self->{"${vc}_id"};
2450 if ($params{"contacts"}) {
2451 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2454 if ($params{"shipto"}) {
2455 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2458 if ($params{"projects"} || $params{"all_projects"}) {
2459 $self->_get_projects($dbh, $params{"all_projects"} ?
2460 $params{"all_projects"} : $params{"projects"},
2461 $params{"all_projects"} ? 1 : 0);
2464 if ($params{"printers"}) {
2465 $self->_get_printers($dbh, $params{"printers"});
2468 if ($params{"languages"}) {
2469 $self->_get_languages($dbh, $params{"languages"});
2472 if ($params{"charts"}) {
2473 $self->_get_charts($dbh, $params{"charts"});
2476 if ($params{"taxcharts"}) {
2477 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2480 if ($params{"taxzones"}) {
2481 $self->_get_taxzones($dbh, $params{"taxzones"});
2484 if ($params{"employees"}) {
2485 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2488 if ($params{"salesmen"}) {
2489 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2492 if ($params{"business_types"}) {
2493 $self->_get_business_types($dbh, $params{"business_types"});
2496 if ($params{"dunning_configs"}) {
2497 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2500 if($params{"currencies"}) {
2501 $self->_get_currencies($dbh, $params{"currencies"});
2504 if($params{"customers"}) {
2505 if (ref $params{"customers"} eq 'HASH') {
2506 $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2508 $self->_get_customers($dbh, $params{"customers"});
2512 if($params{"vendors"}) {
2513 if (ref $params{"vendors"} eq 'HASH') {
2514 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2516 $self->_get_vendors($dbh, $params{"vendors"});
2520 if($params{"payments"}) {
2521 $self->_get_payments($dbh, $params{"payments"});
2524 if($params{"departments"}) {
2525 $self->_get_departments($dbh, $params{"departments"});
2528 if ($params{price_factors}) {
2529 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2532 if ($params{warehouses}) {
2533 $self->_get_warehouses($dbh, $params{warehouses});
2536 # if ($params{groups}) {
2537 # $self->_get_groups($dbh, $params{groups});
2540 if ($params{partsgroup}) {
2541 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2544 $main::lxdebug->leave_sub();
2547 # this sub gets the id and name from $table
2549 $main::lxdebug->enter_sub();
2551 my ($self, $myconfig, $table) = @_;
2553 # connect to database
2554 my $dbh = $self->get_standard_dbh($myconfig);
2556 $table = $table eq "customer" ? "customer" : "vendor";
2557 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2559 my ($query, @values);
2561 if (!$self->{openinvoices}) {
2563 if ($self->{customernumber} ne "") {
2564 $where = qq|(vc.customernumber ILIKE ?)|;
2565 push(@values, '%' . $self->{customernumber} . '%');
2567 $where = qq|(vc.name ILIKE ?)|;
2568 push(@values, '%' . $self->{$table} . '%');
2572 qq~SELECT vc.id, vc.name,
2573 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2575 WHERE $where AND (NOT vc.obsolete)
2579 qq~SELECT DISTINCT vc.id, vc.name,
2580 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2582 JOIN $table vc ON (a.${table}_id = vc.id)
2583 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2585 push(@values, '%' . $self->{$table} . '%');
2588 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2590 $main::lxdebug->leave_sub();
2592 return scalar(@{ $self->{name_list} });
2595 # the selection sub is used in the AR, AP, IS, IR and OE module
2598 $main::lxdebug->enter_sub();
2600 my ($self, $myconfig, $table, $module) = @_;
2603 my $dbh = $self->get_standard_dbh($myconfig);
2605 $table = $table eq "customer" ? "customer" : "vendor";
2607 my $query = qq|SELECT count(*) FROM $table|;
2608 my ($count) = selectrow_query($self, $dbh, $query);
2610 # build selection list
2611 if ($count < $myconfig->{vclimit}) {
2612 $query = qq|SELECT id, name, salesman_id
2613 FROM $table WHERE NOT obsolete
2615 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2619 $self->get_employee($dbh);
2621 # setup sales contacts
2622 $query = qq|SELECT e.id, e.name
2624 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2625 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2628 push(@{ $self->{all_employees} },
2629 { id => $self->{employee_id},
2630 name => $self->{employee} });
2632 # sort the whole thing
2633 @{ $self->{all_employees} } =
2634 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2636 if ($module eq 'AR') {
2638 # prepare query for departments
2639 $query = qq|SELECT id, description
2642 ORDER BY description|;
2645 $query = qq|SELECT id, description
2647 ORDER BY description|;
2650 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2653 $query = qq|SELECT id, description
2657 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2660 $query = qq|SELECT printer_description, id
2662 ORDER BY printer_description|;
2664 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2667 $query = qq|SELECT id, description
2671 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2673 $main::lxdebug->leave_sub();
2676 sub language_payment {
2677 $main::lxdebug->enter_sub();
2679 my ($self, $myconfig) = @_;
2681 my $dbh = $self->get_standard_dbh($myconfig);
2683 my $query = qq|SELECT id, description
2687 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2690 $query = qq|SELECT printer_description, id
2692 ORDER BY printer_description|;
2694 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2697 $query = qq|SELECT id, description
2701 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2703 # get buchungsgruppen
2704 $query = qq|SELECT id, description
2705 FROM buchungsgruppen|;
2707 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2709 $main::lxdebug->leave_sub();
2712 # this is only used for reports
2713 sub all_departments {
2714 $main::lxdebug->enter_sub();
2716 my ($self, $myconfig, $table) = @_;
2718 my $dbh = $self->get_standard_dbh($myconfig);
2721 if ($table eq 'customer') {
2722 $where = "WHERE role = 'P' ";
2725 my $query = qq|SELECT id, description
2728 ORDER BY description|;
2729 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2731 delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2733 $main::lxdebug->leave_sub();
2737 $main::lxdebug->enter_sub();
2739 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2742 if ($table eq "customer") {
2751 $self->all_vc($myconfig, $table, $module);
2753 # get last customers or vendors
2754 my ($query, $sth, $ref);
2756 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2761 my $transdate = "current_date";
2762 if ($self->{transdate}) {
2763 $transdate = $dbh->quote($self->{transdate});
2766 # now get the account numbers
2767 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2768 FROM chart c, taxkeys tk
2769 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2770 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2773 $sth = $dbh->prepare($query);
2775 do_statement($self, $sth, $query, '%' . $module . '%');
2777 $self->{accounts} = "";
2778 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2780 foreach my $key (split(/:/, $ref->{link})) {
2781 if ($key =~ /\Q$module\E/) {
2783 # cross reference for keys
2784 $xkeyref{ $ref->{accno} } = $key;
2786 push @{ $self->{"${module}_links"}{$key} },
2787 { accno => $ref->{accno},
2788 description => $ref->{description},
2789 taxkey => $ref->{taxkey_id},
2790 tax_id => $ref->{tax_id} };
2792 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2798 # get taxkeys and description
2799 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2800 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2802 if (($module eq "AP") || ($module eq "AR")) {
2803 # get tax rates and description
2804 $query = qq|SELECT * FROM tax|;
2805 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2811 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2812 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2813 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2814 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2816 d.description AS department,
2819 JOIN $table c ON (a.${table}_id = c.id)
2820 LEFT JOIN employee e ON (e.id = a.employee_id)
2821 LEFT JOIN department d ON (d.id = a.department_id)
2823 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2825 foreach my $key (keys %$ref) {
2826 $self->{$key} = $ref->{$key};
2829 my $transdate = "current_date";
2830 if ($self->{transdate}) {
2831 $transdate = $dbh->quote($self->{transdate});
2834 # now get the account numbers
2835 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2837 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2839 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2840 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2843 $sth = $dbh->prepare($query);
2844 do_statement($self, $sth, $query, "%$module%");
2846 $self->{accounts} = "";
2847 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2849 foreach my $key (split(/:/, $ref->{link})) {
2850 if ($key =~ /\Q$module\E/) {
2852 # cross reference for keys
2853 $xkeyref{ $ref->{accno} } = $key;
2855 push @{ $self->{"${module}_links"}{$key} },
2856 { accno => $ref->{accno},
2857 description => $ref->{description},
2858 taxkey => $ref->{taxkey_id},
2859 tax_id => $ref->{tax_id} };
2861 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2867 # get amounts from individual entries
2870 c.accno, c.description,
2871 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2875 LEFT JOIN chart c ON (c.id = a.chart_id)
2876 LEFT JOIN project p ON (p.id = a.project_id)
2877 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2878 WHERE (tk.taxkey_id=a.taxkey) AND
2879 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2880 THEN tk.chart_id = a.chart_id
2883 OR (c.link='%tax%')) AND
2884 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2885 WHERE a.trans_id = ?
2886 AND a.fx_transaction = '0'
2887 ORDER BY a.acc_trans_id, a.transdate|;
2888 $sth = $dbh->prepare($query);
2889 do_statement($self, $sth, $query, $self->{id});
2891 # get exchangerate for currency
2892 $self->{exchangerate} =
2893 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2896 # store amounts in {acc_trans}{$key} for multiple accounts
2897 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2898 $ref->{exchangerate} =
2899 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2900 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2903 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2904 $ref->{amount} *= -1;
2906 $ref->{index} = $index;
2908 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2914 d.curr AS currencies, d.closedto, d.revtrans,
2915 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2916 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2918 $ref = selectfirst_hashref_query($self, $dbh, $query);
2919 map { $self->{$_} = $ref->{$_} } keys %$ref;
2926 current_date AS transdate, 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;
2933 if ($self->{"$self->{vc}_id"}) {
2935 # only setup currency
2936 ($self->{currency}) = split(/:/, $self->{currencies});
2940 $self->lastname_used($dbh, $myconfig, $table, $module);
2942 # get exchangerate for currency
2943 $self->{exchangerate} =
2944 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2950 $main::lxdebug->leave_sub();
2954 $main::lxdebug->enter_sub();
2956 my ($self, $dbh, $myconfig, $table, $module) = @_;
2960 $table = $table eq "customer" ? "customer" : "vendor";
2961 my %column_map = ("a.curr" => "currency",
2962 "a.${table}_id" => "${table}_id",
2963 "a.department_id" => "department_id",
2964 "d.description" => "department",
2965 "ct.name" => $table,
2966 "current_date + ct.terms" => "duedate",
2969 if ($self->{type} =~ /delivery_order/) {
2970 $arap = 'delivery_orders';
2971 delete $column_map{"a.curr"};
2973 } elsif ($self->{type} =~ /_order/) {
2975 $where = "quotation = '0'";
2977 } elsif ($self->{type} =~ /_quotation/) {
2979 $where = "quotation = '1'";
2981 } elsif ($table eq 'customer') {
2989 $where = "($where) AND" if ($where);
2990 my $query = qq|SELECT MAX(id) FROM $arap
2991 WHERE $where ${table}_id > 0|;
2992 my ($trans_id) = selectrow_query($self, $dbh, $query);
2995 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2996 $query = qq|SELECT $column_spec
2998 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2999 LEFT JOIN department d ON (a.department_id = d.id)
3001 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3003 map { $self->{$_} = $ref->{$_} } values %column_map;
3005 $main::lxdebug->leave_sub();
3009 $main::lxdebug->enter_sub();
3011 my ($self, $myconfig, $thisdate, $days) = @_;
3013 my $dbh = $self->get_standard_dbh($myconfig);
3018 my $dateformat = $myconfig->{dateformat};
3019 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3020 $thisdate = $dbh->quote($thisdate);
3021 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3023 $query = qq|SELECT current_date AS thisdate|;
3026 ($thisdate) = selectrow_query($self, $dbh, $query);
3028 $main::lxdebug->leave_sub();
3034 $main::lxdebug->enter_sub();
3036 my ($self, $string) = @_;
3038 if ($string !~ /%/) {
3039 $string = "%$string%";
3042 $string =~ s/\'/\'\'/g;
3044 $main::lxdebug->leave_sub();
3050 $main::lxdebug->enter_sub();
3052 my ($self, $flds, $new, $count, $numrows) = @_;
3056 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3061 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3063 my $j = $item->{ndx} - 1;
3064 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3068 for $i ($count + 1 .. $numrows) {
3069 map { delete $self->{"${_}_$i"} } @{$flds};
3072 $main::lxdebug->leave_sub();
3076 $main::lxdebug->enter_sub();
3078 my ($self, $myconfig) = @_;
3082 my $dbh = $self->dbconnect_noauto($myconfig);
3084 my $query = qq|DELETE FROM status
3085 WHERE (formname = ?) AND (trans_id = ?)|;
3086 my $sth = prepare_query($self, $dbh, $query);
3088 if ($self->{formname} =~ /(check|receipt)/) {
3089 for $i (1 .. $self->{rowcount}) {
3090 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3093 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3097 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3098 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3100 my %queued = split / /, $self->{queued};
3103 if ($self->{formname} =~ /(check|receipt)/) {
3105 # this is a check or receipt, add one entry for each lineitem
3106 my ($accno) = split /--/, $self->{account};
3107 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3108 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3109 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3110 $sth = prepare_query($self, $dbh, $query);
3112 for $i (1 .. $self->{rowcount}) {
3113 if ($self->{"checked_$i"}) {
3114 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3120 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3121 VALUES (?, ?, ?, ?, ?)|;
3122 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3123 $queued{$self->{formname}}, $self->{formname});
3129 $main::lxdebug->leave_sub();
3133 $main::lxdebug->enter_sub();
3135 my ($self, $dbh) = @_;
3137 my ($query, $printed, $emailed);
3139 my $formnames = $self->{printed};
3140 my $emailforms = $self->{emailed};
3142 $query = qq|DELETE FROM status
3143 WHERE (formname = ?) AND (trans_id = ?)|;
3144 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3146 # this only applies to the forms
3147 # checks and receipts are posted when printed or queued
3149 if ($self->{queued}) {
3150 my %queued = split / /, $self->{queued};
3152 foreach my $formname (keys %queued) {
3153 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3154 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3156 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3157 VALUES (?, ?, ?, ?, ?)|;
3158 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3160 $formnames =~ s/\Q$self->{formname}\E//;
3161 $emailforms =~ s/\Q$self->{formname}\E//;
3166 # save printed, emailed info
3167 $formnames =~ s/^ +//g;
3168 $emailforms =~ s/^ +//g;
3171 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3172 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3174 foreach my $formname (keys %status) {
3175 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3176 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3178 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3179 VALUES (?, ?, ?, ?)|;
3180 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3183 $main::lxdebug->leave_sub();
3187 # $main::locale->text('SAVED')
3188 # $main::locale->text('DELETED')
3189 # $main::locale->text('ADDED')
3190 # $main::locale->text('PAYMENT POSTED')
3191 # $main::locale->text('POSTED')
3192 # $main::locale->text('POSTED AS NEW')
3193 # $main::locale->text('ELSE')
3194 # $main::locale->text('SAVED FOR DUNNING')
3195 # $main::locale->text('DUNNING STARTED')
3196 # $main::locale->text('PRINTED')
3197 # $main::locale->text('MAILED')
3198 # $main::locale->text('SCREENED')
3199 # $main::locale->text('CANCELED')
3200 # $main::locale->text('invoice')
3201 # $main::locale->text('proforma')
3202 # $main::locale->text('sales_order')
3203 # $main::locale->text('packing_list')
3204 # $main::locale->text('pick_list')
3205 # $main::locale->text('purchase_order')
3206 # $main::locale->text('bin_list')
3207 # $main::locale->text('sales_quotation')
3208 # $main::locale->text('request_quotation')
3211 $main::lxdebug->enter_sub();
3216 if(!exists $self->{employee_id}) {
3217 &get_employee($self, $dbh);
3221 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3222 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3223 my @values = (conv_i($self->{id}), $self->{login},
3224 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3225 do_query($self, $dbh, $query, @values);
3227 $main::lxdebug->leave_sub();
3231 $main::lxdebug->enter_sub();
3233 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3234 my ($orderBy, $desc) = split(/\-\-/, $order);
3235 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3238 if ($trans_id ne "") {
3240 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 | .
3241 qq|FROM history_erp h | .
3242 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3243 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3246 my $sth = $dbh->prepare($query) || $self->dberror($query);
3248 $sth->execute() || $self->dberror("$query");
3250 while(my $hash_ref = $sth->fetchrow_hashref()) {
3251 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3252 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3253 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3254 $tempArray[$i++] = $hash_ref;
3256 $main::lxdebug->leave_sub() and return \@tempArray
3257 if ($i > 0 && $tempArray[0] ne "");
3259 $main::lxdebug->leave_sub();
3263 sub update_defaults {
3264 $main::lxdebug->enter_sub();
3266 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3269 if ($provided_dbh) {
3270 $dbh = $provided_dbh;
3272 $dbh = $self->dbconnect_noauto($myconfig);
3274 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3275 my $sth = $dbh->prepare($query);
3277 $sth->execute || $self->dberror($query);
3278 my ($var) = $sth->fetchrow_array;
3281 if ($var =~ m/\d+$/) {
3282 my $new_var = (substr $var, $-[0]) * 1 + 1;
3283 my $len_diff = length($var) - $-[0] - length($new_var);
3284 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3290 $query = qq|UPDATE defaults SET $fld = ?|;
3291 do_query($self, $dbh, $query, $var);
3293 if (!$provided_dbh) {
3298 $main::lxdebug->leave_sub();
3303 =item update_business
3306 \%config, - config hashref
3307 $business_id, - business id
3308 $dbh - optional database handle
3310 handles business (thats customer/vendor types) sequences.
3312 special behaviour for empty strings in customerinitnumber field:
3313 will in this case not increase the value, and return undef.
3316 sub update_business {
3317 $main::lxdebug->enter_sub();
3319 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3322 if ($provided_dbh) {
3323 $dbh = $provided_dbh;
3325 $dbh = $self->dbconnect_noauto($myconfig);
3328 qq|SELECT customernumberinit FROM business
3329 WHERE id = ? FOR UPDATE|;
3330 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3332 return undef unless $var;
3334 if ($var =~ m/\d+$/) {
3335 my $new_var = (substr $var, $-[0]) * 1 + 1;
3336 my $len_diff = length($var) - $-[0] - length($new_var);
3337 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3343 $query = qq|UPDATE business
3344 SET customernumberinit = ?
3346 do_query($self, $dbh, $query, $var, $business_id);
3348 if (!$provided_dbh) {
3353 $main::lxdebug->leave_sub();
3358 sub get_partsgroup {
3359 $main::lxdebug->enter_sub();
3361 my ($self, $myconfig, $p) = @_;
3362 my $target = $p->{target} || 'all_partsgroup';
3364 my $dbh = $self->get_standard_dbh($myconfig);
3366 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3368 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3371 if ($p->{searchitems} eq 'part') {
3372 $query .= qq|WHERE p.inventory_accno_id > 0|;
3374 if ($p->{searchitems} eq 'service') {
3375 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3377 if ($p->{searchitems} eq 'assembly') {
3378 $query .= qq|WHERE p.assembly = '1'|;
3380 if ($p->{searchitems} eq 'labor') {
3381 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3384 $query .= qq|ORDER BY partsgroup|;
3387 $query = qq|SELECT id, partsgroup FROM partsgroup
3388 ORDER BY partsgroup|;
3391 if ($p->{language_code}) {
3392 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3393 t.description AS translation
3395 JOIN parts p ON (p.partsgroup_id = pg.id)
3396 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3397 ORDER BY translation|;
3398 @values = ($p->{language_code});
3401 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3403 $main::lxdebug->leave_sub();
3406 sub get_pricegroup {
3407 $main::lxdebug->enter_sub();
3409 my ($self, $myconfig, $p) = @_;
3411 my $dbh = $self->get_standard_dbh($myconfig);
3413 my $query = qq|SELECT p.id, p.pricegroup
3416 $query .= qq| ORDER BY pricegroup|;
3419 $query = qq|SELECT id, pricegroup FROM pricegroup
3420 ORDER BY pricegroup|;
3423 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3425 $main::lxdebug->leave_sub();
3429 # usage $form->all_years($myconfig, [$dbh])
3430 # return list of all years where bookings found
3433 $main::lxdebug->enter_sub();
3435 my ($self, $myconfig, $dbh) = @_;
3437 $dbh ||= $self->get_standard_dbh($myconfig);
3440 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3441 (SELECT MAX(transdate) FROM acc_trans)|;
3442 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3444 if ($myconfig->{dateformat} =~ /^yy/) {
3445 ($startdate) = split /\W/, $startdate;
3446 ($enddate) = split /\W/, $enddate;
3448 (@_) = split /\W/, $startdate;
3450 (@_) = split /\W/, $enddate;
3455 $startdate = substr($startdate,0,4);
3456 $enddate = substr($enddate,0,4);
3458 while ($enddate >= $startdate) {
3459 push @all_years, $enddate--;
3464 $main::lxdebug->leave_sub();
3468 $main::lxdebug->enter_sub();
3472 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3474 $main::lxdebug->leave_sub();
3478 $main::lxdebug->enter_sub();
3483 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3485 $main::lxdebug->leave_sub();