1 #====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
15 # Contributors: Thomas Bayen <bayen@gmx.de>
16 # Antti Kaihola <akaihola@siba.fi>
17 # Moritz Bunkus (tex code)
19 # This program is free software; you can redistribute it and/or modify
20 # it under the terms of the GNU General Public License as published by
21 # the Free Software Foundation; either version 2 of the License, or
22 # (at your option) any later version.
24 # This program is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 # GNU General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, write to the Free Software
30 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #======================================================================
32 # Utilities for parsing forms
33 # and supporting routines for linking account numbers
34 # used in AR, AP and IS, IR modules
36 #======================================================================
57 use List::Util qw(first max min sum);
58 use List::MoreUtils qw(any);
66 $standard_dbh->disconnect();
72 $main::lxdebug->enter_sub(2);
78 my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key;
83 $curr = \ $self->{ shift @tokens };
87 my $sep = shift @tokens;
88 my $key = shift @tokens;
90 $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]';
91 $curr = \ $$curr->[max 0, $#$$curr] if $sep eq '[].';
92 $curr = \ $$curr->[++$#$$curr] if $sep eq '[+].';
93 $curr = \ $$curr->{$key}
98 $main::lxdebug->leave_sub(2);
104 $main::lxdebug->enter_sub(2);
109 my @pairs = split(/&/, $input);
112 my ($key, $value) = split(/=/, $_, 2);
113 $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key);
116 $main::lxdebug->leave_sub(2);
119 sub _request_to_hash {
120 $main::lxdebug->enter_sub(2);
125 if (!$ENV{'CONTENT_TYPE'}
126 || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
128 $self->_input_to_hash($input);
130 $main::lxdebug->leave_sub(2);
134 my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
136 my $boundary = '--' . $1;
138 foreach my $line (split m/\n/, $input) {
139 last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
141 if (($line eq $boundary) || ($line eq "$boundary\r")) {
142 ${ $previous } =~ s|\r?\n$|| if $previous;
148 $content_type = "text/plain";
155 next unless $boundary_found;
157 if (!$headers_done) {
158 $line =~ s/[\r\n]*$//;
165 if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
166 if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
168 substr $line, $-[0], $+[0] - $-[0], "";
171 if ($line =~ m|name\s*=\s*"(.*?)"|i) {
173 substr $line, $-[0], $+[0] - $-[0], "";
176 $previous = $self->_store_value($name, '') if ($name);
177 $self->{FILENAME} = $filename if ($filename);
182 if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
189 next unless $previous;
191 ${ $previous } .= "${line}\n";
194 ${ $previous } =~ s|\r?\n$|| if $previous;
196 $main::lxdebug->leave_sub(2);
199 sub _recode_recursively {
200 $main::lxdebug->enter_sub();
201 my ($iconv, $param) = @_;
203 if (any { ref $param eq $_ } qw(Form HASH)) {
204 foreach my $key (keys %{ $param }) {
205 if (!ref $param->{$key}) {
206 # Workaround for a bug: converting $param->{$key} directly
207 # leads to 'undef'. I don't know why. Converting a copy works,
209 $param->{$key} = $iconv->convert("" . $param->{$key});
211 _recode_recursively($iconv, $param->{$key});
215 } elsif (ref $param eq 'ARRAY') {
216 foreach my $idx (0 .. scalar(@{ $param }) - 1) {
217 if (!ref $param->[$idx]) {
218 # Workaround for a bug: converting $param->[$idx] directly
219 # leads to 'undef'. I don't know why. Converting a copy works,
221 $param->[$idx] = $iconv->convert("" . $param->[$idx]);
223 _recode_recursively($iconv, $param->[$idx]);
227 $main::lxdebug->leave_sub();
231 $main::lxdebug->enter_sub();
237 if ($LXDebug::watch_form) {
238 require SL::Watchdog;
239 tie %{ $self }, 'SL::Watchdog';
242 read(STDIN, $_, $ENV{CONTENT_LENGTH});
244 if ($ENV{QUERY_STRING}) {
245 $_ = $ENV{QUERY_STRING};
254 $self->_request_to_hash($_);
256 my $db_charset = $main::dbcharset;
257 $db_charset ||= Common::DEFAULT_CHARSET;
259 if ($self->{INPUT_ENCODING}) {
260 if (lc $self->{INPUT_ENCODING} ne lc $db_charset) {
262 my $iconv = Text::Iconv->new($self->{INPUT_ENCODING}, $db_charset);
264 _recode_recursively($iconv, $self);
267 delete $self->{INPUT_ENCODING};
270 $self->{action} = lc $self->{action};
271 $self->{action} =~ s/( |-|,|\#)/_/g;
273 $self->{version} = "2.6.1 Beta 1";
275 $main::lxdebug->leave_sub();
280 sub _flatten_variables_rec {
281 $main::lxdebug->enter_sub(2);
290 if ('' eq ref $curr->{$key}) {
291 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
293 } elsif ('HASH' eq ref $curr->{$key}) {
294 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
295 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
299 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
300 my $first_array_entry = 1;
302 foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
303 push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
304 $first_array_entry = 0;
309 $main::lxdebug->leave_sub(2);
314 sub flatten_variables {
315 $main::lxdebug->enter_sub(2);
323 push @variables, $self->_flatten_variables_rec($self, '', $_);
326 $main::lxdebug->leave_sub(2);
331 sub flatten_standard_variables {
332 $main::lxdebug->enter_sub(2);
335 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
339 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
340 push @variables, $self->_flatten_variables_rec($self, '', $_);
343 $main::lxdebug->leave_sub(2);
349 $main::lxdebug->enter_sub();
355 map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
357 $main::lxdebug->leave_sub();
361 $main::lxdebug->enter_sub(2);
364 my $password = $self->{password};
366 $self->{password} = 'X' x 8;
368 local $Data::Dumper::Sortkeys = 1;
369 my $output = Dumper($self);
371 $self->{password} = $password;
373 $main::lxdebug->leave_sub(2);
379 $main::lxdebug->enter_sub(2);
381 my ($self, $str) = @_;
383 $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
385 $main::lxdebug->leave_sub(2);
391 $main::lxdebug->enter_sub(2);
393 my ($self, $str) = @_;
398 $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
400 $main::lxdebug->leave_sub(2);
406 $main::lxdebug->enter_sub();
407 my ($self, $str) = @_;
409 if ($str && !ref($str)) {
410 $str =~ s/\"/"/g;
413 $main::lxdebug->leave_sub();
419 $main::lxdebug->enter_sub();
420 my ($self, $str) = @_;
422 if ($str && !ref($str)) {
423 $str =~ s/"/\"/g;
426 $main::lxdebug->leave_sub();
432 $main::lxdebug->enter_sub();
436 map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
438 for (sort keys %$self) {
439 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
440 print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
443 $main::lxdebug->leave_sub();
447 $main::lxdebug->enter_sub();
449 $main::lxdebug->show_backtrace();
451 my ($self, $msg) = @_;
452 if ($ENV{HTTP_USER_AGENT}) {
454 $self->show_generic_error($msg);
461 $main::lxdebug->leave_sub();
465 $main::lxdebug->enter_sub();
467 my ($self, $msg) = @_;
469 if ($ENV{HTTP_USER_AGENT}) {
472 if (!$self->{header}) {
485 if ($self->{info_function}) {
486 &{ $self->{info_function} }($msg);
492 $main::lxdebug->leave_sub();
495 # calculates the number of rows in a textarea based on the content and column number
496 # can be capped with maxrows
498 $main::lxdebug->enter_sub();
499 my ($self, $str, $cols, $maxrows, $minrows) = @_;
503 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
506 $main::lxdebug->leave_sub();
508 return max(min($rows, $maxrows), $minrows);
512 $main::lxdebug->enter_sub();
514 my ($self, $msg) = @_;
516 $self->error("$msg\n" . $DBI::errstr);
518 $main::lxdebug->leave_sub();
522 $main::lxdebug->enter_sub();
524 my ($self, $name, $msg) = @_;
527 foreach my $part (split m/\./, $name) {
528 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
531 $curr = $curr->{$part};
534 $main::lxdebug->leave_sub();
537 sub create_http_response {
538 $main::lxdebug->enter_sub();
543 my $cgi = $main::cgi;
544 $cgi ||= CGI->new('');
548 if ($ENV{HTTP_X_FORWARDED_FOR}) {
549 $base_path = $ENV{HTTP_REFERER};
550 $base_path =~ s|^.*?://.*?/|/|;
552 $base_path = $ENV{REQUEST_URI};
554 $base_path =~ s|[^/]+$||;
555 $base_path =~ s|/$||;
558 if (defined $main::auth) {
559 my $session_cookie_value = $main::auth->get_session_id();
560 $session_cookie_value ||= 'NO_SESSION';
562 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
563 '-value' => $session_cookie_value,
564 '-path' => $base_path,
565 '-secure' => $ENV{HTTPS});
568 my %cgi_params = ('-type' => $params{content_type});
569 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
571 my $output = $cgi->header('-cookie' => $session_cookie,
574 $main::lxdebug->leave_sub();
581 $main::lxdebug->enter_sub();
583 # extra code ist currently only used by menuv3 and menuv4 to set their css.
584 # it is strongly deprecated, and will be changed in a future version.
585 my ($self, $extra_code) = @_;
587 if ($self->{header}) {
588 $main::lxdebug->leave_sub();
592 my ($stylesheet, $favicon, $pagelayout);
594 if ($ENV{HTTP_USER_AGENT}) {
597 if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
598 # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
599 $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
602 my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
604 $stylesheets =~ s|^\s*||;
605 $stylesheets =~ s|\s*$||;
606 foreach my $file (split m/\s+/, $stylesheets) {
608 next if (! -f "css/$file");
610 $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
613 $self->{favicon} = "favicon.ico" unless $self->{favicon};
615 if ($self->{favicon} && (-f "$self->{favicon}")) {
617 qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
621 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
623 if ($self->{landscape}) {
624 $pagelayout = qq|<style type="text/css">
625 \@page { size:landscape; }
630 <script type="text/javascript">
633 document.$self->{fokus}.focus();
637 | if $self->{"fokus"};
641 if ($self->{jsscript} == 1) {
644 <script type="text/javascript" src="js/jquery.js"></script>
645 <script type="text/javascript" src="js/common.js"></script>
646 <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
647 <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
648 <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
649 <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
656 ? "$self->{title} - $self->{titlebar}"
659 foreach my $item (@ { $self->{AJAX} }) {
660 $ajax .= $item->show_javascript();
663 print $self->create_http_response('content_type' => 'text/html',
664 'charset' => $db_charset,);
665 print qq|${doctype}<html>
667 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
668 <title>$self->{titlebar}</title>
677 <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
679 <meta name="robots" content="noindex,nofollow" />
680 <script type="text/javascript" src="js/highlight_input.js"></script>
682 <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
683 <script type="text/javascript" src="js/tabcontent.js">
685 /***********************************************
686 * Tab Content script v2.2- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
687 * This notice MUST stay intact for legal use
688 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
689 ***********************************************/
700 $main::lxdebug->leave_sub();
703 sub ajax_response_header {
704 $main::lxdebug->enter_sub();
708 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
709 my $cgi = $main::cgi || CGI->new('');
710 my $output = $cgi->header('-charset' => $db_charset);
712 $main::lxdebug->leave_sub();
717 sub _prepare_html_template {
718 $main::lxdebug->enter_sub();
720 my ($self, $file, $additional_params) = @_;
723 if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
724 $language = $main::language;
726 $language = $main::myconfig{"countrycode"};
728 $language = "de" unless ($language);
730 if (-f "templates/webpages/${file}_${language}.html") {
731 if ((-f ".developer") &&
732 (-f "templates/webpages/${file}_master.html") &&
733 ((stat("templates/webpages/${file}_master.html"))[9] >
734 (stat("templates/webpages/${file}_${language}.html"))[9])) {
735 my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
736 "Please re-run 'locales.pl' in 'locale/${language}'.";
737 print(qq|<pre>$info</pre>|);
741 $file = "templates/webpages/${file}_${language}.html";
742 } elsif (-f "templates/webpages/${file}.html") {
743 $file = "templates/webpages/${file}.html";
745 my $info = "Web page template '${file}' not found.\n" .
746 "Please re-run 'locales.pl' in 'locale/${language}'.";
747 print(qq|<pre>$info</pre>|);
751 if ($self->{"DEBUG"}) {
752 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
755 if ($additional_params->{"DEBUG"}) {
756 $additional_params->{"DEBUG"} =
757 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
760 if (%main::myconfig) {
761 map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
762 my $jsc_dateformat = $main::myconfig{"dateformat"};
763 $jsc_dateformat =~ s/d+/\%d/gi;
764 $jsc_dateformat =~ s/m+/\%m/gi;
765 $jsc_dateformat =~ s/y+/\%Y/gi;
766 $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
769 $additional_params->{"conf_dbcharset"} = $main::dbcharset;
770 $additional_params->{"conf_webdav"} = $main::webdav;
771 $additional_params->{"conf_lizenzen"} = $main::lizenzen;
772 $additional_params->{"conf_latex_templates"} = $main::latex;
773 $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
774 $additional_params->{"conf_vertreter"} = $main::vertreter;
775 $additional_params->{"conf_show_best_before"} = $main::show_best_before;
777 if (%main::debug_options) {
778 map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
781 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
782 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
783 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
787 $main::lxdebug->leave_sub();
792 sub parse_html_template {
793 $main::lxdebug->enter_sub();
795 my ($self, $file, $additional_params) = @_;
797 $additional_params ||= { };
799 $file = $self->_prepare_html_template($file, $additional_params);
801 my $template = Template->new({ 'INTERPOLATE' => 0,
805 'PLUGIN_BASE' => 'SL::Template::Plugin',
806 'INCLUDE_PATH' => '.:templates/webpages',
809 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
811 my $in = IO::File->new($file, 'r');
814 print STDERR "Error opening template file: $!";
815 $main::lxdebug->leave_sub();
819 my $input = join('', <$in>);
823 $input = $main::locale->{iconv}->convert($input);
827 if (!$template->process(\$input, $additional_params, \$output)) {
828 print STDERR $template->error();
831 $main::lxdebug->leave_sub();
836 sub show_generic_error {
837 $main::lxdebug->enter_sub();
839 my ($self, $error, %params) = @_;
842 'title_error' => $params{title},
843 'label_error' => $error,
846 if ($params{action}) {
849 map { delete($self->{$_}); } qw(action);
850 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
852 $add_params->{SHOW_BUTTON} = 1;
853 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
854 $add_params->{VARIABLES} = \@vars;
856 } elsif ($params{back_button}) {
857 $add_params->{SHOW_BACK_BUTTON} = 1;
860 $self->{title} = $params{title} if $params{title};
863 print $self->parse_html_template("generic/error", $add_params);
865 $main::lxdebug->leave_sub();
867 die("Error: $error\n");
870 sub show_generic_information {
871 $main::lxdebug->enter_sub();
873 my ($self, $text, $title) = @_;
876 'title_information' => $title,
877 'label_information' => $text,
880 $self->{title} = $title if ($title);
883 print $self->parse_html_template("generic/information", $add_params);
885 $main::lxdebug->leave_sub();
887 die("Information: $text\n");
890 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
891 # changed it to accept an arbitrary number of triggers - sschoeling
893 $main::lxdebug->enter_sub();
896 my $myconfig = shift;
899 # set dateform for jsscript
902 "dd.mm.yy" => "%d.%m.%Y",
903 "dd-mm-yy" => "%d-%m-%Y",
904 "dd/mm/yy" => "%d/%m/%Y",
905 "mm/dd/yy" => "%m/%d/%Y",
906 "mm-dd-yy" => "%m-%d-%Y",
907 "yyyy-mm-dd" => "%Y-%m-%d",
910 my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
911 $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
918 inputField : "| . (shift) . qq|",
919 ifFormat :"$ifFormat",
920 align : "| . (shift) . qq|",
921 button : "| . (shift) . qq|"
927 <script type="text/javascript">
928 <!--| . join("", @triggers) . qq|//-->
932 $main::lxdebug->leave_sub();
935 } #end sub write_trigger
938 $main::lxdebug->enter_sub();
940 my ($self, $msg) = @_;
942 if ($self->{callback}) {
944 my ($script, $argv) = split(/\?/, $self->{callback}, 2);
946 $script =~ s|[^a-zA-Z0-9_\.]||g;
947 exec("perl", "$script", $argv);
955 $main::lxdebug->leave_sub();
958 # sort of columns removed - empty sub
960 $main::lxdebug->enter_sub();
962 my ($self, @columns) = @_;
964 $main::lxdebug->leave_sub();
970 $main::lxdebug->enter_sub(2);
972 my ($self, $myconfig, $amount, $places, $dash) = @_;
978 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
980 my $neg = ($amount =~ s/^-//);
981 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
983 if (defined($places) && ($places ne '')) {
989 my ($actual_places) = ($amount =~ /\.(\d+)/);
990 $actual_places = length($actual_places);
991 $places = $actual_places > $places ? $actual_places : $places;
994 $amount = $self->round_amount($amount, $places);
997 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
998 my @p = split(/\./, $amount); # split amount at decimal point
1000 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
1003 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
1006 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
1007 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1008 ($neg ? "-$amount" : "$amount" ) ;
1012 $main::lxdebug->leave_sub(2);
1016 sub format_amount_units {
1017 $main::lxdebug->enter_sub();
1022 my $myconfig = \%main::myconfig;
1023 my $amount = $params{amount} * 1;
1024 my $places = $params{places};
1025 my $part_unit_name = $params{part_unit};
1026 my $amount_unit_name = $params{amount_unit};
1027 my $conv_units = $params{conv_units};
1028 my $max_places = $params{max_places};
1030 if (!$part_unit_name) {
1031 $main::lxdebug->leave_sub();
1035 AM->retrieve_all_units();
1036 my $all_units = $main::all_units;
1038 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1039 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1042 if (!scalar @{ $conv_units }) {
1043 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1044 $main::lxdebug->leave_sub();
1048 my $part_unit = $all_units->{$part_unit_name};
1049 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1051 $amount *= $conv_unit->{factor};
1056 foreach my $unit (@$conv_units) {
1057 my $last = $unit->{name} eq $part_unit->{name};
1059 $num = int($amount / $unit->{factor});
1060 $amount -= $num * $unit->{factor};
1063 if ($last ? $amount : $num) {
1064 push @values, { "unit" => $unit->{name},
1065 "amount" => $last ? $amount / $unit->{factor} : $num,
1066 "places" => $last ? $places : 0 };
1073 push @values, { "unit" => $part_unit_name,
1078 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1080 $main::lxdebug->leave_sub();
1086 $main::lxdebug->enter_sub(2);
1091 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1092 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1093 $input =~ s/\#\#/\#/g;
1095 $main::lxdebug->leave_sub(2);
1103 $main::lxdebug->enter_sub(2);
1105 my ($self, $myconfig, $amount) = @_;
1107 if ( ($myconfig->{numberformat} eq '1.000,00')
1108 || ($myconfig->{numberformat} eq '1000,00')) {
1113 if ($myconfig->{numberformat} eq "1'000.00") {
1119 $main::lxdebug->leave_sub(2);
1121 return ($amount * 1);
1125 $main::lxdebug->enter_sub(2);
1127 my ($self, $amount, $places) = @_;
1130 # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
1132 # Round amounts to eight places before rounding to the requested
1133 # number of places. This gets rid of errors due to internal floating
1134 # point representation.
1135 $amount = $self->round_amount($amount, 8) if $places < 8;
1136 $amount = $amount * (10**($places));
1137 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1139 $main::lxdebug->leave_sub(2);
1141 return $round_amount;
1145 sub parse_template {
1146 $main::lxdebug->enter_sub();
1148 my ($self, $myconfig, $userspath) = @_;
1149 my ($template, $out);
1153 $self->{"cwd"} = getcwd();
1154 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1158 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1159 $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1160 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
1162 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1163 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1164 $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1165 $ext_for_format = 'pdf';
1167 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1168 $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1169 $ext_for_format = 'html';
1171 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1172 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1173 $ext_for_format = 'xml';
1175 } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1176 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1178 } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1179 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1181 } elsif ( defined $self->{'format'}) {
1182 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1184 } elsif ( $self->{'format'} eq '' ) {
1185 $self->error("No Outputformat given: $self->{'format'}");
1187 } else { #Catch the rest
1188 $self->error("Outputformat not defined: $self->{'format'}");
1191 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1192 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1194 if (!$self->{employee_id}) {
1195 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1198 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1200 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1202 # OUT is used for the media, screen, printer, email
1203 # for postscript we store a copy in a temporary file
1205 my $prepend_userspath;
1207 if (!$self->{tmpfile}) {
1208 $self->{tmpfile} = "${fileid}.$self->{IN}";
1209 $prepend_userspath = 1;
1212 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1214 $self->{tmpfile} =~ s|.*/||;
1215 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1216 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1218 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1219 $out = $self->{OUT};
1220 $self->{OUT} = ">$self->{tmpfile}";
1224 open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1226 open(OUT, ">-") or $self->error("STDOUT : $!");
1230 if (!$template->parse(*OUT)) {
1232 $self->error("$self->{IN} : " . $template->get_error());
1237 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1239 if ($self->{media} eq 'email') {
1241 my $mail = new Mailer;
1243 map { $mail->{$_} = $self->{$_} }
1244 qw(cc bcc subject message version format);
1245 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1246 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1247 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1248 $mail->{fileid} = "$fileid.";
1249 $myconfig->{signature} =~ s/\r//g;
1251 # if we send html or plain text inline
1252 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1253 $mail->{contenttype} = "text/html";
1255 $mail->{message} =~ s/\r//g;
1256 $mail->{message} =~ s/\n/<br>\n/g;
1257 $myconfig->{signature} =~ s/\n/<br>\n/g;
1258 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1260 open(IN, $self->{tmpfile})
1261 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1263 $mail->{message} .= $_;
1270 if (!$self->{"do_not_attach"}) {
1271 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1272 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1273 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1274 "name" => $attachment_name }];
1277 $mail->{message} =~ s/\r//g;
1278 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1282 my $err = $mail->send();
1283 $self->error($self->cleanup . "$err") if ($err);
1287 $self->{OUT} = $out;
1289 my $numbytes = (-s $self->{tmpfile});
1290 open(IN, $self->{tmpfile})
1291 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1293 $self->{copies} = 1 unless $self->{media} eq 'printer';
1295 chdir("$self->{cwd}");
1296 #print(STDERR "Kopien $self->{copies}\n");
1297 #print(STDERR "OUT $self->{OUT}\n");
1298 for my $i (1 .. $self->{copies}) {
1300 open(OUT, $self->{OUT})
1301 or $self->error($self->cleanup . "$self->{OUT} : $!");
1303 $self->{attachment_filename} = ($self->{attachment_filename})
1304 ? $self->{attachment_filename}
1305 : $self->generate_attachment_filename();
1307 # launch application
1308 print qq|Content-Type: | . $template->get_mime_type() . qq|
1309 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1310 Content-Length: $numbytes
1314 open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1335 chdir("$self->{cwd}");
1336 $main::lxdebug->leave_sub();
1339 sub get_formname_translation {
1340 $main::lxdebug->enter_sub();
1341 my ($self, $formname) = @_;
1343 $formname ||= $self->{formname};
1345 my %formname_translations = (
1346 bin_list => $main::locale->text('Bin List'),
1347 credit_note => $main::locale->text('Credit Note'),
1348 invoice => $main::locale->text('Invoice'),
1349 packing_list => $main::locale->text('Packing List'),
1350 pick_list => $main::locale->text('Pick List'),
1351 proforma => $main::locale->text('Proforma Invoice'),
1352 purchase_order => $main::locale->text('Purchase Order'),
1353 request_quotation => $main::locale->text('RFQ'),
1354 sales_order => $main::locale->text('Confirmation'),
1355 sales_quotation => $main::locale->text('Quotation'),
1356 storno_invoice => $main::locale->text('Storno Invoice'),
1357 storno_packing_list => $main::locale->text('Storno Packing List'),
1358 sales_delivery_order => $main::locale->text('Delivery Order'),
1359 purchase_delivery_order => $main::locale->text('Delivery Order'),
1360 dunning => $main::locale->text('Dunning'),
1363 $main::lxdebug->leave_sub();
1364 return $formname_translations{$formname}
1367 sub get_number_prefix_for_type {
1368 $main::lxdebug->enter_sub();
1372 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1373 : ($self->{type} =~ /_quotation$/) ? 'quo'
1374 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1377 $main::lxdebug->leave_sub();
1381 sub get_extension_for_format {
1382 $main::lxdebug->enter_sub();
1385 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1386 : $self->{format} =~ /postscript/i ? ".ps"
1387 : $self->{format} =~ /opendocument/i ? ".odt"
1388 : $self->{format} =~ /html/i ? ".html"
1391 $main::lxdebug->leave_sub();
1395 sub generate_attachment_filename {
1396 $main::lxdebug->enter_sub();
1399 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1400 my $prefix = $self->get_number_prefix_for_type();
1402 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1403 $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1405 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1406 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1409 $attachment_filename = "";
1412 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1413 $attachment_filename =~ s|[\s/\\]+|_|g;
1415 $main::lxdebug->leave_sub();
1416 return $attachment_filename;
1419 sub generate_email_subject {
1420 $main::lxdebug->enter_sub();
1423 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1424 my $prefix = $self->get_number_prefix_for_type();
1426 if ($subject && $self->{"${prefix}number"}) {
1427 $subject .= " " . $self->{"${prefix}number"}
1430 $main::lxdebug->leave_sub();
1435 $main::lxdebug->enter_sub();
1439 chdir("$self->{tmpdir}");
1442 if (-f "$self->{tmpfile}.err") {
1443 open(FH, "$self->{tmpfile}.err");
1448 if ($self->{tmpfile} && ! $::keep_temp_files) {
1449 $self->{tmpfile} =~ s|.*/||g;
1451 $self->{tmpfile} =~ s/\.\w+$//g;
1452 my $tmpfile = $self->{tmpfile};
1453 unlink(<$tmpfile.*>);
1456 chdir("$self->{cwd}");
1458 $main::lxdebug->leave_sub();
1464 $main::lxdebug->enter_sub();
1466 my ($self, $date, $myconfig) = @_;
1469 if ($date && $date =~ /\D/) {
1471 if ($myconfig->{dateformat} =~ /^yy/) {
1472 ($yy, $mm, $dd) = split /\D/, $date;
1474 if ($myconfig->{dateformat} =~ /^mm/) {
1475 ($mm, $dd, $yy) = split /\D/, $date;
1477 if ($myconfig->{dateformat} =~ /^dd/) {
1478 ($dd, $mm, $yy) = split /\D/, $date;
1483 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1484 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1486 $dd = "0$dd" if ($dd < 10);
1487 $mm = "0$mm" if ($mm < 10);
1489 $date = "$yy$mm$dd";
1492 $main::lxdebug->leave_sub();
1497 # Database routines used throughout
1500 $main::lxdebug->enter_sub(2);
1502 my ($self, $myconfig) = @_;
1504 # connect to database
1506 DBI->connect($myconfig->{dbconnect},
1507 $myconfig->{dbuser}, $myconfig->{dbpasswd})
1511 if ($myconfig->{dboptions}) {
1512 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1515 $main::lxdebug->leave_sub(2);
1520 sub dbconnect_noauto {
1521 $main::lxdebug->enter_sub();
1523 my ($self, $myconfig) = @_;
1525 # connect to database
1527 DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1528 $myconfig->{dbpasswd}, { AutoCommit => 0 })
1532 if ($myconfig->{dboptions}) {
1533 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1536 $main::lxdebug->leave_sub();
1541 sub get_standard_dbh {
1542 $main::lxdebug->enter_sub(2);
1544 my ($self, $myconfig) = @_;
1546 if ($standard_dbh && !$standard_dbh->{Active}) {
1547 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1548 undef $standard_dbh;
1551 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1553 $main::lxdebug->leave_sub(2);
1555 return $standard_dbh;
1559 $main::lxdebug->enter_sub();
1561 my ($self, $date, $myconfig) = @_;
1562 my $dbh = $self->dbconnect($myconfig);
1564 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1565 my $sth = prepare_execute_query($self, $dbh, $query, $date);
1566 my ($closed) = $sth->fetchrow_array;
1568 $main::lxdebug->leave_sub();
1573 sub update_balance {
1574 $main::lxdebug->enter_sub();
1576 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1578 # if we have a value, go do it
1581 # retrieve balance from table
1582 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1583 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1584 my ($balance) = $sth->fetchrow_array;
1590 $query = "UPDATE $table SET $field = $balance WHERE $where";
1591 do_query($self, $dbh, $query, @values);
1593 $main::lxdebug->leave_sub();
1596 sub update_exchangerate {
1597 $main::lxdebug->enter_sub();
1599 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1601 # some sanity check for currency
1603 $main::lxdebug->leave_sub();
1606 $query = qq|SELECT curr FROM defaults|;
1608 my ($currency) = selectrow_query($self, $dbh, $query);
1609 my ($defaultcurrency) = split m/:/, $currency;
1612 if ($curr eq $defaultcurrency) {
1613 $main::lxdebug->leave_sub();
1617 $query = qq|SELECT e.curr FROM exchangerate e
1618 WHERE e.curr = ? AND e.transdate = ?
1620 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1629 $buy = conv_i($buy, "NULL");
1630 $sell = conv_i($sell, "NULL");
1633 if ($buy != 0 && $sell != 0) {
1634 $set = "buy = $buy, sell = $sell";
1635 } elsif ($buy != 0) {
1636 $set = "buy = $buy";
1637 } elsif ($sell != 0) {
1638 $set = "sell = $sell";
1641 if ($sth->fetchrow_array) {
1642 $query = qq|UPDATE exchangerate
1648 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1649 VALUES (?, $buy, $sell, ?)|;
1652 do_query($self, $dbh, $query, $curr, $transdate);
1654 $main::lxdebug->leave_sub();
1657 sub save_exchangerate {
1658 $main::lxdebug->enter_sub();
1660 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1662 my $dbh = $self->dbconnect($myconfig);
1666 $buy = $rate if $fld eq 'buy';
1667 $sell = $rate if $fld eq 'sell';
1670 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1675 $main::lxdebug->leave_sub();
1678 sub get_exchangerate {
1679 $main::lxdebug->enter_sub();
1681 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1684 unless ($transdate) {
1685 $main::lxdebug->leave_sub();
1689 $query = qq|SELECT curr FROM defaults|;
1691 my ($currency) = selectrow_query($self, $dbh, $query);
1692 my ($defaultcurrency) = split m/:/, $currency;
1694 if ($currency eq $defaultcurrency) {
1695 $main::lxdebug->leave_sub();
1699 $query = qq|SELECT e.$fld FROM exchangerate e
1700 WHERE e.curr = ? AND e.transdate = ?|;
1701 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1705 $main::lxdebug->leave_sub();
1707 return $exchangerate;
1710 sub check_exchangerate {
1711 $main::lxdebug->enter_sub();
1713 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1715 if ($fld !~/^buy|sell$/) {
1716 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1719 unless ($transdate) {
1720 $main::lxdebug->leave_sub();
1724 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1726 if ($currency eq $defaultcurrency) {
1727 $main::lxdebug->leave_sub();
1731 my $dbh = $self->get_standard_dbh($myconfig);
1732 my $query = qq|SELECT e.$fld FROM exchangerate e
1733 WHERE e.curr = ? AND e.transdate = ?|;
1735 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1737 $main::lxdebug->leave_sub();
1739 return $exchangerate;
1742 sub get_all_currencies {
1743 $main::lxdebug->enter_sub();
1745 my ($self, $myconfig) = @_;
1746 my $dbh = $self->get_standard_dbh($myconfig);
1748 my $query = qq|SELECT curr FROM defaults|;
1750 my ($curr) = selectrow_query($self, $dbh, $query);
1751 my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
1753 $main::lxdebug->leave_sub();
1758 sub get_default_currency {
1759 $main::lxdebug->enter_sub();
1761 my ($self, $myconfig) = @_;
1762 my @currencies = $self->get_all_currencies($myconfig);
1764 $main::lxdebug->leave_sub();
1766 return $currencies[0];
1769 sub set_payment_options {
1770 $main::lxdebug->enter_sub();
1772 my ($self, $myconfig, $transdate) = @_;
1774 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1776 my $dbh = $self->get_standard_dbh($myconfig);
1779 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1780 qq|FROM payment_terms p | .
1783 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1784 $self->{payment_terms}) =
1785 selectrow_query($self, $dbh, $query, $self->{payment_id});
1787 if ($transdate eq "") {
1788 if ($self->{invdate}) {
1789 $transdate = $self->{invdate};
1791 $transdate = $self->{transdate};
1796 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1797 qq|FROM payment_terms|;
1798 ($self->{netto_date}, $self->{skonto_date}) =
1799 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1801 my ($invtotal, $total);
1802 my (%amounts, %formatted_amounts);
1804 if ($self->{type} =~ /_order$/) {
1805 $amounts{invtotal} = $self->{ordtotal};
1806 $amounts{total} = $self->{ordtotal};
1808 } elsif ($self->{type} =~ /_quotation$/) {
1809 $amounts{invtotal} = $self->{quototal};
1810 $amounts{total} = $self->{quototal};
1813 $amounts{invtotal} = $self->{invtotal};
1814 $amounts{total} = $self->{total};
1817 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1819 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1820 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1821 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1823 foreach (keys %amounts) {
1824 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1825 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1828 if ($self->{"language_id"}) {
1830 qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1831 qq|FROM translation_payment_terms t | .
1832 qq|LEFT JOIN language l ON t.language_id = l.id | .
1833 qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1834 my ($description_long, $output_numberformat, $output_dateformat,
1835 $output_longdates) =
1836 selectrow_query($self, $dbh, $query,
1837 $self->{"language_id"}, $self->{"payment_id"});
1839 $self->{payment_terms} = $description_long if ($description_long);
1841 if ($output_dateformat) {
1842 foreach my $key (qw(netto_date skonto_date)) {
1844 $main::locale->reformat_date($myconfig, $self->{$key},
1850 if ($output_numberformat &&
1851 ($output_numberformat ne $myconfig->{"numberformat"})) {
1852 my $saved_numberformat = $myconfig->{"numberformat"};
1853 $myconfig->{"numberformat"} = $output_numberformat;
1854 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1855 $myconfig->{"numberformat"} = $saved_numberformat;
1859 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1860 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1861 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1862 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1863 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1864 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1865 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1867 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1869 $main::lxdebug->leave_sub();
1873 sub get_template_language {
1874 $main::lxdebug->enter_sub();
1876 my ($self, $myconfig) = @_;
1878 my $template_code = "";
1880 if ($self->{language_id}) {
1881 my $dbh = $self->get_standard_dbh($myconfig);
1882 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1883 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1886 $main::lxdebug->leave_sub();
1888 return $template_code;
1891 sub get_printer_code {
1892 $main::lxdebug->enter_sub();
1894 my ($self, $myconfig) = @_;
1896 my $template_code = "";
1898 if ($self->{printer_id}) {
1899 my $dbh = $self->get_standard_dbh($myconfig);
1900 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1901 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1904 $main::lxdebug->leave_sub();
1906 return $template_code;
1910 $main::lxdebug->enter_sub();
1912 my ($self, $myconfig) = @_;
1914 my $template_code = "";
1916 if ($self->{shipto_id}) {
1917 my $dbh = $self->get_standard_dbh($myconfig);
1918 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1919 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1920 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1923 $main::lxdebug->leave_sub();
1927 $main::lxdebug->enter_sub();
1929 my ($self, $dbh, $id, $module) = @_;
1934 foreach my $item (qw(name department_1 department_2 street zipcode city country
1935 contact phone fax email)) {
1936 if ($self->{"shipto$item"}) {
1937 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1939 push(@values, $self->{"shipto${item}"});
1943 if ($self->{shipto_id}) {
1944 my $query = qq|UPDATE shipto set
1946 shiptodepartment_1 = ?,
1947 shiptodepartment_2 = ?,
1956 WHERE shipto_id = ?|;
1957 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1959 my $query = qq|SELECT * FROM shipto
1960 WHERE shiptoname = ? AND
1961 shiptodepartment_1 = ? AND
1962 shiptodepartment_2 = ? AND
1963 shiptostreet = ? AND
1964 shiptozipcode = ? AND
1966 shiptocountry = ? AND
1967 shiptocontact = ? AND
1973 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1976 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1977 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1978 shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1979 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1980 do_query($self, $dbh, $query, $id, @values, $module);
1985 $main::lxdebug->leave_sub();
1989 $main::lxdebug->enter_sub();
1991 my ($self, $dbh) = @_;
1993 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1995 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1996 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1997 $self->{"employee_id"} *= 1;
1999 $main::lxdebug->leave_sub();
2002 sub get_employee_data {
2003 $main::lxdebug->enter_sub();
2008 Common::check_params(\%params, qw(prefix));
2009 Common::check_params_x(\%params, qw(id));
2012 $main::lxdebug->leave_sub();
2016 my $myconfig = \%main::myconfig;
2017 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
2019 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2022 my $user = User->new($login);
2023 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2025 $self->{$params{prefix} . '_login'} = $login;
2026 $self->{$params{prefix} . '_name'} ||= $login;
2029 $main::lxdebug->leave_sub();
2033 $main::lxdebug->enter_sub();
2035 my ($self, $myconfig, $reference_date) = @_;
2037 $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2039 my $dbh = $self->get_standard_dbh($myconfig);
2040 my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2041 my ($duedate) = selectrow_query($self, $dbh, $query, $self->{payment_id});
2043 $main::lxdebug->leave_sub();
2049 $main::lxdebug->enter_sub();
2051 my ($self, $dbh, $id, $key) = @_;
2053 $key = "all_contacts" unless ($key);
2057 $main::lxdebug->leave_sub();
2062 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2063 qq|FROM contacts | .
2064 qq|WHERE cp_cv_id = ? | .
2065 qq|ORDER BY lower(cp_name)|;
2067 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2069 $main::lxdebug->leave_sub();
2073 $main::lxdebug->enter_sub();
2075 my ($self, $dbh, $key) = @_;
2077 my ($all, $old_id, $where, @values);
2079 if (ref($key) eq "HASH") {
2082 $key = "ALL_PROJECTS";
2084 foreach my $p (keys(%{$params})) {
2086 $all = $params->{$p};
2087 } elsif ($p eq "old_id") {
2088 $old_id = $params->{$p};
2089 } elsif ($p eq "key") {
2090 $key = $params->{$p};
2096 $where = "WHERE active ";
2098 if (ref($old_id) eq "ARRAY") {
2099 my @ids = grep({ $_ } @{$old_id});
2101 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2102 push(@values, @ids);
2105 $where .= " OR (id = ?) ";
2106 push(@values, $old_id);
2112 qq|SELECT id, projectnumber, description, active | .
2115 qq|ORDER BY lower(projectnumber)|;
2117 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2119 $main::lxdebug->leave_sub();
2123 $main::lxdebug->enter_sub();
2125 my ($self, $dbh, $vc_id, $key) = @_;
2127 $key = "all_shipto" unless ($key);
2130 # get shipping addresses
2131 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2133 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2139 $main::lxdebug->leave_sub();
2143 $main::lxdebug->enter_sub();
2145 my ($self, $dbh, $key) = @_;
2147 $key = "all_printers" unless ($key);
2149 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2151 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2153 $main::lxdebug->leave_sub();
2157 $main::lxdebug->enter_sub();
2159 my ($self, $dbh, $params) = @_;
2162 $key = $params->{key};
2163 $key = "all_charts" unless ($key);
2165 my $transdate = quote_db_date($params->{transdate});
2168 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2170 qq|LEFT JOIN taxkeys tk ON | .
2171 qq|(tk.id = (SELECT id FROM taxkeys | .
2172 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2173 qq| ORDER BY startdate DESC LIMIT 1)) | .
2174 qq|ORDER BY c.accno|;
2176 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2178 $main::lxdebug->leave_sub();
2181 sub _get_taxcharts {
2182 $main::lxdebug->enter_sub();
2184 my ($self, $dbh, $params) = @_;
2186 my $key = "all_taxcharts";
2189 if (ref $params eq 'HASH') {
2190 $key = $params->{key} if ($params->{key});
2191 if ($params->{module} eq 'AR') {
2192 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2194 } elsif ($params->{module} eq 'AP') {
2195 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2202 my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2204 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2206 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2208 $main::lxdebug->leave_sub();
2212 $main::lxdebug->enter_sub();
2214 my ($self, $dbh, $key) = @_;
2216 $key = "all_taxzones" unless ($key);
2218 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2220 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2222 $main::lxdebug->leave_sub();
2225 sub _get_employees {
2226 $main::lxdebug->enter_sub();
2228 my ($self, $dbh, $default_key, $key) = @_;
2230 $key = $default_key unless ($key);
2231 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2233 $main::lxdebug->leave_sub();
2236 sub _get_business_types {
2237 $main::lxdebug->enter_sub();
2239 my ($self, $dbh, $key) = @_;
2241 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2242 $options->{key} ||= "all_business_types";
2245 if (exists $options->{salesman}) {
2246 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2249 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2251 $main::lxdebug->leave_sub();
2254 sub _get_languages {
2255 $main::lxdebug->enter_sub();
2257 my ($self, $dbh, $key) = @_;
2259 $key = "all_languages" unless ($key);
2261 my $query = qq|SELECT * FROM language ORDER BY id|;
2263 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2265 $main::lxdebug->leave_sub();
2268 sub _get_dunning_configs {
2269 $main::lxdebug->enter_sub();
2271 my ($self, $dbh, $key) = @_;
2273 $key = "all_dunning_configs" unless ($key);
2275 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2277 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2279 $main::lxdebug->leave_sub();
2282 sub _get_currencies {
2283 $main::lxdebug->enter_sub();
2285 my ($self, $dbh, $key) = @_;
2287 $key = "all_currencies" unless ($key);
2289 my $query = qq|SELECT curr AS currency FROM defaults|;
2291 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2293 $main::lxdebug->leave_sub();
2297 $main::lxdebug->enter_sub();
2299 my ($self, $dbh, $key) = @_;
2301 $key = "all_payments" unless ($key);
2303 my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2305 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2307 $main::lxdebug->leave_sub();
2310 sub _get_customers {
2311 $main::lxdebug->enter_sub();
2313 my ($self, $dbh, $key) = @_;
2315 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2316 $options->{key} ||= "all_customers";
2317 my $limit_clause = "LIMIT $options->{limit}" if $options->{limit};
2318 my $where = $options->{business_is_salesman} ? qq| AND business_id IN (SELECT id FROM business WHERE salesman)| : '';
2320 my $query = qq|SELECT * FROM customer WHERE NOT obsolete $where ORDER BY name $limit_clause|;
2321 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2323 $main::lxdebug->leave_sub();
2327 $main::lxdebug->enter_sub();
2329 my ($self, $dbh, $key) = @_;
2331 $key = "all_vendors" unless ($key);
2333 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2335 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2337 $main::lxdebug->leave_sub();
2340 sub _get_departments {
2341 $main::lxdebug->enter_sub();
2343 my ($self, $dbh, $key) = @_;
2345 $key = "all_departments" unless ($key);
2347 my $query = qq|SELECT * FROM department ORDER BY description|;
2349 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2351 $main::lxdebug->leave_sub();
2354 sub _get_warehouses {
2355 $main::lxdebug->enter_sub();
2357 my ($self, $dbh, $param) = @_;
2359 my ($key, $bins_key);
2361 if ('' eq ref $param) {
2365 $key = $param->{key};
2366 $bins_key = $param->{bins};
2369 my $query = qq|SELECT w.* FROM warehouse w
2370 WHERE (NOT w.invalid) AND
2371 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2372 ORDER BY w.sortkey|;
2374 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2377 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2378 my $sth = prepare_query($self, $dbh, $query);
2380 foreach my $warehouse (@{ $self->{$key} }) {
2381 do_statement($self, $sth, $query, $warehouse->{id});
2382 $warehouse->{$bins_key} = [];
2384 while (my $ref = $sth->fetchrow_hashref()) {
2385 push @{ $warehouse->{$bins_key} }, $ref;
2391 $main::lxdebug->leave_sub();
2395 $main::lxdebug->enter_sub();
2397 my ($self, $dbh, $table, $key, $sortkey) = @_;
2399 my $query = qq|SELECT * FROM $table|;
2400 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2402 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2404 $main::lxdebug->leave_sub();
2408 # $main::lxdebug->enter_sub();
2410 # my ($self, $dbh, $key) = @_;
2412 # $key ||= "all_groups";
2414 # my $groups = $main::auth->read_groups();
2416 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2418 # $main::lxdebug->leave_sub();
2422 $main::lxdebug->enter_sub();
2427 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2428 my ($sth, $query, $ref);
2430 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2431 my $vc_id = $self->{"${vc}_id"};
2433 if ($params{"contacts"}) {
2434 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2437 if ($params{"shipto"}) {
2438 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2441 if ($params{"projects"} || $params{"all_projects"}) {
2442 $self->_get_projects($dbh, $params{"all_projects"} ?
2443 $params{"all_projects"} : $params{"projects"},
2444 $params{"all_projects"} ? 1 : 0);
2447 if ($params{"printers"}) {
2448 $self->_get_printers($dbh, $params{"printers"});
2451 if ($params{"languages"}) {
2452 $self->_get_languages($dbh, $params{"languages"});
2455 if ($params{"charts"}) {
2456 $self->_get_charts($dbh, $params{"charts"});
2459 if ($params{"taxcharts"}) {
2460 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2463 if ($params{"taxzones"}) {
2464 $self->_get_taxzones($dbh, $params{"taxzones"});
2467 if ($params{"employees"}) {
2468 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2471 if ($params{"salesmen"}) {
2472 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2475 if ($params{"business_types"}) {
2476 $self->_get_business_types($dbh, $params{"business_types"});
2479 if ($params{"dunning_configs"}) {
2480 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2483 if($params{"currencies"}) {
2484 $self->_get_currencies($dbh, $params{"currencies"});
2487 if($params{"customers"}) {
2488 $self->_get_customers($dbh, $params{"customers"});
2491 if($params{"vendors"}) {
2492 if (ref $params{"vendors"} eq 'HASH') {
2493 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2495 $self->_get_vendors($dbh, $params{"vendors"});
2499 if($params{"payments"}) {
2500 $self->_get_payments($dbh, $params{"payments"});
2503 if($params{"departments"}) {
2504 $self->_get_departments($dbh, $params{"departments"});
2507 if ($params{price_factors}) {
2508 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2511 if ($params{warehouses}) {
2512 $self->_get_warehouses($dbh, $params{warehouses});
2515 # if ($params{groups}) {
2516 # $self->_get_groups($dbh, $params{groups});
2519 if ($params{partsgroup}) {
2520 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2523 $main::lxdebug->leave_sub();
2526 # this sub gets the id and name from $table
2528 $main::lxdebug->enter_sub();
2530 my ($self, $myconfig, $table) = @_;
2532 # connect to database
2533 my $dbh = $self->get_standard_dbh($myconfig);
2535 $table = $table eq "customer" ? "customer" : "vendor";
2536 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2538 my ($query, @values);
2540 if (!$self->{openinvoices}) {
2542 if ($self->{customernumber} ne "") {
2543 $where = qq|(vc.customernumber ILIKE ?)|;
2544 push(@values, '%' . $self->{customernumber} . '%');
2546 $where = qq|(vc.name ILIKE ?)|;
2547 push(@values, '%' . $self->{$table} . '%');
2551 qq~SELECT vc.id, vc.name,
2552 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2554 WHERE $where AND (NOT vc.obsolete)
2558 qq~SELECT DISTINCT vc.id, vc.name,
2559 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2561 JOIN $table vc ON (a.${table}_id = vc.id)
2562 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2564 push(@values, '%' . $self->{$table} . '%');
2567 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2569 $main::lxdebug->leave_sub();
2571 return scalar(@{ $self->{name_list} });
2574 # the selection sub is used in the AR, AP, IS, IR and OE module
2577 $main::lxdebug->enter_sub();
2579 my ($self, $myconfig, $table, $module) = @_;
2582 my $dbh = $self->get_standard_dbh($myconfig);
2584 $table = $table eq "customer" ? "customer" : "vendor";
2586 my $query = qq|SELECT count(*) FROM $table|;
2587 my ($count) = selectrow_query($self, $dbh, $query);
2589 # build selection list
2590 if ($count <= $myconfig->{vclimit}) {
2591 $query = qq|SELECT id, name, salesman_id
2592 FROM $table WHERE NOT obsolete
2594 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2598 $self->get_employee($dbh);
2600 # setup sales contacts
2601 $query = qq|SELECT e.id, e.name
2603 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2604 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2607 push(@{ $self->{all_employees} },
2608 { id => $self->{employee_id},
2609 name => $self->{employee} });
2611 # sort the whole thing
2612 @{ $self->{all_employees} } =
2613 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2615 if ($module eq 'AR') {
2617 # prepare query for departments
2618 $query = qq|SELECT id, description
2621 ORDER BY description|;
2624 $query = qq|SELECT id, description
2626 ORDER BY description|;
2629 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2632 $query = qq|SELECT id, description
2636 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2639 $query = qq|SELECT printer_description, id
2641 ORDER BY printer_description|;
2643 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2646 $query = qq|SELECT id, description
2650 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2652 $main::lxdebug->leave_sub();
2655 sub language_payment {
2656 $main::lxdebug->enter_sub();
2658 my ($self, $myconfig) = @_;
2660 my $dbh = $self->get_standard_dbh($myconfig);
2662 my $query = qq|SELECT id, description
2666 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2669 $query = qq|SELECT printer_description, id
2671 ORDER BY printer_description|;
2673 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2676 $query = qq|SELECT id, description
2680 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2682 # get buchungsgruppen
2683 $query = qq|SELECT id, description
2684 FROM buchungsgruppen|;
2686 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2688 $main::lxdebug->leave_sub();
2691 # this is only used for reports
2692 sub all_departments {
2693 $main::lxdebug->enter_sub();
2695 my ($self, $myconfig, $table) = @_;
2697 my $dbh = $self->get_standard_dbh($myconfig);
2700 if ($table eq 'customer') {
2701 $where = "WHERE role = 'P' ";
2704 my $query = qq|SELECT id, description
2707 ORDER BY description|;
2708 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2710 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2712 $main::lxdebug->leave_sub();
2716 $main::lxdebug->enter_sub();
2718 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2721 if ($table eq "customer") {
2730 $self->all_vc($myconfig, $table, $module);
2732 # get last customers or vendors
2733 my ($query, $sth, $ref);
2735 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2740 my $transdate = "current_date";
2741 if ($self->{transdate}) {
2742 $transdate = $dbh->quote($self->{transdate});
2745 # now get the account numbers
2746 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2747 FROM chart c, taxkeys tk
2748 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2749 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2752 $sth = $dbh->prepare($query);
2754 do_statement($self, $sth, $query, '%' . $module . '%');
2756 $self->{accounts} = "";
2757 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2759 foreach my $key (split(/:/, $ref->{link})) {
2760 if ($key =~ /\Q$module\E/) {
2762 # cross reference for keys
2763 $xkeyref{ $ref->{accno} } = $key;
2765 push @{ $self->{"${module}_links"}{$key} },
2766 { accno => $ref->{accno},
2767 description => $ref->{description},
2768 taxkey => $ref->{taxkey_id},
2769 tax_id => $ref->{tax_id} };
2771 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2777 # get taxkeys and description
2778 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2779 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2781 if (($module eq "AP") || ($module eq "AR")) {
2782 # get tax rates and description
2783 $query = qq|SELECT * FROM tax|;
2784 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2790 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2791 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2792 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2793 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2795 d.description AS department,
2798 JOIN $table c ON (a.${table}_id = c.id)
2799 LEFT JOIN employee e ON (e.id = a.employee_id)
2800 LEFT JOIN department d ON (d.id = a.department_id)
2802 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2804 foreach my $key (keys %$ref) {
2805 $self->{$key} = $ref->{$key};
2808 my $transdate = "current_date";
2809 if ($self->{transdate}) {
2810 $transdate = $dbh->quote($self->{transdate});
2813 # now get the account numbers
2814 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2816 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2818 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2819 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2822 $sth = $dbh->prepare($query);
2823 do_statement($self, $sth, $query, "%$module%");
2825 $self->{accounts} = "";
2826 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2828 foreach my $key (split(/:/, $ref->{link})) {
2829 if ($key =~ /\Q$module\E/) {
2831 # cross reference for keys
2832 $xkeyref{ $ref->{accno} } = $key;
2834 push @{ $self->{"${module}_links"}{$key} },
2835 { accno => $ref->{accno},
2836 description => $ref->{description},
2837 taxkey => $ref->{taxkey_id},
2838 tax_id => $ref->{tax_id} };
2840 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2846 # get amounts from individual entries
2849 c.accno, c.description,
2850 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2854 LEFT JOIN chart c ON (c.id = a.chart_id)
2855 LEFT JOIN project p ON (p.id = a.project_id)
2856 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2857 WHERE (tk.taxkey_id=a.taxkey) AND
2858 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2859 THEN tk.chart_id = a.chart_id
2862 OR (c.link='%tax%')) AND
2863 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2864 WHERE a.trans_id = ?
2865 AND a.fx_transaction = '0'
2866 ORDER BY a.acc_trans_id, a.transdate|;
2867 $sth = $dbh->prepare($query);
2868 do_statement($self, $sth, $query, $self->{id});
2870 # get exchangerate for currency
2871 $self->{exchangerate} =
2872 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2875 # store amounts in {acc_trans}{$key} for multiple accounts
2876 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2877 $ref->{exchangerate} =
2878 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2879 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2882 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2883 $ref->{amount} *= -1;
2885 $ref->{index} = $index;
2887 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2893 d.curr AS currencies, d.closedto, d.revtrans,
2894 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2895 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2897 $ref = selectfirst_hashref_query($self, $dbh, $query);
2898 map { $self->{$_} = $ref->{$_} } keys %$ref;
2905 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2906 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2907 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2909 $ref = selectfirst_hashref_query($self, $dbh, $query);
2910 map { $self->{$_} = $ref->{$_} } keys %$ref;
2912 if ($self->{"$self->{vc}_id"}) {
2914 # only setup currency
2915 ($self->{currency}) = split(/:/, $self->{currencies});
2919 $self->lastname_used($dbh, $myconfig, $table, $module);
2921 # get exchangerate for currency
2922 $self->{exchangerate} =
2923 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2929 $main::lxdebug->leave_sub();
2933 $main::lxdebug->enter_sub();
2935 my ($self, $dbh, $myconfig, $table, $module) = @_;
2939 $table = $table eq "customer" ? "customer" : "vendor";
2940 my %column_map = ("a.curr" => "currency",
2941 "a.${table}_id" => "${table}_id",
2942 "a.department_id" => "department_id",
2943 "d.description" => "department",
2944 "ct.name" => $table,
2945 "current_date + ct.terms" => "duedate",
2948 if ($self->{type} =~ /delivery_order/) {
2949 $arap = 'delivery_orders';
2950 delete $column_map{"a.curr"};
2952 } elsif ($self->{type} =~ /_order/) {
2954 $where = "quotation = '0'";
2956 } elsif ($self->{type} =~ /_quotation/) {
2958 $where = "quotation = '1'";
2960 } elsif ($table eq 'customer') {
2968 $where = "($where) AND" if ($where);
2969 my $query = qq|SELECT MAX(id) FROM $arap
2970 WHERE $where ${table}_id > 0|;
2971 my ($trans_id) = selectrow_query($self, $dbh, $query);
2974 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2975 $query = qq|SELECT $column_spec
2977 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2978 LEFT JOIN department d ON (a.department_id = d.id)
2980 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2982 map { $self->{$_} = $ref->{$_} } values %column_map;
2984 $main::lxdebug->leave_sub();
2988 $main::lxdebug->enter_sub();
2991 my $myconfig = shift || \%::myconfig;
2992 my ($thisdate, $days) = @_;
2994 my $dbh = $self->get_standard_dbh($myconfig);
2999 my $dateformat = $myconfig->{dateformat};
3000 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3001 $thisdate = $dbh->quote($thisdate);
3002 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3004 $query = qq|SELECT current_date AS thisdate|;
3007 ($thisdate) = selectrow_query($self, $dbh, $query);
3009 $main::lxdebug->leave_sub();
3015 $main::lxdebug->enter_sub();
3017 my ($self, $string) = @_;
3019 if ($string !~ /%/) {
3020 $string = "%$string%";
3023 $string =~ s/\'/\'\'/g;
3025 $main::lxdebug->leave_sub();
3031 $main::lxdebug->enter_sub();
3033 my ($self, $flds, $new, $count, $numrows) = @_;
3037 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3042 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3044 my $j = $item->{ndx} - 1;
3045 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3049 for $i ($count + 1 .. $numrows) {
3050 map { delete $self->{"${_}_$i"} } @{$flds};
3053 $main::lxdebug->leave_sub();
3057 $main::lxdebug->enter_sub();
3059 my ($self, $myconfig) = @_;
3063 my $dbh = $self->dbconnect_noauto($myconfig);
3065 my $query = qq|DELETE FROM status
3066 WHERE (formname = ?) AND (trans_id = ?)|;
3067 my $sth = prepare_query($self, $dbh, $query);
3069 if ($self->{formname} =~ /(check|receipt)/) {
3070 for $i (1 .. $self->{rowcount}) {
3071 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3074 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3078 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3079 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3081 my %queued = split / /, $self->{queued};
3084 if ($self->{formname} =~ /(check|receipt)/) {
3086 # this is a check or receipt, add one entry for each lineitem
3087 my ($accno) = split /--/, $self->{account};
3088 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3089 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3090 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3091 $sth = prepare_query($self, $dbh, $query);
3093 for $i (1 .. $self->{rowcount}) {
3094 if ($self->{"checked_$i"}) {
3095 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3101 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3102 VALUES (?, ?, ?, ?, ?)|;
3103 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3104 $queued{$self->{formname}}, $self->{formname});
3110 $main::lxdebug->leave_sub();
3114 $main::lxdebug->enter_sub();
3116 my ($self, $dbh) = @_;
3118 my ($query, $printed, $emailed);
3120 my $formnames = $self->{printed};
3121 my $emailforms = $self->{emailed};
3123 $query = qq|DELETE FROM status
3124 WHERE (formname = ?) AND (trans_id = ?)|;
3125 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3127 # this only applies to the forms
3128 # checks and receipts are posted when printed or queued
3130 if ($self->{queued}) {
3131 my %queued = split / /, $self->{queued};
3133 foreach my $formname (keys %queued) {
3134 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3135 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3137 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3138 VALUES (?, ?, ?, ?, ?)|;
3139 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3141 $formnames =~ s/\Q$self->{formname}\E//;
3142 $emailforms =~ s/\Q$self->{formname}\E//;
3147 # save printed, emailed info
3148 $formnames =~ s/^ +//g;
3149 $emailforms =~ s/^ +//g;
3152 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3153 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3155 foreach my $formname (keys %status) {
3156 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3157 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3159 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3160 VALUES (?, ?, ?, ?)|;
3161 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3164 $main::lxdebug->leave_sub();
3168 # $main::locale->text('SAVED')
3169 # $main::locale->text('DELETED')
3170 # $main::locale->text('ADDED')
3171 # $main::locale->text('PAYMENT POSTED')
3172 # $main::locale->text('POSTED')
3173 # $main::locale->text('POSTED AS NEW')
3174 # $main::locale->text('ELSE')
3175 # $main::locale->text('SAVED FOR DUNNING')
3176 # $main::locale->text('DUNNING STARTED')
3177 # $main::locale->text('PRINTED')
3178 # $main::locale->text('MAILED')
3179 # $main::locale->text('SCREENED')
3180 # $main::locale->text('CANCELED')
3181 # $main::locale->text('invoice')
3182 # $main::locale->text('proforma')
3183 # $main::locale->text('sales_order')
3184 # $main::locale->text('packing_list')
3185 # $main::locale->text('pick_list')
3186 # $main::locale->text('purchase_order')
3187 # $main::locale->text('bin_list')
3188 # $main::locale->text('sales_quotation')
3189 # $main::locale->text('request_quotation')
3192 $main::lxdebug->enter_sub();
3197 if(!exists $self->{employee_id}) {
3198 &get_employee($self, $dbh);
3202 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3203 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3204 my @values = (conv_i($self->{id}), $self->{login},
3205 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3206 do_query($self, $dbh, $query, @values);
3208 $main::lxdebug->leave_sub();
3212 $main::lxdebug->enter_sub();
3214 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3215 my ($orderBy, $desc) = split(/\-\-/, $order);
3216 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3219 if ($trans_id ne "") {
3221 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 | .
3222 qq|FROM history_erp h | .
3223 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3224 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3227 my $sth = $dbh->prepare($query) || $self->dberror($query);
3229 $sth->execute() || $self->dberror("$query");
3231 while(my $hash_ref = $sth->fetchrow_hashref()) {
3232 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3233 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3234 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3235 $tempArray[$i++] = $hash_ref;
3237 $main::lxdebug->leave_sub() and return \@tempArray
3238 if ($i > 0 && $tempArray[0] ne "");
3240 $main::lxdebug->leave_sub();
3244 sub update_defaults {
3245 $main::lxdebug->enter_sub();
3247 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3250 if ($provided_dbh) {
3251 $dbh = $provided_dbh;
3253 $dbh = $self->dbconnect_noauto($myconfig);
3255 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3256 my $sth = $dbh->prepare($query);
3258 $sth->execute || $self->dberror($query);
3259 my ($var) = $sth->fetchrow_array;
3262 if ($var =~ m/\d+$/) {
3263 my $new_var = (substr $var, $-[0]) * 1 + 1;
3264 my $len_diff = length($var) - $-[0] - length($new_var);
3265 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3271 $query = qq|UPDATE defaults SET $fld = ?|;
3272 do_query($self, $dbh, $query, $var);
3274 if (!$provided_dbh) {
3279 $main::lxdebug->leave_sub();
3284 sub update_business {
3285 $main::lxdebug->enter_sub();
3287 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3290 if ($provided_dbh) {
3291 $dbh = $provided_dbh;
3293 $dbh = $self->dbconnect_noauto($myconfig);
3296 qq|SELECT customernumberinit FROM business
3297 WHERE id = ? FOR UPDATE|;
3298 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3300 return undef unless $var;
3302 if ($var =~ m/\d+$/) {
3303 my $new_var = (substr $var, $-[0]) * 1 + 1;
3304 my $len_diff = length($var) - $-[0] - length($new_var);
3305 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3311 $query = qq|UPDATE business
3312 SET customernumberinit = ?
3314 do_query($self, $dbh, $query, $var, $business_id);
3316 if (!$provided_dbh) {
3321 $main::lxdebug->leave_sub();
3326 sub get_partsgroup {
3327 $main::lxdebug->enter_sub();
3329 my ($self, $myconfig, $p) = @_;
3330 my $target = $p->{target} || 'all_partsgroup';
3332 my $dbh = $self->get_standard_dbh($myconfig);
3334 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3336 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3339 if ($p->{searchitems} eq 'part') {
3340 $query .= qq|WHERE p.inventory_accno_id > 0|;
3342 if ($p->{searchitems} eq 'service') {
3343 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3345 if ($p->{searchitems} eq 'assembly') {
3346 $query .= qq|WHERE p.assembly = '1'|;
3348 if ($p->{searchitems} eq 'labor') {
3349 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3352 $query .= qq|ORDER BY partsgroup|;
3355 $query = qq|SELECT id, partsgroup FROM partsgroup
3356 ORDER BY partsgroup|;
3359 if ($p->{language_code}) {
3360 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3361 t.description AS translation
3363 JOIN parts p ON (p.partsgroup_id = pg.id)
3364 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3365 ORDER BY translation|;
3366 @values = ($p->{language_code});
3369 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3371 $main::lxdebug->leave_sub();
3374 sub get_pricegroup {
3375 $main::lxdebug->enter_sub();
3377 my ($self, $myconfig, $p) = @_;
3379 my $dbh = $self->get_standard_dbh($myconfig);
3381 my $query = qq|SELECT p.id, p.pricegroup
3384 $query .= qq| ORDER BY pricegroup|;
3387 $query = qq|SELECT id, pricegroup FROM pricegroup
3388 ORDER BY pricegroup|;
3391 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3393 $main::lxdebug->leave_sub();
3397 # usage $form->all_years($myconfig, [$dbh])
3398 # return list of all years where bookings found
3401 $main::lxdebug->enter_sub();
3403 my ($self, $myconfig, $dbh) = @_;
3405 $dbh ||= $self->get_standard_dbh($myconfig);
3408 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3409 (SELECT MAX(transdate) FROM acc_trans)|;
3410 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3412 if ($myconfig->{dateformat} =~ /^yy/) {
3413 ($startdate) = split /\W/, $startdate;
3414 ($enddate) = split /\W/, $enddate;
3416 (@_) = split /\W/, $startdate;
3418 (@_) = split /\W/, $enddate;
3423 $startdate = substr($startdate,0,4);
3424 $enddate = substr($enddate,0,4);
3426 while ($enddate >= $startdate) {
3427 push @all_years, $enddate--;
3432 $main::lxdebug->leave_sub();
3436 $main::lxdebug->enter_sub();
3440 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3442 $main::lxdebug->leave_sub();
3446 $main::lxdebug->enter_sub();
3451 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3453 $main::lxdebug->leave_sub();
3462 SL::Form.pm - main data object.
3466 This is the main data object of Lx-Office.
3467 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3468 Points of interest for a beginner are:
3470 - $form->error - renders a generic error in html. accepts an error message
3471 - $form->get_standard_dbh - returns a database connection for the
3473 =head1 SPECIAL FUNCTIONS
3477 =item _store_value()
3479 parses a complex var name, and stores it in the form.
3482 $form->_store_value($key, $value);
3484 keys must start with a string, and can contain various tokens.
3485 supported key structures are:
3488 simple key strings work as expected
3493 separating two keys by a dot (.) will result in a hash lookup for the inner value
3494 this is similar to the behaviour of java and templating mechanisms.
3496 filter.description => $form->{filter}->{description}
3498 3. array+hashref access
3500 adding brackets ([]) before the dot will cause the next hash to be put into an array.
3501 using [+] instead of [] will force a new array index. this is useful for recurring
3502 data structures like part lists. put a [+] into the first varname, and use [] on the
3505 repeating these names in your template:
3508 invoice.items[].parts_id
3512 $form->{invoice}->{items}->[
3526 using brackets at the end of a name will result in a pure array to be created.
3527 note that you mustn't use [+], which is reserved for array+hash access and will
3528 result in undefined behaviour in array context.
3530 filter.status[] => $form->{status}->[ val1, val2, ... ]
3532 =item update_business PARAMS
3535 \%config, - config hashref
3536 $business_id, - business id
3537 $dbh - optional database handle
3539 handles business (thats customer/vendor types) sequences.
3541 special behaviour for empty strings in customerinitnumber field:
3542 will in this case not increase the value, and return undef.