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.0";
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;
776 if (%main::debug_options) {
777 map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
780 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
781 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
782 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
786 $main::lxdebug->leave_sub();
791 sub parse_html_template {
792 $main::lxdebug->enter_sub();
794 my ($self, $file, $additional_params) = @_;
796 $additional_params ||= { };
798 $file = $self->_prepare_html_template($file, $additional_params);
800 my $template = Template->new({ 'INTERPOLATE' => 0,
804 'PLUGIN_BASE' => 'SL::Template::Plugin',
805 'INCLUDE_PATH' => '.:templates/webpages',
808 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
810 my $in = IO::File->new($file, 'r');
813 print STDERR "Error opening template file: $!";
814 $main::lxdebug->leave_sub();
818 my $input = join('', <$in>);
822 $input = $main::locale->{iconv}->convert($input);
826 if (!$template->process(\$input, $additional_params, \$output)) {
827 print STDERR $template->error();
830 $main::lxdebug->leave_sub();
835 sub show_generic_error {
836 $main::lxdebug->enter_sub();
838 my ($self, $error, %params) = @_;
841 'title_error' => $params{title},
842 'label_error' => $error,
845 if ($params{action}) {
848 map { delete($self->{$_}); } qw(action);
849 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
851 $add_params->{SHOW_BUTTON} = 1;
852 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
853 $add_params->{VARIABLES} = \@vars;
855 } elsif ($params{back_button}) {
856 $add_params->{SHOW_BACK_BUTTON} = 1;
859 $self->{title} = $params{title} if $params{title};
862 print $self->parse_html_template("generic/error", $add_params);
864 $main::lxdebug->leave_sub();
866 die("Error: $error\n");
869 sub show_generic_information {
870 $main::lxdebug->enter_sub();
872 my ($self, $text, $title) = @_;
875 'title_information' => $title,
876 'label_information' => $text,
879 $self->{title} = $title if ($title);
882 print $self->parse_html_template("generic/information", $add_params);
884 $main::lxdebug->leave_sub();
886 die("Information: $text\n");
889 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
890 # changed it to accept an arbitrary number of triggers - sschoeling
892 $main::lxdebug->enter_sub();
895 my $myconfig = shift;
898 # set dateform for jsscript
901 "dd.mm.yy" => "%d.%m.%Y",
902 "dd-mm-yy" => "%d-%m-%Y",
903 "dd/mm/yy" => "%d/%m/%Y",
904 "mm/dd/yy" => "%m/%d/%Y",
905 "mm-dd-yy" => "%m-%d-%Y",
906 "yyyy-mm-dd" => "%Y-%m-%d",
909 my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
910 $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
917 inputField : "| . (shift) . qq|",
918 ifFormat :"$ifFormat",
919 align : "| . (shift) . qq|",
920 button : "| . (shift) . qq|"
926 <script type="text/javascript">
927 <!--| . join("", @triggers) . qq|//-->
931 $main::lxdebug->leave_sub();
934 } #end sub write_trigger
937 $main::lxdebug->enter_sub();
939 my ($self, $msg) = @_;
941 if ($self->{callback}) {
943 my ($script, $argv) = split(/\?/, $self->{callback}, 2);
945 $script =~ s|[^a-zA-Z0-9_\.]||g;
946 exec("perl", "$script", $argv);
954 $main::lxdebug->leave_sub();
957 # sort of columns removed - empty sub
959 $main::lxdebug->enter_sub();
961 my ($self, @columns) = @_;
963 $main::lxdebug->leave_sub();
969 $main::lxdebug->enter_sub(2);
971 my ($self, $myconfig, $amount, $places, $dash) = @_;
977 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
979 my $neg = ($amount =~ s/^-//);
980 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
982 if (defined($places) && ($places ne '')) {
988 my ($actual_places) = ($amount =~ /\.(\d+)/);
989 $actual_places = length($actual_places);
990 $places = $actual_places > $places ? $actual_places : $places;
993 $amount = $self->round_amount($amount, $places);
996 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
997 my @p = split(/\./, $amount); # split amount at decimal point
999 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
1002 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
1005 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
1006 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1007 ($neg ? "-$amount" : "$amount" ) ;
1011 $main::lxdebug->leave_sub(2);
1015 sub format_amount_units {
1016 $main::lxdebug->enter_sub();
1021 my $myconfig = \%main::myconfig;
1022 my $amount = $params{amount} * 1;
1023 my $places = $params{places};
1024 my $part_unit_name = $params{part_unit};
1025 my $amount_unit_name = $params{amount_unit};
1026 my $conv_units = $params{conv_units};
1027 my $max_places = $params{max_places};
1029 if (!$part_unit_name) {
1030 $main::lxdebug->leave_sub();
1034 AM->retrieve_all_units();
1035 my $all_units = $main::all_units;
1037 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1038 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1041 if (!scalar @{ $conv_units }) {
1042 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1043 $main::lxdebug->leave_sub();
1047 my $part_unit = $all_units->{$part_unit_name};
1048 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1050 $amount *= $conv_unit->{factor};
1055 foreach my $unit (@$conv_units) {
1056 my $last = $unit->{name} eq $part_unit->{name};
1058 $num = int($amount / $unit->{factor});
1059 $amount -= $num * $unit->{factor};
1062 if ($last ? $amount : $num) {
1063 push @values, { "unit" => $unit->{name},
1064 "amount" => $last ? $amount / $unit->{factor} : $num,
1065 "places" => $last ? $places : 0 };
1072 push @values, { "unit" => $part_unit_name,
1077 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1079 $main::lxdebug->leave_sub();
1085 $main::lxdebug->enter_sub(2);
1090 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1091 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1092 $input =~ s/\#\#/\#/g;
1094 $main::lxdebug->leave_sub(2);
1102 $main::lxdebug->enter_sub(2);
1104 my ($self, $myconfig, $amount) = @_;
1106 if ( ($myconfig->{numberformat} eq '1.000,00')
1107 || ($myconfig->{numberformat} eq '1000,00')) {
1112 if ($myconfig->{numberformat} eq "1'000.00") {
1118 $main::lxdebug->leave_sub(2);
1120 return ($amount * 1);
1124 $main::lxdebug->enter_sub(2);
1126 my ($self, $amount, $places) = @_;
1129 # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
1131 # Round amounts to eight places before rounding to the requested
1132 # number of places. This gets rid of errors due to internal floating
1133 # point representation.
1134 $amount = $self->round_amount($amount, 8) if $places < 8;
1135 $amount = $amount * (10**($places));
1136 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1138 $main::lxdebug->leave_sub(2);
1140 return $round_amount;
1144 sub parse_template {
1145 $main::lxdebug->enter_sub();
1147 my ($self, $myconfig, $userspath) = @_;
1148 my ($template, $out);
1152 $self->{"cwd"} = getcwd();
1153 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1157 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1158 $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1159 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
1161 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1162 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1163 $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1164 $ext_for_format = 'pdf';
1166 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1167 $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1168 $ext_for_format = 'html';
1170 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1171 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1172 $ext_for_format = 'xml';
1174 } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1175 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1177 } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1178 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1180 } elsif ( defined $self->{'format'}) {
1181 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1183 } elsif ( $self->{'format'} eq '' ) {
1184 $self->error("No Outputformat given: $self->{'format'}");
1186 } else { #Catch the rest
1187 $self->error("Outputformat not defined: $self->{'format'}");
1190 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1191 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1193 if (!$self->{employee_id}) {
1194 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1197 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1199 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1201 # OUT is used for the media, screen, printer, email
1202 # for postscript we store a copy in a temporary file
1204 my $prepend_userspath;
1206 if (!$self->{tmpfile}) {
1207 $self->{tmpfile} = "${fileid}.$self->{IN}";
1208 $prepend_userspath = 1;
1211 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1213 $self->{tmpfile} =~ s|.*/||;
1214 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1215 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1217 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1218 $out = $self->{OUT};
1219 $self->{OUT} = ">$self->{tmpfile}";
1223 open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1225 open(OUT, ">-") or $self->error("STDOUT : $!");
1229 if (!$template->parse(*OUT)) {
1231 $self->error("$self->{IN} : " . $template->get_error());
1236 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1238 if ($self->{media} eq 'email') {
1240 my $mail = new Mailer;
1242 map { $mail->{$_} = $self->{$_} }
1243 qw(cc bcc subject message version format);
1244 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1245 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1246 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1247 $mail->{fileid} = "$fileid.";
1248 $myconfig->{signature} =~ s/\r//g;
1250 # if we send html or plain text inline
1251 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1252 $mail->{contenttype} = "text/html";
1254 $mail->{message} =~ s/\r//g;
1255 $mail->{message} =~ s/\n/<br>\n/g;
1256 $myconfig->{signature} =~ s/\n/<br>\n/g;
1257 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1259 open(IN, $self->{tmpfile})
1260 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1262 $mail->{message} .= $_;
1269 if (!$self->{"do_not_attach"}) {
1270 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1271 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1272 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1273 "name" => $attachment_name }];
1276 $mail->{message} =~ s/\r//g;
1277 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1281 my $err = $mail->send();
1282 $self->error($self->cleanup . "$err") if ($err);
1286 $self->{OUT} = $out;
1288 my $numbytes = (-s $self->{tmpfile});
1289 open(IN, $self->{tmpfile})
1290 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1292 $self->{copies} = 1 unless $self->{media} eq 'printer';
1294 chdir("$self->{cwd}");
1295 #print(STDERR "Kopien $self->{copies}\n");
1296 #print(STDERR "OUT $self->{OUT}\n");
1297 for my $i (1 .. $self->{copies}) {
1299 open(OUT, $self->{OUT})
1300 or $self->error($self->cleanup . "$self->{OUT} : $!");
1302 $self->{attachment_filename} = ($self->{attachment_filename})
1303 ? $self->{attachment_filename}
1304 : $self->generate_attachment_filename();
1306 # launch application
1307 print qq|Content-Type: | . $template->get_mime_type() . qq|
1308 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1309 Content-Length: $numbytes
1313 open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1334 chdir("$self->{cwd}");
1335 $main::lxdebug->leave_sub();
1338 sub get_formname_translation {
1339 $main::lxdebug->enter_sub();
1340 my ($self, $formname) = @_;
1342 $formname ||= $self->{formname};
1344 my %formname_translations = (
1345 bin_list => $main::locale->text('Bin List'),
1346 credit_note => $main::locale->text('Credit Note'),
1347 invoice => $main::locale->text('Invoice'),
1348 packing_list => $main::locale->text('Packing List'),
1349 pick_list => $main::locale->text('Pick List'),
1350 proforma => $main::locale->text('Proforma Invoice'),
1351 purchase_order => $main::locale->text('Purchase Order'),
1352 request_quotation => $main::locale->text('RFQ'),
1353 sales_order => $main::locale->text('Confirmation'),
1354 sales_quotation => $main::locale->text('Quotation'),
1355 storno_invoice => $main::locale->text('Storno Invoice'),
1356 storno_packing_list => $main::locale->text('Storno Packing List'),
1357 sales_delivery_order => $main::locale->text('Delivery Order'),
1358 purchase_delivery_order => $main::locale->text('Delivery Order'),
1359 dunning => $main::locale->text('Dunning'),
1362 $main::lxdebug->leave_sub();
1363 return $formname_translations{$formname}
1366 sub get_number_prefix_for_type {
1367 $main::lxdebug->enter_sub();
1371 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1372 : ($self->{type} =~ /_quotation$/) ? 'quo'
1373 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1376 $main::lxdebug->leave_sub();
1380 sub get_extension_for_format {
1381 $main::lxdebug->enter_sub();
1384 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1385 : $self->{format} =~ /postscript/i ? ".ps"
1386 : $self->{format} =~ /opendocument/i ? ".odt"
1387 : $self->{format} =~ /html/i ? ".html"
1390 $main::lxdebug->leave_sub();
1394 sub generate_attachment_filename {
1395 $main::lxdebug->enter_sub();
1398 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1399 my $prefix = $self->get_number_prefix_for_type();
1401 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1402 $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1404 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1405 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1408 $attachment_filename = "";
1411 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1412 $attachment_filename =~ s|[\s/\\]+|_|g;
1414 $main::lxdebug->leave_sub();
1415 return $attachment_filename;
1418 sub generate_email_subject {
1419 $main::lxdebug->enter_sub();
1422 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1423 my $prefix = $self->get_number_prefix_for_type();
1425 if ($subject && $self->{"${prefix}number"}) {
1426 $subject .= " " . $self->{"${prefix}number"}
1429 $main::lxdebug->leave_sub();
1434 $main::lxdebug->enter_sub();
1438 chdir("$self->{tmpdir}");
1441 if (-f "$self->{tmpfile}.err") {
1442 open(FH, "$self->{tmpfile}.err");
1447 if ($self->{tmpfile} && ! $::keep_temp_files) {
1448 $self->{tmpfile} =~ s|.*/||g;
1450 $self->{tmpfile} =~ s/\.\w+$//g;
1451 my $tmpfile = $self->{tmpfile};
1452 unlink(<$tmpfile.*>);
1455 chdir("$self->{cwd}");
1457 $main::lxdebug->leave_sub();
1463 $main::lxdebug->enter_sub();
1465 my ($self, $date, $myconfig) = @_;
1468 if ($date && $date =~ /\D/) {
1470 if ($myconfig->{dateformat} =~ /^yy/) {
1471 ($yy, $mm, $dd) = split /\D/, $date;
1473 if ($myconfig->{dateformat} =~ /^mm/) {
1474 ($mm, $dd, $yy) = split /\D/, $date;
1476 if ($myconfig->{dateformat} =~ /^dd/) {
1477 ($dd, $mm, $yy) = split /\D/, $date;
1482 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1483 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1485 $dd = "0$dd" if ($dd < 10);
1486 $mm = "0$mm" if ($mm < 10);
1488 $date = "$yy$mm$dd";
1491 $main::lxdebug->leave_sub();
1496 # Database routines used throughout
1499 $main::lxdebug->enter_sub(2);
1501 my ($self, $myconfig) = @_;
1503 # connect to database
1505 DBI->connect($myconfig->{dbconnect},
1506 $myconfig->{dbuser}, $myconfig->{dbpasswd})
1510 if ($myconfig->{dboptions}) {
1511 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1514 $main::lxdebug->leave_sub(2);
1519 sub dbconnect_noauto {
1520 $main::lxdebug->enter_sub();
1522 my ($self, $myconfig) = @_;
1524 # connect to database
1526 DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1527 $myconfig->{dbpasswd}, { AutoCommit => 0 })
1531 if ($myconfig->{dboptions}) {
1532 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1535 $main::lxdebug->leave_sub();
1540 sub get_standard_dbh {
1541 $main::lxdebug->enter_sub(2);
1543 my ($self, $myconfig) = @_;
1545 if ($standard_dbh && !$standard_dbh->{Active}) {
1546 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1547 undef $standard_dbh;
1550 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1552 $main::lxdebug->leave_sub(2);
1554 return $standard_dbh;
1558 $main::lxdebug->enter_sub();
1560 my ($self, $date, $myconfig) = @_;
1561 my $dbh = $self->dbconnect($myconfig);
1563 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1564 my $sth = prepare_execute_query($self, $dbh, $query, $date);
1565 my ($closed) = $sth->fetchrow_array;
1567 $main::lxdebug->leave_sub();
1572 sub update_balance {
1573 $main::lxdebug->enter_sub();
1575 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1577 # if we have a value, go do it
1580 # retrieve balance from table
1581 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1582 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1583 my ($balance) = $sth->fetchrow_array;
1589 $query = "UPDATE $table SET $field = $balance WHERE $where";
1590 do_query($self, $dbh, $query, @values);
1592 $main::lxdebug->leave_sub();
1595 sub update_exchangerate {
1596 $main::lxdebug->enter_sub();
1598 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1600 # some sanity check for currency
1602 $main::lxdebug->leave_sub();
1605 $query = qq|SELECT curr FROM defaults|;
1607 my ($currency) = selectrow_query($self, $dbh, $query);
1608 my ($defaultcurrency) = split m/:/, $currency;
1611 if ($curr eq $defaultcurrency) {
1612 $main::lxdebug->leave_sub();
1616 $query = qq|SELECT e.curr FROM exchangerate e
1617 WHERE e.curr = ? AND e.transdate = ?
1619 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1628 $buy = conv_i($buy, "NULL");
1629 $sell = conv_i($sell, "NULL");
1632 if ($buy != 0 && $sell != 0) {
1633 $set = "buy = $buy, sell = $sell";
1634 } elsif ($buy != 0) {
1635 $set = "buy = $buy";
1636 } elsif ($sell != 0) {
1637 $set = "sell = $sell";
1640 if ($sth->fetchrow_array) {
1641 $query = qq|UPDATE exchangerate
1647 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1648 VALUES (?, $buy, $sell, ?)|;
1651 do_query($self, $dbh, $query, $curr, $transdate);
1653 $main::lxdebug->leave_sub();
1656 sub save_exchangerate {
1657 $main::lxdebug->enter_sub();
1659 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1661 my $dbh = $self->dbconnect($myconfig);
1665 $buy = $rate if $fld eq 'buy';
1666 $sell = $rate if $fld eq 'sell';
1669 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1674 $main::lxdebug->leave_sub();
1677 sub get_exchangerate {
1678 $main::lxdebug->enter_sub();
1680 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1683 unless ($transdate) {
1684 $main::lxdebug->leave_sub();
1688 $query = qq|SELECT curr FROM defaults|;
1690 my ($currency) = selectrow_query($self, $dbh, $query);
1691 my ($defaultcurrency) = split m/:/, $currency;
1693 if ($currency eq $defaultcurrency) {
1694 $main::lxdebug->leave_sub();
1698 $query = qq|SELECT e.$fld FROM exchangerate e
1699 WHERE e.curr = ? AND e.transdate = ?|;
1700 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1704 $main::lxdebug->leave_sub();
1706 return $exchangerate;
1709 sub check_exchangerate {
1710 $main::lxdebug->enter_sub();
1712 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1714 if ($fld !~/^buy|sell$/) {
1715 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1718 unless ($transdate) {
1719 $main::lxdebug->leave_sub();
1723 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1725 if ($currency eq $defaultcurrency) {
1726 $main::lxdebug->leave_sub();
1730 my $dbh = $self->get_standard_dbh($myconfig);
1731 my $query = qq|SELECT e.$fld FROM exchangerate e
1732 WHERE e.curr = ? AND e.transdate = ?|;
1734 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1736 $main::lxdebug->leave_sub();
1738 return $exchangerate;
1741 sub get_all_currencies {
1742 $main::lxdebug->enter_sub();
1744 my ($self, $myconfig) = @_;
1745 my $dbh = $self->get_standard_dbh($myconfig);
1747 my $query = qq|SELECT curr FROM defaults|;
1749 my ($curr) = selectrow_query($self, $dbh, $query);
1750 my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
1752 $main::lxdebug->leave_sub();
1757 sub get_default_currency {
1758 $main::lxdebug->enter_sub();
1760 my ($self, $myconfig) = @_;
1761 my @currencies = $self->get_all_currencies($myconfig);
1763 $main::lxdebug->leave_sub();
1765 return $currencies[0];
1768 sub set_payment_options {
1769 $main::lxdebug->enter_sub();
1771 my ($self, $myconfig, $transdate) = @_;
1773 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1775 my $dbh = $self->get_standard_dbh($myconfig);
1778 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1779 qq|FROM payment_terms p | .
1782 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1783 $self->{payment_terms}) =
1784 selectrow_query($self, $dbh, $query, $self->{payment_id});
1786 if ($transdate eq "") {
1787 if ($self->{invdate}) {
1788 $transdate = $self->{invdate};
1790 $transdate = $self->{transdate};
1795 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1796 qq|FROM payment_terms|;
1797 ($self->{netto_date}, $self->{skonto_date}) =
1798 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1800 my ($invtotal, $total);
1801 my (%amounts, %formatted_amounts);
1803 if ($self->{type} =~ /_order$/) {
1804 $amounts{invtotal} = $self->{ordtotal};
1805 $amounts{total} = $self->{ordtotal};
1807 } elsif ($self->{type} =~ /_quotation$/) {
1808 $amounts{invtotal} = $self->{quototal};
1809 $amounts{total} = $self->{quototal};
1812 $amounts{invtotal} = $self->{invtotal};
1813 $amounts{total} = $self->{total};
1816 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1818 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1819 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1820 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1822 foreach (keys %amounts) {
1823 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1824 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1827 if ($self->{"language_id"}) {
1829 qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1830 qq|FROM translation_payment_terms t | .
1831 qq|LEFT JOIN language l ON t.language_id = l.id | .
1832 qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1833 my ($description_long, $output_numberformat, $output_dateformat,
1834 $output_longdates) =
1835 selectrow_query($self, $dbh, $query,
1836 $self->{"language_id"}, $self->{"payment_id"});
1838 $self->{payment_terms} = $description_long if ($description_long);
1840 if ($output_dateformat) {
1841 foreach my $key (qw(netto_date skonto_date)) {
1843 $main::locale->reformat_date($myconfig, $self->{$key},
1849 if ($output_numberformat &&
1850 ($output_numberformat ne $myconfig->{"numberformat"})) {
1851 my $saved_numberformat = $myconfig->{"numberformat"};
1852 $myconfig->{"numberformat"} = $output_numberformat;
1853 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1854 $myconfig->{"numberformat"} = $saved_numberformat;
1858 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1859 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1860 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1861 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1862 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1863 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1864 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1866 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1868 $main::lxdebug->leave_sub();
1872 sub get_template_language {
1873 $main::lxdebug->enter_sub();
1875 my ($self, $myconfig) = @_;
1877 my $template_code = "";
1879 if ($self->{language_id}) {
1880 my $dbh = $self->get_standard_dbh($myconfig);
1881 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1882 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1885 $main::lxdebug->leave_sub();
1887 return $template_code;
1890 sub get_printer_code {
1891 $main::lxdebug->enter_sub();
1893 my ($self, $myconfig) = @_;
1895 my $template_code = "";
1897 if ($self->{printer_id}) {
1898 my $dbh = $self->get_standard_dbh($myconfig);
1899 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1900 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1903 $main::lxdebug->leave_sub();
1905 return $template_code;
1909 $main::lxdebug->enter_sub();
1911 my ($self, $myconfig) = @_;
1913 my $template_code = "";
1915 if ($self->{shipto_id}) {
1916 my $dbh = $self->get_standard_dbh($myconfig);
1917 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1918 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1919 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1922 $main::lxdebug->leave_sub();
1926 $main::lxdebug->enter_sub();
1928 my ($self, $dbh, $id, $module) = @_;
1933 foreach my $item (qw(name department_1 department_2 street zipcode city country
1934 contact phone fax email)) {
1935 if ($self->{"shipto$item"}) {
1936 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1938 push(@values, $self->{"shipto${item}"});
1942 if ($self->{shipto_id}) {
1943 my $query = qq|UPDATE shipto set
1945 shiptodepartment_1 = ?,
1946 shiptodepartment_2 = ?,
1955 WHERE shipto_id = ?|;
1956 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1958 my $query = qq|SELECT * FROM shipto
1959 WHERE shiptoname = ? AND
1960 shiptodepartment_1 = ? AND
1961 shiptodepartment_2 = ? AND
1962 shiptostreet = ? AND
1963 shiptozipcode = ? AND
1965 shiptocountry = ? AND
1966 shiptocontact = ? AND
1972 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1975 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1976 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1977 shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1978 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1979 do_query($self, $dbh, $query, $id, @values, $module);
1984 $main::lxdebug->leave_sub();
1988 $main::lxdebug->enter_sub();
1990 my ($self, $dbh) = @_;
1992 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1994 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1995 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1996 $self->{"employee_id"} *= 1;
1998 $main::lxdebug->leave_sub();
2001 sub get_employee_data {
2002 $main::lxdebug->enter_sub();
2007 Common::check_params(\%params, qw(prefix));
2008 Common::check_params_x(\%params, qw(id));
2011 $main::lxdebug->leave_sub();
2015 my $myconfig = \%main::myconfig;
2016 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
2018 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2021 my $user = User->new($login);
2022 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2024 $self->{$params{prefix} . '_login'} = $login;
2025 $self->{$params{prefix} . '_name'} ||= $login;
2028 $main::lxdebug->leave_sub();
2032 $main::lxdebug->enter_sub();
2034 my ($self, $myconfig, $reference_date) = @_;
2036 $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2038 my $dbh = $self->get_standard_dbh($myconfig);
2039 my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2040 my ($duedate) = selectrow_query($self, $dbh, $query, $self->{payment_id});
2042 $main::lxdebug->leave_sub();
2048 $main::lxdebug->enter_sub();
2050 my ($self, $dbh, $id, $key) = @_;
2052 $key = "all_contacts" unless ($key);
2056 $main::lxdebug->leave_sub();
2061 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2062 qq|FROM contacts | .
2063 qq|WHERE cp_cv_id = ? | .
2064 qq|ORDER BY lower(cp_name)|;
2066 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2068 $main::lxdebug->leave_sub();
2072 $main::lxdebug->enter_sub();
2074 my ($self, $dbh, $key) = @_;
2076 my ($all, $old_id, $where, @values);
2078 if (ref($key) eq "HASH") {
2081 $key = "ALL_PROJECTS";
2083 foreach my $p (keys(%{$params})) {
2085 $all = $params->{$p};
2086 } elsif ($p eq "old_id") {
2087 $old_id = $params->{$p};
2088 } elsif ($p eq "key") {
2089 $key = $params->{$p};
2095 $where = "WHERE active ";
2097 if (ref($old_id) eq "ARRAY") {
2098 my @ids = grep({ $_ } @{$old_id});
2100 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2101 push(@values, @ids);
2104 $where .= " OR (id = ?) ";
2105 push(@values, $old_id);
2111 qq|SELECT id, projectnumber, description, active | .
2114 qq|ORDER BY lower(projectnumber)|;
2116 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2118 $main::lxdebug->leave_sub();
2122 $main::lxdebug->enter_sub();
2124 my ($self, $dbh, $vc_id, $key) = @_;
2126 $key = "all_shipto" unless ($key);
2129 # get shipping addresses
2130 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2132 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2138 $main::lxdebug->leave_sub();
2142 $main::lxdebug->enter_sub();
2144 my ($self, $dbh, $key) = @_;
2146 $key = "all_printers" unless ($key);
2148 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2150 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2152 $main::lxdebug->leave_sub();
2156 $main::lxdebug->enter_sub();
2158 my ($self, $dbh, $params) = @_;
2161 $key = $params->{key};
2162 $key = "all_charts" unless ($key);
2164 my $transdate = quote_db_date($params->{transdate});
2167 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2169 qq|LEFT JOIN taxkeys tk ON | .
2170 qq|(tk.id = (SELECT id FROM taxkeys | .
2171 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2172 qq| ORDER BY startdate DESC LIMIT 1)) | .
2173 qq|ORDER BY c.accno|;
2175 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2177 $main::lxdebug->leave_sub();
2180 sub _get_taxcharts {
2181 $main::lxdebug->enter_sub();
2183 my ($self, $dbh, $params) = @_;
2185 my $key = "all_taxcharts";
2188 if (ref $params eq 'HASH') {
2189 $key = $params->{key} if ($params->{key});
2190 if ($params->{module} eq 'AR') {
2191 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2193 } elsif ($params->{module} eq 'AP') {
2194 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2201 my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2203 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2205 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2207 $main::lxdebug->leave_sub();
2211 $main::lxdebug->enter_sub();
2213 my ($self, $dbh, $key) = @_;
2215 $key = "all_taxzones" unless ($key);
2217 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2219 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2221 $main::lxdebug->leave_sub();
2224 sub _get_employees {
2225 $main::lxdebug->enter_sub();
2227 my ($self, $dbh, $default_key, $key) = @_;
2229 $key = $default_key unless ($key);
2230 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2232 $main::lxdebug->leave_sub();
2235 sub _get_business_types {
2236 $main::lxdebug->enter_sub();
2238 my ($self, $dbh, $key) = @_;
2240 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2241 $options->{key} ||= "all_business_types";
2244 if (exists $options->{salesman}) {
2245 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2248 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2250 $main::lxdebug->leave_sub();
2253 sub _get_languages {
2254 $main::lxdebug->enter_sub();
2256 my ($self, $dbh, $key) = @_;
2258 $key = "all_languages" unless ($key);
2260 my $query = qq|SELECT * FROM language ORDER BY id|;
2262 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2264 $main::lxdebug->leave_sub();
2267 sub _get_dunning_configs {
2268 $main::lxdebug->enter_sub();
2270 my ($self, $dbh, $key) = @_;
2272 $key = "all_dunning_configs" unless ($key);
2274 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2276 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2278 $main::lxdebug->leave_sub();
2281 sub _get_currencies {
2282 $main::lxdebug->enter_sub();
2284 my ($self, $dbh, $key) = @_;
2286 $key = "all_currencies" unless ($key);
2288 my $query = qq|SELECT curr AS currency FROM defaults|;
2290 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2292 $main::lxdebug->leave_sub();
2296 $main::lxdebug->enter_sub();
2298 my ($self, $dbh, $key) = @_;
2300 $key = "all_payments" unless ($key);
2302 my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2304 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2306 $main::lxdebug->leave_sub();
2309 sub _get_customers {
2310 $main::lxdebug->enter_sub();
2312 my ($self, $dbh, $key) = @_;
2314 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2315 $options->{key} ||= "all_customers";
2316 my $limit_clause = "LIMIT $options->{limit}" if $options->{limit};
2317 my $where = $options->{business_is_salesman} ? qq| AND business_id IN (SELECT id FROM business WHERE salesman)| : '';
2319 my $query = qq|SELECT * FROM customer WHERE NOT obsolete $where ORDER BY name $limit_clause|;
2320 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2322 $main::lxdebug->leave_sub();
2326 $main::lxdebug->enter_sub();
2328 my ($self, $dbh, $key) = @_;
2330 $key = "all_vendors" unless ($key);
2332 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2334 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2336 $main::lxdebug->leave_sub();
2339 sub _get_departments {
2340 $main::lxdebug->enter_sub();
2342 my ($self, $dbh, $key) = @_;
2344 $key = "all_departments" unless ($key);
2346 my $query = qq|SELECT * FROM department ORDER BY description|;
2348 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2350 $main::lxdebug->leave_sub();
2353 sub _get_warehouses {
2354 $main::lxdebug->enter_sub();
2356 my ($self, $dbh, $param) = @_;
2358 my ($key, $bins_key);
2360 if ('' eq ref $param) {
2364 $key = $param->{key};
2365 $bins_key = $param->{bins};
2368 my $query = qq|SELECT w.* FROM warehouse w
2369 WHERE (NOT w.invalid) AND
2370 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2371 ORDER BY w.sortkey|;
2373 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2376 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2377 my $sth = prepare_query($self, $dbh, $query);
2379 foreach my $warehouse (@{ $self->{$key} }) {
2380 do_statement($self, $sth, $query, $warehouse->{id});
2381 $warehouse->{$bins_key} = [];
2383 while (my $ref = $sth->fetchrow_hashref()) {
2384 push @{ $warehouse->{$bins_key} }, $ref;
2390 $main::lxdebug->leave_sub();
2394 $main::lxdebug->enter_sub();
2396 my ($self, $dbh, $table, $key, $sortkey) = @_;
2398 my $query = qq|SELECT * FROM $table|;
2399 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2401 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2403 $main::lxdebug->leave_sub();
2407 # $main::lxdebug->enter_sub();
2409 # my ($self, $dbh, $key) = @_;
2411 # $key ||= "all_groups";
2413 # my $groups = $main::auth->read_groups();
2415 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2417 # $main::lxdebug->leave_sub();
2421 $main::lxdebug->enter_sub();
2426 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2427 my ($sth, $query, $ref);
2429 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2430 my $vc_id = $self->{"${vc}_id"};
2432 if ($params{"contacts"}) {
2433 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2436 if ($params{"shipto"}) {
2437 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2440 if ($params{"projects"} || $params{"all_projects"}) {
2441 $self->_get_projects($dbh, $params{"all_projects"} ?
2442 $params{"all_projects"} : $params{"projects"},
2443 $params{"all_projects"} ? 1 : 0);
2446 if ($params{"printers"}) {
2447 $self->_get_printers($dbh, $params{"printers"});
2450 if ($params{"languages"}) {
2451 $self->_get_languages($dbh, $params{"languages"});
2454 if ($params{"charts"}) {
2455 $self->_get_charts($dbh, $params{"charts"});
2458 if ($params{"taxcharts"}) {
2459 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2462 if ($params{"taxzones"}) {
2463 $self->_get_taxzones($dbh, $params{"taxzones"});
2466 if ($params{"employees"}) {
2467 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2470 if ($params{"salesmen"}) {
2471 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2474 if ($params{"business_types"}) {
2475 $self->_get_business_types($dbh, $params{"business_types"});
2478 if ($params{"dunning_configs"}) {
2479 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2482 if($params{"currencies"}) {
2483 $self->_get_currencies($dbh, $params{"currencies"});
2486 if($params{"customers"}) {
2487 $self->_get_customers($dbh, $params{"customers"});
2490 if($params{"vendors"}) {
2491 if (ref $params{"vendors"} eq 'HASH') {
2492 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2494 $self->_get_vendors($dbh, $params{"vendors"});
2498 if($params{"payments"}) {
2499 $self->_get_payments($dbh, $params{"payments"});
2502 if($params{"departments"}) {
2503 $self->_get_departments($dbh, $params{"departments"});
2506 if ($params{price_factors}) {
2507 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2510 if ($params{warehouses}) {
2511 $self->_get_warehouses($dbh, $params{warehouses});
2514 # if ($params{groups}) {
2515 # $self->_get_groups($dbh, $params{groups});
2518 if ($params{partsgroup}) {
2519 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2522 $main::lxdebug->leave_sub();
2525 # this sub gets the id and name from $table
2527 $main::lxdebug->enter_sub();
2529 my ($self, $myconfig, $table) = @_;
2531 # connect to database
2532 my $dbh = $self->get_standard_dbh($myconfig);
2534 $table = $table eq "customer" ? "customer" : "vendor";
2535 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2537 my ($query, @values);
2539 if (!$self->{openinvoices}) {
2541 if ($self->{customernumber} ne "") {
2542 $where = qq|(vc.customernumber ILIKE ?)|;
2543 push(@values, '%' . $self->{customernumber} . '%');
2545 $where = qq|(vc.name ILIKE ?)|;
2546 push(@values, '%' . $self->{$table} . '%');
2550 qq~SELECT vc.id, vc.name,
2551 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2553 WHERE $where AND (NOT vc.obsolete)
2557 qq~SELECT DISTINCT vc.id, vc.name,
2558 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2560 JOIN $table vc ON (a.${table}_id = vc.id)
2561 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2563 push(@values, '%' . $self->{$table} . '%');
2566 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2568 $main::lxdebug->leave_sub();
2570 return scalar(@{ $self->{name_list} });
2573 # the selection sub is used in the AR, AP, IS, IR and OE module
2576 $main::lxdebug->enter_sub();
2578 my ($self, $myconfig, $table, $module) = @_;
2581 my $dbh = $self->get_standard_dbh($myconfig);
2583 $table = $table eq "customer" ? "customer" : "vendor";
2585 my $query = qq|SELECT count(*) FROM $table|;
2586 my ($count) = selectrow_query($self, $dbh, $query);
2588 # build selection list
2589 if ($count <= $myconfig->{vclimit}) {
2590 $query = qq|SELECT id, name, salesman_id
2591 FROM $table WHERE NOT obsolete
2593 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2597 $self->get_employee($dbh);
2599 # setup sales contacts
2600 $query = qq|SELECT e.id, e.name
2602 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2603 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2606 push(@{ $self->{all_employees} },
2607 { id => $self->{employee_id},
2608 name => $self->{employee} });
2610 # sort the whole thing
2611 @{ $self->{all_employees} } =
2612 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2614 if ($module eq 'AR') {
2616 # prepare query for departments
2617 $query = qq|SELECT id, description
2620 ORDER BY description|;
2623 $query = qq|SELECT id, description
2625 ORDER BY description|;
2628 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2631 $query = qq|SELECT id, description
2635 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2638 $query = qq|SELECT printer_description, id
2640 ORDER BY printer_description|;
2642 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2645 $query = qq|SELECT id, description
2649 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2651 $main::lxdebug->leave_sub();
2654 sub language_payment {
2655 $main::lxdebug->enter_sub();
2657 my ($self, $myconfig) = @_;
2659 my $dbh = $self->get_standard_dbh($myconfig);
2661 my $query = qq|SELECT id, description
2665 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2668 $query = qq|SELECT printer_description, id
2670 ORDER BY printer_description|;
2672 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2675 $query = qq|SELECT id, description
2679 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2681 # get buchungsgruppen
2682 $query = qq|SELECT id, description
2683 FROM buchungsgruppen|;
2685 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2687 $main::lxdebug->leave_sub();
2690 # this is only used for reports
2691 sub all_departments {
2692 $main::lxdebug->enter_sub();
2694 my ($self, $myconfig, $table) = @_;
2696 my $dbh = $self->get_standard_dbh($myconfig);
2699 if ($table eq 'customer') {
2700 $where = "WHERE role = 'P' ";
2703 my $query = qq|SELECT id, description
2706 ORDER BY description|;
2707 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2709 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2711 $main::lxdebug->leave_sub();
2715 $main::lxdebug->enter_sub();
2717 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2720 if ($table eq "customer") {
2729 $self->all_vc($myconfig, $table, $module);
2731 # get last customers or vendors
2732 my ($query, $sth, $ref);
2734 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2739 my $transdate = "current_date";
2740 if ($self->{transdate}) {
2741 $transdate = $dbh->quote($self->{transdate});
2744 # now get the account numbers
2745 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2746 FROM chart c, taxkeys tk
2747 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2748 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2751 $sth = $dbh->prepare($query);
2753 do_statement($self, $sth, $query, '%' . $module . '%');
2755 $self->{accounts} = "";
2756 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2758 foreach my $key (split(/:/, $ref->{link})) {
2759 if ($key =~ /\Q$module\E/) {
2761 # cross reference for keys
2762 $xkeyref{ $ref->{accno} } = $key;
2764 push @{ $self->{"${module}_links"}{$key} },
2765 { accno => $ref->{accno},
2766 description => $ref->{description},
2767 taxkey => $ref->{taxkey_id},
2768 tax_id => $ref->{tax_id} };
2770 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2776 # get taxkeys and description
2777 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2778 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2780 if (($module eq "AP") || ($module eq "AR")) {
2781 # get tax rates and description
2782 $query = qq|SELECT * FROM tax|;
2783 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2789 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2790 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2791 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2792 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2794 d.description AS department,
2797 JOIN $table c ON (a.${table}_id = c.id)
2798 LEFT JOIN employee e ON (e.id = a.employee_id)
2799 LEFT JOIN department d ON (d.id = a.department_id)
2801 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2803 foreach my $key (keys %$ref) {
2804 $self->{$key} = $ref->{$key};
2807 my $transdate = "current_date";
2808 if ($self->{transdate}) {
2809 $transdate = $dbh->quote($self->{transdate});
2812 # now get the account numbers
2813 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2815 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2817 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2818 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2821 $sth = $dbh->prepare($query);
2822 do_statement($self, $sth, $query, "%$module%");
2824 $self->{accounts} = "";
2825 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2827 foreach my $key (split(/:/, $ref->{link})) {
2828 if ($key =~ /\Q$module\E/) {
2830 # cross reference for keys
2831 $xkeyref{ $ref->{accno} } = $key;
2833 push @{ $self->{"${module}_links"}{$key} },
2834 { accno => $ref->{accno},
2835 description => $ref->{description},
2836 taxkey => $ref->{taxkey_id},
2837 tax_id => $ref->{tax_id} };
2839 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2845 # get amounts from individual entries
2848 c.accno, c.description,
2849 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2853 LEFT JOIN chart c ON (c.id = a.chart_id)
2854 LEFT JOIN project p ON (p.id = a.project_id)
2855 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2856 WHERE (tk.taxkey_id=a.taxkey) AND
2857 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2858 THEN tk.chart_id = a.chart_id
2861 OR (c.link='%tax%')) AND
2862 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2863 WHERE a.trans_id = ?
2864 AND a.fx_transaction = '0'
2865 ORDER BY a.acc_trans_id, a.transdate|;
2866 $sth = $dbh->prepare($query);
2867 do_statement($self, $sth, $query, $self->{id});
2869 # get exchangerate for currency
2870 $self->{exchangerate} =
2871 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2874 # store amounts in {acc_trans}{$key} for multiple accounts
2875 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2876 $ref->{exchangerate} =
2877 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2878 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2881 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2882 $ref->{amount} *= -1;
2884 $ref->{index} = $index;
2886 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2892 d.curr AS currencies, d.closedto, d.revtrans,
2893 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2894 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2896 $ref = selectfirst_hashref_query($self, $dbh, $query);
2897 map { $self->{$_} = $ref->{$_} } keys %$ref;
2904 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2905 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2906 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2908 $ref = selectfirst_hashref_query($self, $dbh, $query);
2909 map { $self->{$_} = $ref->{$_} } keys %$ref;
2911 if ($self->{"$self->{vc}_id"}) {
2913 # only setup currency
2914 ($self->{currency}) = split(/:/, $self->{currencies});
2918 $self->lastname_used($dbh, $myconfig, $table, $module);
2920 # get exchangerate for currency
2921 $self->{exchangerate} =
2922 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2928 $main::lxdebug->leave_sub();
2932 $main::lxdebug->enter_sub();
2934 my ($self, $dbh, $myconfig, $table, $module) = @_;
2938 $table = $table eq "customer" ? "customer" : "vendor";
2939 my %column_map = ("a.curr" => "currency",
2940 "a.${table}_id" => "${table}_id",
2941 "a.department_id" => "department_id",
2942 "d.description" => "department",
2943 "ct.name" => $table,
2944 "current_date + ct.terms" => "duedate",
2947 if ($self->{type} =~ /delivery_order/) {
2948 $arap = 'delivery_orders';
2949 delete $column_map{"a.curr"};
2951 } elsif ($self->{type} =~ /_order/) {
2953 $where = "quotation = '0'";
2955 } elsif ($self->{type} =~ /_quotation/) {
2957 $where = "quotation = '1'";
2959 } elsif ($table eq 'customer') {
2967 $where = "($where) AND" if ($where);
2968 my $query = qq|SELECT MAX(id) FROM $arap
2969 WHERE $where ${table}_id > 0|;
2970 my ($trans_id) = selectrow_query($self, $dbh, $query);
2973 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2974 $query = qq|SELECT $column_spec
2976 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2977 LEFT JOIN department d ON (a.department_id = d.id)
2979 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2981 map { $self->{$_} = $ref->{$_} } values %column_map;
2983 $main::lxdebug->leave_sub();
2987 $main::lxdebug->enter_sub();
2990 my $myconfig = shift || \%::myconfig;
2991 my ($thisdate, $days) = @_;
2993 my $dbh = $self->get_standard_dbh($myconfig);
2998 my $dateformat = $myconfig->{dateformat};
2999 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3000 $thisdate = $dbh->quote($thisdate);
3001 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3003 $query = qq|SELECT current_date AS thisdate|;
3006 ($thisdate) = selectrow_query($self, $dbh, $query);
3008 $main::lxdebug->leave_sub();
3014 $main::lxdebug->enter_sub();
3016 my ($self, $string) = @_;
3018 if ($string !~ /%/) {
3019 $string = "%$string%";
3022 $string =~ s/\'/\'\'/g;
3024 $main::lxdebug->leave_sub();
3030 $main::lxdebug->enter_sub();
3032 my ($self, $flds, $new, $count, $numrows) = @_;
3036 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3041 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3043 my $j = $item->{ndx} - 1;
3044 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3048 for $i ($count + 1 .. $numrows) {
3049 map { delete $self->{"${_}_$i"} } @{$flds};
3052 $main::lxdebug->leave_sub();
3056 $main::lxdebug->enter_sub();
3058 my ($self, $myconfig) = @_;
3062 my $dbh = $self->dbconnect_noauto($myconfig);
3064 my $query = qq|DELETE FROM status
3065 WHERE (formname = ?) AND (trans_id = ?)|;
3066 my $sth = prepare_query($self, $dbh, $query);
3068 if ($self->{formname} =~ /(check|receipt)/) {
3069 for $i (1 .. $self->{rowcount}) {
3070 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3073 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3077 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3078 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3080 my %queued = split / /, $self->{queued};
3083 if ($self->{formname} =~ /(check|receipt)/) {
3085 # this is a check or receipt, add one entry for each lineitem
3086 my ($accno) = split /--/, $self->{account};
3087 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3088 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3089 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3090 $sth = prepare_query($self, $dbh, $query);
3092 for $i (1 .. $self->{rowcount}) {
3093 if ($self->{"checked_$i"}) {
3094 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3100 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3101 VALUES (?, ?, ?, ?, ?)|;
3102 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3103 $queued{$self->{formname}}, $self->{formname});
3109 $main::lxdebug->leave_sub();
3113 $main::lxdebug->enter_sub();
3115 my ($self, $dbh) = @_;
3117 my ($query, $printed, $emailed);
3119 my $formnames = $self->{printed};
3120 my $emailforms = $self->{emailed};
3122 $query = qq|DELETE FROM status
3123 WHERE (formname = ?) AND (trans_id = ?)|;
3124 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3126 # this only applies to the forms
3127 # checks and receipts are posted when printed or queued
3129 if ($self->{queued}) {
3130 my %queued = split / /, $self->{queued};
3132 foreach my $formname (keys %queued) {
3133 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3134 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3136 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3137 VALUES (?, ?, ?, ?, ?)|;
3138 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3140 $formnames =~ s/\Q$self->{formname}\E//;
3141 $emailforms =~ s/\Q$self->{formname}\E//;
3146 # save printed, emailed info
3147 $formnames =~ s/^ +//g;
3148 $emailforms =~ s/^ +//g;
3151 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3152 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3154 foreach my $formname (keys %status) {
3155 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3156 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3158 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3159 VALUES (?, ?, ?, ?)|;
3160 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3163 $main::lxdebug->leave_sub();
3167 # $main::locale->text('SAVED')
3168 # $main::locale->text('DELETED')
3169 # $main::locale->text('ADDED')
3170 # $main::locale->text('PAYMENT POSTED')
3171 # $main::locale->text('POSTED')
3172 # $main::locale->text('POSTED AS NEW')
3173 # $main::locale->text('ELSE')
3174 # $main::locale->text('SAVED FOR DUNNING')
3175 # $main::locale->text('DUNNING STARTED')
3176 # $main::locale->text('PRINTED')
3177 # $main::locale->text('MAILED')
3178 # $main::locale->text('SCREENED')
3179 # $main::locale->text('CANCELED')
3180 # $main::locale->text('invoice')
3181 # $main::locale->text('proforma')
3182 # $main::locale->text('sales_order')
3183 # $main::locale->text('packing_list')
3184 # $main::locale->text('pick_list')
3185 # $main::locale->text('purchase_order')
3186 # $main::locale->text('bin_list')
3187 # $main::locale->text('sales_quotation')
3188 # $main::locale->text('request_quotation')
3191 $main::lxdebug->enter_sub();
3196 if(!exists $self->{employee_id}) {
3197 &get_employee($self, $dbh);
3201 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3202 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3203 my @values = (conv_i($self->{id}), $self->{login},
3204 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3205 do_query($self, $dbh, $query, @values);
3207 $main::lxdebug->leave_sub();
3211 $main::lxdebug->enter_sub();
3213 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3214 my ($orderBy, $desc) = split(/\-\-/, $order);
3215 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3218 if ($trans_id ne "") {
3220 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 | .
3221 qq|FROM history_erp h | .
3222 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3223 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3226 my $sth = $dbh->prepare($query) || $self->dberror($query);
3228 $sth->execute() || $self->dberror("$query");
3230 while(my $hash_ref = $sth->fetchrow_hashref()) {
3231 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3232 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3233 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3234 $tempArray[$i++] = $hash_ref;
3236 $main::lxdebug->leave_sub() and return \@tempArray
3237 if ($i > 0 && $tempArray[0] ne "");
3239 $main::lxdebug->leave_sub();
3243 sub update_defaults {
3244 $main::lxdebug->enter_sub();
3246 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3249 if ($provided_dbh) {
3250 $dbh = $provided_dbh;
3252 $dbh = $self->dbconnect_noauto($myconfig);
3254 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3255 my $sth = $dbh->prepare($query);
3257 $sth->execute || $self->dberror($query);
3258 my ($var) = $sth->fetchrow_array;
3261 if ($var =~ m/\d+$/) {
3262 my $new_var = (substr $var, $-[0]) * 1 + 1;
3263 my $len_diff = length($var) - $-[0] - length($new_var);
3264 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3270 $query = qq|UPDATE defaults SET $fld = ?|;
3271 do_query($self, $dbh, $query, $var);
3273 if (!$provided_dbh) {
3278 $main::lxdebug->leave_sub();
3283 sub update_business {
3284 $main::lxdebug->enter_sub();
3286 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3289 if ($provided_dbh) {
3290 $dbh = $provided_dbh;
3292 $dbh = $self->dbconnect_noauto($myconfig);
3295 qq|SELECT customernumberinit FROM business
3296 WHERE id = ? FOR UPDATE|;
3297 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3299 return undef unless $var;
3301 if ($var =~ m/\d+$/) {
3302 my $new_var = (substr $var, $-[0]) * 1 + 1;
3303 my $len_diff = length($var) - $-[0] - length($new_var);
3304 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3310 $query = qq|UPDATE business
3311 SET customernumberinit = ?
3313 do_query($self, $dbh, $query, $var, $business_id);
3315 if (!$provided_dbh) {
3320 $main::lxdebug->leave_sub();
3325 sub get_partsgroup {
3326 $main::lxdebug->enter_sub();
3328 my ($self, $myconfig, $p) = @_;
3329 my $target = $p->{target} || 'all_partsgroup';
3331 my $dbh = $self->get_standard_dbh($myconfig);
3333 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3335 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3338 if ($p->{searchitems} eq 'part') {
3339 $query .= qq|WHERE p.inventory_accno_id > 0|;
3341 if ($p->{searchitems} eq 'service') {
3342 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3344 if ($p->{searchitems} eq 'assembly') {
3345 $query .= qq|WHERE p.assembly = '1'|;
3347 if ($p->{searchitems} eq 'labor') {
3348 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3351 $query .= qq|ORDER BY partsgroup|;
3354 $query = qq|SELECT id, partsgroup FROM partsgroup
3355 ORDER BY partsgroup|;
3358 if ($p->{language_code}) {
3359 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3360 t.description AS translation
3362 JOIN parts p ON (p.partsgroup_id = pg.id)
3363 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3364 ORDER BY translation|;
3365 @values = ($p->{language_code});
3368 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3370 $main::lxdebug->leave_sub();
3373 sub get_pricegroup {
3374 $main::lxdebug->enter_sub();
3376 my ($self, $myconfig, $p) = @_;
3378 my $dbh = $self->get_standard_dbh($myconfig);
3380 my $query = qq|SELECT p.id, p.pricegroup
3383 $query .= qq| ORDER BY pricegroup|;
3386 $query = qq|SELECT id, pricegroup FROM pricegroup
3387 ORDER BY pricegroup|;
3390 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3392 $main::lxdebug->leave_sub();
3396 # usage $form->all_years($myconfig, [$dbh])
3397 # return list of all years where bookings found
3400 $main::lxdebug->enter_sub();
3402 my ($self, $myconfig, $dbh) = @_;
3404 $dbh ||= $self->get_standard_dbh($myconfig);
3407 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3408 (SELECT MAX(transdate) FROM acc_trans)|;
3409 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3411 if ($myconfig->{dateformat} =~ /^yy/) {
3412 ($startdate) = split /\W/, $startdate;
3413 ($enddate) = split /\W/, $enddate;
3415 (@_) = split /\W/, $startdate;
3417 (@_) = split /\W/, $enddate;
3422 $startdate = substr($startdate,0,4);
3423 $enddate = substr($enddate,0,4);
3425 while ($enddate >= $startdate) {
3426 push @all_years, $enddate--;
3431 $main::lxdebug->leave_sub();
3435 $main::lxdebug->enter_sub();
3439 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3441 $main::lxdebug->leave_sub();
3445 $main::lxdebug->enter_sub();
3450 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3452 $main::lxdebug->leave_sub();
3461 SL::Form.pm - main data object.
3465 This is the main data object of Lx-Office.
3466 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3467 Points of interest for a beginner are:
3469 - $form->error - renders a generic error in html. accepts an error message
3470 - $form->get_standard_dbh - returns a database connection for the
3472 =head1 SPECIAL FUNCTIONS
3476 =item _store_value()
3478 parses a complex var name, and stores it in the form.
3481 $form->_store_value($key, $value);
3483 keys must start with a string, and can contain various tokens.
3484 supported key structures are:
3487 simple key strings work as expected
3492 separating two keys by a dot (.) will result in a hash lookup for the inner value
3493 this is similar to the behaviour of java and templating mechanisms.
3495 filter.description => $form->{filter}->{description}
3497 3. array+hashref access
3499 adding brackets ([]) before the dot will cause the next hash to be put into an array.
3500 using [+] instead of [] will force a new array index. this is useful for recurring
3501 data structures like part lists. put a [+] into the first varname, and use [] on the
3504 repeating these names in your template:
3507 invoice.items[].parts_id
3511 $form->{invoice}->{items}->[
3525 using brackets at the end of a name will result in a pure array to be created.
3526 note that you mustn't use [+], which is reserved for array+hash access and will
3527 result in undefined behaviour in array context.
3529 filter.status[] => $form->{status}->[ val1, val2, ... ]
3531 =item update_business PARAMS
3534 \%config, - config hashref
3535 $business_id, - business id
3536 $dbh - optional database handle
3538 handles business (thats customer/vendor types) sequences.
3540 special behaviour for empty strings in customerinitnumber field:
3541 will in this case not increase the value, and return undef.