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 $main::lxdebug->enter_sub();
776 my ($self, $error, %params) = @_;
779 'title_error' => $params{title},
780 'label_error' => $error,
783 if ($params{action}) {
786 map { delete($self->{$_}); } qw(action);
787 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
789 $add_params->{SHOW_BUTTON} = 1;
790 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
791 $add_params->{VARIABLES} = \@vars;
793 } elsif ($params{back_button}) {
794 $add_params->{SHOW_BACK_BUTTON} = 1;
797 $self->{title} = $title if ($title);
800 print $self->parse_html_template("generic/error", $add_params);
802 $main::lxdebug->leave_sub();
804 die("Error: $error\n");
807 sub show_generic_information {
808 $main::lxdebug->enter_sub();
810 my ($self, $text, $title) = @_;
813 'title_information' => $title,
814 'label_information' => $text,
817 $self->{title} = $title if ($title);
820 print $self->parse_html_template("generic/information", $add_params);
822 $main::lxdebug->leave_sub();
824 die("Information: $error\n");
827 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
828 # changed it to accept an arbitrary number of triggers - sschoeling
830 $main::lxdebug->enter_sub();
833 my $myconfig = shift;
836 # set dateform for jsscript
839 "dd.mm.yy" => "%d.%m.%Y",
840 "dd-mm-yy" => "%d-%m-%Y",
841 "dd/mm/yy" => "%d/%m/%Y",
842 "mm/dd/yy" => "%m/%d/%Y",
843 "mm-dd-yy" => "%m-%d-%Y",
844 "yyyy-mm-dd" => "%Y-%m-%d",
847 my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
848 $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
855 inputField : "| . (shift) . qq|",
856 ifFormat :"$ifFormat",
857 align : "| . (shift) . qq|",
858 button : "| . (shift) . qq|"
864 <script type="text/javascript">
865 <!--| . join("", @triggers) . qq|//-->
869 $main::lxdebug->leave_sub();
872 } #end sub write_trigger
875 $main::lxdebug->enter_sub();
877 my ($self, $msg) = @_;
879 if ($self->{callback}) {
881 ($script, $argv) = split(/\?/, $self->{callback}, 2);
883 $script =~ s|[^a-zA-Z0-9_\.]||g;
884 exec("perl", "$script", $argv);
892 $main::lxdebug->leave_sub();
895 # sort of columns removed - empty sub
897 $main::lxdebug->enter_sub();
899 my ($self, @columns) = @_;
901 $main::lxdebug->leave_sub();
907 $main::lxdebug->enter_sub(2);
909 my ($self, $myconfig, $amount, $places, $dash) = @_;
915 # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
917 my $neg = ($amount =~ s/^-//);
918 my $exp = ($amount =~ m/[e]/) ? 1 : 0;
920 if (defined($places) && ($places ne '')) {
926 my ($actual_places) = ($amount =~ /\.(\d+)/);
927 $actual_places = length($actual_places);
928 $places = $actual_places > $places ? $actual_places : $places;
931 $amount = $self->round_amount($amount, $places);
934 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
935 my @p = split(/\./, $amount); # split amount at decimal point
937 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
940 $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
943 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
944 ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
945 ($neg ? "-$amount" : "$amount" ) ;
949 $main::lxdebug->leave_sub(2);
953 sub format_amount_units {
954 $main::lxdebug->enter_sub();
959 my $myconfig = \%main::myconfig;
960 my $amount = $params{amount} * 1;
961 my $places = $params{places};
962 my $part_unit_name = $params{part_unit};
963 my $amount_unit_name = $params{amount_unit};
964 my $conv_units = $params{conv_units};
965 my $max_places = $params{max_places};
967 if (!$part_unit_name) {
968 $main::lxdebug->leave_sub();
972 AM->retrieve_all_units();
973 my $all_units = $main::all_units;
975 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
976 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
979 if (!scalar @{ $conv_units }) {
980 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
981 $main::lxdebug->leave_sub();
985 my $part_unit = $all_units->{$part_unit_name};
986 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
988 $amount *= $conv_unit->{factor};
992 foreach my $unit (@$conv_units) {
993 my $last = $unit->{name} eq $part_unit->{name};
995 $num = int($amount / $unit->{factor});
996 $amount -= $num * $unit->{factor};
999 if ($last ? $amount : $num) {
1000 push @values, { "unit" => $unit->{name},
1001 "amount" => $last ? $amount / $unit->{factor} : $num,
1002 "places" => $last ? $places : 0 };
1009 push @values, { "unit" => $part_unit_name,
1014 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1016 $main::lxdebug->leave_sub();
1022 $main::lxdebug->enter_sub(2);
1027 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
1028 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1029 $input =~ s/\#\#/\#/g;
1031 $main::lxdebug->leave_sub(2);
1039 $main::lxdebug->enter_sub(2);
1041 my ($self, $myconfig, $amount) = @_;
1043 if ( ($myconfig->{numberformat} eq '1.000,00')
1044 || ($myconfig->{numberformat} eq '1000,00')) {
1049 if ($myconfig->{numberformat} eq "1'000.00") {
1055 $main::lxdebug->leave_sub(2);
1057 return ($amount * 1);
1061 $main::lxdebug->enter_sub(2);
1063 my ($self, $amount, $places) = @_;
1066 # Rounding like "Kaufmannsrunden"
1067 # Descr. http://de.wikipedia.org/wiki/Rundung
1069 # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
1072 $amount = $amount * (10**($places));
1073 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1075 $main::lxdebug->leave_sub(2);
1077 return $round_amount;
1081 sub parse_template {
1082 $main::lxdebug->enter_sub();
1084 my ($self, $myconfig, $userspath) = @_;
1085 my ($template, $out);
1089 $self->{"cwd"} = getcwd();
1090 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1092 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1093 $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1094 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1095 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1096 $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1097 } elsif (($self->{"format"} =~ /html/i) ||
1098 (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1099 $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1100 } elsif (($self->{"format"} =~ /xml/i) ||
1101 (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1102 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1103 } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1104 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1105 } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1106 $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1107 } elsif ( defined $self->{'format'}) {
1108 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1109 } elsif ( $self->{'format'} eq '' ) {
1110 $self->error("No Outputformat given: $self->{'format'}");
1111 } else { #Catch the rest
1112 $self->error("Outputformat not defined: $self->{'format'}");
1115 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1116 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1118 if (!$self->{employee_id}) {
1119 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1122 map({ $self->{"${_}"} = $myconfig->{$_}; }
1126 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1128 # OUT is used for the media, screen, printer, email
1129 # for postscript we store a copy in a temporary file
1131 my $prepend_userspath;
1133 if (!$self->{tmpfile}) {
1134 $self->{tmpfile} = "${fileid}.$self->{IN}";
1135 $prepend_userspath = 1;
1138 $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1140 $self->{tmpfile} =~ s|.*/||;
1141 $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1142 $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1144 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1145 $out = $self->{OUT};
1146 $self->{OUT} = ">$self->{tmpfile}";
1150 open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
1152 open(OUT, ">-") or $self->error("STDOUT : $!");
1156 if (!$template->parse(*OUT)) {
1158 $self->error("$self->{IN} : " . $template->get_error());
1163 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1165 if ($self->{media} eq 'email') {
1167 my $mail = new Mailer;
1169 map { $mail->{$_} = $self->{$_} }
1170 qw(cc bcc subject message version format);
1171 $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1172 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1173 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1174 $mail->{fileid} = "$fileid.";
1175 $myconfig->{signature} =~ s/\r//g;
1177 # if we send html or plain text inline
1178 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1179 $mail->{contenttype} = "text/html";
1181 $mail->{message} =~ s/\r//g;
1182 $mail->{message} =~ s/\n/<br>\n/g;
1183 $myconfig->{signature} =~ s/\n/<br>\n/g;
1184 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1186 open(IN, $self->{tmpfile})
1187 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1189 $mail->{message} .= $_;
1196 if (!$self->{"do_not_attach"}) {
1197 @{ $mail->{attachments} } =
1198 ({ "filename" => $self->{"tmpfile"},
1199 "name" => $self->{"attachment_filename"} ?
1200 $self->{"attachment_filename"} : $self->{"tmpfile"} });
1203 $mail->{message} =~ s/\r//g;
1204 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1208 my $err = $mail->send();
1209 $self->error($self->cleanup . "$err") if ($err);
1213 $self->{OUT} = $out;
1215 my $numbytes = (-s $self->{tmpfile});
1216 open(IN, $self->{tmpfile})
1217 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1219 $self->{copies} = 1 unless $self->{media} eq 'printer';
1221 chdir("$self->{cwd}");
1222 #print(STDERR "Kopien $self->{copies}\n");
1223 #print(STDERR "OUT $self->{OUT}\n");
1224 for my $i (1 .. $self->{copies}) {
1226 open(OUT, $self->{OUT})
1227 or $self->error($self->cleanup . "$self->{OUT} : $!");
1229 $self->{attachment_filename} = ($self->{attachment_filename})
1230 ? $self->{attachment_filename}
1231 : $self->generate_attachment_filename();
1233 # launch application
1234 print qq|Content-Type: | . $template->get_mime_type() . qq|
1235 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1236 Content-Length: $numbytes
1240 open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1260 chdir("$self->{cwd}");
1261 $main::lxdebug->leave_sub();
1264 sub get_formname_translation {
1265 my ($self, $formname) = @_;
1267 $formname ||= $self->{formname};
1269 my %formname_translations = (
1270 bin_list => $main::locale->text('Bin List'),
1271 credit_note => $main::locale->text('Credit Note'),
1272 invoice => $main::locale->text('Invoice'),
1273 packing_list => $main::locale->text('Packing List'),
1274 pick_list => $main::locale->text('Pick List'),
1275 proforma => $main::locale->text('Proforma Invoice'),
1276 purchase_order => $main::locale->text('Purchase Order'),
1277 request_quotation => $main::locale->text('RFQ'),
1278 sales_order => $main::locale->text('Confirmation'),
1279 sales_quotation => $main::locale->text('Quotation'),
1280 storno_invoice => $main::locale->text('Storno Invoice'),
1281 storno_packing_list => $main::locale->text('Storno Packing List'),
1282 sales_delivery_order => $main::locale->text('Delivery Order'),
1283 purchase_delivery_order => $main::locale->text('Delivery Order'),
1286 return $formname_translations{$formname}
1289 sub get_number_prefix_for_type {
1293 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1294 : ($self->{type} =~ /_quotation$/) ? 'quo'
1295 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1301 sub get_extension_for_format {
1304 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1305 : $self->{format} =~ /postscript/i ? ".ps"
1306 : $self->{format} =~ /opendocument/i ? ".odt"
1307 : $self->{format} =~ /html/i ? ".html"
1313 sub generate_attachment_filename {
1316 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1317 my $prefix = $self->get_number_prefix_for_type();
1319 if ($attachment_filename && $self->{"${prefix}number"}) {
1320 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1321 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1322 $attachment_filename =~ s|[\s/\\]+|_|g;
1324 $attachment_filename = "";
1327 return $attachment_filename;
1330 sub generate_email_subject {
1333 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1334 my $prefix = $self->get_number_prefix_for_type();
1336 if ($subject && $self->{"${prefix}number"}) {
1337 $subject .= " " . $self->{"${prefix}number"}
1344 $main::lxdebug->enter_sub();
1348 chdir("$self->{tmpdir}");
1351 if (-f "$self->{tmpfile}.err") {
1352 open(FH, "$self->{tmpfile}.err");
1357 if ($self->{tmpfile}) {
1358 $self->{tmpfile} =~ s|.*/||g;
1360 $self->{tmpfile} =~ s/\.\w+$//g;
1361 my $tmpfile = $self->{tmpfile};
1362 unlink(<$tmpfile.*>);
1365 chdir("$self->{cwd}");
1367 $main::lxdebug->leave_sub();
1373 $main::lxdebug->enter_sub();
1375 my ($self, $date, $myconfig) = @_;
1377 if ($date && $date =~ /\D/) {
1379 if ($myconfig->{dateformat} =~ /^yy/) {
1380 ($yy, $mm, $dd) = split /\D/, $date;
1382 if ($myconfig->{dateformat} =~ /^mm/) {
1383 ($mm, $dd, $yy) = split /\D/, $date;
1385 if ($myconfig->{dateformat} =~ /^dd/) {
1386 ($dd, $mm, $yy) = split /\D/, $date;
1391 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1392 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1394 $dd = "0$dd" if ($dd < 10);
1395 $mm = "0$mm" if ($mm < 10);
1397 $date = "$yy$mm$dd";
1400 $main::lxdebug->leave_sub();
1405 # Database routines used throughout
1408 $main::lxdebug->enter_sub(2);
1410 my ($self, $myconfig) = @_;
1412 # connect to database
1414 DBI->connect($myconfig->{dbconnect},
1415 $myconfig->{dbuser}, $myconfig->{dbpasswd})
1419 if ($myconfig->{dboptions}) {
1420 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1423 $main::lxdebug->leave_sub(2);
1428 sub dbconnect_noauto {
1429 $main::lxdebug->enter_sub();
1431 my ($self, $myconfig) = @_;
1433 # connect to database
1435 DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1436 $myconfig->{dbpasswd}, { AutoCommit => 0 })
1440 if ($myconfig->{dboptions}) {
1441 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1444 $main::lxdebug->leave_sub();
1449 sub get_standard_dbh {
1450 $main::lxdebug->enter_sub(2);
1452 my ($self, $myconfig) = @_;
1454 if ($standard_dbh && !$standard_dbh->{Active}) {
1455 $main::lxdebug->message(LXDebug::INFO, "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1456 undef $standard_dbh;
1459 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1461 $main::lxdebug->leave_sub(2);
1463 return $standard_dbh;
1467 $main::lxdebug->enter_sub();
1469 my ($self, $date, $myconfig) = @_;
1470 my $dbh = $self->dbconnect($myconfig);
1472 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1473 my $sth = prepare_execute_query($self, $dbh, $query, $date);
1474 my ($closed) = $sth->fetchrow_array;
1476 $main::lxdebug->leave_sub();
1481 sub update_balance {
1482 $main::lxdebug->enter_sub();
1484 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1486 # if we have a value, go do it
1489 # retrieve balance from table
1490 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1491 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1492 my ($balance) = $sth->fetchrow_array;
1498 $query = "UPDATE $table SET $field = $balance WHERE $where";
1499 do_query($self, $dbh, $query, @values);
1501 $main::lxdebug->leave_sub();
1504 sub update_exchangerate {
1505 $main::lxdebug->enter_sub();
1507 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1509 # some sanity check for currency
1511 $main::lxdebug->leave_sub();
1514 $query = qq|SELECT curr FROM defaults|;
1516 my ($currency) = selectrow_query($self, $dbh, $query);
1517 my ($defaultcurrency) = split m/:/, $currency;
1520 if ($curr eq $defaultcurrency) {
1521 $main::lxdebug->leave_sub();
1525 $query = qq|SELECT e.curr FROM exchangerate e
1526 WHERE e.curr = ? AND e.transdate = ?
1528 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1537 $buy = conv_i($buy, "NULL");
1538 $sell = conv_i($sell, "NULL");
1541 if ($buy != 0 && $sell != 0) {
1542 $set = "buy = $buy, sell = $sell";
1543 } elsif ($buy != 0) {
1544 $set = "buy = $buy";
1545 } elsif ($sell != 0) {
1546 $set = "sell = $sell";
1549 if ($sth->fetchrow_array) {
1550 $query = qq|UPDATE exchangerate
1556 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1557 VALUES (?, $buy, $sell, ?)|;
1560 do_query($self, $dbh, $query, $curr, $transdate);
1562 $main::lxdebug->leave_sub();
1565 sub save_exchangerate {
1566 $main::lxdebug->enter_sub();
1568 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1570 my $dbh = $self->dbconnect($myconfig);
1574 $buy = $rate if $fld eq 'buy';
1575 $sell = $rate if $fld eq 'sell';
1578 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1583 $main::lxdebug->leave_sub();
1586 sub get_exchangerate {
1587 $main::lxdebug->enter_sub();
1589 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1592 unless ($transdate) {
1593 $main::lxdebug->leave_sub();
1597 $query = qq|SELECT curr FROM defaults|;
1599 my ($currency) = selectrow_query($self, $dbh, $query);
1600 my ($defaultcurrency) = split m/:/, $currency;
1602 if ($currency eq $defaultcurrency) {
1603 $main::lxdebug->leave_sub();
1607 $query = qq|SELECT e.$fld FROM exchangerate e
1608 WHERE e.curr = ? AND e.transdate = ?|;
1609 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1613 $main::lxdebug->leave_sub();
1615 return $exchangerate;
1618 sub check_exchangerate {
1619 $main::lxdebug->enter_sub();
1621 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1623 unless ($transdate) {
1624 $main::lxdebug->leave_sub();
1628 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1630 if ($currency eq $defaultcurrency) {
1631 $main::lxdebug->leave_sub();
1635 my $dbh = $self->get_standard_dbh($myconfig);
1636 my $query = qq|SELECT e.$fld FROM exchangerate e
1637 WHERE e.curr = ? AND e.transdate = ?|;
1639 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1641 $main::lxdebug->leave_sub();
1643 return $exchangerate;
1646 sub get_default_currency {
1647 $main::lxdebug->enter_sub();
1649 my ($self, $myconfig) = @_;
1650 my $dbh = $self->get_standard_dbh($myconfig);
1652 my $query = qq|SELECT curr FROM defaults|;
1654 my ($curr) = selectrow_query($self, $dbh, $query);
1655 my ($defaultcurrency) = split m/:/, $curr;
1657 $main::lxdebug->leave_sub();
1659 return $defaultcurrency;
1663 sub set_payment_options {
1664 $main::lxdebug->enter_sub();
1666 my ($self, $myconfig, $transdate) = @_;
1668 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1670 my $dbh = $self->get_standard_dbh($myconfig);
1673 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1674 qq|FROM payment_terms p | .
1677 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1678 $self->{payment_terms}) =
1679 selectrow_query($self, $dbh, $query, $self->{payment_id});
1681 if ($transdate eq "") {
1682 if ($self->{invdate}) {
1683 $transdate = $self->{invdate};
1685 $transdate = $self->{transdate};
1690 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1691 qq|FROM payment_terms|;
1692 ($self->{netto_date}, $self->{skonto_date}) =
1693 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1695 my ($invtotal, $total);
1696 my (%amounts, %formatted_amounts);
1698 if ($self->{type} =~ /_order$/) {
1699 $amounts{invtotal} = $self->{ordtotal};
1700 $amounts{total} = $self->{ordtotal};
1702 } elsif ($self->{type} =~ /_quotation$/) {
1703 $amounts{invtotal} = $self->{quototal};
1704 $amounts{total} = $self->{quototal};
1707 $amounts{invtotal} = $self->{invtotal};
1708 $amounts{total} = $self->{total};
1711 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1713 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1714 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1715 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1717 foreach (keys %amounts) {
1718 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1719 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1722 if ($self->{"language_id"}) {
1724 qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1725 qq|FROM translation_payment_terms t | .
1726 qq|LEFT JOIN language l ON t.language_id = l.id | .
1727 qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1728 my ($description_long, $output_numberformat, $output_dateformat,
1729 $output_longdates) =
1730 selectrow_query($self, $dbh, $query,
1731 $self->{"language_id"}, $self->{"payment_id"});
1733 $self->{payment_terms} = $description_long if ($description_long);
1735 if ($output_dateformat) {
1736 foreach my $key (qw(netto_date skonto_date)) {
1738 $main::locale->reformat_date($myconfig, $self->{$key},
1744 if ($output_numberformat &&
1745 ($output_numberformat ne $myconfig->{"numberformat"})) {
1746 my $saved_numberformat = $myconfig->{"numberformat"};
1747 $myconfig->{"numberformat"} = $output_numberformat;
1748 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1749 $myconfig->{"numberformat"} = $saved_numberformat;
1753 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1754 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1755 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1756 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1757 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1758 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1759 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1761 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1763 $main::lxdebug->leave_sub();
1767 sub get_template_language {
1768 $main::lxdebug->enter_sub();
1770 my ($self, $myconfig) = @_;
1772 my $template_code = "";
1774 if ($self->{language_id}) {
1775 my $dbh = $self->get_standard_dbh($myconfig);
1776 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1777 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1780 $main::lxdebug->leave_sub();
1782 return $template_code;
1785 sub get_printer_code {
1786 $main::lxdebug->enter_sub();
1788 my ($self, $myconfig) = @_;
1790 my $template_code = "";
1792 if ($self->{printer_id}) {
1793 my $dbh = $self->get_standard_dbh($myconfig);
1794 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1795 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1798 $main::lxdebug->leave_sub();
1800 return $template_code;
1804 $main::lxdebug->enter_sub();
1806 my ($self, $myconfig) = @_;
1808 my $template_code = "";
1810 if ($self->{shipto_id}) {
1811 my $dbh = $self->get_standard_dbh($myconfig);
1812 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1813 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1814 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1817 $main::lxdebug->leave_sub();
1821 $main::lxdebug->enter_sub();
1823 my ($self, $dbh, $id, $module) = @_;
1828 foreach my $item (qw(name department_1 department_2 street zipcode city country
1829 contact phone fax email)) {
1830 if ($self->{"shipto$item"}) {
1831 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1833 push(@values, $self->{"shipto${item}"});
1837 if ($self->{shipto_id}) {
1838 my $query = qq|UPDATE shipto set
1840 shiptodepartment_1 = ?,
1841 shiptodepartment_2 = ?,
1850 WHERE shipto_id = ?|;
1851 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1853 my $query = qq|SELECT * FROM shipto
1854 WHERE shiptoname = ? AND
1855 shiptodepartment_1 = ? AND
1856 shiptodepartment_2 = ? AND
1857 shiptostreet = ? AND
1858 shiptozipcode = ? AND
1860 shiptocountry = ? AND
1861 shiptocontact = ? AND
1867 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1870 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1871 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1872 shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1873 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1874 do_query($self, $dbh, $query, $id, @values, $module);
1879 $main::lxdebug->leave_sub();
1883 $main::lxdebug->enter_sub();
1885 my ($self, $dbh) = @_;
1887 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1888 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1889 $self->{"employee_id"} *= 1;
1891 $main::lxdebug->leave_sub();
1894 sub get_employee_data {
1895 $main::lxdebug->enter_sub();
1900 Common::check_params(\%params, qw(prefix));
1901 Common::check_params_x(\%params, qw(id));
1904 $main::lxdebug->leave_sub();
1908 my $myconfig = \%main::myconfig;
1909 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
1911 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
1914 my $user = User->new($login);
1915 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
1917 $self->{$params{prefix} . '_login'} = $login;
1918 $self->{$params{prefix} . '_name'} ||= $login;
1921 $main::lxdebug->leave_sub();
1925 $main::lxdebug->enter_sub();
1927 my ($self, $myconfig) = @_;
1929 my $dbh = $self->get_standard_dbh($myconfig);
1930 my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1931 ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1933 $main::lxdebug->leave_sub();
1937 $main::lxdebug->enter_sub();
1939 my ($self, $dbh, $id, $key) = @_;
1941 $key = "all_contacts" unless ($key);
1945 $main::lxdebug->leave_sub();
1950 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1951 qq|FROM contacts | .
1952 qq|WHERE cp_cv_id = ? | .
1953 qq|ORDER BY lower(cp_name)|;
1955 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1957 $main::lxdebug->leave_sub();
1961 $main::lxdebug->enter_sub();
1963 my ($self, $dbh, $key) = @_;
1965 my ($all, $old_id, $where, @values);
1967 if (ref($key) eq "HASH") {
1970 $key = "ALL_PROJECTS";
1972 foreach my $p (keys(%{$params})) {
1974 $all = $params->{$p};
1975 } elsif ($p eq "old_id") {
1976 $old_id = $params->{$p};
1977 } elsif ($p eq "key") {
1978 $key = $params->{$p};
1984 $where = "WHERE active ";
1986 if (ref($old_id) eq "ARRAY") {
1987 my @ids = grep({ $_ } @{$old_id});
1989 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1990 push(@values, @ids);
1993 $where .= " OR (id = ?) ";
1994 push(@values, $old_id);
2000 qq|SELECT id, projectnumber, description, active | .
2003 qq|ORDER BY lower(projectnumber)|;
2005 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2007 $main::lxdebug->leave_sub();
2011 $main::lxdebug->enter_sub();
2013 my ($self, $dbh, $vc_id, $key) = @_;
2015 $key = "all_shipto" unless ($key);
2018 # get shipping addresses
2019 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2021 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2027 $main::lxdebug->leave_sub();
2031 $main::lxdebug->enter_sub();
2033 my ($self, $dbh, $key) = @_;
2035 $key = "all_printers" unless ($key);
2037 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2039 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2041 $main::lxdebug->leave_sub();
2045 $main::lxdebug->enter_sub();
2047 my ($self, $dbh, $params) = @_;
2049 $key = $params->{key};
2050 $key = "all_charts" unless ($key);
2052 my $transdate = quote_db_date($params->{transdate});
2055 qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
2057 qq|LEFT JOIN taxkeys tk ON | .
2058 qq|(tk.id = (SELECT id FROM taxkeys | .
2059 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2060 qq| ORDER BY startdate DESC LIMIT 1)) | .
2061 qq|ORDER BY c.accno|;
2063 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2065 $main::lxdebug->leave_sub();
2068 sub _get_taxcharts {
2069 $main::lxdebug->enter_sub();
2071 my ($self, $dbh, $key) = @_;
2073 $key = "all_taxcharts" unless ($key);
2075 my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
2077 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2079 $main::lxdebug->leave_sub();
2083 $main::lxdebug->enter_sub();
2085 my ($self, $dbh, $key) = @_;
2087 $key = "all_taxzones" unless ($key);
2089 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2091 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2093 $main::lxdebug->leave_sub();
2096 sub _get_employees {
2097 $main::lxdebug->enter_sub();
2099 my ($self, $dbh, $default_key, $key) = @_;
2101 $key = $default_key unless ($key);
2102 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2104 $main::lxdebug->leave_sub();
2107 sub _get_business_types {
2108 $main::lxdebug->enter_sub();
2110 my ($self, $dbh, $key) = @_;
2112 $key = "all_business_types" unless ($key);
2114 selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
2116 $main::lxdebug->leave_sub();
2119 sub _get_languages {
2120 $main::lxdebug->enter_sub();
2122 my ($self, $dbh, $key) = @_;
2124 $key = "all_languages" unless ($key);
2126 my $query = qq|SELECT * FROM language ORDER BY id|;
2128 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2130 $main::lxdebug->leave_sub();
2133 sub _get_dunning_configs {
2134 $main::lxdebug->enter_sub();
2136 my ($self, $dbh, $key) = @_;
2138 $key = "all_dunning_configs" unless ($key);
2140 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2142 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2144 $main::lxdebug->leave_sub();
2147 sub _get_currencies {
2148 $main::lxdebug->enter_sub();
2150 my ($self, $dbh, $key) = @_;
2152 $key = "all_currencies" unless ($key);
2154 my $query = qq|SELECT curr AS currency FROM defaults|;
2156 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2158 $main::lxdebug->leave_sub();
2162 $main::lxdebug->enter_sub();
2164 my ($self, $dbh, $key) = @_;
2166 $key = "all_payments" unless ($key);
2168 my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2170 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2172 $main::lxdebug->leave_sub();
2175 sub _get_customers {
2176 $main::lxdebug->enter_sub();
2178 my ($self, $dbh, $key, $limit) = @_;
2180 $key = "all_customers" unless ($key);
2181 $limit_clause = "LIMIT $limit" if $limit;
2183 my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
2185 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2187 $main::lxdebug->leave_sub();
2191 $main::lxdebug->enter_sub();
2193 my ($self, $dbh, $key) = @_;
2195 $key = "all_vendors" unless ($key);
2197 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2199 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2201 $main::lxdebug->leave_sub();
2204 sub _get_departments {
2205 $main::lxdebug->enter_sub();
2207 my ($self, $dbh, $key) = @_;
2209 $key = "all_departments" unless ($key);
2211 my $query = qq|SELECT * FROM department ORDER BY description|;
2213 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2215 $main::lxdebug->leave_sub();
2218 sub _get_warehouses {
2219 $main::lxdebug->enter_sub();
2221 my ($self, $dbh, $param) = @_;
2223 my ($key, $bins_key);
2225 if ('' eq ref $param) {
2229 $key = $param->{key};
2230 $bins_key = $param->{bins};
2233 my $query = qq|SELECT w.* FROM warehouse w
2234 WHERE (NOT w.invalid) AND
2235 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2236 ORDER BY w.sortkey|;
2238 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2241 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2242 my $sth = prepare_query($self, $dbh, $query);
2244 foreach my $warehouse (@{ $self->{$key} }) {
2245 do_statement($self, $sth, $query, $warehouse->{id});
2246 $warehouse->{$bins_key} = [];
2248 while (my $ref = $sth->fetchrow_hashref()) {
2249 push @{ $warehouse->{$bins_key} }, $ref;
2255 $main::lxdebug->leave_sub();
2259 $main::lxdebug->enter_sub();
2261 my ($self, $dbh, $table, $key, $sortkey) = @_;
2263 my $query = qq|SELECT * FROM $table|;
2264 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2266 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2268 $main::lxdebug->leave_sub();
2272 $main::lxdebug->enter_sub();
2274 my ($self, $dbh, $key) = @_;
2276 $key ||= "all_groups";
2278 my $groups = $main::auth->read_groups();
2280 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2282 $main::lxdebug->leave_sub();
2286 $main::lxdebug->enter_sub();
2291 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2292 my ($sth, $query, $ref);
2294 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2295 my $vc_id = $self->{"${vc}_id"};
2297 if ($params{"contacts"}) {
2298 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2301 if ($params{"shipto"}) {
2302 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2305 if ($params{"projects"} || $params{"all_projects"}) {
2306 $self->_get_projects($dbh, $params{"all_projects"} ?
2307 $params{"all_projects"} : $params{"projects"},
2308 $params{"all_projects"} ? 1 : 0);
2311 if ($params{"printers"}) {
2312 $self->_get_printers($dbh, $params{"printers"});
2315 if ($params{"languages"}) {
2316 $self->_get_languages($dbh, $params{"languages"});
2319 if ($params{"charts"}) {
2320 $self->_get_charts($dbh, $params{"charts"});
2323 if ($params{"taxcharts"}) {
2324 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2327 if ($params{"taxzones"}) {
2328 $self->_get_taxzones($dbh, $params{"taxzones"});
2331 if ($params{"employees"}) {
2332 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2335 if ($params{"salesmen"}) {
2336 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2339 if ($params{"business_types"}) {
2340 $self->_get_business_types($dbh, $params{"business_types"});
2343 if ($params{"dunning_configs"}) {
2344 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2347 if($params{"currencies"}) {
2348 $self->_get_currencies($dbh, $params{"currencies"});
2351 if($params{"customers"}) {
2352 if (ref $params{"customers"} eq 'HASH') {
2353 $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2355 $self->_get_customers($dbh, $params{"customers"});
2359 if($params{"vendors"}) {
2360 if (ref $params{"vendors"} eq 'HASH') {
2361 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2363 $self->_get_vendors($dbh, $params{"vendors"});
2367 if($params{"payments"}) {
2368 $self->_get_payments($dbh, $params{"payments"});
2371 if($params{"departments"}) {
2372 $self->_get_departments($dbh, $params{"departments"});
2375 if ($params{price_factors}) {
2376 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2379 if ($params{warehouses}) {
2380 $self->_get_warehouses($dbh, $params{warehouses});
2383 if ($params{groups}) {
2384 $self->_get_groups($dbh, $params{groups});
2386 if ($params{partsgroup}) {
2387 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2390 $main::lxdebug->leave_sub();
2393 # this sub gets the id and name from $table
2395 $main::lxdebug->enter_sub();
2397 my ($self, $myconfig, $table) = @_;
2399 # connect to database
2400 my $dbh = $self->get_standard_dbh($myconfig);
2402 $table = $table eq "customer" ? "customer" : "vendor";
2403 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2405 my ($query, @values);
2407 if (!$self->{openinvoices}) {
2409 if ($self->{customernumber} ne "") {
2410 $where = qq|(vc.customernumber ILIKE ?)|;
2411 push(@values, '%' . $self->{customernumber} . '%');
2413 $where = qq|(vc.name ILIKE ?)|;
2414 push(@values, '%' . $self->{$table} . '%');
2418 qq~SELECT vc.id, vc.name,
2419 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2421 WHERE $where AND (NOT vc.obsolete)
2425 qq~SELECT DISTINCT vc.id, vc.name,
2426 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2428 JOIN $table vc ON (a.${table}_id = vc.id)
2429 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2431 push(@values, '%' . $self->{$table} . '%');
2434 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2436 $main::lxdebug->leave_sub();
2438 return scalar(@{ $self->{name_list} });
2441 # the selection sub is used in the AR, AP, IS, IR and OE module
2444 $main::lxdebug->enter_sub();
2446 my ($self, $myconfig, $table, $module) = @_;
2449 my $dbh = $self->get_standard_dbh($myconfig);
2451 $table = $table eq "customer" ? "customer" : "vendor";
2453 my $query = qq|SELECT count(*) FROM $table|;
2454 my ($count) = selectrow_query($self, $dbh, $query);
2456 # build selection list
2457 if ($count < $myconfig->{vclimit}) {
2458 $query = qq|SELECT id, name, salesman_id
2459 FROM $table WHERE NOT obsolete
2461 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2465 $self->get_employee($dbh);
2467 # setup sales contacts
2468 $query = qq|SELECT e.id, e.name
2470 WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2471 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2474 push(@{ $self->{all_employees} },
2475 { id => $self->{employee_id},
2476 name => $self->{employee} });
2478 # sort the whole thing
2479 @{ $self->{all_employees} } =
2480 sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2482 if ($module eq 'AR') {
2484 # prepare query for departments
2485 $query = qq|SELECT id, description
2488 ORDER BY description|;
2491 $query = qq|SELECT id, description
2493 ORDER BY description|;
2496 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2499 $query = qq|SELECT id, description
2503 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2506 $query = qq|SELECT printer_description, id
2508 ORDER BY printer_description|;
2510 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2513 $query = qq|SELECT id, description
2517 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2519 $main::lxdebug->leave_sub();
2522 sub language_payment {
2523 $main::lxdebug->enter_sub();
2525 my ($self, $myconfig) = @_;
2527 my $dbh = $self->get_standard_dbh($myconfig);
2529 my $query = qq|SELECT id, description
2533 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2536 $query = qq|SELECT printer_description, id
2538 ORDER BY printer_description|;
2540 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2543 $query = qq|SELECT id, description
2547 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2549 # get buchungsgruppen
2550 $query = qq|SELECT id, description
2551 FROM buchungsgruppen|;
2553 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2555 $main::lxdebug->leave_sub();
2558 # this is only used for reports
2559 sub all_departments {
2560 $main::lxdebug->enter_sub();
2562 my ($self, $myconfig, $table) = @_;
2564 my $dbh = $self->get_standard_dbh($myconfig);
2567 if ($table eq 'customer') {
2568 $where = "WHERE role = 'P' ";
2571 my $query = qq|SELECT id, description
2574 ORDER BY description|;
2575 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2577 delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2579 $main::lxdebug->leave_sub();
2583 $main::lxdebug->enter_sub();
2585 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2588 if ($table eq "customer") {
2597 $self->all_vc($myconfig, $table, $module);
2599 # get last customers or vendors
2600 my ($query, $sth, $ref);
2602 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2607 my $transdate = "current_date";
2608 if ($self->{transdate}) {
2609 $transdate = $dbh->quote($self->{transdate});
2612 # now get the account numbers
2613 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2614 FROM chart c, taxkeys tk
2615 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2616 (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2619 $sth = $dbh->prepare($query);
2621 do_statement($self, $sth, $query, '%' . $module . '%');
2623 $self->{accounts} = "";
2624 while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2626 foreach my $key (split(/:/, $ref->{link})) {
2627 if ($key =~ /\Q$module\E/) {
2629 # cross reference for keys
2630 $xkeyref{ $ref->{accno} } = $key;
2632 push @{ $self->{"${module}_links"}{$key} },
2633 { accno => $ref->{accno},
2634 description => $ref->{description},
2635 taxkey => $ref->{taxkey_id},
2636 tax_id => $ref->{tax_id} };
2638 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2644 # get taxkeys and description
2645 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2646 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2648 if (($module eq "AP") || ($module eq "AR")) {
2649 # get tax rates and description
2650 $query = qq|SELECT * FROM tax|;
2651 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2657 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2658 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2659 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2660 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2662 d.description AS department,
2665 JOIN $table c ON (a.${table}_id = c.id)
2666 LEFT JOIN employee e ON (e.id = a.employee_id)
2667 LEFT JOIN department d ON (d.id = a.department_id)
2669 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2671 foreach $key (keys %$ref) {
2672 $self->{$key} = $ref->{$key};
2675 my $transdate = "current_date";
2676 if ($self->{transdate}) {
2677 $transdate = $dbh->quote($self->{transdate});
2680 # now get the account numbers
2681 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2683 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2685 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2686 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2689 $sth = $dbh->prepare($query);
2690 do_statement($self, $sth, $query, "%$module%");
2692 $self->{accounts} = "";
2693 while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2695 foreach my $key (split(/:/, $ref->{link})) {
2696 if ($key =~ /\Q$module\E/) {
2698 # cross reference for keys
2699 $xkeyref{ $ref->{accno} } = $key;
2701 push @{ $self->{"${module}_links"}{$key} },
2702 { accno => $ref->{accno},
2703 description => $ref->{description},
2704 taxkey => $ref->{taxkey_id},
2705 tax_id => $ref->{tax_id} };
2707 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2713 # get amounts from individual entries
2716 c.accno, c.description,
2717 a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2721 LEFT JOIN chart c ON (c.id = a.chart_id)
2722 LEFT JOIN project p ON (p.id = a.project_id)
2723 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2724 WHERE (tk.taxkey_id=a.taxkey) AND
2725 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2726 THEN tk.chart_id = a.chart_id
2729 OR (c.link='%tax%')) AND
2730 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2731 WHERE a.trans_id = ?
2732 AND a.fx_transaction = '0'
2733 ORDER BY a.oid, a.transdate|;
2734 $sth = $dbh->prepare($query);
2735 do_statement($self, $sth, $query, $self->{id});
2737 # get exchangerate for currency
2738 $self->{exchangerate} =
2739 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2742 # store amounts in {acc_trans}{$key} for multiple accounts
2743 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2744 $ref->{exchangerate} =
2745 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2746 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2749 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2750 $ref->{amount} *= -1;
2752 $ref->{index} = $index;
2754 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2760 d.curr AS currencies, d.closedto, d.revtrans,
2761 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2762 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2764 $ref = selectfirst_hashref_query($self, $dbh, $query);
2765 map { $self->{$_} = $ref->{$_} } keys %$ref;
2772 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2773 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2774 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2776 $ref = selectfirst_hashref_query($self, $dbh, $query);
2777 map { $self->{$_} = $ref->{$_} } keys %$ref;
2779 if ($self->{"$self->{vc}_id"}) {
2781 # only setup currency
2782 ($self->{currency}) = split(/:/, $self->{currencies});
2786 $self->lastname_used($dbh, $myconfig, $table, $module);
2788 # get exchangerate for currency
2789 $self->{exchangerate} =
2790 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2796 $main::lxdebug->leave_sub();
2800 $main::lxdebug->enter_sub();
2802 my ($self, $dbh, $myconfig, $table, $module) = @_;
2806 $table = $table eq "customer" ? "customer" : "vendor";
2807 my %column_map = ("a.curr" => "currency",
2808 "a.${table}_id" => "${table}_id",
2809 "a.department_id" => "department_id",
2810 "d.description" => "department",
2811 "ct.name" => $table,
2812 "current_date + ct.terms" => "duedate",
2815 if ($self->{type} =~ /delivery_order/) {
2816 $arap = 'delivery_orders';
2817 delete $column_map{"a.curr"};
2819 } elsif ($self->{type} =~ /_order/) {
2821 $where = "quotation = '0'";
2823 } elsif ($self->{type} =~ /_quotation/) {
2825 $where = "quotation = '1'";
2827 } elsif ($table eq 'customer') {
2835 $where = "($where) AND" if ($where);
2836 my $query = qq|SELECT MAX(id) FROM $arap
2837 WHERE $where ${table}_id > 0|;
2838 my ($trans_id) = selectrow_query($self, $dbh, $query);
2841 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2842 $query = qq|SELECT $column_spec
2844 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2845 LEFT JOIN department d ON (a.department_id = d.id)
2847 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2849 map { $self->{$_} = $ref->{$_} } values %column_map;
2851 $main::lxdebug->leave_sub();
2855 $main::lxdebug->enter_sub();
2857 my ($self, $myconfig, $thisdate, $days) = @_;
2859 my $dbh = $self->get_standard_dbh($myconfig);
2864 my $dateformat = $myconfig->{dateformat};
2865 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2866 $thisdate = $dbh->quote($thisdate);
2867 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2869 $query = qq|SELECT current_date AS thisdate|;
2872 ($thisdate) = selectrow_query($self, $dbh, $query);
2874 $main::lxdebug->leave_sub();
2880 $main::lxdebug->enter_sub();
2882 my ($self, $string) = @_;
2884 if ($string !~ /%/) {
2885 $string = "%$string%";
2888 $string =~ s/\'/\'\'/g;
2890 $main::lxdebug->leave_sub();
2896 $main::lxdebug->enter_sub();
2898 my ($self, $flds, $new, $count, $numrows) = @_;
2902 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2907 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2909 $j = $item->{ndx} - 1;
2910 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2914 for $i ($count + 1 .. $numrows) {
2915 map { delete $self->{"${_}_$i"} } @{$flds};
2918 $main::lxdebug->leave_sub();
2922 $main::lxdebug->enter_sub();
2924 my ($self, $myconfig) = @_;
2928 my $dbh = $self->dbconnect_noauto($myconfig);
2930 my $query = qq|DELETE FROM status
2931 WHERE (formname = ?) AND (trans_id = ?)|;
2932 my $sth = prepare_query($self, $dbh, $query);
2934 if ($self->{formname} =~ /(check|receipt)/) {
2935 for $i (1 .. $self->{rowcount}) {
2936 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2939 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2943 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2944 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2946 my %queued = split / /, $self->{queued};
2949 if ($self->{formname} =~ /(check|receipt)/) {
2951 # this is a check or receipt, add one entry for each lineitem
2952 my ($accno) = split /--/, $self->{account};
2953 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2954 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2955 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2956 $sth = prepare_query($self, $dbh, $query);
2958 for $i (1 .. $self->{rowcount}) {
2959 if ($self->{"checked_$i"}) {
2960 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2966 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2967 VALUES (?, ?, ?, ?, ?)|;
2968 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2969 $queued{$self->{formname}}, $self->{formname});
2975 $main::lxdebug->leave_sub();
2979 $main::lxdebug->enter_sub();
2981 my ($self, $dbh) = @_;
2983 my ($query, $printed, $emailed);
2985 my $formnames = $self->{printed};
2986 my $emailforms = $self->{emailed};
2988 $query = qq|DELETE FROM status
2989 WHERE (formname = ?) AND (trans_id = ?)|;
2990 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2992 # this only applies to the forms
2993 # checks and receipts are posted when printed or queued
2995 if ($self->{queued}) {
2996 my %queued = split / /, $self->{queued};
2998 foreach my $formname (keys %queued) {
2999 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3000 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3002 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3003 VALUES (?, ?, ?, ?, ?)|;
3004 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3006 $formnames =~ s/\Q$self->{formname}\E//;
3007 $emailforms =~ s/\Q$self->{formname}\E//;
3012 # save printed, emailed info
3013 $formnames =~ s/^ +//g;
3014 $emailforms =~ s/^ +//g;
3017 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3018 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3020 foreach my $formname (keys %status) {
3021 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3022 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3024 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3025 VALUES (?, ?, ?, ?)|;
3026 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3029 $main::lxdebug->leave_sub();
3033 # $main::locale->text('SAVED')
3034 # $main::locale->text('DELETED')
3035 # $main::locale->text('ADDED')
3036 # $main::locale->text('PAYMENT POSTED')
3037 # $main::locale->text('POSTED')
3038 # $main::locale->text('POSTED AS NEW')
3039 # $main::locale->text('ELSE')
3040 # $main::locale->text('SAVED FOR DUNNING')
3041 # $main::locale->text('DUNNING STARTED')
3042 # $main::locale->text('PRINTED')
3043 # $main::locale->text('MAILED')
3044 # $main::locale->text('SCREENED')
3045 # $main::locale->text('CANCELED')
3046 # $main::locale->text('invoice')
3047 # $main::locale->text('proforma')
3048 # $main::locale->text('sales_order')
3049 # $main::locale->text('packing_list')
3050 # $main::locale->text('pick_list')
3051 # $main::locale->text('purchase_order')
3052 # $main::locale->text('bin_list')
3053 # $main::locale->text('sales_quotation')
3054 # $main::locale->text('request_quotation')
3057 $main::lxdebug->enter_sub();
3062 if(!exists $self->{employee_id}) {
3063 &get_employee($self, $dbh);
3067 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3068 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3069 my @values = (conv_i($self->{id}), $self->{login},
3070 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3071 do_query($self, $dbh, $query, @values);
3073 $main::lxdebug->leave_sub();
3077 $main::lxdebug->enter_sub();
3079 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3080 my ($orderBy, $desc) = split(/\-\-/, $order);
3081 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3084 if ($trans_id ne "") {
3086 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 | .
3087 qq|FROM history_erp h | .
3088 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3089 qq|WHERE trans_id = | . $trans_id
3090 . $restriction . qq| |
3093 my $sth = $dbh->prepare($query) || $self->dberror($query);
3095 $sth->execute() || $self->dberror("$query");
3097 while(my $hash_ref = $sth->fetchrow_hashref()) {
3098 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3099 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3100 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3101 $tempArray[$i++] = $hash_ref;
3103 $main::lxdebug->leave_sub() and return \@tempArray
3104 if ($i > 0 && $tempArray[0] ne "");
3106 $main::lxdebug->leave_sub();
3110 sub update_defaults {
3111 $main::lxdebug->enter_sub();
3113 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3116 if ($provided_dbh) {
3117 $dbh = $provided_dbh;
3119 $dbh = $self->dbconnect_noauto($myconfig);
3121 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3122 my $sth = $dbh->prepare($query);
3124 $sth->execute || $self->dberror($query);
3125 my ($var) = $sth->fetchrow_array;
3128 if ($var =~ m/\d+$/) {
3129 my $new_var = (substr $var, $-[0]) * 1 + 1;
3130 my $len_diff = length($var) - $-[0] - length($new_var);
3131 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3137 $query = qq|UPDATE defaults SET $fld = ?|;
3138 do_query($self, $dbh, $query, $var);
3140 if (!$provided_dbh) {
3145 $main::lxdebug->leave_sub();
3150 sub update_business {
3151 $main::lxdebug->enter_sub();
3153 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3156 if ($provided_dbh) {
3157 $dbh = $provided_dbh;
3159 $dbh = $self->dbconnect_noauto($myconfig);
3162 qq|SELECT customernumberinit FROM business
3163 WHERE id = ? FOR UPDATE|;
3164 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3166 if ($var =~ m/\d+$/) {
3167 my $new_var = (substr $var, $-[0]) * 1 + 1;
3168 my $len_diff = length($var) - $-[0] - length($new_var);
3169 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3175 $query = qq|UPDATE business
3176 SET customernumberinit = ?
3178 do_query($self, $dbh, $query, $var, $business_id);
3180 if (!$provided_dbh) {
3185 $main::lxdebug->leave_sub();
3190 sub get_partsgroup {
3191 $main::lxdebug->enter_sub();
3193 my ($self, $myconfig, $p) = @_;
3194 my $target = $p->{target} || 'all_partsgroup';
3196 my $dbh = $self->get_standard_dbh($myconfig);
3198 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3200 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3203 if ($p->{searchitems} eq 'part') {
3204 $query .= qq|WHERE p.inventory_accno_id > 0|;
3206 if ($p->{searchitems} eq 'service') {
3207 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3209 if ($p->{searchitems} eq 'assembly') {
3210 $query .= qq|WHERE p.assembly = '1'|;
3212 if ($p->{searchitems} eq 'labor') {
3213 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3216 $query .= qq|ORDER BY partsgroup|;
3219 $query = qq|SELECT id, partsgroup FROM partsgroup
3220 ORDER BY partsgroup|;
3223 if ($p->{language_code}) {
3224 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3225 t.description AS translation
3227 JOIN parts p ON (p.partsgroup_id = pg.id)
3228 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3229 ORDER BY translation|;
3230 @values = ($p->{language_code});
3233 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3235 $main::lxdebug->leave_sub();
3238 sub get_pricegroup {
3239 $main::lxdebug->enter_sub();
3241 my ($self, $myconfig, $p) = @_;
3243 my $dbh = $self->get_standard_dbh($myconfig);
3245 my $query = qq|SELECT p.id, p.pricegroup
3248 $query .= qq| ORDER BY pricegroup|;
3251 $query = qq|SELECT id, pricegroup FROM pricegroup
3252 ORDER BY pricegroup|;
3255 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3257 $main::lxdebug->leave_sub();
3261 # usage $form->all_years($myconfig, [$dbh])
3262 # return list of all years where bookings found
3265 $main::lxdebug->enter_sub();
3267 my ($self, $myconfig, $dbh) = @_;
3269 $dbh ||= $self->get_standard_dbh($myconfig);
3272 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3273 (SELECT MAX(transdate) FROM acc_trans)|;
3274 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3276 if ($myconfig->{dateformat} =~ /^yy/) {
3277 ($startdate) = split /\W/, $startdate;
3278 ($enddate) = split /\W/, $enddate;
3280 (@_) = split /\W/, $startdate;
3282 (@_) = split /\W/, $enddate;
3287 $startdate = substr($startdate,0,4);
3288 $enddate = substr($enddate,0,4);
3290 while ($enddate >= $startdate) {
3291 push @all_years, $enddate--;
3296 $main::lxdebug->leave_sub();
3300 $main::lxdebug->enter_sub();
3304 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if $self->{$_} } @vars;
3306 $main::lxdebug->leave_sub();
3310 $main::lxdebug->enter_sub();
3315 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if $self->{_VAR_BACKUP}->{$_} } @vars;
3317 $main::lxdebug->leave_sub();