1 #====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
15 # Contributors: Thomas Bayen <bayen@gmx.de>
16 # Antti Kaihola <akaihola@siba.fi>
17 # Moritz Bunkus (tex code)
19 # This program is free software; you can redistribute it and/or modify
20 # it under the terms of the GNU General Public License as published by
21 # the Free Software Foundation; either version 2 of the License, or
22 # (at your option) any later version.
24 # This program is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 # GNU General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, write to the Free Software
30 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #======================================================================
32 # Utilities for parsing forms
33 # and supporting routines for linking account numbers
34 # used in AR, AP and IS, IR modules
36 #======================================================================
59 use SL::Layout::Dispatcher;
63 use SL::MoreCommon qw(uri_encode uri_decode);
71 use List::Util qw(first max min sum);
72 use List::MoreUtils qw(all any apply);
79 disconnect_standard_dbh();
82 sub disconnect_standard_dbh {
83 return unless $standard_dbh;
84 $standard_dbh->disconnect();
89 $main::lxdebug->enter_sub();
96 if ($LXDebug::watch_form) {
98 tie %{ $self }, 'SL::Watchdog';
103 open VERSION_FILE, "VERSION"; # New but flexible code reads version from VERSION-file
104 $self->{version} = <VERSION_FILE>;
106 $self->{version} =~ s/[^0-9A-Za-z\.\_\-]//g; # only allow numbers, letters, points, underscores and dashes. Prevents injecting of malicious code.
108 $main::lxdebug->leave_sub();
115 SL::Request::read_cgi_input($self);
118 sub _flatten_variables_rec {
119 $main::lxdebug->enter_sub(2);
128 if ('' eq ref $curr->{$key}) {
129 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
131 } elsif ('HASH' eq ref $curr->{$key}) {
132 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
133 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
137 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
138 my $first_array_entry = 1;
140 foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
141 push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
142 $first_array_entry = 0;
147 $main::lxdebug->leave_sub(2);
152 sub flatten_variables {
153 $main::lxdebug->enter_sub(2);
161 push @variables, $self->_flatten_variables_rec($self, '', $_);
164 $main::lxdebug->leave_sub(2);
169 sub flatten_standard_variables {
170 $main::lxdebug->enter_sub(2);
173 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
177 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
178 push @variables, $self->_flatten_variables_rec($self, '', $_);
181 $main::lxdebug->leave_sub(2);
187 $main::lxdebug->enter_sub();
193 map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
195 $main::lxdebug->leave_sub();
199 $main::lxdebug->enter_sub(2);
202 my $password = $self->{password};
204 $self->{password} = 'X' x 8;
206 local $Data::Dumper::Sortkeys = 1;
207 my $output = Dumper($self);
209 $self->{password} = $password;
211 $main::lxdebug->leave_sub(2);
217 my ($self, $str) = @_;
219 return uri_encode($str);
223 my ($self, $str) = @_;
225 return uri_decode($str);
229 $main::lxdebug->enter_sub();
230 my ($self, $str) = @_;
232 if ($str && !ref($str)) {
233 $str =~ s/\"/"/g;
236 $main::lxdebug->leave_sub();
242 $main::lxdebug->enter_sub();
243 my ($self, $str) = @_;
245 if ($str && !ref($str)) {
246 $str =~ s/"/\"/g;
249 $main::lxdebug->leave_sub();
255 $main::lxdebug->enter_sub();
259 map({ print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
261 for (sort keys %$self) {
262 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
263 print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
266 $main::lxdebug->leave_sub();
270 my ($self, $code) = @_;
271 local $self->{__ERROR_HANDLER} = sub { die SL::X::FormError->new($_[0]) };
276 $main::lxdebug->enter_sub();
278 $main::lxdebug->show_backtrace();
280 my ($self, $msg) = @_;
282 if ($self->{__ERROR_HANDLER}) {
283 $self->{__ERROR_HANDLER}->($msg);
285 } elsif ($ENV{HTTP_USER_AGENT}) {
287 $self->show_generic_error($msg);
290 print STDERR "Error: $msg\n";
294 $main::lxdebug->leave_sub();
298 $main::lxdebug->enter_sub();
300 my ($self, $msg) = @_;
302 if ($ENV{HTTP_USER_AGENT}) {
305 if (!$self->{header}) {
311 <p class="message_ok"><b>$msg</b></p>
313 <script type="text/javascript">
315 // If JavaScript is enabled, the whole thing will be reloaded.
316 // The reason is: When one changes his menu setup (HTML / CSS ...)
317 // it now loads the correct code into the browser instead of do nothing.
318 setTimeout("top.frames.location.href='login.pl'",500);
327 if ($self->{info_function}) {
328 &{ $self->{info_function} }($msg);
334 $main::lxdebug->leave_sub();
337 # calculates the number of rows in a textarea based on the content and column number
338 # can be capped with maxrows
340 $main::lxdebug->enter_sub();
341 my ($self, $str, $cols, $maxrows, $minrows) = @_;
345 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
348 $main::lxdebug->leave_sub();
350 return max(min($rows, $maxrows), $minrows);
354 $main::lxdebug->enter_sub();
356 my ($self, $msg) = @_;
358 $self->error("$msg\n" . $DBI::errstr);
360 $main::lxdebug->leave_sub();
364 $main::lxdebug->enter_sub();
366 my ($self, $name, $msg) = @_;
369 foreach my $part (split m/\./, $name) {
370 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
373 $curr = $curr->{$part};
376 $main::lxdebug->leave_sub();
379 sub _get_request_uri {
382 return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
383 return URI->new if !$ENV{REQUEST_URI}; # for testing
385 my $scheme = $ENV{HTTPS} && (lc $ENV{HTTPS} eq 'on') ? 'https' : 'http';
386 my $port = $ENV{SERVER_PORT};
387 $port = undef if (($scheme eq 'http' ) && ($port == 80))
388 || (($scheme eq 'https') && ($port == 443));
390 my $uri = URI->new("${scheme}://");
391 $uri->scheme($scheme);
393 $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
394 $uri->path_query($ENV{REQUEST_URI});
400 sub _add_to_request_uri {
403 my $relative_new_path = shift;
404 my $request_uri = shift || $self->_get_request_uri;
405 my $relative_new_uri = URI->new($relative_new_path);
406 my @request_segments = $request_uri->path_segments;
408 my $new_uri = $request_uri->clone;
409 $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
414 sub create_http_response {
415 $main::lxdebug->enter_sub();
420 my $cgi = $::request->{cgi};
423 if (defined $main::auth) {
424 my $uri = $self->_get_request_uri;
425 my @segments = $uri->path_segments;
427 $uri->path_segments(@segments);
429 my $session_cookie_value = $main::auth->get_session_id();
431 if ($session_cookie_value) {
432 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
433 '-value' => $session_cookie_value,
434 '-path' => $uri->path,
435 '-secure' => $ENV{HTTPS});
439 my %cgi_params = ('-type' => $params{content_type});
440 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
441 $cgi_params{'-cookie'} = $session_cookie if ($session_cookie);
443 map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length);
445 my $output = $cgi->header(%cgi_params);
447 $main::lxdebug->leave_sub();
453 $::lxdebug->enter_sub;
455 my ($self, %params) = @_;
456 my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
459 $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
461 if ($params{no_layout}) {
462 $::request->{layout} = SL::Layout::Dispatcher->new(style => 'none');
465 my $layout = $::request->{layout};
467 # standard css for all
468 # this should gradually move to the layouts that need it
469 $layout->use_stylesheet("$_.css") for qw(
470 main menu list_accounts jquery.autocomplete
471 jquery.multiselect2side frame_header/header
472 ui-lightness/jquery-ui
476 $layout->use_javascript("$_.js") for (qw(
477 jquery jquery-ui jquery.cookie jqModal jquery.checkall
478 common part_selection switchmenuframe
479 ), "jquery/ui/i18n/jquery.ui.datepicker-$::myconfig{countrycode}");
481 $self->{favicon} ||= "favicon.ico";
482 $self->{titlebar} = join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->{version} if $self->{title} || !$self->{titlebar};
485 if ($self->{refresh_url} || $self->{refresh_time}) {
486 my $refresh_time = $self->{refresh_time} || 3;
487 my $refresh_url = $self->{refresh_url} || $ENV{REFERER};
488 push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
491 my $auto_reload_resources_param = $layout->auto_reload_resources_param;
493 push @header, map { qq|<link rel="stylesheet" href="${_}${auto_reload_resources_param}" type="text/css" title="Stylesheet">| } $layout->stylesheets;
494 push @header, "<style type='text/css'>\@page { size:landscape; }</style> " if $self->{landscape};
495 push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
496 push @header, map { qq|<script type="text/javascript" src="${_}${auto_reload_resources_param}"></script>| } $layout->javascripts;
497 push @header, $self->{javascript} if $self->{javascript};
498 push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
501 strict => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
502 transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
503 frameset => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
504 html5 => qq|<!DOCTYPE html>|,
508 print $self->create_http_response(content_type => 'text/html', charset => $db_charset);
509 print $doctypes{$params{doctype} || 'transitional'}, $/;
513 <meta http-equiv="Content-Type" content="text/html; charset=$db_charset">
514 <title>$self->{titlebar}</title>
516 print " $_\n" for @header;
518 <meta name="robots" content="noindex,nofollow">
523 print $::request->{layout}->pre_content;
524 print $::request->{layout}->start_content;
526 $layout->header_done;
528 $::lxdebug->leave_sub;
532 return unless $::request->{layout}->need_footer;
534 print $::request->{layout}->end_content;
535 print $::request->{layout}->post_content;
537 if (my @inline_scripts = $::request->{layout}->javascripts_inline) {
538 print "<script type='text/javascript'>@inline_scripts</script>\n";
547 sub ajax_response_header {
548 $main::lxdebug->enter_sub();
552 my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
553 my $output = $::request->{cgi}->header('-charset' => $db_charset);
555 $main::lxdebug->leave_sub();
560 sub redirect_header {
564 my $base_uri = $self->_get_request_uri;
565 my $new_uri = URI->new_abs($new_url, $base_uri);
567 die "Headers already sent" if $self->{header};
570 return $::request->{cgi}->redirect($new_uri);
573 sub set_standard_title {
574 $::lxdebug->enter_sub;
577 $self->{titlebar} = "kivitendo " . $::locale->text('Version') . " $self->{version}";
578 $self->{titlebar} .= "- $::myconfig{name}" if $::myconfig{name};
579 $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
581 $::lxdebug->leave_sub;
584 sub _prepare_html_template {
585 $main::lxdebug->enter_sub();
587 my ($self, $file, $additional_params) = @_;
590 if (!%::myconfig || !$::myconfig{"countrycode"}) {
591 $language = $::lx_office_conf{system}->{language};
593 $language = $main::myconfig{"countrycode"};
595 $language = "de" unless ($language);
597 if (-f "templates/webpages/${file}.html") {
598 $file = "templates/webpages/${file}.html";
601 my $info = "Web page template '${file}' not found.\n";
602 print qq|<pre>$info</pre>|;
606 if ($self->{"DEBUG"}) {
607 $additional_params->{"DEBUG"} = $self->{"DEBUG"};
610 if ($additional_params->{"DEBUG"}) {
611 $additional_params->{"DEBUG"} =
612 "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
615 if (%main::myconfig) {
616 $::myconfig{jsc_dateformat} = apply {
620 } $::myconfig{"dateformat"};
621 $additional_params->{"myconfig"} ||= \%::myconfig;
622 map { $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys %::myconfig;
625 $additional_params->{"conf_dbcharset"} = $::lx_office_conf{system}->{dbcharset};
626 $additional_params->{"conf_webdav"} = $::lx_office_conf{features}->{webdav};
627 $additional_params->{"conf_latex_templates"} = $::lx_office_conf{print_templates}->{latex};
628 $additional_params->{"conf_opendocument_templates"} = $::lx_office_conf{print_templates}->{opendocument};
629 $additional_params->{"conf_vertreter"} = $::lx_office_conf{features}->{vertreter};
630 $additional_params->{"conf_parts_image_css"} = $::lx_office_conf{features}->{parts_image_css};
631 $additional_params->{"conf_parts_listing_images"} = $::lx_office_conf{features}->{parts_listing_images};
632 $additional_params->{"conf_parts_show_image"} = $::lx_office_conf{features}->{parts_show_image};
633 $additional_params->{"INSTANCE_CONF"} = $::instance_conf;
635 if (my $debug_options = $::lx_office_conf{debug}{options}) {
636 map { $additional_params->{'DEBUG_' . uc($_)} = $debug_options->{$_} } keys %$debug_options;
639 if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
640 while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
641 $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
645 $main::lxdebug->leave_sub();
650 sub parse_html_template {
651 $main::lxdebug->enter_sub();
653 my ($self, $file, $additional_params) = @_;
655 $additional_params ||= { };
657 my $real_file = $self->_prepare_html_template($file, $additional_params);
658 my $template = $self->template || $self->init_template;
660 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
663 $template->process($real_file, $additional_params, \$output) || die $template->error;
665 $main::lxdebug->leave_sub();
673 return $self->template if $self->template;
675 # Force scripts/locales.pl to pick up the exception handling template.
676 # parse_html_template('generic/exception')
677 return $self->template(Template->new({
682 'PLUGIN_BASE' => 'SL::Template::Plugin',
683 'INCLUDE_PATH' => '.:templates/webpages',
684 'COMPILE_EXT' => '.tcc',
685 'COMPILE_DIR' => $::lx_office_conf{paths}->{userspath} . '/templates-cache',
686 'ERROR' => 'templates/webpages/generic/exception.html',
692 $self->{template_object} = shift if @_;
693 return $self->{template_object};
696 sub show_generic_error {
697 $main::lxdebug->enter_sub();
699 my ($self, $error, %params) = @_;
701 if ($self->{__ERROR_HANDLER}) {
702 $self->{__ERROR_HANDLER}->($error);
703 $main::lxdebug->leave_sub();
708 'title_error' => $params{title},
709 'label_error' => $error,
712 if ($params{action}) {
715 map { delete($self->{$_}); } qw(action);
716 map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
718 $add_params->{SHOW_BUTTON} = 1;
719 $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
720 $add_params->{VARIABLES} = \@vars;
722 } elsif ($params{back_button}) {
723 $add_params->{SHOW_BACK_BUTTON} = 1;
726 $self->{title} = $params{title} if $params{title};
729 print $self->parse_html_template("generic/error", $add_params);
731 print STDERR "Error: $error\n";
733 $main::lxdebug->leave_sub();
738 sub show_generic_information {
739 $main::lxdebug->enter_sub();
741 my ($self, $text, $title) = @_;
744 'title_information' => $title,
745 'label_information' => $text,
748 $self->{title} = $title if ($title);
751 print $self->parse_html_template("generic/information", $add_params);
753 $main::lxdebug->leave_sub();
758 sub _store_redirect_info_in_session {
761 return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
763 my ($controller, $params) = ($1, $2);
764 my $form = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
765 $self->{callback} = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
769 $main::lxdebug->enter_sub();
771 my ($self, $msg) = @_;
773 if (!$self->{callback}) {
777 $self->_store_redirect_info_in_session;
778 print $::form->redirect_header($self->{callback});
783 $main::lxdebug->leave_sub();
786 # sort of columns removed - empty sub
788 $main::lxdebug->enter_sub();
790 my ($self, @columns) = @_;
792 $main::lxdebug->leave_sub();
798 $main::lxdebug->enter_sub(2);
800 my ($self, $myconfig, $amount, $places, $dash) = @_;
803 my $neg = $amount < 0;
804 my $force_places = defined $places && $places >= 0;
806 $amount = $self->round_amount($amount, abs $places) if $force_places;
807 $amount = sprintf "%.*f", ($force_places ? $places : 10), abs $amount; # 6 is default for %fa
809 # before the sprintf amount was a number, afterwards it's a string. because of the dynamic nature of perl
810 # this is easy to confuse, so keep in mind: before this comment no s///, m//, concat or other strong ops on
811 # $amount. after this comment no +,-,*,/,abs. it will only introduce subtle bugs.
813 $amount =~ s/0*$// unless defined $places && $places == 0; # cull trailing 0s
815 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
816 my @p = split(/\./, $amount); # split amount at decimal point
818 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
820 if ($places || $p[1]) {
823 . (0 x (abs($places || 0) - length ($p[1]||''))); # pad the fraction
827 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
828 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
829 ($neg ? "-$amount" : "$amount" ) ;
832 $main::lxdebug->leave_sub(2);
836 sub format_amount_units {
837 $main::lxdebug->enter_sub();
842 my $myconfig = \%main::myconfig;
843 my $amount = $params{amount} * 1;
844 my $places = $params{places};
845 my $part_unit_name = $params{part_unit};
846 my $amount_unit_name = $params{amount_unit};
847 my $conv_units = $params{conv_units};
848 my $max_places = $params{max_places};
850 if (!$part_unit_name) {
851 $main::lxdebug->leave_sub();
855 my $all_units = AM->retrieve_all_units;
857 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
858 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
861 if (!scalar @{ $conv_units }) {
862 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
863 $main::lxdebug->leave_sub();
867 my $part_unit = $all_units->{$part_unit_name};
868 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
870 $amount *= $conv_unit->{factor};
875 foreach my $unit (@$conv_units) {
876 my $last = $unit->{name} eq $part_unit->{name};
878 $num = int($amount / $unit->{factor});
879 $amount -= $num * $unit->{factor};
882 if ($last ? $amount : $num) {
883 push @values, { "unit" => $unit->{name},
884 "amount" => $last ? $amount / $unit->{factor} : $num,
885 "places" => $last ? $places : 0 };
892 push @values, { "unit" => $part_unit_name,
897 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
899 $main::lxdebug->leave_sub();
905 $main::lxdebug->enter_sub(2);
910 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
911 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
912 $input =~ s/\#\#/\#/g;
914 $main::lxdebug->leave_sub(2);
922 $main::lxdebug->enter_sub(2);
924 my ($self, $myconfig, $amount) = @_;
926 if ( ($myconfig->{numberformat} eq '1.000,00')
927 || ($myconfig->{numberformat} eq '1000,00')) {
932 if ($myconfig->{numberformat} eq "1'000.00") {
938 $main::lxdebug->leave_sub(2);
940 # Make sure no code wich is not a math expression ends up in eval().
941 return 0 unless $amount =~ /^ [\s \d \( \) \- \+ \* \/ \. ]* $/x;
942 return scalar(eval($amount)) * 1 ;
946 $main::lxdebug->enter_sub(2);
948 my ($self, $amount, $places) = @_;
951 # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
953 # Round amounts to eight places before rounding to the requested
954 # number of places. This gets rid of errors due to internal floating
955 # point representation.
956 $amount = $self->round_amount($amount, 8) if $places < 8;
957 $amount = $amount * (10**($places));
958 $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
960 $main::lxdebug->leave_sub(2);
962 return $round_amount;
967 $main::lxdebug->enter_sub();
969 my ($self, $myconfig) = @_;
970 my ($out, $out_mode);
974 my $userspath = $::lx_office_conf{paths}->{userspath};
976 $self->{"cwd"} = getcwd();
977 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
982 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
983 $template_type = 'OpenDocument';
984 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
986 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
987 $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
988 $template_type = 'LaTeX';
989 $ext_for_format = 'pdf';
991 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
992 $template_type = 'HTML';
993 $ext_for_format = 'html';
995 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
996 $template_type = 'XML';
997 $ext_for_format = 'xml';
999 } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
1000 $template_type = 'XML';
1002 } elsif ( $self->{"format"} =~ /excel/i ) {
1003 $template_type = 'Excel';
1004 $ext_for_format = 'xls';
1006 } elsif ( defined $self->{'format'}) {
1007 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1009 } elsif ( $self->{'format'} eq '' ) {
1010 $self->error("No Outputformat given: $self->{'format'}");
1012 } else { #Catch the rest
1013 $self->error("Outputformat not defined: $self->{'format'}");
1016 my $template = SL::Template::create(type => $template_type,
1017 file_name => $self->{IN},
1019 myconfig => $myconfig,
1020 userspath => $userspath);
1022 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1023 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1025 if (!$self->{employee_id}) {
1026 map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1029 map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1030 map { $self->{"myconfig_${_}"} = $myconfig->{$_} } grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
1032 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1034 # OUT is used for the media, screen, printer, email
1035 # for postscript we store a copy in a temporary file
1036 my ($temp_fh, $suffix);
1037 $suffix = $self->{IN};
1038 $suffix =~ s/.*\.//;
1039 ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
1040 'kivitendo-printXXXXXX',
1041 SUFFIX => '.' . ($suffix || 'tex'),
1043 UNLINK => ($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})? 0 : 1,
1046 (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
1048 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1049 $out = $self->{OUT};
1050 $out_mode = $self->{OUT_MODE} || '>';
1051 $self->{OUT} = "$self->{tmpfile}";
1052 $self->{OUT_MODE} = '>';
1056 my $command_formatter = sub {
1057 my ($out_mode, $out) = @_;
1058 return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
1062 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1063 open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
1065 *OUT = ($::dispatcher->get_standard_filehandles)[1];
1069 if (!$template->parse(*OUT)) {
1071 $self->error("$self->{IN} : " . $template->get_error());
1074 close OUT if $self->{OUT};
1076 if ($self->{media} eq 'file') {
1077 copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
1079 chdir("$self->{cwd}");
1081 $::lxdebug->leave_sub();
1086 if ($template->uses_temp_file() || $self->{media} eq 'email') {
1088 if ($self->{media} eq 'email') {
1090 my $mail = new Mailer;
1092 map { $mail->{$_} = $self->{$_} }
1093 qw(cc bcc subject message version format);
1094 $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
1095 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1096 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1097 $mail->{fileid} = time() . '.' . $$ . '.';
1098 $myconfig->{signature} =~ s/\r//g;
1100 # if we send html or plain text inline
1101 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1102 $mail->{contenttype} = "text/html";
1103 $mail->{message} =~ s/\r//g;
1104 $mail->{message} =~ s/\n/<br>\n/g;
1105 $myconfig->{signature} =~ s/\n/<br>\n/g;
1106 $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1108 open(IN, "<", $self->{tmpfile})
1109 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1110 $mail->{message} .= $_ while <IN>;
1115 if (!$self->{"do_not_attach"}) {
1116 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1117 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1118 $mail->{attachments} = [{ "filename" => $self->{tmpfile},
1119 "name" => $attachment_name }];
1122 $mail->{message} =~ s/\r//g;
1123 $mail->{message} .= "\n-- \n$myconfig->{signature}";
1127 my $err = $mail->send();
1128 $self->error($self->cleanup . "$err") if ($err);
1132 $self->{OUT} = $out;
1133 $self->{OUT_MODE} = $out_mode;
1135 my $numbytes = (-s $self->{tmpfile});
1136 open(IN, "<", $self->{tmpfile})
1137 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1140 $self->{copies} = 1 unless $self->{media} eq 'printer';
1142 chdir("$self->{cwd}");
1143 #print(STDERR "Kopien $self->{copies}\n");
1144 #print(STDERR "OUT $self->{OUT}\n");
1145 for my $i (1 .. $self->{copies}) {
1147 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1149 open OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1150 print OUT $_ while <IN>;
1155 $self->{attachment_filename} = ($self->{attachment_filename})
1156 ? $self->{attachment_filename}
1157 : $self->generate_attachment_filename();
1159 # launch application
1160 print qq|Content-Type: | . $template->get_mime_type() . qq|
1161 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1162 Content-Length: $numbytes
1166 $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1177 chdir("$self->{cwd}");
1178 $main::lxdebug->leave_sub();
1181 sub get_formname_translation {
1182 $main::lxdebug->enter_sub();
1183 my ($self, $formname) = @_;
1185 $formname ||= $self->{formname};
1187 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1188 local $::locale = Locale->new($self->{recipient_locale});
1190 my %formname_translations = (
1191 bin_list => $main::locale->text('Bin List'),
1192 credit_note => $main::locale->text('Credit Note'),
1193 invoice => $main::locale->text('Invoice'),
1194 pick_list => $main::locale->text('Pick List'),
1195 proforma => $main::locale->text('Proforma Invoice'),
1196 purchase_order => $main::locale->text('Purchase Order'),
1197 request_quotation => $main::locale->text('RFQ'),
1198 sales_order => $main::locale->text('Confirmation'),
1199 sales_quotation => $main::locale->text('Quotation'),
1200 storno_invoice => $main::locale->text('Storno Invoice'),
1201 sales_delivery_order => $main::locale->text('Delivery Order'),
1202 purchase_delivery_order => $main::locale->text('Delivery Order'),
1203 dunning => $main::locale->text('Dunning'),
1206 $main::lxdebug->leave_sub();
1207 return $formname_translations{$formname};
1210 sub get_number_prefix_for_type {
1211 $main::lxdebug->enter_sub();
1215 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1216 : ($self->{type} =~ /_quotation$/) ? 'quo'
1217 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1220 $main::lxdebug->leave_sub();
1224 sub get_extension_for_format {
1225 $main::lxdebug->enter_sub();
1228 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1229 : $self->{format} =~ /postscript/i ? ".ps"
1230 : $self->{format} =~ /opendocument/i ? ".odt"
1231 : $self->{format} =~ /excel/i ? ".xls"
1232 : $self->{format} =~ /html/i ? ".html"
1235 $main::lxdebug->leave_sub();
1239 sub generate_attachment_filename {
1240 $main::lxdebug->enter_sub();
1243 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1244 my $recipient_locale = Locale->new($self->{recipient_locale});
1246 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1247 my $prefix = $self->get_number_prefix_for_type();
1249 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1250 $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
1252 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1253 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1256 $attachment_filename = "";
1259 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1260 $attachment_filename =~ s|[\s/\\]+|_|g;
1262 $main::lxdebug->leave_sub();
1263 return $attachment_filename;
1266 sub generate_email_subject {
1267 $main::lxdebug->enter_sub();
1270 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1271 my $prefix = $self->get_number_prefix_for_type();
1273 if ($subject && $self->{"${prefix}number"}) {
1274 $subject .= " " . $self->{"${prefix}number"}
1277 $main::lxdebug->leave_sub();
1282 $main::lxdebug->enter_sub();
1284 my ($self, $application) = @_;
1286 my $error_code = $?;
1288 chdir("$self->{tmpdir}");
1291 if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1292 push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1294 } elsif (-f "$self->{tmpfile}.err") {
1295 open(FH, "$self->{tmpfile}.err");
1300 if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1301 $self->{tmpfile} =~ s|.*/||g;
1303 $self->{tmpfile} =~ s/\.\w+$//g;
1304 my $tmpfile = $self->{tmpfile};
1305 unlink(<$tmpfile.*>);
1308 chdir("$self->{cwd}");
1310 $main::lxdebug->leave_sub();
1316 $main::lxdebug->enter_sub();
1318 my ($self, $date, $myconfig) = @_;
1321 if ($date && $date =~ /\D/) {
1323 if ($myconfig->{dateformat} =~ /^yy/) {
1324 ($yy, $mm, $dd) = split /\D/, $date;
1326 if ($myconfig->{dateformat} =~ /^mm/) {
1327 ($mm, $dd, $yy) = split /\D/, $date;
1329 if ($myconfig->{dateformat} =~ /^dd/) {
1330 ($dd, $mm, $yy) = split /\D/, $date;
1335 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1336 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1338 $dd = "0$dd" if ($dd < 10);
1339 $mm = "0$mm" if ($mm < 10);
1341 $date = "$yy$mm$dd";
1344 $main::lxdebug->leave_sub();
1349 # Database routines used throughout
1351 sub _dbconnect_options {
1353 my $options = { pg_enable_utf8 => $::locale->is_utf8,
1360 $main::lxdebug->enter_sub(2);
1362 my ($self, $myconfig) = @_;
1364 # connect to database
1365 my $dbh = SL::DBConnect->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options)
1369 if ($myconfig->{dboptions}) {
1370 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1373 $main::lxdebug->leave_sub(2);
1378 sub dbconnect_noauto {
1379 $main::lxdebug->enter_sub();
1381 my ($self, $myconfig) = @_;
1383 # connect to database
1384 my $dbh = SL::DBConnect->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options(AutoCommit => 0))
1388 if ($myconfig->{dboptions}) {
1389 $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1392 $main::lxdebug->leave_sub();
1397 sub get_standard_dbh {
1398 $main::lxdebug->enter_sub(2);
1401 my $myconfig = shift || \%::myconfig;
1403 if ($standard_dbh && !$standard_dbh->{Active}) {
1404 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1405 undef $standard_dbh;
1408 $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1410 $main::lxdebug->leave_sub(2);
1412 return $standard_dbh;
1416 $main::lxdebug->enter_sub();
1418 my ($self, $date, $myconfig) = @_;
1419 my $dbh = $self->dbconnect($myconfig);
1421 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1422 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1424 # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1425 # es ist sicher ein conv_date vorher IMMER auszuführen.
1426 # Testfälle ohne definiertes closedto:
1427 # Leere Datumseingabe i.O.
1428 # SELECT 1 FROM defaults WHERE '' < closedto
1429 # normale Zahlungsbuchung über Rechnungsmaske i.O.
1430 # SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1431 # Testfälle mit definiertem closedto (30.04.2011):
1432 # Leere Datumseingabe i.O.
1433 # SELECT 1 FROM defaults WHERE '' < closedto
1434 # normale Buchung im geschloßenem Zeitraum i.O.
1435 # SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1436 # Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1437 # normale Buchung in aktiver Buchungsperiode i.O.
1438 # SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1440 my ($closed) = $sth->fetchrow_array;
1442 $main::lxdebug->leave_sub();
1447 sub update_balance {
1448 $main::lxdebug->enter_sub();
1450 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1452 # if we have a value, go do it
1455 # retrieve balance from table
1456 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1457 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1458 my ($balance) = $sth->fetchrow_array;
1464 $query = "UPDATE $table SET $field = $balance WHERE $where";
1465 do_query($self, $dbh, $query, @values);
1467 $main::lxdebug->leave_sub();
1470 sub update_exchangerate {
1471 $main::lxdebug->enter_sub();
1473 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1475 # some sanity check for currency
1477 $main::lxdebug->leave_sub();
1480 $query = qq|SELECT curr FROM defaults|;
1482 my ($currency) = selectrow_query($self, $dbh, $query);
1483 my ($defaultcurrency) = split m/:/, $currency;
1486 if ($curr eq $defaultcurrency) {
1487 $main::lxdebug->leave_sub();
1491 $query = qq|SELECT e.curr FROM exchangerate e
1492 WHERE e.curr = ? AND e.transdate = ?
1494 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1503 $buy = conv_i($buy, "NULL");
1504 $sell = conv_i($sell, "NULL");
1507 if ($buy != 0 && $sell != 0) {
1508 $set = "buy = $buy, sell = $sell";
1509 } elsif ($buy != 0) {
1510 $set = "buy = $buy";
1511 } elsif ($sell != 0) {
1512 $set = "sell = $sell";
1515 if ($sth->fetchrow_array) {
1516 $query = qq|UPDATE exchangerate
1522 $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1523 VALUES (?, $buy, $sell, ?)|;
1526 do_query($self, $dbh, $query, $curr, $transdate);
1528 $main::lxdebug->leave_sub();
1531 sub save_exchangerate {
1532 $main::lxdebug->enter_sub();
1534 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1536 my $dbh = $self->dbconnect($myconfig);
1540 $buy = $rate if $fld eq 'buy';
1541 $sell = $rate if $fld eq 'sell';
1544 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1549 $main::lxdebug->leave_sub();
1552 sub get_exchangerate {
1553 $main::lxdebug->enter_sub();
1555 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1558 unless ($transdate && $curr) {
1559 $main::lxdebug->leave_sub();
1563 $query = qq|SELECT curr FROM defaults|;
1565 my ($currency) = selectrow_query($self, $dbh, $query);
1566 my ($defaultcurrency) = split m/:/, $currency;
1568 if ($currency eq $defaultcurrency) {
1569 $main::lxdebug->leave_sub();
1573 $query = qq|SELECT e.$fld FROM exchangerate e
1574 WHERE e.curr = ? AND e.transdate = ?|;
1575 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1579 $main::lxdebug->leave_sub();
1581 return $exchangerate;
1584 sub check_exchangerate {
1585 $main::lxdebug->enter_sub();
1587 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1589 if ($fld !~/^buy|sell$/) {
1590 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1593 unless ($transdate) {
1594 $main::lxdebug->leave_sub();
1598 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1600 if ($currency eq $defaultcurrency) {
1601 $main::lxdebug->leave_sub();
1605 my $dbh = $self->get_standard_dbh($myconfig);
1606 my $query = qq|SELECT e.$fld FROM exchangerate e
1607 WHERE e.curr = ? AND e.transdate = ?|;
1609 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1611 $main::lxdebug->leave_sub();
1613 return $exchangerate;
1616 sub get_all_currencies {
1617 $main::lxdebug->enter_sub();
1620 my $myconfig = shift || \%::myconfig;
1621 my $dbh = $self->get_standard_dbh($myconfig);
1623 my $query = qq|SELECT curr FROM defaults|;
1625 my ($curr) = selectrow_query($self, $dbh, $query);
1626 my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
1628 $main::lxdebug->leave_sub();
1633 sub get_default_currency {
1634 $main::lxdebug->enter_sub();
1636 my ($self, $myconfig) = @_;
1637 my @currencies = $self->get_all_currencies($myconfig);
1639 $main::lxdebug->leave_sub();
1641 return $currencies[0];
1644 sub set_payment_options {
1645 $main::lxdebug->enter_sub();
1647 my ($self, $myconfig, $transdate) = @_;
1649 return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1651 my $dbh = $self->get_standard_dbh($myconfig);
1654 qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long , p.description | .
1655 qq|FROM payment_terms p | .
1658 ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1659 $self->{payment_terms}, $self->{payment_description}) =
1660 selectrow_query($self, $dbh, $query, $self->{payment_id});
1662 if ($transdate eq "") {
1663 if ($self->{invdate}) {
1664 $transdate = $self->{invdate};
1666 $transdate = $self->{transdate};
1671 qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1672 qq|FROM payment_terms|;
1673 ($self->{netto_date}, $self->{skonto_date}) =
1674 selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1676 my ($invtotal, $total);
1677 my (%amounts, %formatted_amounts);
1679 if ($self->{type} =~ /_order$/) {
1680 $amounts{invtotal} = $self->{ordtotal};
1681 $amounts{total} = $self->{ordtotal};
1683 } elsif ($self->{type} =~ /_quotation$/) {
1684 $amounts{invtotal} = $self->{quototal};
1685 $amounts{total} = $self->{quototal};
1688 $amounts{invtotal} = $self->{invtotal};
1689 $amounts{total} = $self->{total};
1691 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1693 $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1694 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1695 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1696 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1698 foreach (keys %amounts) {
1699 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1700 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1703 if ($self->{"language_id"}) {
1705 qq|SELECT t.translation, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1706 qq|FROM generic_translations t | .
1707 qq|LEFT JOIN language l ON t.language_id = l.id | .
1708 qq|WHERE (t.language_id = ?)
1709 AND (t.translation_id = ?)
1710 AND (t.translation_type = 'SL::DB::PaymentTerm/description_long')|;
1711 my ($description_long, $output_numberformat, $output_dateformat,
1712 $output_longdates) =
1713 selectrow_query($self, $dbh, $query,
1714 $self->{"language_id"}, $self->{"payment_id"});
1716 $self->{payment_terms} = $description_long if ($description_long);
1718 if ($output_dateformat) {
1719 foreach my $key (qw(netto_date skonto_date)) {
1721 $main::locale->reformat_date($myconfig, $self->{$key},
1727 if ($output_numberformat &&
1728 ($output_numberformat ne $myconfig->{"numberformat"})) {
1729 my $saved_numberformat = $myconfig->{"numberformat"};
1730 $myconfig->{"numberformat"} = $output_numberformat;
1731 map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1732 $myconfig->{"numberformat"} = $saved_numberformat;
1736 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1737 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1738 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1739 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1740 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1741 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1742 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1744 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1746 $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1748 $main::lxdebug->leave_sub();
1752 sub get_template_language {
1753 $main::lxdebug->enter_sub();
1755 my ($self, $myconfig) = @_;
1757 my $template_code = "";
1759 if ($self->{language_id}) {
1760 my $dbh = $self->get_standard_dbh($myconfig);
1761 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1762 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1765 $main::lxdebug->leave_sub();
1767 return $template_code;
1770 sub get_printer_code {
1771 $main::lxdebug->enter_sub();
1773 my ($self, $myconfig) = @_;
1775 my $template_code = "";
1777 if ($self->{printer_id}) {
1778 my $dbh = $self->get_standard_dbh($myconfig);
1779 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1780 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1783 $main::lxdebug->leave_sub();
1785 return $template_code;
1789 $main::lxdebug->enter_sub();
1791 my ($self, $myconfig) = @_;
1793 my $template_code = "";
1795 if ($self->{shipto_id}) {
1796 my $dbh = $self->get_standard_dbh($myconfig);
1797 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1798 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1799 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1802 $main::lxdebug->leave_sub();
1806 $main::lxdebug->enter_sub();
1808 my ($self, $dbh, $id, $module) = @_;
1813 foreach my $item (qw(name department_1 department_2 street zipcode city country
1814 contact cp_gender phone fax email)) {
1815 if ($self->{"shipto$item"}) {
1816 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1818 push(@values, $self->{"shipto${item}"});
1822 if ($self->{shipto_id}) {
1823 my $query = qq|UPDATE shipto set
1825 shiptodepartment_1 = ?,
1826 shiptodepartment_2 = ?,
1832 shiptocp_gender = ?,
1836 WHERE shipto_id = ?|;
1837 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1839 my $query = qq|SELECT * FROM shipto
1840 WHERE shiptoname = ? AND
1841 shiptodepartment_1 = ? AND
1842 shiptodepartment_2 = ? AND
1843 shiptostreet = ? AND
1844 shiptozipcode = ? AND
1846 shiptocountry = ? AND
1847 shiptocontact = ? AND
1848 shiptocp_gender = ? AND
1854 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1857 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1858 shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1859 shiptocontact, shiptocp_gender, shiptophone, shiptofax, shiptoemail, module)
1860 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1861 do_query($self, $dbh, $query, $id, @values, $module);
1866 $main::lxdebug->leave_sub();
1870 $main::lxdebug->enter_sub();
1872 my ($self, $dbh) = @_;
1874 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1876 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1877 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1878 $self->{"employee_id"} *= 1;
1880 $main::lxdebug->leave_sub();
1883 sub get_employee_data {
1884 $main::lxdebug->enter_sub();
1889 Common::check_params(\%params, qw(prefix));
1890 Common::check_params_x(\%params, qw(id));
1893 $main::lxdebug->leave_sub();
1897 my $myconfig = \%main::myconfig;
1898 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
1900 my ($login) = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
1903 my $user = User->new(login => $login);
1904 map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
1906 $self->{$params{prefix} . '_login'} = $login;
1907 $self->{$params{prefix} . '_name'} ||= $login;
1910 $main::lxdebug->leave_sub();
1914 $main::lxdebug->enter_sub();
1916 my ($self, $myconfig, $reference_date) = @_;
1918 $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
1920 my $dbh = $self->get_standard_dbh($myconfig);
1921 my ($payment_id, $duedate);
1923 if($self->{payment_id}) {
1924 $payment_id = $self->{payment_id};
1925 } elsif($self->{vendor_id}) {
1926 my $query = 'SELECT payment_id FROM vendor WHERE id = ?';
1927 ($payment_id) = selectrow_query($self, $dbh, $query, $self->{vendor_id});
1931 my $query = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
1932 ($duedate) = selectrow_query($self, $dbh, $query, $payment_id);
1935 $main::lxdebug->leave_sub();
1941 $main::lxdebug->enter_sub();
1943 my ($self, $dbh, $id, $key) = @_;
1945 $key = "all_contacts" unless ($key);
1949 $main::lxdebug->leave_sub();
1954 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1955 qq|FROM contacts | .
1956 qq|WHERE cp_cv_id = ? | .
1957 qq|ORDER BY lower(cp_name)|;
1959 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1961 $main::lxdebug->leave_sub();
1965 $main::lxdebug->enter_sub();
1967 my ($self, $dbh, $key) = @_;
1969 my ($all, $old_id, $where, @values);
1971 if (ref($key) eq "HASH") {
1974 $key = "ALL_PROJECTS";
1976 foreach my $p (keys(%{$params})) {
1978 $all = $params->{$p};
1979 } elsif ($p eq "old_id") {
1980 $old_id = $params->{$p};
1981 } elsif ($p eq "key") {
1982 $key = $params->{$p};
1988 $where = "WHERE active ";
1990 if (ref($old_id) eq "ARRAY") {
1991 my @ids = grep({ $_ } @{$old_id});
1993 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1994 push(@values, @ids);
1997 $where .= " OR (id = ?) ";
1998 push(@values, $old_id);
2004 qq|SELECT id, projectnumber, description, active | .
2007 qq|ORDER BY lower(projectnumber)|;
2009 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2011 $main::lxdebug->leave_sub();
2015 $main::lxdebug->enter_sub();
2017 my ($self, $dbh, $vc_id, $key) = @_;
2019 $key = "all_shipto" unless ($key);
2022 # get shipping addresses
2023 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2025 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2031 $main::lxdebug->leave_sub();
2035 $main::lxdebug->enter_sub();
2037 my ($self, $dbh, $key) = @_;
2039 $key = "all_printers" unless ($key);
2041 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2043 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2045 $main::lxdebug->leave_sub();
2049 $main::lxdebug->enter_sub();
2051 my ($self, $dbh, $params) = @_;
2054 $key = $params->{key};
2055 $key = "all_charts" unless ($key);
2057 my $transdate = quote_db_date($params->{transdate});
2060 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2062 qq|LEFT JOIN taxkeys tk ON | .
2063 qq|(tk.id = (SELECT id FROM taxkeys | .
2064 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2065 qq| ORDER BY startdate DESC LIMIT 1)) | .
2066 qq|ORDER BY c.accno|;
2068 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2070 $main::lxdebug->leave_sub();
2073 sub _get_taxcharts {
2074 $main::lxdebug->enter_sub();
2076 my ($self, $dbh, $params) = @_;
2078 my $key = "all_taxcharts";
2081 if (ref $params eq 'HASH') {
2082 $key = $params->{key} if ($params->{key});
2083 if ($params->{module} eq 'AR') {
2084 push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2086 } elsif ($params->{module} eq 'AP') {
2087 push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2094 my $where = @where ? ' WHERE ' . join(' AND ', map { "($_)" } @where) : '';
2096 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2098 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2100 $main::lxdebug->leave_sub();
2104 $main::lxdebug->enter_sub();
2106 my ($self, $dbh, $key) = @_;
2108 $key = "all_taxzones" unless ($key);
2110 my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2112 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2114 $main::lxdebug->leave_sub();
2117 sub _get_employees {
2118 $main::lxdebug->enter_sub();
2120 my ($self, $dbh, $default_key, $key) = @_;
2122 $key = $default_key unless ($key);
2123 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2125 $main::lxdebug->leave_sub();
2128 sub _get_business_types {
2129 $main::lxdebug->enter_sub();
2131 my ($self, $dbh, $key) = @_;
2133 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2134 $options->{key} ||= "all_business_types";
2137 if (exists $options->{salesman}) {
2138 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2141 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2143 $main::lxdebug->leave_sub();
2146 sub _get_languages {
2147 $main::lxdebug->enter_sub();
2149 my ($self, $dbh, $key) = @_;
2151 $key = "all_languages" unless ($key);
2153 my $query = qq|SELECT * FROM language ORDER BY id|;
2155 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2157 $main::lxdebug->leave_sub();
2160 sub _get_dunning_configs {
2161 $main::lxdebug->enter_sub();
2163 my ($self, $dbh, $key) = @_;
2165 $key = "all_dunning_configs" unless ($key);
2167 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2169 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2171 $main::lxdebug->leave_sub();
2174 sub _get_currencies {
2175 $main::lxdebug->enter_sub();
2177 my ($self, $dbh, $key) = @_;
2179 $key = "all_currencies" unless ($key);
2181 my $query = qq|SELECT curr AS currency FROM defaults|;
2183 $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2185 $main::lxdebug->leave_sub();
2189 $main::lxdebug->enter_sub();
2191 my ($self, $dbh, $key) = @_;
2193 $key = "all_payments" unless ($key);
2195 my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2197 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2199 $main::lxdebug->leave_sub();
2202 sub _get_customers {
2203 $main::lxdebug->enter_sub();
2205 my ($self, $dbh, $key) = @_;
2207 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2208 $options->{key} ||= "all_customers";
2209 my $limit_clause = $options->{limit} ? "LIMIT $options->{limit}" : '';
2212 push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman};
2213 push @where, qq|NOT obsolete| if !$options->{with_obsolete};
2214 my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2216 my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2217 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2219 $main::lxdebug->leave_sub();
2223 $main::lxdebug->enter_sub();
2225 my ($self, $dbh, $key) = @_;
2227 $key = "all_vendors" unless ($key);
2229 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2231 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2233 $main::lxdebug->leave_sub();
2236 sub _get_departments {
2237 $main::lxdebug->enter_sub();
2239 my ($self, $dbh, $key) = @_;
2241 $key = "all_departments" unless ($key);
2243 my $query = qq|SELECT * FROM department ORDER BY description|;
2245 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2247 $main::lxdebug->leave_sub();
2250 sub _get_warehouses {
2251 $main::lxdebug->enter_sub();
2253 my ($self, $dbh, $param) = @_;
2255 my ($key, $bins_key);
2257 if ('' eq ref $param) {
2261 $key = $param->{key};
2262 $bins_key = $param->{bins};
2265 my $query = qq|SELECT w.* FROM warehouse w
2266 WHERE (NOT w.invalid) AND
2267 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2268 ORDER BY w.sortkey|;
2270 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2273 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2274 ORDER BY description|;
2275 my $sth = prepare_query($self, $dbh, $query);
2277 foreach my $warehouse (@{ $self->{$key} }) {
2278 do_statement($self, $sth, $query, $warehouse->{id});
2279 $warehouse->{$bins_key} = [];
2281 while (my $ref = $sth->fetchrow_hashref()) {
2282 push @{ $warehouse->{$bins_key} }, $ref;
2288 $main::lxdebug->leave_sub();
2292 $main::lxdebug->enter_sub();
2294 my ($self, $dbh, $table, $key, $sortkey) = @_;
2296 my $query = qq|SELECT * FROM $table|;
2297 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2299 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2301 $main::lxdebug->leave_sub();
2305 # $main::lxdebug->enter_sub();
2307 # my ($self, $dbh, $key) = @_;
2309 # $key ||= "all_groups";
2311 # my $groups = $main::auth->read_groups();
2313 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2315 # $main::lxdebug->leave_sub();
2319 $main::lxdebug->enter_sub();
2324 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2325 my ($sth, $query, $ref);
2327 my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2328 my $vc_id = $self->{"${vc}_id"};
2330 if ($params{"contacts"}) {
2331 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2334 if ($params{"shipto"}) {
2335 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2338 if ($params{"projects"} || $params{"all_projects"}) {
2339 $self->_get_projects($dbh, $params{"all_projects"} ?
2340 $params{"all_projects"} : $params{"projects"},
2341 $params{"all_projects"} ? 1 : 0);
2344 if ($params{"printers"}) {
2345 $self->_get_printers($dbh, $params{"printers"});
2348 if ($params{"languages"}) {
2349 $self->_get_languages($dbh, $params{"languages"});
2352 if ($params{"charts"}) {
2353 $self->_get_charts($dbh, $params{"charts"});
2356 if ($params{"taxcharts"}) {
2357 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2360 if ($params{"taxzones"}) {
2361 $self->_get_taxzones($dbh, $params{"taxzones"});
2364 if ($params{"employees"}) {
2365 $self->_get_employees($dbh, "all_employees", $params{"employees"});
2368 if ($params{"salesmen"}) {
2369 $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2372 if ($params{"business_types"}) {
2373 $self->_get_business_types($dbh, $params{"business_types"});
2376 if ($params{"dunning_configs"}) {
2377 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2380 if($params{"currencies"}) {
2381 $self->_get_currencies($dbh, $params{"currencies"});
2384 if($params{"customers"}) {
2385 $self->_get_customers($dbh, $params{"customers"});
2388 if($params{"vendors"}) {
2389 if (ref $params{"vendors"} eq 'HASH') {
2390 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2392 $self->_get_vendors($dbh, $params{"vendors"});
2396 if($params{"payments"}) {
2397 $self->_get_payments($dbh, $params{"payments"});
2400 if($params{"departments"}) {
2401 $self->_get_departments($dbh, $params{"departments"});
2404 if ($params{price_factors}) {
2405 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2408 if ($params{warehouses}) {
2409 $self->_get_warehouses($dbh, $params{warehouses});
2412 # if ($params{groups}) {
2413 # $self->_get_groups($dbh, $params{groups});
2416 if ($params{partsgroup}) {
2417 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2420 $main::lxdebug->leave_sub();
2423 # this sub gets the id and name from $table
2425 $main::lxdebug->enter_sub();
2427 my ($self, $myconfig, $table) = @_;
2429 # connect to database
2430 my $dbh = $self->get_standard_dbh($myconfig);
2432 $table = $table eq "customer" ? "customer" : "vendor";
2433 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2435 my ($query, @values);
2437 if (!$self->{openinvoices}) {
2439 if ($self->{customernumber} ne "") {
2440 $where = qq|(vc.customernumber ILIKE ?)|;
2441 push(@values, '%' . $self->{customernumber} . '%');
2443 $where = qq|(vc.name ILIKE ?)|;
2444 push(@values, '%' . $self->{$table} . '%');
2448 qq~SELECT vc.id, vc.name,
2449 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2451 WHERE $where AND (NOT vc.obsolete)
2455 qq~SELECT DISTINCT vc.id, vc.name,
2456 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2458 JOIN $table vc ON (a.${table}_id = vc.id)
2459 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2461 push(@values, '%' . $self->{$table} . '%');
2464 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2466 $main::lxdebug->leave_sub();
2468 return scalar(@{ $self->{name_list} });
2471 # the selection sub is used in the AR, AP, IS, IR, DO and OE module
2474 $main::lxdebug->enter_sub();
2476 my ($self, $myconfig, $table, $module) = @_;
2479 my $dbh = $self->get_standard_dbh;
2481 $table = $table eq "customer" ? "customer" : "vendor";
2483 # build selection list
2484 # Hotfix für Bug 1837 - Besser wäre es alte Buchungsbelege
2485 # OHNE Auswahlliste (reines Textfeld) zu laden. Hilft aber auch
2486 # nicht für veränderbare Belege (oe, do, ...)
2487 my $obsolete = $self->{id} ? '' : "WHERE NOT obsolete";
2488 my $query = qq|SELECT count(*) FROM $table $obsolete|;
2489 my ($count) = selectrow_query($self, $dbh, $query);
2491 if ($count < $myconfig->{vclimit}) {
2492 $query = qq|SELECT id, name, salesman_id
2493 FROM $table $obsolete
2495 $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2499 $self->get_employee($dbh);
2501 # setup sales contacts
2502 $query = qq|SELECT e.id, e.name
2504 WHERE (e.sales = '1') AND (NOT e.id = ?)
2506 $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2509 push(@{ $self->{all_employees} },
2510 { id => $self->{employee_id},
2511 name => $self->{employee} });
2513 # prepare query for departments
2514 $query = qq|SELECT id, description
2516 ORDER BY description|;
2518 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2521 $query = qq|SELECT id, description
2525 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2528 $query = qq|SELECT printer_description, id
2530 ORDER BY printer_description|;
2532 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2535 $query = qq|SELECT id, description
2539 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2541 $main::lxdebug->leave_sub();
2544 sub language_payment {
2545 $main::lxdebug->enter_sub();
2547 my ($self, $myconfig) = @_;
2549 my $dbh = $self->get_standard_dbh($myconfig);
2551 my $query = qq|SELECT id, description
2555 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2558 $query = qq|SELECT printer_description, id
2560 ORDER BY printer_description|;
2562 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2565 $query = qq|SELECT id, description
2569 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2571 # get buchungsgruppen
2572 $query = qq|SELECT id, description
2573 FROM buchungsgruppen|;
2575 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2577 $main::lxdebug->leave_sub();
2580 # this is only used for reports
2581 sub all_departments {
2582 $main::lxdebug->enter_sub();
2584 my ($self, $myconfig, $table) = @_;
2586 my $dbh = $self->get_standard_dbh($myconfig);
2588 my $query = qq|SELECT id, description
2590 ORDER BY description|;
2591 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2593 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2595 $main::lxdebug->leave_sub();
2599 $main::lxdebug->enter_sub();
2601 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2604 if ($table eq "customer") {
2613 $self->all_vc($myconfig, $table, $module);
2615 # get last customers or vendors
2616 my ($query, $sth, $ref);
2618 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2623 my $transdate = "current_date";
2624 if ($self->{transdate}) {
2625 $transdate = $dbh->quote($self->{transdate});
2628 # now get the account numbers
2629 # $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2630 # FROM chart c, taxkeys tk
2631 # WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2632 # (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2633 # ORDER BY c.accno|;
2635 # same query as above, but without expensive subquery for each row. about 80% faster
2637 SELECT c.accno, c.description, c.link, c.taxkey_id, tk2.tax_id
2639 -- find newest entries in taxkeys
2641 SELECT chart_id, MAX(startdate) AS startdate
2643 WHERE (startdate <= $transdate)
2645 ) tk ON (c.id = tk.chart_id)
2646 -- and load all of those entries
2647 INNER JOIN taxkeys tk2
2648 ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
2649 WHERE (c.link LIKE ?)
2652 $sth = $dbh->prepare($query);
2654 do_statement($self, $sth, $query, '%' . $module . '%');
2656 $self->{accounts} = "";
2657 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2659 foreach my $key (split(/:/, $ref->{link})) {
2660 if ($key =~ /\Q$module\E/) {
2662 # cross reference for keys
2663 $xkeyref{ $ref->{accno} } = $key;
2665 push @{ $self->{"${module}_links"}{$key} },
2666 { accno => $ref->{accno},
2667 description => $ref->{description},
2668 taxkey => $ref->{taxkey_id},
2669 tax_id => $ref->{tax_id} };
2671 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2677 # get taxkeys and description
2678 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2679 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2681 if (($module eq "AP") || ($module eq "AR")) {
2682 # get tax rates and description
2683 $query = qq|SELECT * FROM tax|;
2684 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2687 my $extra_columns = '';
2688 $extra_columns .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
2693 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2694 a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2695 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2696 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2697 a.globalproject_id, ${extra_columns}
2699 d.description AS department,
2702 JOIN $table c ON (a.${table}_id = c.id)
2703 LEFT JOIN employee e ON (e.id = a.employee_id)
2704 LEFT JOIN department d ON (d.id = a.department_id)
2706 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2708 foreach my $key (keys %$ref) {
2709 $self->{$key} = $ref->{$key};
2712 # remove any trailing whitespace
2713 $self->{currency} =~ s/\s*$//;
2715 my $transdate = "current_date";
2716 if ($self->{transdate}) {
2717 $transdate = $dbh->quote($self->{transdate});
2720 # now get the account numbers
2721 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2723 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2725 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2726 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2729 $sth = $dbh->prepare($query);
2730 do_statement($self, $sth, $query, "%$module%");
2732 $self->{accounts} = "";
2733 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2735 foreach my $key (split(/:/, $ref->{link})) {
2736 if ($key =~ /\Q$module\E/) {
2738 # cross reference for keys
2739 $xkeyref{ $ref->{accno} } = $key;
2741 push @{ $self->{"${module}_links"}{$key} },
2742 { accno => $ref->{accno},
2743 description => $ref->{description},
2744 taxkey => $ref->{taxkey_id},
2745 tax_id => $ref->{tax_id} };
2747 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2753 # get amounts from individual entries
2756 c.accno, c.description,
2757 a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey,
2761 LEFT JOIN chart c ON (c.id = a.chart_id)
2762 LEFT JOIN project p ON (p.id = a.project_id)
2763 LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2764 WHERE (tk.taxkey_id=a.taxkey) AND
2765 ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2766 THEN tk.chart_id = a.chart_id
2769 OR (c.link='%tax%')) AND
2770 (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2771 WHERE a.trans_id = ?
2772 AND a.fx_transaction = '0'
2773 ORDER BY a.acc_trans_id, a.transdate|;
2774 $sth = $dbh->prepare($query);
2775 do_statement($self, $sth, $query, $self->{id});
2777 # get exchangerate for currency
2778 $self->{exchangerate} =
2779 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2782 # store amounts in {acc_trans}{$key} for multiple accounts
2783 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2784 $ref->{exchangerate} =
2785 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2786 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2789 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2790 $ref->{amount} *= -1;
2792 $ref->{index} = $index;
2794 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2800 d.curr AS currencies, d.closedto, d.revtrans,
2801 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2802 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2804 $ref = selectfirst_hashref_query($self, $dbh, $query);
2805 map { $self->{$_} = $ref->{$_} } keys %$ref;
2812 current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2813 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2814 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2816 $ref = selectfirst_hashref_query($self, $dbh, $query);
2817 map { $self->{$_} = $ref->{$_} } keys %$ref;
2819 if ($self->{"$self->{vc}_id"}) {
2821 # only setup currency
2822 ($self->{currency}) = split(/:/, $self->{currencies}) if !$self->{currency};
2826 $self->lastname_used($dbh, $myconfig, $table, $module);
2828 # get exchangerate for currency
2829 $self->{exchangerate} =
2830 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2836 $main::lxdebug->leave_sub();
2840 $main::lxdebug->enter_sub();
2842 my ($self, $dbh, $myconfig, $table, $module) = @_;
2846 $table = $table eq "customer" ? "customer" : "vendor";
2847 my %column_map = ("a.curr" => "currency",
2848 "a.${table}_id" => "${table}_id",
2849 "a.department_id" => "department_id",
2850 "d.description" => "department",
2851 "ct.name" => $table,
2852 "ct.curr" => "cv_curr",
2853 "current_date + ct.terms" => "duedate",
2856 if ($self->{type} =~ /delivery_order/) {
2857 $arap = 'delivery_orders';
2858 delete $column_map{"a.curr"};
2859 delete $column_map{"ct.curr"};
2861 } elsif ($self->{type} =~ /_order/) {
2863 $where = "quotation = '0'";
2865 } elsif ($self->{type} =~ /_quotation/) {
2867 $where = "quotation = '1'";
2869 } elsif ($table eq 'customer') {
2877 $where = "($where) AND" if ($where);
2878 my $query = qq|SELECT MAX(id) FROM $arap
2879 WHERE $where ${table}_id > 0|;
2880 my ($trans_id) = selectrow_query($self, $dbh, $query);
2883 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2884 $query = qq|SELECT $column_spec
2886 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2887 LEFT JOIN department d ON (a.department_id = d.id)
2889 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2891 map { $self->{$_} = $ref->{$_} } values %column_map;
2893 # remove any trailing whitespace
2894 $self->{currency} =~ s/\s*$// if $self->{currency};
2895 $self->{cv_curr} =~ s/\s*$// if $self->{cv_curr};
2897 # if customer/vendor currency is set use this
2898 $self->{currency} = $self->{cv_curr} if $self->{cv_curr};
2900 $main::lxdebug->leave_sub();
2904 $main::lxdebug->enter_sub();
2907 my $myconfig = shift || \%::myconfig;
2908 my ($thisdate, $days) = @_;
2910 my $dbh = $self->get_standard_dbh($myconfig);
2915 my $dateformat = $myconfig->{dateformat};
2916 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2917 $thisdate = $dbh->quote($thisdate);
2918 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2920 $query = qq|SELECT current_date AS thisdate|;
2923 ($thisdate) = selectrow_query($self, $dbh, $query);
2925 $main::lxdebug->leave_sub();
2931 $main::lxdebug->enter_sub();
2933 my ($self, $string) = @_;
2935 if ($string !~ /%/) {
2936 $string = "%$string%";
2939 $string =~ s/\'/\'\'/g;
2941 $main::lxdebug->leave_sub();
2947 $main::lxdebug->enter_sub();
2949 my ($self, $flds, $new, $count, $numrows) = @_;
2953 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2958 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2960 my $j = $item->{ndx} - 1;
2961 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2965 for $i ($count + 1 .. $numrows) {
2966 map { delete $self->{"${_}_$i"} } @{$flds};
2969 $main::lxdebug->leave_sub();
2973 $main::lxdebug->enter_sub();
2975 my ($self, $myconfig) = @_;
2979 my $dbh = $self->dbconnect_noauto($myconfig);
2981 my $query = qq|DELETE FROM status
2982 WHERE (formname = ?) AND (trans_id = ?)|;
2983 my $sth = prepare_query($self, $dbh, $query);
2985 if ($self->{formname} =~ /(check|receipt)/) {
2986 for $i (1 .. $self->{rowcount}) {
2987 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2990 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2994 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2995 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2997 my %queued = split / /, $self->{queued};
3000 if ($self->{formname} =~ /(check|receipt)/) {
3002 # this is a check or receipt, add one entry for each lineitem
3003 my ($accno) = split /--/, $self->{account};
3004 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3005 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3006 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3007 $sth = prepare_query($self, $dbh, $query);
3009 for $i (1 .. $self->{rowcount}) {
3010 if ($self->{"checked_$i"}) {
3011 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3017 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3018 VALUES (?, ?, ?, ?, ?)|;
3019 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3020 $queued{$self->{formname}}, $self->{formname});
3026 $main::lxdebug->leave_sub();
3030 $main::lxdebug->enter_sub();
3032 my ($self, $dbh) = @_;
3034 my ($query, $printed, $emailed);
3036 my $formnames = $self->{printed};
3037 my $emailforms = $self->{emailed};
3039 $query = qq|DELETE FROM status
3040 WHERE (formname = ?) AND (trans_id = ?)|;
3041 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3043 # this only applies to the forms
3044 # checks and receipts are posted when printed or queued
3046 if ($self->{queued}) {
3047 my %queued = split / /, $self->{queued};
3049 foreach my $formname (keys %queued) {
3050 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3051 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3053 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3054 VALUES (?, ?, ?, ?, ?)|;
3055 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3057 $formnames =~ s/\Q$self->{formname}\E//;
3058 $emailforms =~ s/\Q$self->{formname}\E//;
3063 # save printed, emailed info
3064 $formnames =~ s/^ +//g;
3065 $emailforms =~ s/^ +//g;
3068 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3069 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3071 foreach my $formname (keys %status) {
3072 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3073 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3075 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3076 VALUES (?, ?, ?, ?)|;
3077 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3080 $main::lxdebug->leave_sub();
3084 # $main::locale->text('SAVED')
3085 # $main::locale->text('DELETED')
3086 # $main::locale->text('ADDED')
3087 # $main::locale->text('PAYMENT POSTED')
3088 # $main::locale->text('POSTED')
3089 # $main::locale->text('POSTED AS NEW')
3090 # $main::locale->text('ELSE')
3091 # $main::locale->text('SAVED FOR DUNNING')
3092 # $main::locale->text('DUNNING STARTED')
3093 # $main::locale->text('PRINTED')
3094 # $main::locale->text('MAILED')
3095 # $main::locale->text('SCREENED')
3096 # $main::locale->text('CANCELED')
3097 # $main::locale->text('invoice')
3098 # $main::locale->text('proforma')
3099 # $main::locale->text('sales_order')
3100 # $main::locale->text('pick_list')
3101 # $main::locale->text('purchase_order')
3102 # $main::locale->text('bin_list')
3103 # $main::locale->text('sales_quotation')
3104 # $main::locale->text('request_quotation')
3107 $main::lxdebug->enter_sub();
3110 my $dbh = shift || $self->get_standard_dbh;
3112 if(!exists $self->{employee_id}) {
3113 &get_employee($self, $dbh);
3117 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3118 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3119 my @values = (conv_i($self->{id}), $self->{login},
3120 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3121 do_query($self, $dbh, $query, @values);
3125 $main::lxdebug->leave_sub();
3129 $main::lxdebug->enter_sub();
3131 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3132 my ($orderBy, $desc) = split(/\-\-/, $order);
3133 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3136 if ($trans_id ne "") {
3138 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 | .
3139 qq|FROM history_erp h | .
3140 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3141 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3144 my $sth = $dbh->prepare($query) || $self->dberror($query);
3146 $sth->execute() || $self->dberror("$query");
3148 while(my $hash_ref = $sth->fetchrow_hashref()) {
3149 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3150 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3151 $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3152 $tempArray[$i++] = $hash_ref;
3154 $main::lxdebug->leave_sub() and return \@tempArray
3155 if ($i > 0 && $tempArray[0] ne "");
3157 $main::lxdebug->leave_sub();
3161 sub update_defaults {
3162 $main::lxdebug->enter_sub();
3164 my ($self, $myconfig, $fld, $provided_dbh) = @_;
3167 if ($provided_dbh) {
3168 $dbh = $provided_dbh;
3170 $dbh = $self->dbconnect_noauto($myconfig);
3172 my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3173 my $sth = $dbh->prepare($query);
3175 $sth->execute || $self->dberror($query);
3176 my ($var) = $sth->fetchrow_array;
3179 if ($var =~ m/\d+$/) {
3180 my $new_var = (substr $var, $-[0]) * 1 + 1;
3181 my $len_diff = length($var) - $-[0] - length($new_var);
3182 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3188 $query = qq|UPDATE defaults SET $fld = ?|;
3189 do_query($self, $dbh, $query, $var);
3191 if (!$provided_dbh) {
3196 $main::lxdebug->leave_sub();
3201 sub update_business {
3202 $main::lxdebug->enter_sub();
3204 my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3207 if ($provided_dbh) {
3208 $dbh = $provided_dbh;
3210 $dbh = $self->dbconnect_noauto($myconfig);
3213 qq|SELECT customernumberinit FROM business
3214 WHERE id = ? FOR UPDATE|;
3215 my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3217 return undef unless $var;
3219 if ($var =~ m/\d+$/) {
3220 my $new_var = (substr $var, $-[0]) * 1 + 1;
3221 my $len_diff = length($var) - $-[0] - length($new_var);
3222 $var = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3228 $query = qq|UPDATE business
3229 SET customernumberinit = ?
3231 do_query($self, $dbh, $query, $var, $business_id);
3233 if (!$provided_dbh) {
3238 $main::lxdebug->leave_sub();
3243 sub get_partsgroup {
3244 $main::lxdebug->enter_sub();
3246 my ($self, $myconfig, $p) = @_;
3247 my $target = $p->{target} || 'all_partsgroup';
3249 my $dbh = $self->get_standard_dbh($myconfig);
3251 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3253 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3256 if ($p->{searchitems} eq 'part') {
3257 $query .= qq|WHERE p.inventory_accno_id > 0|;
3259 if ($p->{searchitems} eq 'service') {
3260 $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3262 if ($p->{searchitems} eq 'assembly') {
3263 $query .= qq|WHERE p.assembly = '1'|;
3265 if ($p->{searchitems} eq 'labor') {
3266 $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3269 $query .= qq|ORDER BY partsgroup|;
3272 $query = qq|SELECT id, partsgroup FROM partsgroup
3273 ORDER BY partsgroup|;
3276 if ($p->{language_code}) {
3277 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3278 t.description AS translation
3280 JOIN parts p ON (p.partsgroup_id = pg.id)
3281 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3282 ORDER BY translation|;
3283 @values = ($p->{language_code});
3286 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3288 $main::lxdebug->leave_sub();
3291 sub get_pricegroup {
3292 $main::lxdebug->enter_sub();
3294 my ($self, $myconfig, $p) = @_;
3296 my $dbh = $self->get_standard_dbh($myconfig);
3298 my $query = qq|SELECT p.id, p.pricegroup
3301 $query .= qq| ORDER BY pricegroup|;
3304 $query = qq|SELECT id, pricegroup FROM pricegroup
3305 ORDER BY pricegroup|;
3308 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3310 $main::lxdebug->leave_sub();
3314 # usage $form->all_years($myconfig, [$dbh])
3315 # return list of all years where bookings found
3318 $main::lxdebug->enter_sub();
3320 my ($self, $myconfig, $dbh) = @_;
3322 $dbh ||= $self->get_standard_dbh($myconfig);
3325 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3326 (SELECT MAX(transdate) FROM acc_trans)|;
3327 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3329 if ($myconfig->{dateformat} =~ /^yy/) {
3330 ($startdate) = split /\W/, $startdate;
3331 ($enddate) = split /\W/, $enddate;
3333 (@_) = split /\W/, $startdate;
3335 (@_) = split /\W/, $enddate;
3340 $startdate = substr($startdate,0,4);
3341 $enddate = substr($enddate,0,4);
3343 while ($enddate >= $startdate) {
3344 push @all_years, $enddate--;
3349 $main::lxdebug->leave_sub();
3353 $main::lxdebug->enter_sub();
3357 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3359 $main::lxdebug->leave_sub();
3363 $main::lxdebug->enter_sub();
3368 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3370 $main::lxdebug->leave_sub();
3373 sub prepare_for_printing {
3376 $self->{templates} ||= $::myconfig{templates};
3377 $self->{formname} ||= $self->{type};
3378 $self->{media} ||= 'email';
3380 die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3382 # set shipto from billto unless set
3383 my $has_shipto = any { $self->{"shipto$_"} } qw(name street zipcode city country contact);
3384 if (!$has_shipto && ($self->{type} =~ m/^(?:purchase_order|request_quotation)$/)) {
3385 $self->{shiptoname} = $::myconfig{company};
3386 $self->{shiptostreet} = $::myconfig{address};
3389 my $language = $self->{language} ? '_' . $self->{language} : '';
3391 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3392 if ($self->{language_id}) {
3393 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3395 $output_dateformat = $::myconfig{dateformat};
3396 $output_numberformat = $::myconfig{numberformat};
3397 $output_longdates = 1;
3400 # Retrieve accounts for tax calculation.
3401 IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3403 if ($self->{type} =~ /_delivery_order$/) {
3404 DO->order_details();
3405 } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3406 OE->order_details(\%::myconfig, $self);
3408 IS->invoice_details(\%::myconfig, $self, $::locale);
3411 # Chose extension & set source file name
3412 my $extension = 'html';
3413 if ($self->{format} eq 'postscript') {
3414 $self->{postscript} = 1;
3416 } elsif ($self->{"format"} =~ /pdf/) {
3418 $extension = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3419 } elsif ($self->{"format"} =~ /opendocument/) {
3420 $self->{opendocument} = 1;
3422 } elsif ($self->{"format"} =~ /excel/) {
3427 my $printer_code = $self->{printer_code} ? '_' . $self->{printer_code} : '';
3428 my $email_extension = -f "$::myconfig{templates}/$self->{formname}_email${language}.${extension}" ? '_email' : '';
3429 $self->{IN} = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3432 $self->format_dates($output_dateformat, $output_longdates,
3433 qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate datepaid
3434 transdate_oe deliverydate_oe employee_startdate employee_enddate),
3435 grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3437 $self->reformat_numbers($output_numberformat, 2,
3438 qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3439 grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3441 $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3443 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3445 if (scalar @{ $cvar_date_fields }) {
3446 $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3449 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3450 $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3457 my ($self, $dateformat, $longformat, @indices) = @_;
3459 $dateformat ||= $::myconfig{dateformat};
3461 foreach my $idx (@indices) {
3462 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3463 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3464 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3468 next unless defined $self->{$idx};
3470 if (!ref($self->{$idx})) {
3471 $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3473 } elsif (ref($self->{$idx}) eq "ARRAY") {
3474 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3475 $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3481 sub reformat_numbers {
3482 my ($self, $numberformat, $places, @indices) = @_;
3484 return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3486 foreach my $idx (@indices) {
3487 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3488 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3489 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3493 next unless defined $self->{$idx};
3495 if (!ref($self->{$idx})) {
3496 $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3498 } elsif (ref($self->{$idx}) eq "ARRAY") {
3499 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3500 $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3505 my $saved_numberformat = $::myconfig{numberformat};
3506 $::myconfig{numberformat} = $numberformat;
3508 foreach my $idx (@indices) {
3509 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3510 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3511 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3515 next unless defined $self->{$idx};
3517 if (!ref($self->{$idx})) {
3518 $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3520 } elsif (ref($self->{$idx}) eq "ARRAY") {
3521 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3522 $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3527 $::myconfig{numberformat} = $saved_numberformat;
3532 $::lxdebug->enter_sub;
3534 my %style_to_script_map = (
3539 my $menu_script = $style_to_script_map{$::myconfig{menustyle}} || '';
3542 require "bin/mozilla/menu$menu_script.pl";
3544 require SL::Controller::FrameHeader;
3547 my $layout = SL::Controller::FrameHeader->new->action_header . ::render();
3549 $::lxdebug->leave_sub;
3559 SL::Form.pm - main data object.
3563 This is the main data object of kivitendo.
3564 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3565 Points of interest for a beginner are:
3567 - $form->error - renders a generic error in html. accepts an error message
3568 - $form->get_standard_dbh - returns a database connection for the
3570 =head1 SPECIAL FUNCTIONS
3572 =head2 C<update_business> PARAMS
3575 \%config, - config hashref
3576 $business_id, - business id
3577 $dbh - optional database handle
3579 handles business (thats customer/vendor types) sequences.
3581 special behaviour for empty strings in customerinitnumber field:
3582 will in this case not increase the value, and return undef.
3584 =head2 C<redirect_header> $url
3586 Generates a HTTP redirection header for the new C<$url>. Constructs an
3587 absolute URL including scheme, host name and port. If C<$url> is a
3588 relative URL then it is considered relative to kivitendo base URL.
3590 This function C<die>s if headers have already been created with
3591 C<$::form-E<gt>header>.
3595 print $::form->redirect_header('oe.pl?action=edit&id=1234');
3596 print $::form->redirect_header('http://www.lx-office.org/');
3600 Generates a general purpose http/html header and includes most of the scripts
3601 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3603 Only one header will be generated. If the method was already called in this
3604 request it will not output anything and return undef. Also if no
3605 HTTP_USER_AGENT is found, no header is generated.
3607 Although header does not accept parameters itself, it will honor special
3608 hashkeys of its Form instance:
3616 If one of these is set, a http-equiv refresh is generated. Missing parameters
3617 default to 3 seconds and the refering url.
3621 Either a scalar or an array ref. Will be inlined into the header. Add
3622 stylesheets with the L<use_stylesheet> function.
3626 If true, a css snippet will be generated that sets the page in landscape mode.
3630 Used to override the default favicon.
3634 A html page title will be generated from this