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 #======================================================================
56 use List::Util qw(first max min sum);
62 $standard_dbh->disconnect();
68 $main::lxdebug->enter_sub(2);
76 while ($key =~ /\[\+?\]\.|\./) {
77 substr($key, 0, $+[0]) = '';
85 if (!scalar @{ $curr->{$`} } || $& eq '[+].') {
86 push @{ $curr->{$`} }, { };
89 $curr = $curr->{$`}->[-1];
93 $curr->{$key} = $value;
95 $main::lxdebug->leave_sub(2);
97 return \$curr->{$key};
101 $main::lxdebug->enter_sub(2);
106 my @pairs = split(/&/, $input);
109 my ($key, $value) = split(/=/, $_, 2);
110 $self->_store_value($self->unescape($key), $self->unescape($value));
113 $main::lxdebug->leave_sub(2);
116 sub _request_to_hash {
117 $main::lxdebug->enter_sub(2);
122 if (!$ENV{'CONTENT_TYPE'}
123 || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
125 $self->_input_to_hash($input);
127 $main::lxdebug->leave_sub(2);
131 my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
133 my $boundary = '--' . $1;
135 foreach my $line (split m/\n/, $input) {
136 last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
138 if (($line eq $boundary) || ($line eq "$boundary\r")) {
139 ${ $previous } =~ s|\r?\n$|| if $previous;
145 $content_type = "text/plain";
152 next unless $boundary_found;
154 if (!$headers_done) {
155 $line =~ s/[\r\n]*$//;
162 if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
163 if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
165 substr $line, $-[0], $+[0] - $-[0], "";
168 if ($line =~ m|name\s*=\s*"(.*?)"|i) {
170 substr $line, $-[0], $+[0] - $-[0], "";
173 $previous = $self->_store_value($name, '');
174 $self->{FILENAME} = $filename if ($filename);
179 if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
186 next unless $previous;
188 ${ $previous } .= "${line}\n";
191 ${ $previous } =~ s|\r?\n$|| if $previous;
193 $main::lxdebug->leave_sub(2);
197 $main::lxdebug->enter_sub();
203 if ($LXDebug::watch_form) {
204 require SL::Watchdog;
205 tie %{ $self }, 'SL::Watchdog';
208 read(STDIN, $_, $ENV{CONTENT_LENGTH});
210 if ($ENV{QUERY_STRING}) {
211 $_ = $ENV{QUERY_STRING};
220 $self->_request_to_hash($_);
222 $self->{action} = lc $self->{action};
223 $self->{action} =~ s/( |-|,|\#)/_/g;
225 $self->{version} = "2.4.3";
227 $main::lxdebug->leave_sub();
232 sub _flatten_variables_rec {
233 $main::lxdebug->enter_sub(2);
242 if ('' eq ref $curr->{$key}) {
243 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
245 } elsif ('HASH' eq ref $curr->{$key}) {
246 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
247 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
251 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
252 my $first_array_entry = 1;
254 foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
255 push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
256 $first_array_entry = 0;
261 $main::lxdebug->leave_sub(2);
266 sub flatten_variables {
267 $main::lxdebug->enter_sub(2);
275 push @variables, $self->_flatten_variables_rec($self, '', $_);
278 $main::lxdebug->leave_sub(2);
283 sub flatten_standard_variables {
284 $main::lxdebug->enter_sub(2);
287 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
291 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
292 push @variables, $self->_flatten_variables_rec($self, '', $_);
295 $main::lxdebug->leave_sub(2);
301 $main::lxdebug->enter_sub();
307 map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
309 $main::lxdebug->leave_sub();
313 $main::lxdebug->enter_sub(2);
316 my $password = $self->{password};
318 $self->{password} = 'X' x 8;
320 local $Data::Dumper::Sortkeys = 1;
321 my $output = Dumper($self);
323 $self->{password} = $password;
325 $main::lxdebug->leave_sub(2);
331 $main::lxdebug->enter_sub(2);
333 my ($self, $str) = @_;
335 $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
337 $main::lxdebug->leave_sub(2);
343 $main::lxdebug->enter_sub(2);
345 my ($self, $str) = @_;
350 $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
352 $main::lxdebug->leave_sub(2);
358 my ($self, $str) = @_;
360 if ($str && !ref($str)) {
361 $str =~ s/\"/"/g;
369 my ($self, $str) = @_;
371 if ($str && !ref($str)) {
372 $str =~ s/"/\"/g;
383 map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
385 for (sort keys %$self) {
386 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
387 print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
394 $main::lxdebug->enter_sub();
396 $main::lxdebug->show_backtrace();
398 my ($self, $msg) = @_;
399 if ($ENV{HTTP_USER_AGENT}) {
401 $self->show_generic_error($msg);
408 $main::lxdebug->leave_sub();
412 $main::lxdebug->enter_sub();
414 my ($self, $msg) = @_;
416 if ($ENV{HTTP_USER_AGENT}) {
419 if (!$self->{header}) {
432 if ($self->{info_function}) {
433 &{ $self->{info_function} }($msg);
439 $main::lxdebug->leave_sub();
442 # calculates the number of rows in a textarea based on the content and column number
443 # can be capped with maxrows
445 $main::lxdebug->enter_sub();
446 my ($self, $str, $cols, $maxrows, $minrows) = @_;
450 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
453 $main::lxdebug->leave_sub();
455 return max(min($rows, $maxrows), $minrows);
459 $main::lxdebug->enter_sub();
461 my ($self, $msg) = @_;
463 $self->error("$msg\n" . $DBI::errstr);
465 $main::lxdebug->leave_sub();
469 $main::lxdebug->enter_sub();
471 my ($self, $name, $msg) = @_;
474 foreach my $part (split m/\./, $name) {
475 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
478 $curr = $curr->{$part};
481 $main::lxdebug->leave_sub();
484 sub create_http_response {
485 $main::lxdebug->enter_sub();
490 my $cgi = $main::cgi;
491 $cgi ||= CGI->new('');
495 if ($ENV{HTTP_X_FORWARDED_FOR}) {
496 $base_path = $ENV{HTTP_REFERER};
497 $base_path =~ s|^.*?://.*?/|/|;
499 $base_path = $ENV{REQUEST_URI};
501 $base_path =~ s|[^/]+$||;
502 $base_path =~ s|/$||;
505 if (defined $main::auth) {
506 my $session_cookie_value = $main::auth->get_session_id();
507 $session_cookie_value ||= 'NO_SESSION';
509 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
510 '-value' => $session_cookie_value,
511 '-path' => $base_path);
514 my %cgi_params = ('-type' => $params{content_type});
515 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
517 my $output = $cgi->header('-cookie' => $session_cookie,
520 $main::lxdebug->leave_sub();
527 $main::lxdebug->enter_sub();
529 my ($self, $extra_code) = @_;
531 if ($self->{header}) {
532 $main::lxdebug->leave_sub();
536 my ($stylesheet, $favicon);
538 if ($ENV{HTTP_USER_AGENT}) {
541 if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
542 # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
543 $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
546 my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
548 $stylesheets =~ s|^\s*||;
549 $stylesheets =~ s|\s*$||;
550 foreach my $file (split m/\s+/, $stylesheets) {
552 next if (! -f "css/$file");
554 $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
557 $self->{favicon} = "favicon.ico" unless $self->{favicon};
559 if ($self->{favicon} && (-f "$self->{favicon}")) {
561 qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
565 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
567 if ($self->{landscape}) {
568 $pagelayout = qq|<style type="text/css">
569 \@page { size:landscape; }
573 my $fokus = qq| document.$self->{fokus}.focus();| if ($self->{"fokus"});
577 if ($self->{jsscript} == 1) {
580 <script type="text/javascript" src="js/common.js"></script>
581 <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
582 <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
583 <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
584 <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
591 ? "$self->{title} - $self->{titlebar}"
594 foreach $item (@ { $self->{AJAX} }) {
595 $ajax .= $item->show_javascript();
598 print $self->create_http_response('content_type' => 'text/html',
599 'charset' => $db_charset,);
600 print qq|${doctype}<html>
602 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
603 <title>$self->{titlebar}</title>
610 <script type="text/javascript">
618 <meta name="robots" content="noindex,nofollow" />
619 <script type="text/javascript" src="js/highlight_input.js"></script>
620 <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
622 <script type="text/javascript" src="js/tabcontent.js">
624 /***********************************************
625 * Tab Content script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
626 * This notice MUST stay intact for legal use
627 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
628 ***********************************************/
639 $main::lxdebug->leave_sub();
642 sub ajax_response_header {
643 $main::lxdebug->enter_sub();
647 my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
648 my $cgi = $main::cgi || CGI->new('');
649 my $output = $cgi->header('-charset' => $db_charset);
651 $main::lxdebug->leave_sub();
656 sub _prepare_html_template {
657 $main::lxdebug->enter_sub();
659 my ($self, $file, $additional_params) = @_;
662 if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
663 $language = $main::language;
665 $language = $main::myconfig{"countrycode"};
667 $language = "de" unless ($language);
669 if (-f "templates/webpages/${file}_${language}.html") {
670 if ((-f ".developer") &&
671 (-f "templates/webpages/${file}_master.html") &&
672 ((stat("templates/webpages/${file}_master.html"))[9] >
673 (stat("templates/webpages/${file}_${language}.html"))[9])) {
674 my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
675 "Please re-run 'locales.pl' in 'locale/${language}'.";
676 print(qq|<pre>$info</pre>|);
680 $file = "templates/webpages/${file}_${language}.html";
681 } elsif (-f "templates/webpages/${file}.html") {
682 $file = "templates/webpages/${file}.html";
684 my $info = "Web page template '${file}' not found.\n" .
685 "Please re-run 'locales.pl' in 'locale/${language}'.";
686 print(qq|<pre>$info</pre>|);
690 if ($self->{"DEBUG"}) {
691 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
694 if ($additional_params->{"DEBUG"}) {
695 $additional_params->{"DEBUG"} =
696 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
699 if (%main::myconfig) {
700 map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
701 my $jsc_dateformat = $main::myconfig{"dateformat"};
702 $jsc_dateformat =~ s/d+/\%d/gi;
703 $jsc_dateformat =~ s/m+/\%m/gi;
704 $jsc_dateformat =~ s/y+/\%Y/gi;
705 $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
708 $additional_params->{"conf_dbcharset"} = $main::dbcharset;
709 $additional_params->{"conf_webdav"} = $main::webdav;
710 $additional_params->{"conf_lizenzen"} = $main::lizenzen;
711 $additional_params->{"conf_latex_templates"} = $main::latex;
712 $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
714 if (%main::debug_options) {
715 map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
718 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
719 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
720 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
724 $main::lxdebug->leave_sub();
729 sub parse_html_template {
730 $main::lxdebug->enter_sub();
732 my ($self, $file, $additional_params) = @_;
734 $additional_params ||= { };
736 $file = $self->_prepare_html_template($file, $additional_params);
738 my $template = Template->new({ 'INTERPOLATE' => 0,
742 'PLUGIN_BASE' => 'SL::Template::Plugin',
743 'INCLUDE_PATH' => '.:templates/webpages',
746 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
748 my $in = IO::File->new($file, 'r');
751 print STDERR "Error opening template file: $!";
752 $main::lxdebug->leave_sub();
756 my $input = join('', <$in>);
760 $input = $main::locale->{iconv}->convert($input);
764 if (!$template->process(\$input, $additional_params, \$output)) {
765 print STDERR $template->error();
768 $main::lxdebug->leave_sub();
773 sub show_generic_error {
774 my ($self, $error, %params) = @_;
777 'title_error' => $params{title},
778 'label_error' => $error,
781 if ($params{action}) {
784 map { delete($self->{$_}); } qw(action);
785 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
787 $add_params->{SHOW_BUTTON} = 1;
788 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
789 $add_params->{VARIABLES} = \@vars;
791 } elsif ($params{back_button}) {
792 $add_params->{SHOW_BACK_BUTTON} = 1;
795 $self->{title} = $title if ($title);
798 print $self->parse_html_template("generic/error", $add_params);
800 die("Error: $error\n");
803 sub show_generic_information {
804 my ($self, $text, $title) = @_;
807 'title_information' => $title,
808 'label_information' => $text,
811 $self->{title} = $title if ($title);
814 print $self->parse_html_template("generic/information", $add_params);
816 die("Information: $error\n");
819 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
820 # changed it to accept an arbitrary number of triggers - sschoeling
822 $main::lxdebug->enter_sub();
825 my $myconfig = shift;
828 # set dateform for jsscript
831 "dd.mm.yy" => "%d.%m.%Y",
832 "dd-mm-yy" => "%d-%m-%Y",
833 "dd/mm/yy" => "%d/%m/%Y",
834 "mm/dd/yy" => "%m/%d/%Y",
835 "mm-dd-yy" => "%m-%d-%Y",
836 "yyyy-mm-dd" => "%Y-%m-%d",
839 my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
840 $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
847 inputField : "| . (shift) . qq|",
848 ifFormat :"$ifFormat",
849 align : "| . (shift) . qq|",
850 button : "| . (shift) . qq|"
856 <script type="text/javascript">
857 <!--| . join("", @triggers) . qq|//-->
861 $main::lxdebug->leave_sub();
864 } #end sub write_trigger
867 $main::lxdebug->enter_sub();
869 my ($self, $msg) = @_;
871 if ($self->{callback}) {
873 ($script, $argv) = split(/\?/, $self->{callback}, 2);
875 $script =~ s|[^a-zA-Z0-9_\.]||g;
876 exec("perl", "$script", $argv);
884 $main::lxdebug->leave_sub();
887 # sort of columns removed - empty sub
889 $main::lxdebug->enter_sub();
891 my ($self, @columns) = @_;
893 $main::lxdebug->leave_sub();
899 $main::lxdebug->enter_sub(2);
901 my ($self, $myconfig, $amount, $places, $dash) = @_;
907 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
909 my $neg = ($amount =~ s/^-//);
910 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
912 if (defined($places) && ($places ne '')) {
918 my ($actual_places) = ($amount =~ /\.(\d+)/);
919 $actual_places = length($actual_places);
920 $places = $actual_places > $places ? $actual_places : $places;
923 $amount = $self->round_amount($amount, $places);
926 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
927 my @p = split(/\./, $amount); # split amount at decimal point
929 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
932 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
935 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
936 ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
937 ($neg ? "-$amount" : "$amount" ) ;
941 $main::lxdebug->leave_sub(2);
945 sub format_amount_units {
946 $main::lxdebug->enter_sub();
951 my $myconfig = \%main::myconfig;
952 my $amount = $params{amount} * 1;
953 my $places = $params{places};
954 my $part_unit_name = $params{part_unit};
955 my $amount_unit_name = $params{amount_unit};
956 my $conv_units = $params{conv_units};
957 my $max_places = $params{max_places};
959 if (!$part_unit_name) {
960 $main::lxdebug->leave_sub();
964 AM->retrieve_all_units();
965 my $all_units = $main::all_units;
967 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
968 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
971 if (!scalar @{ $conv_units }) {
972 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
973 $main::lxdebug->leave_sub();
977 my $part_unit = $all_units->{$part_unit_name};
978 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
980 $amount *= $conv_unit->{factor};
984 foreach my $unit (@$conv_units) {
985 my $last = $unit->{name} eq $part_unit->{name};
987 $num = int($amount / $unit->{factor});
988 $amount -= $num * $unit->{factor};
991 if ($last ? $amount : $num) {
992 push @values, { "unit" => $unit->{name},
993 "amount" => $last ? $amount / $unit->{factor} : $num,
994 "places" => $last ? $places : 0 };
1001 push @values, { "unit" => $part_unit_name,
1006 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1008 $main::lxdebug->leave_sub();
1014 $main::lxdebug->enter_sub(2);
1019 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1020 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1021 $input =~ s/\#\#/\#/g;
1023 $main::lxdebug->leave_sub(2);
1031 $main::lxdebug->enter_sub(2);
1033 my ($self, $myconfig, $amount) = @_;
1035 if ( ($myconfig->{numberformat} eq '1.000,00')
1036 || ($myconfig->{numberformat} eq '1000,00')) {
1041 if ($myconfig->{numberformat} eq "1'000.00") {
1047 $main::lxdebug->leave_sub(2);
1049 return ($amount * 1);
1053 $main::lxdebug->enter_sub(2);
1055 my ($self, $amount, $places) = @_;
1058 # Rounding like "Kaufmannsrunden"
1059 # Descr. http://de.wikipedia.org/wiki/Rundung
1061 # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
1064 $amount = $amount * (10**($places));
1065 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1067 $main::lxdebug->leave_sub(2);
1069 return $round_amount;
1073 sub parse_template {
1074 $main::lxdebug->enter_sub();
1076 my ($self, $myconfig, $userspath) = @_;
1077 my ($template, $out);
1081 $self->{"cwd"} = getcwd();
1082 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1084 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1085 $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1086 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1087 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1088 $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1089 } elsif (($self->{"format"} =~ /html/i) ||
1090 (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1091 $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1092 } elsif (($self->{"format"} =~ /xml/i) ||
1093 (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1094 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1095 } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1096 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1097 } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1098 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1099 } elsif ( defined $self->{'format'}) {
1100 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1101 } elsif ( $self->{'format'} eq '' ) {
1102 $self->error("No Outputformat given: $self->{'format'}");
1103 } else { #Catch the rest
1104 $self->error("Outputformat not defined: $self->{'format'}");
1107 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1108 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1110 map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
1111 qw(email tel fax name signature company address businessnumber
1112 co_ustid taxnumber duns));
1114 map({ $self->{"${_}"} = $myconfig->{$_}; }
1118 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1120 # OUT is used for the media, screen, printer, email
1121 # for postscript we store a copy in a temporary file
1123 my $prepend_userspath;
1125 if (!$self->{tmpfile}) {
1126 $self->{tmpfile} = "${fileid}.$self->{IN}";
1127 $prepend_userspath = 1;
1130 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1132 $self->{tmpfile} =~ s|.*/||;
1133 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1134 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1136 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1137 $out = $self->{OUT};
1138 $self->{OUT} = ">$self->{tmpfile}";
1142 open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1144 open(OUT, ">-") or $self->error("STDOUT : $!");
1148 if (!$template->parse(*OUT)) {
1150 $self->error("$self->{IN} : " . $template->get_error());
1155 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1157 if ($self->{media} eq 'email') {
1159 my $mail = new Mailer;
1161 map { $mail->{$_} = $self->{$_} }
1162 qw(cc bcc subject message version format);
1163 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1164 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1165 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1166 $mail->{fileid} = "$fileid.";
1167 $myconfig->{signature} =~ s/\r//g;
1169 # if we send html or plain text inline
1170 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1171 $mail->{contenttype} = "text/html";
1173 $mail->{message} =~ s/\r//g;
1174 $mail->{message} =~ s/\n/<br>\n/g;
1175 $myconfig->{signature} =~ s/\n/<br>\n/g;
1176 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1178 open(IN, $self->{tmpfile})
1179 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1181 $mail->{message} .= $_;
1188 if (!$self->{"do_not_attach"}) {
1189 @{ $mail->{attachments} } =
1190 ({ "filename" => $self->{"tmpfile"},
1191 "name" => $self->{"attachment_filename"} ?
1192 $self->{"attachment_filename"} : $self->{"tmpfile"} });
1195 $mail->{message} =~ s/\r//g;
1196 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1200 my $err = $mail->send();
1201 $self->error($self->cleanup . "$err") if ($err);
1205 $self->{OUT} = $out;
1207 my $numbytes = (-s $self->{tmpfile});
1208 open(IN, $self->{tmpfile})
1209 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1211 $self->{copies} = 1 unless $self->{media} eq 'printer';
1213 chdir("$self->{cwd}");
1214 #print(STDERR "Kopien $self->{copies}\n");
1215 #print(STDERR "OUT $self->{OUT}\n");
1216 for my $i (1 .. $self->{copies}) {
1218 open(OUT, $self->{OUT})
1219 or $self->error($self->cleanup . "$self->{OUT} : $!");
1221 $self->{attachment_filename} = ($self->{attachment_filename})
1222 ? $self->{attachment_filename}
1223 : $self->generate_attachment_filename();
1225 # launch application
1226 print qq|Content-Type: | . $template->get_mime_type() . qq|
1227 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1228 Content-Length: $numbytes
1232 open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1252 chdir("$self->{cwd}");
1253 $main::lxdebug->leave_sub();
1256 sub get_formname_translation {
1257 my ($self, $formname) = @_;
1259 $formname ||= $self->{formname};
1261 my %formname_translations = (
1262 bin_list => $main::locale->text('Bin List'),
1263 credit_note => $main::locale->text('Credit Note'),
1264 invoice => $main::locale->text('Invoice'),
1265 packing_list => $main::locale->text('Packing List'),
1266 pick_list => $main::locale->text('Pick List'),
1267 proforma => $main::locale->text('Proforma Invoice'),
1268 purchase_order => $main::locale->text('Purchase Order'),
1269 request_quotation => $main::locale->text('RFQ'),
1270 sales_order => $main::locale->text('Confirmation'),
1271 sales_quotation => $main::locale->text('Quotation'),
1272 storno_invoice => $main::locale->text('Storno Invoice'),
1273 storno_packing_list => $main::locale->text('Storno Packing List'),
1274 sales_delivery_order => $main::locale->text('Delivery Order'),
1275 purchase_delivery_order => $main::locale->text('Delivery Order'),
1278 return $formname_translations{$formname}
1281 sub get_number_prefix_for_type {
1285 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1286 : ($self->{type} =~ /_quotation$/) ? 'quo'
1287 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1293 sub get_extension_for_format {
1296 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1297 : $self->{format} =~ /postscript/i ? ".ps"
1298 : $self->{format} =~ /opendocument/i ? ".odt"
1299 : $self->{format} =~ /html/i ? ".html"
1305 sub generate_attachment_filename {
1308 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1309 my $prefix = $self->get_number_prefix_for_type();
1311 if ($attachment_filename && $self->{"${prefix}number"}) {
1312 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1313 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1314 $attachment_filename =~ s|[\s/\\]+|_|g;
1316 $attachment_filename = "";
1319 return $attachment_filename;
1322 sub generate_email_subject {
1325 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1326 my $prefix = $self->get_number_prefix_for_type();
1328 if ($subject && $self->{"${prefix}number"}) {
1329 $subject .= " " . $self->{"${prefix}number"}
1336 $main::lxdebug->enter_sub();
1340 chdir("$self->{tmpdir}");
1343 if (-f "$self->{tmpfile}.err") {
1344 open(FH, "$self->{tmpfile}.err");
1349 if ($self->{tmpfile}) {
1350 $self->{tmpfile} =~ s|.*/||g;
1352 $self->{tmpfile} =~ s/\.\w+$//g;
1353 my $tmpfile = $self->{tmpfile};
1354 unlink(<$tmpfile.*>);
1357 chdir("$self->{cwd}");
1359 $main::lxdebug->leave_sub();
1365 $main::lxdebug->enter_sub();
1367 my ($self, $date, $myconfig) = @_;
1369 if ($date && $date =~ /\D/) {
1371 if ($myconfig->{dateformat} =~ /^yy/) {
1372 ($yy, $mm, $dd) = split /\D/, $date;
1374 if ($myconfig->{dateformat} =~ /^mm/) {
1375 ($mm, $dd, $yy) = split /\D/, $date;
1377 if ($myconfig->{dateformat} =~ /^dd/) {
1378 ($dd, $mm, $yy) = split /\D/, $date;
1383 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1384 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1386 $dd = "0$dd" if ($dd < 10);
1387 $mm = "0$mm" if ($mm < 10);
1389 $date = "$yy$mm$dd";
1392 $main::lxdebug->leave_sub();
1397 # Database routines used throughout
1400 $main::lxdebug->enter_sub(2);
1402 my ($self, $myconfig) = @_;
1404 # connect to database
1406 DBI->connect($myconfig->{dbconnect},
1407 $myconfig->{dbuser}, $myconfig->{dbpasswd})
1411 if ($myconfig->{dboptions}) {
1412 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1415 $main::lxdebug->leave_sub(2);
1420 sub dbconnect_noauto {
1421 $main::lxdebug->enter_sub();
1423 my ($self, $myconfig) = @_;
1425 # connect to database
1427 DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1428 $myconfig->{dbpasswd}, { AutoCommit => 0 })
1432 if ($myconfig->{dboptions}) {
1433 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1436 $main::lxdebug->leave_sub();
1441 sub get_standard_dbh {
1442 $main::lxdebug->enter_sub(2);
1444 my ($self, $myconfig) = @_;
1446 if ($standard_dbh && !$standard_dbh->{Active}) {
1447 $main::lxdebug->message(LXDebug::INFO, "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1448 undef $standard_dbh;
1451 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1453 $main::lxdebug->leave_sub(2);
1455 return $standard_dbh;
1459 $main::lxdebug->enter_sub();
1461 my ($self, $date, $myconfig) = @_;
1462 my $dbh = $self->dbconnect($myconfig);
1464 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1465 my $sth = prepare_execute_query($self, $dbh, $query, $date);
1466 my ($closed) = $sth->fetchrow_array;
1468 $main::lxdebug->leave_sub();
1473 sub update_balance {
1474 $main::lxdebug->enter_sub();
1476 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1478 # if we have a value, go do it
1481 # retrieve balance from table
1482 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1483 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1484 my ($balance) = $sth->fetchrow_array;
1490 $query = "UPDATE $table SET $field = $balance WHERE $where";
1491 do_query($self, $dbh, $query, @values);
1493 $main::lxdebug->leave_sub();
1496 sub update_exchangerate {
1497 $main::lxdebug->enter_sub();
1499 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1501 # some sanity check for currency
1503 $main::lxdebug->leave_sub();
1506 $query = qq|SELECT curr FROM defaults|;
1508 my ($currency) = selectrow_query($self, $dbh, $query);
1509 my ($defaultcurrency) = split m/:/, $currency;
1512 if ($curr eq $defaultcurrency) {
1513 $main::lxdebug->leave_sub();
1517 $query = qq|SELECT e.curr FROM exchangerate e
1518 WHERE e.curr = ? AND e.transdate = ?
1520 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1529 $buy = conv_i($buy, "NULL");
1530 $sell = conv_i($sell, "NULL");
1533 if ($buy != 0 && $sell != 0) {
1534 $set = "buy = $buy, sell = $sell";
1535 } elsif ($buy != 0) {
1536 $set = "buy = $buy";
1537 } elsif ($sell != 0) {
1538 $set = "sell = $sell";
1541 if ($sth->fetchrow_array) {
1542 $query = qq|UPDATE exchangerate
1548 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1549 VALUES (?, $buy, $sell, ?)|;
1552 do_query($self, $dbh, $query, $curr, $transdate);
1554 $main::lxdebug->leave_sub();
1557 sub save_exchangerate {
1558 $main::lxdebug->enter_sub();
1560 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1562 my $dbh = $self->dbconnect($myconfig);
1566 $buy = $rate if $fld eq 'buy';
1567 $sell = $rate if $fld eq 'sell';
1570 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1575 $main::lxdebug->leave_sub();
1578 sub get_exchangerate {
1579 $main::lxdebug->enter_sub();
1581 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1584 unless ($transdate) {
1585 $main::lxdebug->leave_sub();
1589 $query = qq|SELECT curr FROM defaults|;
1591 my ($currency) = selectrow_query($self, $dbh, $query);
1592 my ($defaultcurrency) = split m/:/, $currency;
1594 if ($currency eq $defaultcurrency) {
1595 $main::lxdebug->leave_sub();
1599 $query = qq|SELECT e.$fld FROM exchangerate e
1600 WHERE e.curr = ? AND e.transdate = ?|;
1601 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1605 $main::lxdebug->leave_sub();
1607 return $exchangerate;
1610 sub check_exchangerate {
1611 $main::lxdebug->enter_sub();
1613 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1615 unless ($transdate) {
1616 $main::lxdebug->leave_sub();
1620 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1622 if ($currency eq $defaultcurrency) {
1623 $main::lxdebug->leave_sub();
1627 my $dbh = $self->get_standard_dbh($myconfig);
1628 my $query = qq|SELECT e.$fld FROM exchangerate e
1629 WHERE e.curr = ? AND e.transdate = ?|;
1631 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1633 $main::lxdebug->leave_sub();
1635 return $exchangerate;
1638 sub get_default_currency {
1639 $main::lxdebug->enter_sub();
1641 my ($self, $myconfig) = @_;
1642 my $dbh = $self->get_standard_dbh($myconfig);
1644 my $query = qq|SELECT curr FROM defaults|;
1646 my ($curr) = selectrow_query($self, $dbh, $query);
1647 my ($defaultcurrency) = split m/:/, $curr;
1649 $main::lxdebug->leave_sub();
1651 return $defaultcurrency;
1655 sub set_payment_options {
1656 $main::lxdebug->enter_sub();
1658 my ($self, $myconfig, $transdate) = @_;
1660 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1662 my $dbh = $self->get_standard_dbh($myconfig);
1665 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1666 qq|FROM payment_terms p | .
1669 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1670 $self->{payment_terms}) =
1671 selectrow_query($self, $dbh, $query, $self->{payment_id});
1673 if ($transdate eq "") {
1674 if ($self->{invdate}) {
1675 $transdate = $self->{invdate};
1677 $transdate = $self->{transdate};
1682 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1683 qq|FROM payment_terms|;
1684 ($self->{netto_date}, $self->{skonto_date}) =
1685 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1687 my ($invtotal, $total);
1688 my (%amounts, %formatted_amounts);
1690 if ($self->{type} =~ /_order$/) {
1691 $amounts{invtotal} = $self->{ordtotal};
1692 $amounts{total} = $self->{ordtotal};
1694 } elsif ($self->{type} =~ /_quotation$/) {
1695 $amounts{invtotal} = $self->{quototal};
1696 $amounts{total} = $self->{quototal};
1699 $amounts{invtotal} = $self->{invtotal};
1700 $amounts{total} = $self->{total};
1703 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1705 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1706 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1707 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1709 foreach (keys %amounts) {
1710 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1711 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1714 if ($self->{"language_id"}) {
1716 qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1717 qq|FROM translation_payment_terms t | .
1718 qq|LEFT JOIN language l ON t.language_id = l.id | .
1719 qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1720 my ($description_long, $output_numberformat, $output_dateformat,
1721 $output_longdates) =
1722 selectrow_query($self, $dbh, $query,
1723 $self->{"language_id"}, $self->{"payment_id"});
1725 $self->{payment_terms} = $description_long if ($description_long);
1727 if ($output_dateformat) {
1728 foreach my $key (qw(netto_date skonto_date)) {
1730 $main::locale->reformat_date($myconfig, $self->{$key},
1736 if ($output_numberformat &&
1737 ($output_numberformat ne $myconfig->{"numberformat"})) {
1738 my $saved_numberformat = $myconfig->{"numberformat"};
1739 $myconfig->{"numberformat"} = $output_numberformat;
1740 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1741 $myconfig->{"numberformat"} = $saved_numberformat;
1745 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1746 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1747 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1748 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1749 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1750 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1751 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1753 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1755 $main::lxdebug->leave_sub();
1759 sub get_template_language {
1760 $main::lxdebug->enter_sub();
1762 my ($self, $myconfig) = @_;
1764 my $template_code = "";
1766 if ($self->{language_id}) {
1767 my $dbh = $self->get_standard_dbh($myconfig);
1768 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1769 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1772 $main::lxdebug->leave_sub();
1774 return $template_code;
1777 sub get_printer_code {
1778 $main::lxdebug->enter_sub();
1780 my ($self, $myconfig) = @_;
1782 my $template_code = "";
1784 if ($self->{printer_id}) {
1785 my $dbh = $self->get_standard_dbh($myconfig);
1786 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1787 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1790 $main::lxdebug->leave_sub();
1792 return $template_code;
1796 $main::lxdebug->enter_sub();
1798 my ($self, $myconfig) = @_;
1800 my $template_code = "";
1802 if ($self->{shipto_id}) {
1803 my $dbh = $self->get_standard_dbh($myconfig);
1804 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1805 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1806 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1809 $main::lxdebug->leave_sub();
1813 $main::lxdebug->enter_sub();
1815 my ($self, $dbh, $id, $module) = @_;
1820 foreach my $item (qw(name department_1 department_2 street zipcode city country
1821 contact phone fax email)) {
1822 if ($self->{"shipto$item"}) {
1823 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1825 push(@values, $self->{"shipto${item}"});
1829 if ($self->{shipto_id}) {
1830 my $query = qq|UPDATE shipto set
1832 shiptodepartment_1 = ?,
1833 shiptodepartment_2 = ?,
1842 WHERE shipto_id = ?|;
1843 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1845 my $query = qq|SELECT * FROM shipto
1846 WHERE shiptoname = ? AND
1847 shiptodepartment_1 = ? AND
1848 shiptodepartment_2 = ? AND
1849 shiptostreet = ? AND
1850 shiptozipcode = ? AND
1852 shiptocountry = ? AND
1853 shiptocontact = ? AND
1859 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1862 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1863 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1864 shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1865 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1866 do_query($self, $dbh, $query, $id, @values, $module);
1871 $main::lxdebug->leave_sub();
1875 $main::lxdebug->enter_sub();
1877 my ($self, $dbh) = @_;
1879 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1880 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1881 $self->{"employee_id"} *= 1;
1883 $main::lxdebug->leave_sub();
1887 $main::lxdebug->enter_sub();
1889 my ($self, $myconfig, $salesman_id) = @_;
1891 $main::lxdebug->leave_sub() and return unless $salesman_id;
1893 my $dbh = $self->get_standard_dbh($myconfig);
1896 selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
1900 my $user = new User($main::memberfile, $login);
1901 map({ $self->{"salesman_$_"} = $user->{$_}; }
1902 qw(address businessnumber co_ustid company duns email fax name
1904 $self->{salesman_login} = $login;
1906 $self->{salesman_name} = $login
1907 if ($self->{salesman_name} eq "");
1910 $main::lxdebug->leave_sub();
1914 $main::lxdebug->enter_sub();
1916 my ($self, $myconfig) = @_;
1918 my $dbh = $self->get_standard_dbh($myconfig);
1919 my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1920 ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1922 $main::lxdebug->leave_sub();
1926 $main::lxdebug->enter_sub();
1928 my ($self, $dbh, $id, $key) = @_;
1930 $key = "all_contacts" unless ($key);
1934 $main::lxdebug->leave_sub();
1939 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1940 qq|FROM contacts | .
1941 qq|WHERE cp_cv_id = ? | .
1942 qq|ORDER BY lower(cp_name)|;
1944 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1946 $main::lxdebug->leave_sub();
1950 $main::lxdebug->enter_sub();
1952 my ($self, $dbh, $key) = @_;
1954 my ($all, $old_id, $where, @values);
1956 if (ref($key) eq "HASH") {
1959 $key = "ALL_PROJECTS";
1961 foreach my $p (keys(%{$params})) {
1963 $all = $params->{$p};
1964 } elsif ($p eq "old_id") {
1965 $old_id = $params->{$p};
1966 } elsif ($p eq "key") {
1967 $key = $params->{$p};
1973 $where = "WHERE active ";
1975 if (ref($old_id) eq "ARRAY") {
1976 my @ids = grep({ $_ } @{$old_id});
1978 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1979 push(@values, @ids);
1982 $where .= " OR (id = ?) ";
1983 push(@values, $old_id);
1989 qq|SELECT id, projectnumber, description, active | .
1992 qq|ORDER BY lower(projectnumber)|;
1994 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1996 $main::lxdebug->leave_sub();
2000 $main::lxdebug->enter_sub();
2002 my ($self, $dbh, $vc_id, $key) = @_;
2004 $key = "all_shipto" unless ($key);
2007 # get shipping addresses
2008 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2010 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2016 $main::lxdebug->leave_sub();
2020 $main::lxdebug->enter_sub();
2022 my ($self, $dbh, $key) = @_;
2024 $key = "all_printers" unless ($key);
2026 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2028 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2030 $main::lxdebug->leave_sub();
2034 $main::lxdebug->enter_sub();
2036 my ($self, $dbh, $params) = @_;
2038 $key = $params->{key};
2039 $key = "all_charts" unless ($key);
2041 my $transdate = quote_db_date($params->{transdate});
2044 qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
2046 qq|LEFT JOIN taxkeys tk ON | .
2047 qq|(tk.id = (SELECT id FROM taxkeys | .
2048 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2049 qq| ORDER BY startdate DESC LIMIT 1)) | .
2050 qq|ORDER BY c.accno|;
2052 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2054 $main::lxdebug->leave_sub();
2057 sub _get_taxcharts {
2058 $main::lxdebug->enter_sub();
2060 my ($self, $dbh, $key) = @_;
2062 $key = "all_taxcharts" unless ($key);
2064 my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
2066 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2068 $main::lxdebug->leave_sub();
2072 $main::lxdebug->enter_sub();
2074 my ($self, $dbh, $key) = @_;
2076 $key = "all_taxzones" unless ($key);
2078 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2080 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2082 $main::lxdebug->leave_sub();
2085 sub _get_employees {
2086 $main::lxdebug->enter_sub();
2088 my ($self, $dbh, $default_key, $key) = @_;
2090 $key = $default_key unless ($key);
2091 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2093 $main::lxdebug->leave_sub();
2096 sub _get_business_types {
2097 $main::lxdebug->enter_sub();
2099 my ($self, $dbh, $key) = @_;
2101 $key = "all_business_types" unless ($key);
2103 selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2105 $main::lxdebug->leave_sub();
2108 sub _get_languages {
2109 $main::lxdebug->enter_sub();
2111 my ($self, $dbh, $key) = @_;
2113 $key = "all_languages" unless ($key);
2115 my $query = qq|SELECT * FROM language ORDER BY id|;
2117 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2119 $main::lxdebug->leave_sub();
2122 sub _get_dunning_configs {
2123 $main::lxdebug->enter_sub();
2125 my ($self, $dbh, $key) = @_;
2127 $key = "all_dunning_configs" unless ($key);
2129 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2131 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2133 $main::lxdebug->leave_sub();
2136 sub _get_currencies {
2137 $main::lxdebug->enter_sub();
2139 my ($self, $dbh, $key) = @_;
2141 $key = "all_currencies" unless ($key);
2143 my $query = qq|SELECT curr AS currency FROM defaults|;
2145 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2147 $main::lxdebug->leave_sub();
2151 $main::lxdebug->enter_sub();
2153 my ($self, $dbh, $key) = @_;
2155 $key = "all_payments" unless ($key);
2157 my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2159 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2161 $main::lxdebug->leave_sub();
2164 sub _get_customers {
2165 $main::lxdebug->enter_sub();
2167 my ($self, $dbh, $key, $limit) = @_;
2169 $key = "all_customers" unless ($key);
2170 $limit_clause = "LIMIT $limit" if $limit;
2172 my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2174 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2176 $main::lxdebug->leave_sub();
2180 $main::lxdebug->enter_sub();
2182 my ($self, $dbh, $key) = @_;
2184 $key = "all_vendors" unless ($key);
2186 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2188 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2190 $main::lxdebug->leave_sub();
2193 sub _get_departments {
2194 $main::lxdebug->enter_sub();
2196 my ($self, $dbh, $key) = @_;
2198 $key = "all_departments" unless ($key);
2200 my $query = qq|SELECT * FROM department ORDER BY description|;
2202 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2204 $main::lxdebug->leave_sub();
2207 sub _get_warehouses {
2208 $main::lxdebug->enter_sub();
2210 my ($self, $dbh, $param) = @_;
2212 my ($key, $bins_key);
2214 if ('' eq ref $param) {
2218 $key = $param->{key};
2219 $bins_key = $param->{bins};
2222 my $query = qq|SELECT w.* FROM warehouse w
2223 WHERE (NOT w.invalid) AND
2224 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2225 ORDER BY w.sortkey|;
2227 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2230 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2231 my $sth = prepare_query($self, $dbh, $query);
2233 foreach my $warehouse (@{ $self->{$key} }) {
2234 do_statement($self, $sth, $query, $warehouse->{id});
2235 $warehouse->{$bins_key} = [];
2237 while (my $ref = $sth->fetchrow_hashref()) {
2238 push @{ $warehouse->{$bins_key} }, $ref;
2244 $main::lxdebug->leave_sub();
2248 $main::lxdebug->enter_sub();
2250 my ($self, $dbh, $table, $key, $sortkey) = @_;
2252 my $query = qq|SELECT * FROM $table|;
2253 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2255 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2257 $main::lxdebug->leave_sub();
2261 $main::lxdebug->enter_sub();
2263 my ($self, $dbh, $key) = @_;
2265 $key ||= "all_groups";
2267 my $groups = $main::auth->read_groups();
2269 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2271 $main::lxdebug->leave_sub();
2275 $main::lxdebug->enter_sub();
2280 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2281 my ($sth, $query, $ref);
2283 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2284 my $vc_id = $self->{"${vc}_id"};
2286 if ($params{"contacts"}) {
2287 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2290 if ($params{"shipto"}) {
2291 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2294 if ($params{"projects"} || $params{"all_projects"}) {
2295 $self->_get_projects($dbh, $params{"all_projects"} ?
2296 $params{"all_projects"} : $params{"projects"},
2297 $params{"all_projects"} ? 1 : 0);
2300 if ($params{"printers"}) {
2301 $self->_get_printers($dbh, $params{"printers"});
2304 if ($params{"languages"}) {
2305 $self->_get_languages($dbh, $params{"languages"});
2308 if ($params{"charts"}) {
2309 $self->_get_charts($dbh, $params{"charts"});
2312 if ($params{"taxcharts"}) {
2313 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2316 if ($params{"taxzones"}) {
2317 $self->_get_taxzones($dbh, $params{"taxzones"});
2320 if ($params{"employees"}) {
2321 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2324 if ($params{"salesmen"}) {
2325 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2328 if ($params{"business_types"}) {
2329 $self->_get_business_types($dbh, $params{"business_types"});
2332 if ($params{"dunning_configs"}) {
2333 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2336 if($params{"currencies"}) {
2337 $self->_get_currencies($dbh, $params{"currencies"});
2340 if($params{"customers"}) {
2341 if (ref $params{"customers"} eq 'HASH') {
2342 $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2344 $self->_get_customers($dbh, $params{"customers"});
2348 if($params{"vendors"}) {
2349 if (ref $params{"vendors"} eq 'HASH') {
2350 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2352 $self->_get_vendors($dbh, $params{"vendors"});
2356 if($params{"payments"}) {
2357 $self->_get_payments($dbh, $params{"payments"});
2360 if($params{"departments"}) {
2361 $self->_get_departments($dbh, $params{"departments"});
2364 if ($params{price_factors}) {
2365 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2368 if ($params{warehouses}) {
2369 $self->_get_warehouses($dbh, $params{warehouses});
2372 if ($params{groups}) {
2373 $self->_get_groups($dbh, $params{groups});
2375 if ($params{partsgroup}) {
2376 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2379 $main::lxdebug->leave_sub();
2382 # this sub gets the id and name from $table
2384 $main::lxdebug->enter_sub();
2386 my ($self, $myconfig, $table) = @_;
2388 # connect to database
2389 my $dbh = $self->get_standard_dbh($myconfig);
2391 $table = $table eq "customer" ? "customer" : "vendor";
2392 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2394 my ($query, @values);
2396 if (!$self->{openinvoices}) {
2398 if ($self->{customernumber} ne "") {
2399 $where = qq|(vc.customernumber ILIKE ?)|;
2400 push(@values, '%' . $self->{customernumber} . '%');
2402 $where = qq|(vc.name ILIKE ?)|;
2403 push(@values, '%' . $self->{$table} . '%');
2407 qq~SELECT vc.id, vc.name,
2408 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2410 WHERE $where AND (NOT vc.obsolete)
2414 qq~SELECT DISTINCT vc.id, vc.name,
2415 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2417 JOIN $table vc ON (a.${table}_id = vc.id)
2418 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2420 push(@values, '%' . $self->{$table} . '%');
2423 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2425 $main::lxdebug->leave_sub();
2427 return scalar(@{ $self->{name_list} });
2430 # the selection sub is used in the AR, AP, IS, IR and OE module
2433 $main::lxdebug->enter_sub();
2435 my ($self, $myconfig, $table, $module) = @_;
2438 my $dbh = $self->get_standard_dbh($myconfig);
2440 $table = $table eq "customer" ? "customer" : "vendor";
2442 my $query = qq|SELECT count(*) FROM $table|;
2443 my ($count) = selectrow_query($self, $dbh, $query);
2445 # build selection list
2446 if ($count < $myconfig->{vclimit}) {
2447 $query = qq|SELECT id, name, salesman_id
2448 FROM $table WHERE NOT obsolete
2450 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2454 $self->get_employee($dbh);
2456 # setup sales contacts
2457 $query = qq|SELECT e.id, e.name
2459 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2460 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2463 push(@{ $self->{all_employees} },
2464 { id => $self->{employee_id},
2465 name => $self->{employee} });
2467 # sort the whole thing
2468 @{ $self->{all_employees} } =
2469 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2471 if ($module eq 'AR') {
2473 # prepare query for departments
2474 $query = qq|SELECT id, description
2477 ORDER BY description|;
2480 $query = qq|SELECT id, description
2482 ORDER BY description|;
2485 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2488 $query = qq|SELECT id, description
2492 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2495 $query = qq|SELECT printer_description, id
2497 ORDER BY printer_description|;
2499 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2502 $query = qq|SELECT id, description
2506 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2508 $main::lxdebug->leave_sub();
2511 sub language_payment {
2512 $main::lxdebug->enter_sub();
2514 my ($self, $myconfig) = @_;
2516 my $dbh = $self->get_standard_dbh($myconfig);
2518 my $query = qq|SELECT id, description
2522 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2525 $query = qq|SELECT printer_description, id
2527 ORDER BY printer_description|;
2529 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2532 $query = qq|SELECT id, description
2536 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2538 # get buchungsgruppen
2539 $query = qq|SELECT id, description
2540 FROM buchungsgruppen|;
2542 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2544 $main::lxdebug->leave_sub();
2547 # this is only used for reports
2548 sub all_departments {
2549 $main::lxdebug->enter_sub();
2551 my ($self, $myconfig, $table) = @_;
2553 my $dbh = $self->get_standard_dbh($myconfig);
2556 if ($table eq 'customer') {
2557 $where = "WHERE role = 'P' ";
2560 my $query = qq|SELECT id, description
2563 ORDER BY description|;
2564 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2566 delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2568 $main::lxdebug->leave_sub();
2572 $main::lxdebug->enter_sub();
2574 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2577 if ($table eq "customer") {
2586 $self->all_vc($myconfig, $table, $module);
2588 # get last customers or vendors
2589 my ($query, $sth, $ref);
2591 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2596 my $transdate = "current_date";
2597 if ($self->{transdate}) {
2598 $transdate = $dbh->quote($self->{transdate});
2601 # now get the account numbers
2602 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2603 FROM chart c, taxkeys tk
2604 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2605 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2608 $sth = $dbh->prepare($query);
2610 do_statement($self, $sth, $query, '%' . $module . '%');
2612 $self->{accounts} = "";
2613 while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2615 foreach my $key (split(/:/, $ref->{link})) {
2616 if ($key =~ /\Q$module\E/) {
2618 # cross reference for keys
2619 $xkeyref{ $ref->{accno} } = $key;
2621 push @{ $self->{"${module}_links"}{$key} },
2622 { accno => $ref->{accno},
2623 description => $ref->{description},
2624 taxkey => $ref->{taxkey_id},
2625 tax_id => $ref->{tax_id} };
2627 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2633 # get taxkeys and description
2634 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2635 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2637 if (($module eq "AP") || ($module eq "AR")) {
2638 # get tax rates and description
2639 $query = qq|SELECT * FROM tax|;
2640 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2646 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2647 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2648 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2649 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2651 d.description AS department,
2654 JOIN $table c ON (a.${table}_id = c.id)
2655 LEFT JOIN employee e ON (e.id = a.employee_id)
2656 LEFT JOIN department d ON (d.id = a.department_id)
2658 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2660 foreach $key (keys %$ref) {
2661 $self->{$key} = $ref->{$key};
2664 my $transdate = "current_date";
2665 if ($self->{transdate}) {
2666 $transdate = $dbh->quote($self->{transdate});
2669 # now get the account numbers
2670 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2672 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2674 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2675 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2678 $sth = $dbh->prepare($query);
2679 do_statement($self, $sth, $query, "%$module%");
2681 $self->{accounts} = "";
2682 while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2684 foreach my $key (split(/:/, $ref->{link})) {
2685 if ($key =~ /\Q$module\E/) {
2687 # cross reference for keys
2688 $xkeyref{ $ref->{accno} } = $key;
2690 push @{ $self->{"${module}_links"}{$key} },
2691 { accno => $ref->{accno},
2692 description => $ref->{description},
2693 taxkey => $ref->{taxkey_id},
2694 tax_id => $ref->{tax_id} };
2696 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2702 # get amounts from individual entries
2705 c.accno, c.description,
2706 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2710 LEFT JOIN chart c ON (c.id = a.chart_id)
2711 LEFT JOIN project p ON (p.id = a.project_id)
2712 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2713 WHERE (tk.taxkey_id=a.taxkey) AND
2714 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2715 THEN tk.chart_id = a.chart_id
2718 OR (c.link='%tax%')) AND
2719 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2720 WHERE a.trans_id = ?
2721 AND a.fx_transaction = '0'
2722 ORDER BY a.oid, a.transdate|;
2723 $sth = $dbh->prepare($query);
2724 do_statement($self, $sth, $query, $self->{id});
2726 # get exchangerate for currency
2727 $self->{exchangerate} =
2728 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2731 # store amounts in {acc_trans}{$key} for multiple accounts
2732 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2733 $ref->{exchangerate} =
2734 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2735 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2738 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2739 $ref->{amount} *= -1;
2741 $ref->{index} = $index;
2743 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2749 d.curr AS currencies, d.closedto, d.revtrans,
2750 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2751 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2753 $ref = selectfirst_hashref_query($self, $dbh, $query);
2754 map { $self->{$_} = $ref->{$_} } keys %$ref;
2761 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2762 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2763 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2765 $ref = selectfirst_hashref_query($self, $dbh, $query);
2766 map { $self->{$_} = $ref->{$_} } keys %$ref;
2768 if ($self->{"$self->{vc}_id"}) {
2770 # only setup currency
2771 ($self->{currency}) = split(/:/, $self->{currencies});
2775 $self->lastname_used($dbh, $myconfig, $table, $module);
2777 # get exchangerate for currency
2778 $self->{exchangerate} =
2779 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2785 $main::lxdebug->leave_sub();
2789 $main::lxdebug->enter_sub();
2791 my ($self, $dbh, $myconfig, $table, $module) = @_;
2795 $table = $table eq "customer" ? "customer" : "vendor";
2796 my %column_map = ("a.curr" => "currency",
2797 "a.${table}_id" => "${table}_id",
2798 "a.department_id" => "department_id",
2799 "d.description" => "department",
2800 "ct.name" => $table,
2801 "current_date + ct.terms" => "duedate",
2804 if ($self->{type} =~ /delivery_order/) {
2805 $arap = 'delivery_orders';
2806 delete $column_map{"a.curr"};
2808 } elsif ($self->{type} =~ /_order/) {
2810 $where = "quotation = '0'";
2812 } elsif ($self->{type} =~ /_quotation/) {
2814 $where = "quotation = '1'";
2816 } elsif ($table eq 'customer') {
2824 $where = "($where) AND" if ($where);
2825 my $query = qq|SELECT MAX(id) FROM $arap
2826 WHERE $where ${table}_id > 0|;
2827 my ($trans_id) = selectrow_query($self, $dbh, $query);
2830 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2831 $query = qq|SELECT $column_spec
2833 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2834 LEFT JOIN department d ON (a.department_id = d.id)
2836 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2838 map { $self->{$_} = $ref->{$_} } values %column_map;
2840 $main::lxdebug->leave_sub();
2844 $main::lxdebug->enter_sub();
2846 my ($self, $myconfig, $thisdate, $days) = @_;
2848 my $dbh = $self->get_standard_dbh($myconfig);
2853 my $dateformat = $myconfig->{dateformat};
2854 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2855 $thisdate = $dbh->quote($thisdate);
2856 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2858 $query = qq|SELECT current_date AS thisdate|;
2861 ($thisdate) = selectrow_query($self, $dbh, $query);
2863 $main::lxdebug->leave_sub();
2869 $main::lxdebug->enter_sub();
2871 my ($self, $string) = @_;
2873 if ($string !~ /%/) {
2874 $string = "%$string%";
2877 $string =~ s/\'/\'\'/g;
2879 $main::lxdebug->leave_sub();
2885 $main::lxdebug->enter_sub();
2887 my ($self, $flds, $new, $count, $numrows) = @_;
2891 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2896 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2898 $j = $item->{ndx} - 1;
2899 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2903 for $i ($count + 1 .. $numrows) {
2904 map { delete $self->{"${_}_$i"} } @{$flds};
2907 $main::lxdebug->leave_sub();
2911 $main::lxdebug->enter_sub();
2913 my ($self, $myconfig) = @_;
2917 my $dbh = $self->dbconnect_noauto($myconfig);
2919 my $query = qq|DELETE FROM status
2920 WHERE (formname = ?) AND (trans_id = ?)|;
2921 my $sth = prepare_query($self, $dbh, $query);
2923 if ($self->{formname} =~ /(check|receipt)/) {
2924 for $i (1 .. $self->{rowcount}) {
2925 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2928 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2932 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2933 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2935 my %queued = split / /, $self->{queued};
2938 if ($self->{formname} =~ /(check|receipt)/) {
2940 # this is a check or receipt, add one entry for each lineitem
2941 my ($accno) = split /--/, $self->{account};
2942 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2943 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2944 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2945 $sth = prepare_query($self, $dbh, $query);
2947 for $i (1 .. $self->{rowcount}) {
2948 if ($self->{"checked_$i"}) {
2949 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2955 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2956 VALUES (?, ?, ?, ?, ?)|;
2957 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2958 $queued{$self->{formname}}, $self->{formname});
2964 $main::lxdebug->leave_sub();
2968 $main::lxdebug->enter_sub();
2970 my ($self, $dbh) = @_;
2972 my ($query, $printed, $emailed);
2974 my $formnames = $self->{printed};
2975 my $emailforms = $self->{emailed};
2977 $query = qq|DELETE FROM status
2978 WHERE (formname = ?) AND (trans_id = ?)|;
2979 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2981 # this only applies to the forms
2982 # checks and receipts are posted when printed or queued
2984 if ($self->{queued}) {
2985 my %queued = split / /, $self->{queued};
2987 foreach my $formname (keys %queued) {
2988 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2989 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2991 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2992 VALUES (?, ?, ?, ?, ?)|;
2993 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2995 $formnames =~ s/\Q$self->{formname}\E//;
2996 $emailforms =~ s/\Q$self->{formname}\E//;
3001 # save printed, emailed info
3002 $formnames =~ s/^ +//g;
3003 $emailforms =~ s/^ +//g;
3006 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3007 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3009 foreach my $formname (keys %status) {
3010 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3011 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3013 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3014 VALUES (?, ?, ?, ?)|;
3015 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3018 $main::lxdebug->leave_sub();
3022 # $main::locale->text('SAVED')
3023 # $main::locale->text('DELETED')
3024 # $main::locale->text('ADDED')
3025 # $main::locale->text('PAYMENT POSTED')
3026 # $main::locale->text('POSTED')
3027 # $main::locale->text('POSTED AS NEW')
3028 # $main::locale->text('ELSE')
3029 # $main::locale->text('SAVED FOR DUNNING')
3030 # $main::locale->text('DUNNING STARTED')
3031 # $main::locale->text('PRINTED')
3032 # $main::locale->text('MAILED')
3033 # $main::locale->text('SCREENED')
3034 # $main::locale->text('CANCELED')
3035 # $main::locale->text('invoice')
3036 # $main::locale->text('proforma')
3037 # $main::locale->text('sales_order')
3038 # $main::locale->text('packing_list')
3039 # $main::locale->text('pick_list')
3040 # $main::locale->text('purchase_order')
3041 # $main::locale->text('bin_list')
3042 # $main::locale->text('sales_quotation')
3043 # $main::locale->text('request_quotation')
3046 $main::lxdebug->enter_sub();
3051 if(!exists $self->{employee_id}) {
3052 &get_employee($self, $dbh);
3056 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3057 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3058 my @values = (conv_i($self->{id}), $self->{login},
3059 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3060 do_query($self, $dbh, $query, @values);
3062 $main::lxdebug->leave_sub();
3066 $main::lxdebug->enter_sub();
3068 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3069 my ($orderBy, $desc) = split(/\-\-/, $order);
3070 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3073 if ($trans_id ne "") {
3075 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 | .
3076 qq|FROM history_erp h | .
3077 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3078 qq|WHERE trans_id = | . $trans_id
3079 . $restriction . qq| |
3082 my $sth = $dbh->prepare($query) || $self->dberror($query);
3084 $sth->execute() || $self->dberror("$query");
3086 while(my $hash_ref = $sth->fetchrow_hashref()) {
3087 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3088 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3089 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3090 $tempArray[$i++] = $hash_ref;
3092 $main::lxdebug->leave_sub() and return \@tempArray
3093 if ($i > 0 && $tempArray[0] ne "");
3095 $main::lxdebug->leave_sub();
3099 sub update_defaults {
3100 $main::lxdebug->enter_sub();
3102 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3105 if ($provided_dbh) {
3106 $dbh = $provided_dbh;
3108 $dbh = $self->dbconnect_noauto($myconfig);
3110 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3111 my $sth = $dbh->prepare($query);
3113 $sth->execute || $self->dberror($query);
3114 my ($var) = $sth->fetchrow_array;
3117 if ($var =~ m/\d+$/) {
3118 my $new_var = (substr $var, $-[0]) * 1 + 1;
3119 my $len_diff = length($var) - $-[0] - length($new_var);
3120 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3126 $query = qq|UPDATE defaults SET $fld = ?|;
3127 do_query($self, $dbh, $query, $var);
3129 if (!$provided_dbh) {
3134 $main::lxdebug->leave_sub();
3139 sub update_business {
3140 $main::lxdebug->enter_sub();
3142 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3145 if ($provided_dbh) {
3146 $dbh = $provided_dbh;
3148 $dbh = $self->dbconnect_noauto($myconfig);
3151 qq|SELECT customernumberinit FROM business
3152 WHERE id = ? FOR UPDATE|;
3153 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3155 if ($var =~ m/\d+$/) {
3156 my $new_var = (substr $var, $-[0]) * 1 + 1;
3157 my $len_diff = length($var) - $-[0] - length($new_var);
3158 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3164 $query = qq|UPDATE business
3165 SET customernumberinit = ?
3167 do_query($self, $dbh, $query, $var, $business_id);
3169 if (!$provided_dbh) {
3174 $main::lxdebug->leave_sub();
3179 sub get_partsgroup {
3180 $main::lxdebug->enter_sub();
3182 my ($self, $myconfig, $p) = @_;
3183 my $target = $p->{target} || 'all_partsgroup';
3185 my $dbh = $self->get_standard_dbh($myconfig);
3187 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3189 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3192 if ($p->{searchitems} eq 'part') {
3193 $query .= qq|WHERE p.inventory_accno_id > 0|;
3195 if ($p->{searchitems} eq 'service') {
3196 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3198 if ($p->{searchitems} eq 'assembly') {
3199 $query .= qq|WHERE p.assembly = '1'|;
3201 if ($p->{searchitems} eq 'labor') {
3202 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3205 $query .= qq|ORDER BY partsgroup|;
3208 $query = qq|SELECT id, partsgroup FROM partsgroup
3209 ORDER BY partsgroup|;
3212 if ($p->{language_code}) {
3213 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3214 t.description AS translation
3216 JOIN parts p ON (p.partsgroup_id = pg.id)
3217 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3218 ORDER BY translation|;
3219 @values = ($p->{language_code});
3222 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3224 $main::lxdebug->leave_sub();
3227 sub get_pricegroup {
3228 $main::lxdebug->enter_sub();
3230 my ($self, $myconfig, $p) = @_;
3232 my $dbh = $self->get_standard_dbh($myconfig);
3234 my $query = qq|SELECT p.id, p.pricegroup
3237 $query .= qq| ORDER BY pricegroup|;
3240 $query = qq|SELECT id, pricegroup FROM pricegroup
3241 ORDER BY pricegroup|;
3244 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3246 $main::lxdebug->leave_sub();
3250 # usage $form->all_years($myconfig, [$dbh])
3251 # return list of all years where bookings found
3254 $main::lxdebug->enter_sub();
3256 my ($self, $myconfig, $dbh) = @_;
3258 $dbh ||= $self->get_standard_dbh($myconfig);
3261 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3262 (SELECT MAX(transdate) FROM acc_trans)|;
3263 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3265 if ($myconfig->{dateformat} =~ /^yy/) {
3266 ($startdate) = split /\W/, $startdate;
3267 ($enddate) = split /\W/, $enddate;
3269 (@_) = split /\W/, $startdate;
3271 (@_) = split /\W/, $enddate;
3276 $startdate = substr($startdate,0,4);
3277 $enddate = substr($enddate,0,4);
3279 while ($enddate >= $startdate) {
3280 push @all_years, $enddate--;
3285 $main::lxdebug->leave_sub();
3289 $main::lxdebug->enter_sub();
3293 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if $self->{$_} } @vars;
3295 $main::lxdebug->leave_sub();
3299 $main::lxdebug->enter_sub();
3304 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if $self->{_VAR_BACKUP}->{$_} } @vars;
3306 $main::lxdebug->leave_sub();