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., 51 Franklin Street, Fifth Floor, Boston,
32 #======================================================================
33 # Utilities for parsing forms
34 # and supporting routines for linking account numbers
35 # used in AR, AP and IS, IR modules
37 #======================================================================
52 use POSIX qw(strftime);
64 use SL::DB::PaymentTerm;
67 use SL::Helper::Flash qw();
70 use SL::Layout::Dispatcher;
72 use SL::Locale::String;
75 use SL::MoreCommon qw(uri_encode uri_decode);
77 use SL::PrefixedNumber;
86 use List::Util qw(first max min sum);
87 use List::MoreUtils qw(all any apply);
89 use SL::Helper::File qw(:all);
90 use SL::Helper::CreatePDF qw(merge_pdfs);
95 SL::Version->get_version;
99 $main::lxdebug->enter_sub();
106 if ($LXDebug::watch_form) {
107 require SL::Watchdog;
108 tie %{ $self }, 'SL::Watchdog';
113 $main::lxdebug->leave_sub();
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 my $element = $curr->{$key}[$idx];
142 if ('HASH' eq ref $element) {
143 foreach my $hash_key (sort keys %{ $element }) {
144 push @result, $self->_flatten_variables_rec($element, $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
145 $first_array_entry = 0;
148 push @result, { 'key' => $prefix . $key . '[]', 'value' => $element };
153 $main::lxdebug->leave_sub(2);
158 sub flatten_variables {
159 $main::lxdebug->enter_sub(2);
167 push @variables, $self->_flatten_variables_rec($self, '', $_);
170 $main::lxdebug->leave_sub(2);
175 sub flatten_standard_variables {
176 $main::lxdebug->enter_sub(2);
179 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar), @_);
183 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
184 push @variables, $self->_flatten_variables_rec($self, '', $_);
187 $main::lxdebug->leave_sub(2);
193 my ($self, $str) = @_;
195 return uri_encode($str);
199 my ($self, $str) = @_;
201 return uri_decode($str);
205 $main::lxdebug->enter_sub();
206 my ($self, $str) = @_;
208 if ($str && !ref($str)) {
209 $str =~ s/\"/"/g;
212 $main::lxdebug->leave_sub();
218 $main::lxdebug->enter_sub();
219 my ($self, $str) = @_;
221 if ($str && !ref($str)) {
222 $str =~ s/"/\"/g;
225 $main::lxdebug->leave_sub();
231 $main::lxdebug->enter_sub();
235 map({ print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
237 for (sort keys %$self) {
238 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
239 print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
242 $main::lxdebug->leave_sub();
246 my ($self, $code) = @_;
247 local $self->{__ERROR_HANDLER} = sub { SL::X::FormError->throw(error => $_[0]) };
252 $main::lxdebug->enter_sub();
254 $main::lxdebug->show_backtrace();
256 my ($self, $msg) = @_;
258 if ($self->{__ERROR_HANDLER}) {
259 $self->{__ERROR_HANDLER}->($msg);
261 } elsif ($ENV{HTTP_USER_AGENT}) {
263 $self->show_generic_error($msg);
266 confess "Error: $msg\n";
269 $main::lxdebug->leave_sub();
273 $main::lxdebug->enter_sub();
275 my ($self, $msg) = @_;
277 if ($ENV{HTTP_USER_AGENT}) {
279 print $self->parse_html_template('generic/form_info', { message => $msg });
281 } elsif ($self->{info_function}) {
282 &{ $self->{info_function} }($msg);
287 $main::lxdebug->leave_sub();
290 # calculates the number of rows in a textarea based on the content and column number
291 # can be capped with maxrows
293 $main::lxdebug->enter_sub();
294 my ($self, $str, $cols, $maxrows, $minrows) = @_;
298 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
301 $main::lxdebug->leave_sub();
303 return max(min($rows, $maxrows), $minrows);
307 my ($self, $msg) = @_;
309 SL::X::DBError->throw(
311 db_error => $DBI::errstr,
316 $main::lxdebug->enter_sub();
318 my ($self, $name, $msg) = @_;
321 foreach my $part (split m/\./, $name) {
322 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
325 $curr = $curr->{$part};
328 $main::lxdebug->leave_sub();
331 sub _get_request_uri {
334 return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
335 return URI->new if !$ENV{REQUEST_URI}; # for testing
337 my $scheme = $::request->is_https ? 'https' : 'http';
338 my $port = $ENV{SERVER_PORT};
339 $port = undef if (($scheme eq 'http' ) && ($port == 80))
340 || (($scheme eq 'https') && ($port == 443));
342 my $uri = URI->new("${scheme}://");
343 $uri->scheme($scheme);
345 $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
346 $uri->path_query($ENV{REQUEST_URI});
352 sub _add_to_request_uri {
355 my $relative_new_path = shift;
356 my $request_uri = shift || $self->_get_request_uri;
357 my $relative_new_uri = URI->new($relative_new_path);
358 my @request_segments = $request_uri->path_segments;
360 my $new_uri = $request_uri->clone;
361 $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
366 sub create_http_response {
367 $main::lxdebug->enter_sub();
372 my $cgi = $::request->{cgi};
375 if (defined $main::auth) {
376 my $uri = $self->_get_request_uri;
377 my @segments = $uri->path_segments;
379 $uri->path_segments(@segments);
381 my $session_cookie_value = $main::auth->get_session_id();
383 if ($session_cookie_value) {
384 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
385 '-value' => $session_cookie_value,
386 '-path' => $uri->path,
387 '-secure' => $::request->is_https);
391 my %cgi_params = ('-type' => $params{content_type});
392 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
393 $cgi_params{'-cookie'} = $session_cookie if ($session_cookie);
395 map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length status);
397 my $output = $cgi->header(%cgi_params);
399 $main::lxdebug->leave_sub();
405 $::lxdebug->enter_sub;
407 my ($self, %params) = @_;
410 $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
412 if ($params{no_layout}) {
413 $::request->{layout} = SL::Layout::Dispatcher->new(style => 'none');
416 my $layout = $::request->{layout};
418 # standard css for all
419 # this should gradually move to the layouts that need it
420 $layout->use_stylesheet("$_.css") for qw(
421 common main menu list_accounts jquery.autocomplete
422 jquery.multiselect2side
423 ui-lightness/jquery-ui
425 tooltipster themes/tooltipster-light
428 $layout->use_javascript("$_.js") for (qw(
429 jquery jquery-ui jquery.cookie jquery.checkall jquery.download
430 jquery/jquery.form jquery/fixes client_js
431 jquery/jquery.tooltipster.min
432 common part_selection
433 ), "jquery/ui/i18n/jquery.ui.datepicker-$::myconfig{countrycode}");
435 $self->{favicon} ||= "favicon.ico";
436 $self->{titlebar} = join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->read_version if $self->{title} || !$self->{titlebar};
439 if ($self->{refresh_url} || $self->{refresh_time}) {
440 my $refresh_time = $self->{refresh_time} || 3;
441 my $refresh_url = $self->{refresh_url} || $ENV{REFERER};
442 push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
445 my $auto_reload_resources_param = $layout->auto_reload_resources_param;
447 push @header, map { qq|<link rel="stylesheet" href="${_}${auto_reload_resources_param}" type="text/css" title="Stylesheet">| } $layout->stylesheets;
448 push @header, "<style type='text/css'>\@page { size:landscape; }</style> " if $self->{landscape};
449 push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
450 push @header, map { qq|<script type="text/javascript" src="${_}${auto_reload_resources_param}"></script>| } $layout->javascripts;
451 push @header, $self->{javascript} if $self->{javascript};
452 push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
455 strict => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
456 transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
457 frameset => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
458 html5 => qq|<!DOCTYPE html>|,
462 print $self->create_http_response(content_type => 'text/html', charset => 'UTF-8');
463 print $doctypes{$params{doctype} || 'transitional'}, $/;
467 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
468 <title>$self->{titlebar}</title>
470 print " $_\n" for @header;
472 <meta name="robots" content="noindex,nofollow">
477 print $::request->{layout}->pre_content;
478 print $::request->{layout}->start_content;
480 $layout->header_done;
482 $::lxdebug->leave_sub;
486 return unless $::request->{layout}->need_footer;
488 print $::request->{layout}->end_content;
489 print $::request->{layout}->post_content;
491 if (my @inline_scripts = $::request->{layout}->javascripts_inline) {
492 print "<script type='text/javascript'>" . join("; ", @inline_scripts) . "</script>\n";
501 sub ajax_response_header {
502 $main::lxdebug->enter_sub();
506 my $output = $::request->{cgi}->header('-charset' => 'UTF-8');
508 $main::lxdebug->leave_sub();
513 sub redirect_header {
517 my $base_uri = $self->_get_request_uri;
518 my $new_uri = URI->new_abs($new_url, $base_uri);
520 die "Headers already sent" if $self->{header};
523 return $::request->{cgi}->redirect($new_uri);
526 sub set_standard_title {
527 $::lxdebug->enter_sub;
530 $self->{titlebar} = "kivitendo " . $::locale->text('Version') . " " . $self->read_version;
531 $self->{titlebar} .= "- $::myconfig{name}" if $::myconfig{name};
532 $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
534 $::lxdebug->leave_sub;
537 sub _prepare_html_template {
538 $main::lxdebug->enter_sub();
540 my ($self, $file, $additional_params) = @_;
543 if (!%::myconfig || !$::myconfig{"countrycode"}) {
544 $language = $::lx_office_conf{system}->{language};
546 $language = $main::myconfig{"countrycode"};
548 $language = "de" unless ($language);
550 if (-f "templates/webpages/${file}.html") {
551 $file = "templates/webpages/${file}.html";
553 } elsif (ref $file eq 'SCALAR') {
554 # file is a scalarref, use inline mode
556 my $info = "Web page template '${file}' not found.\n";
558 print qq|<pre>$info</pre>|;
559 $::dispatcher->end_request;
562 $additional_params->{AUTH} = $::auth;
563 $additional_params->{INSTANCE_CONF} = $::instance_conf;
564 $additional_params->{LOCALE} = $::locale;
565 $additional_params->{LXCONFIG} = \%::lx_office_conf;
566 $additional_params->{LXDEBUG} = $::lxdebug;
567 $additional_params->{MYCONFIG} = \%::myconfig;
569 $main::lxdebug->leave_sub();
574 sub parse_html_template {
575 $main::lxdebug->enter_sub();
577 my ($self, $file, $additional_params) = @_;
579 $additional_params ||= { };
581 my $real_file = $self->_prepare_html_template($file, $additional_params);
582 my $template = $self->template;
584 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
587 $template->process($real_file, $additional_params, \$output) || die $template->error;
589 $main::lxdebug->leave_sub();
594 sub template { $::request->presenter->get_template }
596 sub show_generic_error {
597 $main::lxdebug->enter_sub();
599 my ($self, $error, %params) = @_;
601 if ($self->{__ERROR_HANDLER}) {
602 $self->{__ERROR_HANDLER}->($error);
603 $main::lxdebug->leave_sub();
607 if ($::request->is_ajax) {
610 ->render(SL::Controller::Base->new);
611 $::dispatcher->end_request;
615 'title_error' => $params{title},
616 'label_error' => $error,
619 $self->{title} = $params{title} if $params{title};
621 for my $bar ($::request->layout->get('actionbar')) {
625 call => [ 'kivi.history_back' ],
626 accesskey => 'enter',
632 print $self->parse_html_template("generic/error", $add_params);
634 print STDERR "Error: $error\n";
636 $main::lxdebug->leave_sub();
638 $::dispatcher->end_request;
641 sub show_generic_information {
642 $main::lxdebug->enter_sub();
644 my ($self, $text, $title) = @_;
647 'title_information' => $title,
648 'label_information' => $text,
651 $self->{title} = $title if ($title);
654 print $self->parse_html_template("generic/information", $add_params);
656 $main::lxdebug->leave_sub();
658 $::dispatcher->end_request;
661 sub _store_redirect_info_in_session {
664 return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
666 my ($controller, $params) = ($1, $2);
667 my $form = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
668 $self->{callback} = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
672 $main::lxdebug->enter_sub();
674 my ($self, $msg) = @_;
676 if (!$self->{callback}) {
680 SL::Helper::Flash::flash_later('info', $msg) if $msg;
681 $self->_store_redirect_info_in_session;
682 print $::form->redirect_header($self->{callback});
685 $::dispatcher->end_request;
687 $main::lxdebug->leave_sub();
690 # sort of columns removed - empty sub
692 $main::lxdebug->enter_sub();
694 my ($self, @columns) = @_;
696 $main::lxdebug->leave_sub();
702 $main::lxdebug->enter_sub(2);
704 my ($self, $myconfig, $amount, $places, $dash) = @_;
707 my $neg = $amount < 0;
708 my $force_places = defined $places && $places >= 0;
710 $amount = $self->round_amount($amount, abs $places) if $force_places;
711 $neg = 0 if $amount == 0; # don't show negative zero
712 $amount = sprintf "%.*f", ($force_places ? $places : 10), abs $amount; # 6 is default for %fa
714 # before the sprintf amount was a number, afterwards it's a string. because of the dynamic nature of perl
715 # this is easy to confuse, so keep in mind: before this comment no s///, m//, concat or other strong ops on
716 # $amount. after this comment no +,-,*,/,abs. it will only introduce subtle bugs.
718 $amount =~ s/0*$// unless defined $places && $places == 0; # cull trailing 0s
720 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
721 my @p = split(/\./, $amount); # split amount at decimal point
723 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
725 if ($places || $p[1]) {
728 . (0 x max(abs($places || 0) - length ($p[1]||''), 0)); # pad the fraction
732 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
733 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
734 ($neg ? "-$amount" : "$amount" ) ;
737 $main::lxdebug->leave_sub(2);
741 sub format_amount_units {
742 $main::lxdebug->enter_sub();
747 my $myconfig = \%main::myconfig;
748 my $amount = $params{amount} * 1;
749 my $places = $params{places};
750 my $part_unit_name = $params{part_unit};
751 my $amount_unit_name = $params{amount_unit};
752 my $conv_units = $params{conv_units};
753 my $max_places = $params{max_places};
755 if (!$part_unit_name) {
756 $main::lxdebug->leave_sub();
760 my $all_units = AM->retrieve_all_units;
762 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
763 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
766 if (!scalar @{ $conv_units }) {
767 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
768 $main::lxdebug->leave_sub();
772 my $part_unit = $all_units->{$part_unit_name};
773 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
775 $amount *= $conv_unit->{factor};
780 foreach my $unit (@$conv_units) {
781 my $last = $unit->{name} eq $part_unit->{name};
783 $num = int($amount / $unit->{factor});
784 $amount -= $num * $unit->{factor};
787 if ($last ? $amount : $num) {
788 push @values, { "unit" => $unit->{name},
789 "amount" => $last ? $amount / $unit->{factor} : $num,
790 "places" => $last ? $places : 0 };
797 push @values, { "unit" => $part_unit_name,
802 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
804 $main::lxdebug->leave_sub();
810 $main::lxdebug->enter_sub(2);
815 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
816 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
817 $input =~ s/\#\#/\#/g;
819 $main::lxdebug->leave_sub(2);
827 $main::lxdebug->enter_sub(2);
829 my ($self, $myconfig, $amount) = @_;
831 if (!defined($amount) || ($amount eq '')) {
832 $main::lxdebug->leave_sub(2);
836 if ( ($myconfig->{numberformat} eq '1.000,00')
837 || ($myconfig->{numberformat} eq '1000,00')) {
842 if ($myconfig->{numberformat} eq "1'000.00") {
848 $main::lxdebug->leave_sub(2);
850 # Make sure no code wich is not a math expression ends up in eval().
851 return 0 unless $amount =~ /^ [\s \d \( \) \- \+ \* \/ \. ]* $/x;
853 # Prevent numbers from being parsed as octals;
854 $amount =~ s{ (?<! [\d.] ) 0+ (?= [1-9] ) }{}gx;
856 return scalar(eval($amount)) * 1 ;
860 my ($self, $amount, $places, $adjust) = @_;
862 return 0 if !defined $amount;
867 my $precision = $::instance_conf->get_precision || 0.01;
868 return $self->round_amount( $self->round_amount($amount / $precision, 0) * $precision, $places);
871 # We use Perl's knowledge of string representation for
872 # rounding. First, convert the floating point number to a string
873 # with a high number of places. Then split the string on the decimal
874 # sign and use integer calculation for rounding the decimal places
875 # part. If an overflow occurs then apply that overflow to the part
876 # before the decimal sign as well using integer arithmetic again.
878 my $int_amount = int(abs $amount);
879 my $str_places = max(min(10, 16 - length("$int_amount") - $places), $places);
880 my $amount_str = sprintf '%.*f', $places + $str_places, abs($amount);
882 return $amount unless $amount_str =~ m{^(\d+)\.(\d+)$};
884 my ($pre, $post) = ($1, $2);
885 my $decimals = '1' . substr($post, 0, $places);
887 my $propagation_limit = $Config{i32size} == 4 ? 7 : 18;
888 my $add_for_rounding = substr($post, $places, 1) >= 5 ? 1 : 0;
890 if ($places > $propagation_limit) {
891 $decimals = Math::BigInt->new($decimals)->badd($add_for_rounding);
892 $pre = Math::BigInt->new($decimals)->badd(1) if substr($decimals, 0, 1) eq '2';
895 $decimals += $add_for_rounding;
896 $pre += 1 if substr($decimals, 0, 1) eq '2';
899 $amount = ("${pre}." . substr($decimals, 1)) * ($amount <=> 0);
905 $main::lxdebug->enter_sub();
907 my ($self, $myconfig) = @_;
908 my ($out, $out_mode);
912 my $defaults = SL::DB::Default->get;
913 my $userspath = $::lx_office_conf{paths}->{userspath};
915 $self->{"cwd"} = getcwd();
916 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
921 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
922 $template_type = 'OpenDocument';
923 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
925 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
926 $template_type = 'LaTeX';
927 $ext_for_format = 'pdf';
929 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
930 $template_type = 'HTML';
931 $ext_for_format = 'html';
933 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
934 $template_type = 'XML';
935 $ext_for_format = 'xml';
937 } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
938 $template_type = 'XML';
940 } elsif ( $self->{"format"} =~ /excel/i ) {
941 $template_type = 'Excel';
942 $ext_for_format = 'xls';
944 } elsif ( defined $self->{'format'}) {
945 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
947 } elsif ( $self->{'format'} eq '' ) {
948 $self->error("No Outputformat given: $self->{'format'}");
950 } else { #Catch the rest
951 $self->error("Outputformat not defined: $self->{'format'}");
954 my $template = SL::Template::create(type => $template_type,
955 file_name => $self->{IN},
957 myconfig => $myconfig,
958 userspath => $userspath,
959 %{ $self->{TEMPLATE_DRIVER_OPTIONS} || {} });
961 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
962 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" } if exists $self->{ $self->{"formname"} . "notes" };
964 if (!$self->{employee_id}) {
965 $self->{"employee_${_}"} = $myconfig->{$_} for qw(email tel fax name signature);
966 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
969 $self->{"myconfig_${_}"} = $myconfig->{$_} for grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
970 $self->{$_} = $defaults->$_ for qw(co_ustid);
971 $self->{"myconfig_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
972 $self->{AUTH} = $::auth;
973 $self->{INSTANCE_CONF} = $::instance_conf;
974 $self->{LOCALE} = $::locale;
975 $self->{LXCONFIG} = $::lx_office_conf;
976 $self->{LXDEBUG} = $::lxdebug;
977 $self->{MYCONFIG} = \%::myconfig;
979 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
981 # OUT is used for the media, screen, printer, email
982 # for postscript we store a copy in a temporary file
983 my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
985 my ($temp_fh, $suffix);
986 $suffix = $self->{IN};
988 ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
989 strftime('kivitendo-print-%Y%m%d%H%M%S-XXXXXX', localtime()),
990 SUFFIX => '.' . ($suffix || 'tex'),
992 UNLINK => $keep_temp_files ? 0 : 1,
995 chmod 0644, $self->{tmpfile} if $keep_temp_files;
996 (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
999 $out_mode = $self->{OUT_MODE} || '>';
1000 $self->{OUT} = "$self->{tmpfile}";
1001 $self->{OUT_MODE} = '>';
1004 my $command_formatter = sub {
1005 my ($out_mode, $out) = @_;
1006 return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
1010 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1011 open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
1013 *OUT = ($::dispatcher->get_standard_filehandles)[1];
1017 if (!$template->parse(*OUT)) {
1019 $self->error("$self->{IN} : " . $template->get_error());
1022 close OUT if $self->{OUT};
1023 # check only one flag (webdav_documents)
1024 # therefore copy to webdav, even if we do not have the webdav feature enabled (just archive)
1025 my $copy_to_webdav = $::instance_conf->get_webdav_documents && !$self->{preview} && $self->{tmpdir} && $self->{tmpfile} && $self->{type}
1026 && $self->{type} ne 'statement';
1027 if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
1028 $self->append_general_pdf_attachments(filepath => $self->{tmpdir}."/".$self->{tmpfile},
1029 type => $self->{type});
1031 if ($self->{media} eq 'file') {
1032 copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
1034 if ($copy_to_webdav) {
1035 if (my $error = Common::copy_file_to_webdav_folder($self)) {
1036 chdir("$self->{cwd}");
1037 $self->error($error);
1041 if (!$self->{preview} && $self->doc_storage_enabled)
1043 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1044 $self->store_pdf($self);
1047 chdir("$self->{cwd}");
1049 $::lxdebug->leave_sub();
1054 if ($copy_to_webdav) {
1055 if (my $error = Common::copy_file_to_webdav_folder($self)) {
1056 chdir("$self->{cwd}");
1057 $self->error($error);
1061 if ( !$self->{preview} && $ext_for_format eq 'pdf' && $self->doc_storage_enabled) {
1062 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1063 my $file_obj = $self->store_pdf($self);
1064 $self->{print_file_id} = $file_obj->id if $file_obj;
1066 if ($self->{media} eq 'email') {
1067 if ( getcwd() eq $self->{"tmpdir"} ) {
1068 # in the case of generating pdf we are in the tmpdir, but WHY ???
1069 $self->{tmpfile} = $userspath."/".$self->{tmpfile};
1070 chdir("$self->{cwd}");
1072 $self->send_email(\%::myconfig,$ext_for_format);
1075 $self->{OUT} = $out;
1076 $self->{OUT_MODE} = $out_mode;
1077 $self->output_file($template->get_mime_type,$command_formatter);
1079 delete $self->{print_file_id};
1083 chdir("$self->{cwd}");
1084 $main::lxdebug->leave_sub();
1087 sub get_bcc_defaults {
1088 my ($self, $myconfig, $mybcc) = @_;
1089 if (SL::DB::Default->get->bcc_to_login) {
1090 $mybcc .= ", " if $mybcc;
1091 $mybcc .= $myconfig->{email};
1093 my $otherbcc = SL::DB::Default->get->global_bcc;
1095 $mybcc .= ", " if $mybcc;
1096 $mybcc .= $otherbcc;
1102 $main::lxdebug->enter_sub();
1103 my ($self, $myconfig, $ext_for_format) = @_;
1104 my $mail = Mailer->new;
1106 map { $mail->{$_} = $self->{$_} }
1107 qw(cc subject message format);
1109 $mail->{bcc} = $self->get_bcc_defaults($myconfig, $self->{bcc});
1110 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1111 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1112 $mail->{fileid} = time() . '.' . $$ . '.';
1113 my $full_signature = $self->create_email_signature();
1114 $full_signature =~ s/\r//g;
1116 $mail->{attachments} = [];
1118 # if we send html or plain text inline
1119 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1120 $mail->{content_type} = "text/html";
1121 $mail->{message} =~ s/\r//g;
1122 $mail->{message} =~ s/\n/<br>\n/g;
1123 $full_signature =~ s/\n/<br>\n/g;
1124 $mail->{message} .= $full_signature;
1126 open(IN, "<", $self->{tmpfile})
1127 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1128 $mail->{message} .= $_ while <IN>;
1131 } elsif (($self->{attachment_policy} // '') ne 'no_file') {
1132 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1133 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1135 if (($self->{attachment_policy} // '') eq 'old_file') {
1136 my ( $attfile ) = SL::File->get_all(object_id => $self->{id},
1137 object_type => $self->{formname},
1138 file_type => 'document');
1141 $attfile->{override_file_name} = $attachment_name if $attachment_name;
1142 push @attfiles, $attfile;
1146 push @{ $mail->{attachments} }, { path => $self->{tmpfile},
1147 id => $self->{print_file_id},
1148 type => "application/pdf",
1149 name => $attachment_name };
1155 map { SL::File->get(id => $_) }
1156 @{ $self->{attach_file_ids} // [] };
1158 foreach my $attfile ( @attfiles ) {
1159 push @{ $mail->{attachments} }, {
1160 path => $attfile->get_file,
1162 type => $attfile->mime_type,
1163 name => $attfile->{override_file_name} // $attfile->file_name,
1164 content => $attfile->get_content ? ${ $attfile->get_content } : undef,
1168 $mail->{message} =~ s/\r//g;
1169 $mail->{message} .= $full_signature;
1170 $self->{emailerr} = $mail->send();
1172 if ($self->{emailerr}) {
1174 $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
1177 $self->{email_journal_id} = $mail->{journalentry};
1178 $self->{snumbers} = "emailjournal" . "_" . $self->{email_journal_id};
1179 $self->{what_done} = $::form->{type};
1180 $self->{addition} = "MAILED";
1181 $self->save_history;
1183 #write back for message info and mail journal
1184 $self->{cc} = $mail->{cc};
1185 $self->{bcc} = $mail->{bcc};
1186 $self->{email} = $mail->{to};
1188 $main::lxdebug->leave_sub();
1192 $main::lxdebug->enter_sub();
1194 my ($self,$mimeType,$command_formatter) = @_;
1195 my $numbytes = (-s $self->{tmpfile});
1196 open(IN, "<", $self->{tmpfile})
1197 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1200 $self->{copies} = 1 unless $self->{media} eq 'printer';
1202 chdir("$self->{cwd}");
1203 for my $i (1 .. $self->{copies}) {
1205 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1207 open OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1208 print OUT $_ while <IN>;
1213 my %headers = ('-type' => $mimeType,
1214 '-connection' => 'close',
1215 '-charset' => 'UTF-8');
1217 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1219 if ($self->{attachment_filename}) {
1222 '-attachment' => $self->{attachment_filename},
1223 '-content-length' => $numbytes,
1228 print $::request->cgi->header(%headers);
1230 $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1234 $main::lxdebug->leave_sub();
1237 sub get_formname_translation {
1238 $main::lxdebug->enter_sub();
1239 my ($self, $formname) = @_;
1241 $formname ||= $self->{formname};
1243 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1244 local $::locale = Locale->new($self->{recipient_locale});
1246 my %formname_translations = (
1247 bin_list => $main::locale->text('Bin List'),
1248 credit_note => $main::locale->text('Credit Note'),
1249 invoice => $main::locale->text('Invoice'),
1250 pick_list => $main::locale->text('Pick List'),
1251 proforma => $main::locale->text('Proforma Invoice'),
1252 purchase_order => $main::locale->text('Purchase Order'),
1253 request_quotation => $main::locale->text('RFQ'),
1254 sales_order => $main::locale->text('Confirmation'),
1255 sales_quotation => $main::locale->text('Quotation'),
1256 storno_invoice => $main::locale->text('Storno Invoice'),
1257 sales_delivery_order => $main::locale->text('Delivery Order'),
1258 purchase_delivery_order => $main::locale->text('Delivery Order'),
1259 dunning => $main::locale->text('Dunning'),
1260 dunning1 => $main::locale->text('Payment Reminder'),
1261 dunning2 => $main::locale->text('Dunning'),
1262 dunning3 => $main::locale->text('Last Dunning'),
1263 dunning_invoice => $main::locale->text('Dunning Invoice'),
1264 letter => $main::locale->text('Letter'),
1265 ic_supply => $main::locale->text('Intra-Community supply'),
1266 statement => $main::locale->text('Statement'),
1269 $main::lxdebug->leave_sub();
1270 return $formname_translations{$formname};
1273 sub get_number_prefix_for_type {
1274 $main::lxdebug->enter_sub();
1278 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1279 : ($self->{type} =~ /_quotation$/) ? 'quo'
1280 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1281 : ($self->{type} =~ /letter/) ? 'letter'
1284 # better default like this?
1285 # : ($self->{type} =~ /(sales|purcharse)_order/ : 'ord';
1286 # : 'prefix_undefined';
1288 $main::lxdebug->leave_sub();
1292 sub get_extension_for_format {
1293 $main::lxdebug->enter_sub();
1296 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1297 : $self->{format} =~ /postscript/i ? ".ps"
1298 : $self->{format} =~ /opendocument/i ? ".odt"
1299 : $self->{format} =~ /excel/i ? ".xls"
1300 : $self->{format} =~ /html/i ? ".html"
1303 $main::lxdebug->leave_sub();
1307 sub generate_attachment_filename {
1308 $main::lxdebug->enter_sub();
1311 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1312 my $recipient_locale = Locale->new($self->{recipient_locale});
1314 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1315 my $prefix = $self->get_number_prefix_for_type();
1317 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1318 $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
1320 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1321 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1323 } elsif ($attachment_filename) {
1324 $attachment_filename .= $self->get_extension_for_format();
1327 $attachment_filename = "";
1330 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1331 $attachment_filename =~ s|[\s/\\]+|_|g;
1333 $main::lxdebug->leave_sub();
1334 return $attachment_filename;
1337 sub generate_email_subject {
1338 $main::lxdebug->enter_sub();
1341 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1342 my $prefix = $self->get_number_prefix_for_type();
1344 if ($subject && $self->{"${prefix}number"}) {
1345 $subject .= " " . $self->{"${prefix}number"}
1348 $main::lxdebug->leave_sub();
1352 sub generate_email_body {
1353 $main::lxdebug->enter_sub();
1354 my ($self, %params) = @_;
1355 # simple german and english will work grammatically (most european languages as well)
1356 # Dear Mr Alan Greenspan:
1357 # Sehr geehrte Frau Meyer,
1358 # A l’attention de Mme Villeroy,
1359 # Gentile Signora Ferrari,
1362 if ($self->{cp_id} && !$params{record_email}) {
1363 my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
1364 my $name = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
1365 my $gender = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
1366 my $mf = $gender eq 'f' ? 'female' : 'male';
1367 $body = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
1368 $body .= ' ' . $givenname . ' ' . $name if $body;
1370 $body = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
1373 return undef unless $body;
1375 $body .= GenericTranslations->get(translation_type =>"salutation_punctuation_mark", language_id => $self->{language_id}) . "\n";
1376 $body .= GenericTranslations->get(translation_type =>"preset_text_$self->{formname}", language_id => $self->{language_id});
1378 $body = $main::locale->unquote_special_chars('HTML', $body);
1380 $main::lxdebug->leave_sub();
1385 $main::lxdebug->enter_sub();
1387 my ($self, $application) = @_;
1389 my $error_code = $?;
1391 chdir("$self->{tmpdir}");
1394 if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1395 push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1397 } elsif (-f "$self->{tmpfile}.err") {
1398 open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
1403 if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1404 $self->{tmpfile} =~ s|.*/||g;
1406 $self->{tmpfile} =~ s/\.\w+$//g;
1407 my $tmpfile = $self->{tmpfile};
1408 unlink(<$tmpfile.*>);
1411 chdir("$self->{cwd}");
1413 $main::lxdebug->leave_sub();
1419 $main::lxdebug->enter_sub();
1421 my ($self, $date, $myconfig) = @_;
1424 if ($date && $date =~ /\D/) {
1426 if ($myconfig->{dateformat} =~ /^yy/) {
1427 ($yy, $mm, $dd) = split /\D/, $date;
1429 if ($myconfig->{dateformat} =~ /^mm/) {
1430 ($mm, $dd, $yy) = split /\D/, $date;
1432 if ($myconfig->{dateformat} =~ /^dd/) {
1433 ($dd, $mm, $yy) = split /\D/, $date;
1438 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1439 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1441 $dd = "0$dd" if ($dd < 10);
1442 $mm = "0$mm" if ($mm < 10);
1444 $date = "$yy$mm$dd";
1447 $main::lxdebug->leave_sub();
1452 # Database routines used throughout
1453 # DB Handling got moved to SL::DB, these are only shims for compatibility
1456 SL::DB->client->dbh;
1459 sub get_standard_dbh {
1460 my $dbh = SL::DB->client->dbh;
1462 if ($dbh && !$dbh->{Active}) {
1463 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
1464 SL::DB->client->dbh(undef);
1467 SL::DB->client->dbh;
1470 sub disconnect_standard_dbh {
1471 SL::DB->client->dbh->rollback;
1477 $main::lxdebug->enter_sub();
1479 my ($self, $date, $myconfig) = @_;
1480 my $dbh = $self->get_standard_dbh;
1482 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1483 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1485 # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1486 # es ist sicher ein conv_date vorher IMMER auszuführen.
1487 # Testfälle ohne definiertes closedto:
1488 # Leere Datumseingabe i.O.
1489 # SELECT 1 FROM defaults WHERE '' < closedto
1490 # normale Zahlungsbuchung über Rechnungsmaske i.O.
1491 # SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1492 # Testfälle mit definiertem closedto (30.04.2011):
1493 # Leere Datumseingabe i.O.
1494 # SELECT 1 FROM defaults WHERE '' < closedto
1495 # normale Buchung im geschloßenem Zeitraum i.O.
1496 # SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1497 # Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1498 # normale Buchung in aktiver Buchungsperiode i.O.
1499 # SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1501 my ($closed) = $sth->fetchrow_array;
1503 $main::lxdebug->leave_sub();
1508 # prevents bookings to the to far away future
1509 sub date_max_future {
1510 $main::lxdebug->enter_sub();
1512 my ($self, $date, $myconfig) = @_;
1513 my $dbh = $self->get_standard_dbh;
1515 my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
1516 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1518 my ($max_future_booking_interval) = $sth->fetchrow_array;
1520 $main::lxdebug->leave_sub();
1522 return $max_future_booking_interval;
1526 sub update_balance {
1527 $main::lxdebug->enter_sub();
1529 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1531 # if we have a value, go do it
1534 # retrieve balance from table
1535 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1536 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1537 my ($balance) = $sth->fetchrow_array;
1543 $query = "UPDATE $table SET $field = $balance WHERE $where";
1544 do_query($self, $dbh, $query, @values);
1546 $main::lxdebug->leave_sub();
1549 sub update_exchangerate {
1550 $main::lxdebug->enter_sub();
1552 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1554 # some sanity check for currency
1556 $main::lxdebug->leave_sub();
1559 $query = qq|SELECT name AS curr FROM currencies WHERE id=(SELECT currency_id FROM defaults)|;
1561 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1563 if ($curr eq $defaultcurrency) {
1564 $main::lxdebug->leave_sub();
1568 $query = qq|SELECT e.currency_id FROM exchangerate e
1569 WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
1571 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1580 $buy = conv_i($buy, "NULL");
1581 $sell = conv_i($sell, "NULL");
1584 if ($buy != 0 && $sell != 0) {
1585 $set = "buy = $buy, sell = $sell";
1586 } elsif ($buy != 0) {
1587 $set = "buy = $buy";
1588 } elsif ($sell != 0) {
1589 $set = "sell = $sell";
1592 if ($sth->fetchrow_array) {
1593 $query = qq|UPDATE exchangerate
1595 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
1599 $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
1600 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
1603 do_query($self, $dbh, $query, $curr, $transdate);
1605 $main::lxdebug->leave_sub();
1608 sub save_exchangerate {
1609 $main::lxdebug->enter_sub();
1611 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1613 SL::DB->client->with_transaction(sub {
1614 my $dbh = SL::DB->client->dbh;
1618 $buy = $rate if $fld eq 'buy';
1619 $sell = $rate if $fld eq 'sell';
1622 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1624 }) or do { die SL::DB->client->error };
1626 $main::lxdebug->leave_sub();
1629 sub get_exchangerate {
1630 $main::lxdebug->enter_sub();
1632 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1635 unless ($transdate && $curr) {
1636 $main::lxdebug->leave_sub();
1640 $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1642 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1644 if ($curr eq $defaultcurrency) {
1645 $main::lxdebug->leave_sub();
1649 $query = qq|SELECT e.$fld FROM exchangerate e
1650 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1651 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1655 $main::lxdebug->leave_sub();
1657 return $exchangerate;
1660 sub check_exchangerate {
1661 $main::lxdebug->enter_sub();
1663 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1665 if ($fld !~/^buy|sell$/) {
1666 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1669 unless ($transdate) {
1670 $main::lxdebug->leave_sub();
1674 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1676 if ($currency eq $defaultcurrency) {
1677 $main::lxdebug->leave_sub();
1681 my $dbh = $self->get_standard_dbh($myconfig);
1682 my $query = qq|SELECT e.$fld FROM exchangerate e
1683 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1685 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1687 $main::lxdebug->leave_sub();
1689 return $exchangerate;
1692 sub get_all_currencies {
1693 $main::lxdebug->enter_sub();
1696 my $myconfig = shift || \%::myconfig;
1697 my $dbh = $self->get_standard_dbh($myconfig);
1699 my $query = qq|SELECT name FROM currencies|;
1700 my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
1702 $main::lxdebug->leave_sub();
1707 sub get_default_currency {
1708 $main::lxdebug->enter_sub();
1710 my ($self, $myconfig) = @_;
1711 my $dbh = $self->get_standard_dbh($myconfig);
1712 my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1714 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1716 $main::lxdebug->leave_sub();
1718 return $defaultcurrency;
1721 sub set_payment_options {
1722 my ($self, $myconfig, $transdate, $type) = @_;
1724 my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
1727 my $is_invoice = $type =~ m{invoice}i;
1729 $transdate ||= $self->{invdate} || $self->{transdate};
1730 my $due_date = $self->{duedate} || $self->{reqdate};
1732 $self->{$_} = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
1733 $self->{payment_description} = $terms->description;
1734 $self->{netto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
1735 $self->{skonto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
1737 my ($invtotal, $total);
1738 my (%amounts, %formatted_amounts);
1740 if ($self->{type} =~ /_order$/) {
1741 $amounts{invtotal} = $self->{ordtotal};
1742 $amounts{total} = $self->{ordtotal};
1744 } elsif ($self->{type} =~ /_quotation$/) {
1745 $amounts{invtotal} = $self->{quototal};
1746 $amounts{total} = $self->{quototal};
1749 $amounts{invtotal} = $self->{invtotal};
1750 $amounts{total} = $self->{total};
1752 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1754 $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1755 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1756 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1757 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1759 foreach (keys %amounts) {
1760 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1761 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1764 if ($self->{"language_id"}) {
1765 my $language = SL::DB::Language->new(id => $self->{language_id})->load;
1767 $self->{payment_terms} = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
1768 $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
1770 if ($language->output_dateformat) {
1771 foreach my $key (qw(netto_date skonto_date)) {
1772 $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
1776 if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
1777 local $myconfig->{numberformat};
1778 $myconfig->{"numberformat"} = $language->output_numberformat;
1779 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
1783 $self->{payment_terms} = $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
1785 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1786 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1787 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1788 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1789 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1790 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1791 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1792 $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
1793 $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
1794 $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
1795 $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
1797 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1799 $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1803 sub get_template_language {
1804 $main::lxdebug->enter_sub();
1806 my ($self, $myconfig) = @_;
1808 my $template_code = "";
1810 if ($self->{language_id}) {
1811 my $dbh = $self->get_standard_dbh($myconfig);
1812 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1813 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1816 $main::lxdebug->leave_sub();
1818 return $template_code;
1821 sub get_printer_code {
1822 $main::lxdebug->enter_sub();
1824 my ($self, $myconfig) = @_;
1826 my $template_code = "";
1828 if ($self->{printer_id}) {
1829 my $dbh = $self->get_standard_dbh($myconfig);
1830 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1831 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1834 $main::lxdebug->leave_sub();
1836 return $template_code;
1840 $main::lxdebug->enter_sub();
1842 my ($self, $myconfig) = @_;
1844 my $template_code = "";
1846 if ($self->{shipto_id}) {
1847 my $dbh = $self->get_standard_dbh($myconfig);
1848 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1849 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1850 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1852 my $cvars = CVar->get_custom_variables(
1855 trans_id => $self->{shipto_id},
1857 $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
1860 $main::lxdebug->leave_sub();
1864 my ($self, $dbh, $id, $module) = @_;
1869 foreach my $item (qw(name department_1 department_2 street zipcode city country gln
1870 contact phone fax email)) {
1871 if ($self->{"shipto$item"}) {
1872 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1874 push(@values, $self->{"shipto${item}"});
1879 # shiptocp_gender only makes sense, if any other shipto attribute is set.
1880 # Because shiptocp_gender is set to 'm' by default in forms
1881 # it must not be considered above to decide if shiptos has to be added or
1882 # updated, but must be inserted or updated as well in case.
1883 push(@values, $self->{shiptocp_gender});
1885 my $shipto_id = $self->{shipto_id};
1887 if ($self->{shipto_id}) {
1888 my $query = qq|UPDATE shipto set
1890 shiptodepartment_1 = ?,
1891 shiptodepartment_2 = ?,
1898 shiptocp_gender = ?,
1902 WHERE shipto_id = ?|;
1903 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1905 my $query = qq|SELECT * FROM shipto
1906 WHERE shiptoname = ? AND
1907 shiptodepartment_1 = ? AND
1908 shiptodepartment_2 = ? AND
1909 shiptostreet = ? AND
1910 shiptozipcode = ? AND
1912 shiptocountry = ? AND
1914 shiptocontact = ? AND
1915 shiptocp_gender = ? AND
1921 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1924 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1925 shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
1926 shiptocontact, shiptocp_gender, shiptophone, shiptofax, shiptoemail, module)
1927 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1928 do_query($self, $dbh, $insert_query, $id, @values, $module);
1930 $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1933 $shipto_id = $insert_check->{shipto_id};
1936 return unless $shipto_id;
1938 CVar->save_custom_variables(
1941 trans_id => $shipto_id,
1943 name_prefix => 'shipto',
1948 $main::lxdebug->enter_sub();
1950 my ($self, $dbh) = @_;
1952 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1954 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1955 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1956 $self->{"employee_id"} *= 1;
1958 $main::lxdebug->leave_sub();
1961 sub get_employee_data {
1962 $main::lxdebug->enter_sub();
1966 my $defaults = SL::DB::Default->get;
1968 Common::check_params(\%params, qw(prefix));
1969 Common::check_params_x(\%params, qw(id));
1972 $main::lxdebug->leave_sub();
1976 my $myconfig = \%main::myconfig;
1977 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
1979 my ($login, $deleted) = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
1982 # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
1983 $self->{$params{prefix} . '_login'} = $login;
1984 $self->{$params{prefix} . "_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
1987 # get employee data from auth.user_config
1988 my $user = User->new(login => $login);
1989 $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
1991 # get saved employee data from employee
1992 my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
1993 $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
1994 $self->{$params{prefix} . "_name"} = $employee->name;
1997 $main::lxdebug->leave_sub();
2001 $main::lxdebug->enter_sub();
2003 my ($self, $dbh, $id, $key) = @_;
2005 $key = "all_contacts" unless ($key);
2009 $main::lxdebug->leave_sub();
2014 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2015 qq|FROM contacts | .
2016 qq|WHERE cp_cv_id = ? | .
2017 qq|ORDER BY lower(cp_name)|;
2019 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2021 $main::lxdebug->leave_sub();
2025 $main::lxdebug->enter_sub();
2027 my ($self, $dbh, $key) = @_;
2029 my ($all, $old_id, $where, @values);
2031 if (ref($key) eq "HASH") {
2034 $key = "ALL_PROJECTS";
2036 foreach my $p (keys(%{$params})) {
2038 $all = $params->{$p};
2039 } elsif ($p eq "old_id") {
2040 $old_id = $params->{$p};
2041 } elsif ($p eq "key") {
2042 $key = $params->{$p};
2048 $where = "WHERE active ";
2050 if (ref($old_id) eq "ARRAY") {
2051 my @ids = grep({ $_ } @{$old_id});
2053 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2054 push(@values, @ids);
2057 $where .= " OR (id = ?) ";
2058 push(@values, $old_id);
2064 qq|SELECT id, projectnumber, description, active | .
2067 qq|ORDER BY lower(projectnumber)|;
2069 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2071 $main::lxdebug->leave_sub();
2075 $main::lxdebug->enter_sub();
2077 my ($self, $dbh, $key) = @_;
2079 $key = "all_printers" unless ($key);
2081 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2083 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2085 $main::lxdebug->leave_sub();
2089 $main::lxdebug->enter_sub();
2091 my ($self, $dbh, $params) = @_;
2094 $key = $params->{key};
2095 $key = "all_charts" unless ($key);
2097 my $transdate = quote_db_date($params->{transdate});
2100 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2102 qq|LEFT JOIN taxkeys tk ON | .
2103 qq|(tk.id = (SELECT id FROM taxkeys | .
2104 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2105 qq| ORDER BY startdate DESC LIMIT 1)) | .
2106 qq|ORDER BY c.accno|;
2108 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2110 $main::lxdebug->leave_sub();
2113 sub _get_taxcharts {
2114 $main::lxdebug->enter_sub();
2116 my ($self, $dbh, $params) = @_;
2118 my $key = "all_taxcharts";
2121 if (ref $params eq 'HASH') {
2122 $key = $params->{key} if ($params->{key});
2123 if ($params->{module} eq 'AR') {
2124 push @where, 'chart_categories ~ \'[ACILQ]\'';
2126 } elsif ($params->{module} eq 'AP') {
2127 push @where, 'chart_categories ~ \'[ACELQ]\'';
2134 my $where = @where ? ' WHERE ' . join(' AND ', map { "($_)" } @where) : '';
2136 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey, rate|;
2138 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2140 $main::lxdebug->leave_sub();
2144 $main::lxdebug->enter_sub();
2146 my ($self, $dbh, $key) = @_;
2148 $key = "all_taxzones" unless ($key);
2150 $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
2152 my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
2154 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2156 $main::lxdebug->leave_sub();
2159 sub _get_employees {
2160 $main::lxdebug->enter_sub();
2162 my ($self, $dbh, $params) = @_;
2167 if (ref $params eq 'HASH') {
2168 $key = $params->{key};
2169 $deleted = $params->{deleted};
2175 $key ||= "all_employees";
2176 my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
2177 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
2179 $main::lxdebug->leave_sub();
2182 sub _get_business_types {
2183 $main::lxdebug->enter_sub();
2185 my ($self, $dbh, $key) = @_;
2187 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2188 $options->{key} ||= "all_business_types";
2191 if (exists $options->{salesman}) {
2192 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2195 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2197 $main::lxdebug->leave_sub();
2200 sub _get_languages {
2201 $main::lxdebug->enter_sub();
2203 my ($self, $dbh, $key) = @_;
2205 $key = "all_languages" unless ($key);
2207 my $query = qq|SELECT * FROM language ORDER BY id|;
2209 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2211 $main::lxdebug->leave_sub();
2214 sub _get_dunning_configs {
2215 $main::lxdebug->enter_sub();
2217 my ($self, $dbh, $key) = @_;
2219 $key = "all_dunning_configs" unless ($key);
2221 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2223 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2225 $main::lxdebug->leave_sub();
2228 sub _get_currencies {
2229 $main::lxdebug->enter_sub();
2231 my ($self, $dbh, $key) = @_;
2233 $key = "all_currencies" unless ($key);
2235 $self->{$key} = [$self->get_all_currencies()];
2237 $main::lxdebug->leave_sub();
2241 $main::lxdebug->enter_sub();
2243 my ($self, $dbh, $key) = @_;
2245 $key = "all_payments" unless ($key);
2247 my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2249 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2251 $main::lxdebug->leave_sub();
2254 sub _get_customers {
2255 $main::lxdebug->enter_sub();
2257 my ($self, $dbh, $key) = @_;
2259 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2260 $options->{key} ||= "all_customers";
2261 my $limit_clause = $options->{limit} ? "LIMIT $options->{limit}" : '';
2264 push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman};
2265 push @where, qq|NOT obsolete| if !$options->{with_obsolete};
2266 my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2268 my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2269 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2271 $main::lxdebug->leave_sub();
2275 $main::lxdebug->enter_sub();
2277 my ($self, $dbh, $key) = @_;
2279 $key = "all_vendors" unless ($key);
2281 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2283 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2285 $main::lxdebug->leave_sub();
2288 sub _get_departments {
2289 $main::lxdebug->enter_sub();
2291 my ($self, $dbh, $key) = @_;
2293 $key = "all_departments" unless ($key);
2295 my $query = qq|SELECT * FROM department ORDER BY description|;
2297 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2299 $main::lxdebug->leave_sub();
2302 sub _get_warehouses {
2303 $main::lxdebug->enter_sub();
2305 my ($self, $dbh, $param) = @_;
2307 my ($key, $bins_key);
2309 if ('' eq ref $param) {
2313 $key = $param->{key};
2314 $bins_key = $param->{bins};
2317 my $query = qq|SELECT w.* FROM warehouse w
2318 WHERE (NOT w.invalid) AND
2319 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2320 ORDER BY w.sortkey|;
2322 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2325 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2326 ORDER BY description|;
2327 my $sth = prepare_query($self, $dbh, $query);
2329 foreach my $warehouse (@{ $self->{$key} }) {
2330 do_statement($self, $sth, $query, $warehouse->{id});
2331 $warehouse->{$bins_key} = [];
2333 while (my $ref = $sth->fetchrow_hashref()) {
2334 push @{ $warehouse->{$bins_key} }, $ref;
2340 $main::lxdebug->leave_sub();
2344 $main::lxdebug->enter_sub();
2346 my ($self, $dbh, $table, $key, $sortkey) = @_;
2348 my $query = qq|SELECT * FROM $table|;
2349 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2351 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2353 $main::lxdebug->leave_sub();
2357 $main::lxdebug->enter_sub();
2362 croak "get_lists: shipto is no longer supported" if $params{shipto};
2364 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2365 my ($sth, $query, $ref);
2368 if ($params{contacts}) {
2369 $vc = 'customer' if $self->{"vc"} eq "customer";
2370 $vc = 'vendor' if $self->{"vc"} eq "vendor";
2371 die "invalid use of get_lists, need 'vc'" unless $vc;
2372 $vc_id = $self->{"${vc}_id"};
2375 if ($params{"contacts"}) {
2376 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2379 if ($params{"projects"} || $params{"all_projects"}) {
2380 $self->_get_projects($dbh, $params{"all_projects"} ?
2381 $params{"all_projects"} : $params{"projects"},
2382 $params{"all_projects"} ? 1 : 0);
2385 if ($params{"printers"}) {
2386 $self->_get_printers($dbh, $params{"printers"});
2389 if ($params{"languages"}) {
2390 $self->_get_languages($dbh, $params{"languages"});
2393 if ($params{"charts"}) {
2394 $self->_get_charts($dbh, $params{"charts"});
2397 if ($params{"taxcharts"}) {
2398 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2401 if ($params{"taxzones"}) {
2402 $self->_get_taxzones($dbh, $params{"taxzones"});
2405 if ($params{"employees"}) {
2406 $self->_get_employees($dbh, $params{"employees"});
2409 if ($params{"salesmen"}) {
2410 $self->_get_employees($dbh, $params{"salesmen"});
2413 if ($params{"business_types"}) {
2414 $self->_get_business_types($dbh, $params{"business_types"});
2417 if ($params{"dunning_configs"}) {
2418 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2421 if($params{"currencies"}) {
2422 $self->_get_currencies($dbh, $params{"currencies"});
2425 if($params{"customers"}) {
2426 $self->_get_customers($dbh, $params{"customers"});
2429 if($params{"vendors"}) {
2430 if (ref $params{"vendors"} eq 'HASH') {
2431 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2433 $self->_get_vendors($dbh, $params{"vendors"});
2437 if($params{"payments"}) {
2438 $self->_get_payments($dbh, $params{"payments"});
2441 if($params{"departments"}) {
2442 $self->_get_departments($dbh, $params{"departments"});
2445 if ($params{price_factors}) {
2446 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2449 if ($params{warehouses}) {
2450 $self->_get_warehouses($dbh, $params{warehouses});
2453 if ($params{partsgroup}) {
2454 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2457 $main::lxdebug->leave_sub();
2460 # this sub gets the id and name from $table
2462 $main::lxdebug->enter_sub();
2464 my ($self, $myconfig, $table) = @_;
2466 # connect to database
2467 my $dbh = $self->get_standard_dbh($myconfig);
2469 $table = $table eq "customer" ? "customer" : "vendor";
2470 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2472 my ($query, @values);
2474 if (!$self->{openinvoices}) {
2476 if ($self->{customernumber} ne "") {
2477 $where = qq|(vc.customernumber ILIKE ?)|;
2478 push(@values, like($self->{customernumber}));
2480 $where = qq|(vc.name ILIKE ?)|;
2481 push(@values, like($self->{$table}));
2485 qq~SELECT vc.id, vc.name,
2486 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2488 WHERE $where AND (NOT vc.obsolete)
2492 qq~SELECT DISTINCT vc.id, vc.name,
2493 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2495 JOIN $table vc ON (a.${table}_id = vc.id)
2496 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2498 push(@values, like($self->{$table}));
2501 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2503 $main::lxdebug->leave_sub();
2505 return scalar(@{ $self->{name_list} });
2510 my ($self, $table, $provided_dbh) = @_;
2512 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
2513 return unless $self->{id};
2514 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2516 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2517 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2518 $ref->{mtime} ||= $ref->{itime};
2519 $self->{lastmtime} = $ref->{mtime};
2523 sub mtime_ischanged {
2524 my ($self, $table, $option) = @_;
2526 return unless $self->{id};
2527 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2529 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2530 my $ref = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
2531 $ref->{mtime} ||= $ref->{itime};
2533 if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
2534 $self->error(($option eq 'mail') ?
2535 t8("The document has been changed by another user. No mail was sent. Please reopen it in another window and copy the changes to the new window") :
2536 t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
2538 $::dispatcher->end_request;
2542 # language_payment duplicates some of the functionality of all_vc (language,
2543 # printer, payment_terms), and at least in the case of sales invoices both
2544 # all_vc and language_payment are called when adding new invoices
2545 sub language_payment {
2546 $main::lxdebug->enter_sub();
2548 my ($self, $myconfig) = @_;
2550 my $dbh = $self->get_standard_dbh($myconfig);
2552 my $query = qq|SELECT id, description
2556 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2559 $query = qq|SELECT printer_description, id
2561 ORDER BY printer_description|;
2563 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2566 $query = qq|SELECT id, description
2568 WHERE ( obsolete IS FALSE OR id = ? )
2570 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
2572 # get buchungsgruppen
2573 $query = qq|SELECT id, description
2574 FROM buchungsgruppen|;
2576 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2578 $main::lxdebug->leave_sub();
2581 # this is only used for reports
2582 sub all_departments {
2583 $main::lxdebug->enter_sub();
2585 my ($self, $myconfig, $table) = @_;
2587 my $dbh = $self->get_standard_dbh($myconfig);
2589 my $query = qq|SELECT id, description
2591 ORDER BY description|;
2592 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2594 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2596 $main::lxdebug->leave_sub();
2600 $main::lxdebug->enter_sub();
2602 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2605 if ($table eq "customer") {
2614 # get last customers or vendors
2615 my ($query, $sth, $ref);
2617 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2622 my $transdate = "current_date";
2623 if ($self->{transdate}) {
2624 $transdate = $dbh->quote($self->{transdate});
2627 # now get the account numbers
2629 SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
2631 -- find newest entries in taxkeys
2633 SELECT chart_id, MAX(startdate) AS startdate
2635 WHERE (startdate <= $transdate)
2637 ) tk ON (c.id = tk.chart_id)
2638 -- and load all of those entries
2639 INNER JOIN taxkeys tk2
2640 ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
2641 WHERE (c.link LIKE ?)
2644 $sth = $dbh->prepare($query);
2646 do_statement($self, $sth, $query, like($module));
2648 $self->{accounts} = "";
2649 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2651 foreach my $key (split(/:/, $ref->{link})) {
2652 if ($key =~ /\Q$module\E/) {
2654 # cross reference for keys
2655 $xkeyref{ $ref->{accno} } = $key;
2657 push @{ $self->{"${module}_links"}{$key} },
2658 { accno => $ref->{accno},
2659 chart_id => $ref->{chart_id},
2660 description => $ref->{description},
2661 taxkey => $ref->{taxkey_id},
2662 tax_id => $ref->{tax_id} };
2664 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2670 # get taxkeys and description
2671 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2672 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2674 if (($module eq "AP") || ($module eq "AR")) {
2675 # get tax rates and description
2676 $query = qq|SELECT * FROM tax|;
2677 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2680 my $extra_columns = '';
2681 $extra_columns .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
2686 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2687 a.duedate, a.ordnumber, a.taxincluded, (SELECT cu.name FROM currencies cu WHERE cu.id=a.currency_id) AS currency, a.notes,
2689 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2690 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2691 a.globalproject_id, ${extra_columns}
2693 d.description AS department,
2696 JOIN $table c ON (a.${table}_id = c.id)
2697 LEFT JOIN employee e ON (e.id = a.employee_id)
2698 LEFT JOIN department d ON (d.id = a.department_id)
2700 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2702 foreach my $key (keys %$ref) {
2703 $self->{$key} = $ref->{$key};
2705 $self->{mtime} ||= $self->{itime};
2706 $self->{lastmtime} = $self->{mtime};
2707 my $transdate = "current_date";
2708 if ($self->{transdate}) {
2709 $transdate = $dbh->quote($self->{transdate});
2712 # now get the account numbers
2713 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
2715 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2717 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2718 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2721 $sth = $dbh->prepare($query);
2722 do_statement($self, $sth, $query, like($module));
2724 $self->{accounts} = "";
2725 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2727 foreach my $key (split(/:/, $ref->{link})) {
2728 if ($key =~ /\Q$module\E/) {
2730 # cross reference for keys
2731 $xkeyref{ $ref->{accno} } = $key;
2733 push @{ $self->{"${module}_links"}{$key} },
2734 { accno => $ref->{accno},
2735 chart_id => $ref->{chart_id},
2736 description => $ref->{description},
2737 taxkey => $ref->{taxkey_id},
2738 tax_id => $ref->{tax_id} };
2740 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2746 # get amounts from individual entries
2749 c.accno, c.description,
2750 a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
2754 LEFT JOIN chart c ON (c.id = a.chart_id)
2755 LEFT JOIN project p ON (p.id = a.project_id)
2756 LEFT JOIN tax t ON (t.id= a.tax_id)
2757 WHERE a.trans_id = ?
2758 AND a.fx_transaction = '0'
2759 ORDER BY a.acc_trans_id, a.transdate|;
2760 $sth = $dbh->prepare($query);
2761 do_statement($self, $sth, $query, $self->{id});
2763 # get exchangerate for currency
2764 $self->{exchangerate} =
2765 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2768 # store amounts in {acc_trans}{$key} for multiple accounts
2769 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2770 $ref->{exchangerate} =
2771 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2772 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2775 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2776 $ref->{amount} *= -1;
2778 $ref->{index} = $index;
2780 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2787 d.closedto, d.revtrans,
2788 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2789 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2790 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2791 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2792 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2794 $ref = selectfirst_hashref_query($self, $dbh, $query);
2795 map { $self->{$_} = $ref->{$_} } keys %$ref;
2802 current_date AS transdate, d.closedto, d.revtrans,
2803 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2804 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2805 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2806 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2807 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2809 $ref = selectfirst_hashref_query($self, $dbh, $query);
2810 map { $self->{$_} = $ref->{$_} } keys %$ref;
2812 if ($self->{"$self->{vc}_id"}) {
2814 # only setup currency
2815 ($self->{currency}) = $self->{defaultcurrency} if !$self->{currency};
2819 $self->lastname_used($dbh, $myconfig, $table, $module);
2821 # get exchangerate for currency
2822 $self->{exchangerate} =
2823 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2829 $main::lxdebug->leave_sub();
2833 $main::lxdebug->enter_sub();
2835 my ($self, $dbh, $myconfig, $table, $module) = @_;
2839 $table = $table eq "customer" ? "customer" : "vendor";
2840 my %column_map = ("a.${table}_id" => "${table}_id",
2841 "a.department_id" => "department_id",
2842 "d.description" => "department",
2843 "ct.name" => $table,
2844 "cu.name" => "currency",
2847 if ($self->{type} =~ /delivery_order/) {
2848 $arap = 'delivery_orders';
2849 delete $column_map{"cu.currency"};
2851 } elsif ($self->{type} =~ /_order/) {
2853 $where = "quotation = '0'";
2855 } elsif ($self->{type} =~ /_quotation/) {
2857 $where = "quotation = '1'";
2859 } elsif ($table eq 'customer') {
2867 $where = "($where) AND" if ($where);
2868 my $query = qq|SELECT MAX(id) FROM $arap
2869 WHERE $where ${table}_id > 0|;
2870 my ($trans_id) = selectrow_query($self, $dbh, $query);
2873 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2874 $query = qq|SELECT $column_spec
2876 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2877 LEFT JOIN department d ON (a.department_id = d.id)
2878 LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
2880 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2882 map { $self->{$_} = $ref->{$_} } values %column_map;
2884 $main::lxdebug->leave_sub();
2887 sub get_variable_content_types {
2888 my %html_variables = (
2889 longdescription => 'html',
2890 partnotes => 'html',
2892 orignotes => 'html',
2897 header_text => 'html',
2898 footer_text => 'html',
2900 return \%html_variables;
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, $flds, $new, $count, $numrows) = @_;
2937 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2942 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2944 my $j = $item->{ndx} - 1;
2945 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2949 for $i ($count + 1 .. $numrows) {
2950 map { delete $self->{"${_}_$i"} } @{$flds};
2953 $main::lxdebug->leave_sub();
2957 $main::lxdebug->enter_sub();
2959 my ($self, $myconfig) = @_;
2963 SL::DB->client->with_transaction(sub {
2964 my $dbh = SL::DB->client->dbh;
2966 my $query = qq|DELETE FROM status
2967 WHERE (formname = ?) AND (trans_id = ?)|;
2968 my $sth = prepare_query($self, $dbh, $query);
2970 if ($self->{formname} =~ /(check|receipt)/) {
2971 for $i (1 .. $self->{rowcount}) {
2972 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2975 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2979 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2980 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2982 my %queued = split / /, $self->{queued};
2985 if ($self->{formname} =~ /(check|receipt)/) {
2987 # this is a check or receipt, add one entry for each lineitem
2988 my ($accno) = split /--/, $self->{account};
2989 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2990 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2991 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2992 $sth = prepare_query($self, $dbh, $query);
2994 for $i (1 .. $self->{rowcount}) {
2995 if ($self->{"checked_$i"}) {
2996 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3002 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3003 VALUES (?, ?, ?, ?, ?)|;
3004 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3005 $queued{$self->{formname}}, $self->{formname});
3008 }) or do { die SL::DB->client->error };
3010 $main::lxdebug->leave_sub();
3014 $main::lxdebug->enter_sub();
3016 my ($self, $dbh) = @_;
3018 my ($query, $printed, $emailed);
3020 my $formnames = $self->{printed};
3021 my $emailforms = $self->{emailed};
3023 $query = qq|DELETE FROM status
3024 WHERE (formname = ?) AND (trans_id = ?)|;
3025 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3027 # this only applies to the forms
3028 # checks and receipts are posted when printed or queued
3030 if ($self->{queued}) {
3031 my %queued = split / /, $self->{queued};
3033 foreach my $formname (keys %queued) {
3034 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3035 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3037 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3038 VALUES (?, ?, ?, ?, ?)|;
3039 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3041 $formnames =~ s/\Q$self->{formname}\E//;
3042 $emailforms =~ s/\Q$self->{formname}\E//;
3047 # save printed, emailed info
3048 $formnames =~ s/^ +//g;
3049 $emailforms =~ s/^ +//g;
3052 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3053 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3055 foreach my $formname (keys %status) {
3056 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3057 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3059 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3060 VALUES (?, ?, ?, ?)|;
3061 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3064 $main::lxdebug->leave_sub();
3068 # $main::locale->text('SAVED')
3069 # $main::locale->text('SCREENED')
3070 # $main::locale->text('DELETED')
3071 # $main::locale->text('ADDED')
3072 # $main::locale->text('PAYMENT POSTED')
3073 # $main::locale->text('POSTED')
3074 # $main::locale->text('POSTED AS NEW')
3075 # $main::locale->text('ELSE')
3076 # $main::locale->text('SAVED FOR DUNNING')
3077 # $main::locale->text('DUNNING STARTED')
3078 # $main::locale->text('PRINTED')
3079 # $main::locale->text('MAILED')
3080 # $main::locale->text('SCREENED')
3081 # $main::locale->text('CANCELED')
3082 # $main::locale->text('IMPORT')
3083 # $main::locale->text('UNIMPORT')
3084 # $main::locale->text('invoice')
3085 # $main::locale->text('proforma')
3086 # $main::locale->text('sales_order')
3087 # $main::locale->text('pick_list')
3088 # $main::locale->text('purchase_order')
3089 # $main::locale->text('bin_list')
3090 # $main::locale->text('sales_quotation')
3091 # $main::locale->text('request_quotation')
3094 $main::lxdebug->enter_sub();
3097 my $dbh = shift || SL::DB->client->dbh;
3098 SL::DB->client->with_transaction(sub {
3100 if(!exists $self->{employee_id}) {
3101 &get_employee($self, $dbh);
3105 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3106 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3107 my @values = (conv_i($self->{id}), $self->{login},
3108 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3109 do_query($self, $dbh, $query, @values);
3111 }) or do { die SL::DB->client->error };
3113 $main::lxdebug->leave_sub();
3117 $main::lxdebug->enter_sub();
3119 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3120 my ($orderBy, $desc) = split(/\-\-/, $order);
3121 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3124 if ($trans_id ne "") {
3126 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 | .
3127 qq|FROM history_erp h | .
3128 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3129 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3132 my $sth = $dbh->prepare($query) || $self->dberror($query);
3134 $sth->execute() || $self->dberror("$query");
3136 while(my $hash_ref = $sth->fetchrow_hashref()) {
3137 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3138 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3139 my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
3140 $hash_ref->{snumbers} = $number;
3141 $hash_ref->{haslink} = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
3142 $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
3143 $tempArray[$i++] = $hash_ref;
3145 $main::lxdebug->leave_sub() and return \@tempArray
3146 if ($i > 0 && $tempArray[0] ne "");
3148 $main::lxdebug->leave_sub();
3152 sub get_partsgroup {
3153 $main::lxdebug->enter_sub();
3155 my ($self, $myconfig, $p) = @_;
3156 my $target = $p->{target} || 'all_partsgroup';
3158 my $dbh = $self->get_standard_dbh($myconfig);
3160 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3162 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3165 if ($p->{searchitems} eq 'part') {
3166 $query .= qq|WHERE p.part_type = 'part'|;
3168 if ($p->{searchitems} eq 'service') {
3169 $query .= qq|WHERE p.part_type = 'service'|;
3171 if ($p->{searchitems} eq 'assembly') {
3172 $query .= qq|WHERE p.part_type = 'assembly'|;
3175 $query .= qq|ORDER BY partsgroup|;
3178 $query = qq|SELECT id, partsgroup FROM partsgroup
3179 ORDER BY partsgroup|;
3182 if ($p->{language_code}) {
3183 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3184 t.description AS translation
3186 JOIN parts p ON (p.partsgroup_id = pg.id)
3187 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3188 ORDER BY translation|;
3189 @values = ($p->{language_code});
3192 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3194 $main::lxdebug->leave_sub();
3197 sub get_pricegroup {
3198 $main::lxdebug->enter_sub();
3200 my ($self, $myconfig, $p) = @_;
3202 my $dbh = $self->get_standard_dbh($myconfig);
3204 my $query = qq|SELECT p.id, p.pricegroup
3207 $query .= qq| ORDER BY pricegroup|;
3210 $query = qq|SELECT id, pricegroup FROM pricegroup
3211 ORDER BY pricegroup|;
3214 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3216 $main::lxdebug->leave_sub();
3220 # usage $form->all_years($myconfig, [$dbh])
3221 # return list of all years where bookings found
3224 $main::lxdebug->enter_sub();
3226 my ($self, $myconfig, $dbh) = @_;
3228 $dbh ||= $self->get_standard_dbh($myconfig);
3231 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3232 (SELECT MAX(transdate) FROM acc_trans)|;
3233 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3235 if ($myconfig->{dateformat} =~ /^yy/) {
3236 ($startdate) = split /\W/, $startdate;
3237 ($enddate) = split /\W/, $enddate;
3239 (@_) = split /\W/, $startdate;
3241 (@_) = split /\W/, $enddate;
3246 $startdate = substr($startdate,0,4);
3247 $enddate = substr($enddate,0,4);
3249 while ($enddate >= $startdate) {
3250 push @all_years, $enddate--;
3255 $main::lxdebug->leave_sub();
3259 $main::lxdebug->enter_sub();
3263 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3265 $main::lxdebug->leave_sub();
3269 $main::lxdebug->enter_sub();
3274 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3276 $main::lxdebug->leave_sub();
3279 sub prepare_for_printing {
3282 my $defaults = SL::DB::Default->get;
3284 $self->{templates} ||= $defaults->templates;
3285 $self->{formname} ||= $self->{type};
3286 $self->{media} ||= 'email';
3288 die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3290 # Several fields that used to reside in %::myconfig (stored in
3291 # auth.user_config) are now stored in defaults. Copy them over for
3293 $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
3295 $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
3297 if (!$self->{employee_id}) {
3298 $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
3299 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
3302 # Load shipping address from database. If shipto_id is set then it's
3303 # one from the customer's/vendor's master data. Otherwise look an a
3304 # customized address linking back to the current record.
3305 my $shipto_module = $self->{type} =~ /_delivery_order$/ ? 'DO'
3306 : $self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/ ? 'OE'
3308 my $shipto = $self->{shipto_id} ? SL::DB::Shipto->new(shipto_id => $self->{shipto_id})->load
3309 : SL::DB::Manager::Shipto->get_first(where => [ module => $shipto_module, trans_id => $self->{id} ]);
3311 $self->{$_} = $shipto->$_ for grep { m{^shipto} } map { $_->name } @{ $shipto->meta->columns };
3312 $self->{"shiptocvar_" . $_->config->name} = $_->value_as_text for @{ $shipto->cvars_by_config };
3315 my $language = $self->{language} ? '_' . $self->{language} : '';
3317 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3318 if ($self->{language_id}) {
3319 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3322 $output_dateformat ||= $::myconfig{dateformat};
3323 $output_numberformat ||= $::myconfig{numberformat};
3324 $output_longdates //= 1;
3326 $self->{myconfig_output_dateformat} = $output_dateformat // $::myconfig{dateformat};
3327 $self->{myconfig_output_longdates} = $output_longdates // 1;
3328 $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
3330 # Retrieve accounts for tax calculation.
3331 IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3333 if ($self->{type} =~ /_delivery_order$/) {
3334 DO->order_details(\%::myconfig, $self);
3335 } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3336 OE->order_details(\%::myconfig, $self);
3338 IS->invoice_details(\%::myconfig, $self, $::locale);
3341 # Chose extension & set source file name
3342 my $extension = 'html';
3343 if ($self->{format} eq 'postscript') {
3344 $self->{postscript} = 1;
3346 } elsif ($self->{"format"} =~ /pdf/) {
3348 $extension = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3349 } elsif ($self->{"format"} =~ /opendocument/) {
3350 $self->{opendocument} = 1;
3352 } elsif ($self->{"format"} =~ /excel/) {
3357 my $printer_code = $self->{printer_code} ? '_' . $self->{printer_code} : '';
3358 my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
3359 $self->{IN} = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3362 $self->format_dates($output_dateformat, $output_longdates,
3363 qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate datepaid
3364 transdate_oe deliverydate_oe employee_startdate employee_enddate),
3365 grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3367 $self->reformat_numbers($output_numberformat, 2,
3368 qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3369 grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3371 $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3373 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3375 if (scalar @{ $cvar_date_fields }) {
3376 $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3379 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3380 $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3384 if (($self->{language} // '') ne '') {
3385 my $template_arrays = $self->{TEMPLATE_ARRAYS} || $self;
3386 for my $idx (0..scalar(@{ $template_arrays->{unit} }) - 1) {
3387 $template_arrays->{unit}->[$idx] = AM->translate_units($self, $self->{language}, $template_arrays->{unit}->[$idx], $template_arrays->{qty}->[$idx])
3391 $self->{template_meta} = {
3392 formname => $self->{formname},
3393 language => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
3394 format => $self->{format},
3395 media => $self->{media},
3396 extension => $extension,
3397 printer => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
3398 today => DateTime->today,
3404 sub calculate_arap {
3405 my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
3407 # this function is used to calculate netamount, total_tax and amount for AP and
3408 # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
3410 # Thus it needs a fully prepared $form to work on.
3411 # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
3413 # The calculated total values are all rounded (default is to 2 places) and
3414 # returned as parameters rather than directly modifying form. The aim is to
3415 # make the calculation of AP and AR behave identically. There is a test-case
3416 # for this function in t/form/arap.t
3418 # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
3419 # modified and formatted and receive the correct sign for writing straight to
3420 # acc_trans, depending on whether they are ar or ap.
3423 die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
3424 die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
3425 die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
3426 $roundplaces = 2 unless $roundplaces;
3428 my $sign = 1; # adjust final results for writing amount to acc_trans
3429 $sign = -1 if $buysell eq 'buy';
3431 my ($netamount,$total_tax,$amount);
3435 # parse and round amounts, setting correct sign for writing to acc_trans
3436 for my $i (1 .. $self->{rowcount}) {
3437 $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
3439 $amount += $self->{"amount_$i"} * $sign;
3442 for my $i (1 .. $self->{rowcount}) {
3443 next unless $self->{"amount_$i"};
3444 ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
3445 my $tax_id = $self->{"tax_id_$i"};
3447 my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
3449 if ( $selected_tax ) {
3451 if ( $buysell eq 'sell' ) {
3452 $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3454 $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3457 $self->{"taxkey_$i"} = $selected_tax->taxkey;
3458 $self->{"taxrate_$i"} = $selected_tax->rate;
3461 ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
3463 $netamount += $self->{"amount_$i"};
3464 $total_tax += $self->{"tax_$i"};
3467 $amount = $netamount + $total_tax;
3469 # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
3470 # but reverse sign of totals for writing amounts to ar
3471 if ( $buysell eq 'buy' ) {
3477 return($netamount,$total_tax,$amount);
3481 my ($self, $dateformat, $longformat, @indices) = @_;
3483 $dateformat ||= $::myconfig{dateformat};
3485 foreach my $idx (@indices) {
3486 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3487 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3488 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3492 next unless defined $self->{$idx};
3494 if (!ref($self->{$idx})) {
3495 $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3497 } elsif (ref($self->{$idx}) eq "ARRAY") {
3498 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3499 $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3505 sub reformat_numbers {
3506 my ($self, $numberformat, $places, @indices) = @_;
3508 return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3510 foreach my $idx (@indices) {
3511 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3512 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3513 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3517 next unless defined $self->{$idx};
3519 if (!ref($self->{$idx})) {
3520 $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3522 } elsif (ref($self->{$idx}) eq "ARRAY") {
3523 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3524 $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3529 my $saved_numberformat = $::myconfig{numberformat};
3530 $::myconfig{numberformat} = $numberformat;
3532 foreach my $idx (@indices) {
3533 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3534 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3535 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3539 next unless defined $self->{$idx};
3541 if (!ref($self->{$idx})) {
3542 $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3544 } elsif (ref($self->{$idx}) eq "ARRAY") {
3545 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3546 $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3551 $::myconfig{numberformat} = $saved_numberformat;
3554 sub create_email_signature {
3556 my $client_signature = $::instance_conf->get_signature;
3557 my $user_signature = $::myconfig{signature};
3560 if ( $client_signature or $user_signature ) {
3561 $signature = "\n\n-- \n";
3562 $signature .= $user_signature . "\n" if $user_signature;
3563 $signature .= $client_signature . "\n" if $client_signature;
3570 # this function calculates the net amount and tax for the lines in ar, ap and
3571 # gl and is used for update as well as post. When used with update the return
3572 # value of amount isn't needed
3574 # calculate_tax should always work with positive values, or rather as the user inputs them
3575 # calculate_tax uses db/perl numberformat, i.e. parsed numbers
3576 # convert to negative numbers (when necessary) only when writing to acc_trans
3577 # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
3578 # for post_transaction amount already contains exchangerate and correct sign and is rounded
3579 # calculate_tax doesn't (need to) know anything about exchangerate
3581 my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
3589 # calculate tax (unrounded), subtract from amount, round amount and round tax
3590 $tax = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
3591 $amount = $self->round_amount($amount - $tax, $roundplaces);
3592 $tax = $self->round_amount($tax, $roundplaces);
3594 $tax = $amount * $taxrate;
3595 $tax = $self->round_amount($tax, $roundplaces);
3598 $tax = 0 unless $tax;
3600 return ($amount,$tax);
3609 SL::Form.pm - main data object.
3613 This is the main data object of kivitendo.
3614 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3615 Points of interest for a beginner are:
3617 - $form->error - renders a generic error in html. accepts an error message
3618 - $form->get_standard_dbh - returns a database connection for the
3620 =head1 SPECIAL FUNCTIONS
3622 =head2 C<redirect_header> $url
3624 Generates a HTTP redirection header for the new C<$url>. Constructs an
3625 absolute URL including scheme, host name and port. If C<$url> is a
3626 relative URL then it is considered relative to kivitendo base URL.
3628 This function C<die>s if headers have already been created with
3629 C<$::form-E<gt>header>.
3633 print $::form->redirect_header('oe.pl?action=edit&id=1234');
3634 print $::form->redirect_header('http://www.lx-office.org/');
3638 Generates a general purpose http/html header and includes most of the scripts
3639 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3641 Only one header will be generated. If the method was already called in this
3642 request it will not output anything and return undef. Also if no
3643 HTTP_USER_AGENT is found, no header is generated.
3645 Although header does not accept parameters itself, it will honor special
3646 hashkeys of its Form instance:
3654 If one of these is set, a http-equiv refresh is generated. Missing parameters
3655 default to 3 seconds and the refering url.
3659 Either a scalar or an array ref. Will be inlined into the header. Add
3660 stylesheets with the L<use_stylesheet> function.
3664 If true, a css snippet will be generated that sets the page in landscape mode.
3668 Used to override the default favicon.
3672 A html page title will be generated from this
3674 =item mtime_ischanged
3676 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
3678 Can be used / called with any table, that has itime and mtime attributes.
3679 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
3680 Can be called wit C<option> mail to generate a different error message.
3682 Returns undef if no save operation has been done yet ($self->{id} not present).
3683 Returns undef if no concurrent write process is detected otherwise a error message.