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 $self->{version} = $self->read_version;
115 $main::lxdebug->leave_sub();
122 SL::Request::read_cgi_input($self);
125 sub _flatten_variables_rec {
126 $main::lxdebug->enter_sub(2);
135 if ('' eq ref $curr->{$key}) {
136 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
138 } elsif ('HASH' eq ref $curr->{$key}) {
139 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
140 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
144 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
145 my $first_array_entry = 1;
147 my $element = $curr->{$key}[$idx];
149 if ('HASH' eq ref $element) {
150 foreach my $hash_key (sort keys %{ $element }) {
151 push @result, $self->_flatten_variables_rec($element, $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
152 $first_array_entry = 0;
155 @result = ({ 'key' => $prefix . $key . ($first_array_entry ? '[+]' : '[]'), 'value' => $element });
160 $main::lxdebug->leave_sub(2);
165 sub flatten_variables {
166 $main::lxdebug->enter_sub(2);
174 push @variables, $self->_flatten_variables_rec($self, '', $_);
177 $main::lxdebug->leave_sub(2);
182 sub flatten_standard_variables {
183 $main::lxdebug->enter_sub(2);
186 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
190 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
191 push @variables, $self->_flatten_variables_rec($self, '', $_);
194 $main::lxdebug->leave_sub(2);
200 $main::lxdebug->enter_sub();
206 map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
208 $main::lxdebug->leave_sub();
212 $main::lxdebug->enter_sub(2);
215 my $password = $self->{password};
217 $self->{password} = 'X' x 8;
219 local $Data::Dumper::Sortkeys = 1;
220 my $output = Dumper($self);
222 $self->{password} = $password;
224 $main::lxdebug->leave_sub(2);
230 my ($self, $str) = @_;
232 return uri_encode($str);
236 my ($self, $str) = @_;
238 return uri_decode($str);
242 $main::lxdebug->enter_sub();
243 my ($self, $str) = @_;
245 if ($str && !ref($str)) {
246 $str =~ s/\"/"/g;
249 $main::lxdebug->leave_sub();
255 $main::lxdebug->enter_sub();
256 my ($self, $str) = @_;
258 if ($str && !ref($str)) {
259 $str =~ s/"/\"/g;
262 $main::lxdebug->leave_sub();
268 $main::lxdebug->enter_sub();
272 map({ print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
274 for (sort keys %$self) {
275 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
276 print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
279 $main::lxdebug->leave_sub();
283 my ($self, $code) = @_;
284 local $self->{__ERROR_HANDLER} = sub { die SL::X::FormError->new($_[0]) };
289 $main::lxdebug->enter_sub();
291 $main::lxdebug->show_backtrace();
293 my ($self, $msg) = @_;
295 if ($self->{__ERROR_HANDLER}) {
296 $self->{__ERROR_HANDLER}->($msg);
298 } elsif ($ENV{HTTP_USER_AGENT}) {
300 $self->show_generic_error($msg);
303 confess "Error: $msg\n";
306 $main::lxdebug->leave_sub();
310 $main::lxdebug->enter_sub();
312 my ($self, $msg) = @_;
314 if ($ENV{HTTP_USER_AGENT}) {
316 print $self->parse_html_template('generic/form_info', { message => $msg });
318 } elsif ($self->{info_function}) {
319 &{ $self->{info_function} }($msg);
324 $main::lxdebug->leave_sub();
327 # calculates the number of rows in a textarea based on the content and column number
328 # can be capped with maxrows
330 $main::lxdebug->enter_sub();
331 my ($self, $str, $cols, $maxrows, $minrows) = @_;
335 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
338 $main::lxdebug->leave_sub();
340 return max(min($rows, $maxrows), $minrows);
344 my ($self, $msg) = @_;
346 die SL::X::DBError->new(
348 error => $DBI::errstr,
353 $main::lxdebug->enter_sub();
355 my ($self, $name, $msg) = @_;
358 foreach my $part (split m/\./, $name) {
359 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
362 $curr = $curr->{$part};
365 $main::lxdebug->leave_sub();
368 sub _get_request_uri {
371 return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
372 return URI->new if !$ENV{REQUEST_URI}; # for testing
374 my $scheme = $::request->is_https ? 'https' : 'http';
375 my $port = $ENV{SERVER_PORT};
376 $port = undef if (($scheme eq 'http' ) && ($port == 80))
377 || (($scheme eq 'https') && ($port == 443));
379 my $uri = URI->new("${scheme}://");
380 $uri->scheme($scheme);
382 $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
383 $uri->path_query($ENV{REQUEST_URI});
389 sub _add_to_request_uri {
392 my $relative_new_path = shift;
393 my $request_uri = shift || $self->_get_request_uri;
394 my $relative_new_uri = URI->new($relative_new_path);
395 my @request_segments = $request_uri->path_segments;
397 my $new_uri = $request_uri->clone;
398 $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
403 sub create_http_response {
404 $main::lxdebug->enter_sub();
409 my $cgi = $::request->{cgi};
412 if (defined $main::auth) {
413 my $uri = $self->_get_request_uri;
414 my @segments = $uri->path_segments;
416 $uri->path_segments(@segments);
418 my $session_cookie_value = $main::auth->get_session_id();
420 if ($session_cookie_value) {
421 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
422 '-value' => $session_cookie_value,
423 '-path' => $uri->path,
424 '-secure' => $::request->is_https);
428 my %cgi_params = ('-type' => $params{content_type});
429 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
430 $cgi_params{'-cookie'} = $session_cookie if ($session_cookie);
432 map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length);
434 my $output = $cgi->header(%cgi_params);
436 $main::lxdebug->leave_sub();
442 $::lxdebug->enter_sub;
444 my ($self, %params) = @_;
447 $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
449 if ($params{no_layout}) {
450 $::request->{layout} = SL::Layout::Dispatcher->new(style => 'none');
453 my $layout = $::request->{layout};
455 # standard css for all
456 # this should gradually move to the layouts that need it
457 $layout->use_stylesheet("$_.css") for qw(
458 common main menu list_accounts jquery.autocomplete
459 jquery.multiselect2side
460 ui-lightness/jquery-ui
462 tooltipster themes/tooltipster-light
465 $layout->use_javascript("$_.js") for (qw(
466 jquery jquery-ui jquery.cookie jquery.checkall jquery.download
467 jquery/jquery.form jquery/fixes client_js
468 jquery/jquery.tooltipster.min
469 common part_selection
470 ), "jquery/ui/i18n/jquery.ui.datepicker-$::myconfig{countrycode}");
472 $self->{favicon} ||= "favicon.ico";
473 $self->{titlebar} = join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->{version} if $self->{title} || !$self->{titlebar};
476 if ($self->{refresh_url} || $self->{refresh_time}) {
477 my $refresh_time = $self->{refresh_time} || 3;
478 my $refresh_url = $self->{refresh_url} || $ENV{REFERER};
479 push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
482 my $auto_reload_resources_param = $layout->auto_reload_resources_param;
484 push @header, map { qq|<link rel="stylesheet" href="${_}${auto_reload_resources_param}" type="text/css" title="Stylesheet">| } $layout->stylesheets;
485 push @header, "<style type='text/css'>\@page { size:landscape; }</style> " if $self->{landscape};
486 push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
487 push @header, map { qq|<script type="text/javascript" src="${_}${auto_reload_resources_param}"></script>| } $layout->javascripts;
488 push @header, $self->{javascript} if $self->{javascript};
489 push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
492 strict => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
493 transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
494 frameset => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
495 html5 => qq|<!DOCTYPE html>|,
499 print $self->create_http_response(content_type => 'text/html', charset => 'UTF-8');
500 print $doctypes{$params{doctype} || 'transitional'}, $/;
504 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
505 <title>$self->{titlebar}</title>
507 print " $_\n" for @header;
509 <meta name="robots" content="noindex,nofollow">
514 print $::request->{layout}->pre_content;
515 print $::request->{layout}->start_content;
517 $layout->header_done;
519 $::lxdebug->leave_sub;
523 return unless $::request->{layout}->need_footer;
525 print $::request->{layout}->end_content;
526 print $::request->{layout}->post_content;
528 if (my @inline_scripts = $::request->{layout}->javascripts_inline) {
529 print "<script type='text/javascript'>" . join("; ", @inline_scripts) . "</script>\n";
538 sub ajax_response_header {
539 $main::lxdebug->enter_sub();
543 my $output = $::request->{cgi}->header('-charset' => 'UTF-8');
545 $main::lxdebug->leave_sub();
550 sub redirect_header {
554 my $base_uri = $self->_get_request_uri;
555 my $new_uri = URI->new_abs($new_url, $base_uri);
557 die "Headers already sent" if $self->{header};
560 return $::request->{cgi}->redirect($new_uri);
563 sub set_standard_title {
564 $::lxdebug->enter_sub;
567 $self->{titlebar} = "kivitendo " . $::locale->text('Version') . " $self->{version}";
568 $self->{titlebar} .= "- $::myconfig{name}" if $::myconfig{name};
569 $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
571 $::lxdebug->leave_sub;
574 sub _prepare_html_template {
575 $main::lxdebug->enter_sub();
577 my ($self, $file, $additional_params) = @_;
580 if (!%::myconfig || !$::myconfig{"countrycode"}) {
581 $language = $::lx_office_conf{system}->{language};
583 $language = $main::myconfig{"countrycode"};
585 $language = "de" unless ($language);
587 if (-f "templates/webpages/${file}.html") {
588 $file = "templates/webpages/${file}.html";
590 } elsif (ref $file eq 'SCALAR') {
591 # file is a scalarref, use inline mode
593 my $info = "Web page template '${file}' not found.\n";
595 print qq|<pre>$info</pre>|;
596 $::dispatcher->end_request;
599 $additional_params->{AUTH} = $::auth;
600 $additional_params->{INSTANCE_CONF} = $::instance_conf;
601 $additional_params->{LOCALE} = $::locale;
602 $additional_params->{LXCONFIG} = \%::lx_office_conf;
603 $additional_params->{LXDEBUG} = $::lxdebug;
604 $additional_params->{MYCONFIG} = \%::myconfig;
606 $main::lxdebug->leave_sub();
611 sub parse_html_template {
612 $main::lxdebug->enter_sub();
614 my ($self, $file, $additional_params) = @_;
616 $additional_params ||= { };
618 my $real_file = $self->_prepare_html_template($file, $additional_params);
619 my $template = $self->template;
621 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
624 $template->process($real_file, $additional_params, \$output) || die $template->error;
626 $main::lxdebug->leave_sub();
631 sub template { $::request->presenter->get_template }
633 sub show_generic_error {
634 $main::lxdebug->enter_sub();
636 my ($self, $error, %params) = @_;
638 if ($self->{__ERROR_HANDLER}) {
639 $self->{__ERROR_HANDLER}->($error);
640 $main::lxdebug->leave_sub();
644 if ($::request->is_ajax) {
647 ->render(SL::Controller::Base->new);
648 $::dispatcher->end_request;
652 'title_error' => $params{title},
653 'label_error' => $error,
656 $self->{title} = $params{title} if $params{title};
658 for my $bar ($::request->layout->get('actionbar')) {
662 call => [ 'kivi.history_back' ],
663 accesskey => 'enter',
669 print $self->parse_html_template("generic/error", $add_params);
671 print STDERR "Error: $error\n";
673 $main::lxdebug->leave_sub();
675 $::dispatcher->end_request;
678 sub show_generic_information {
679 $main::lxdebug->enter_sub();
681 my ($self, $text, $title) = @_;
684 'title_information' => $title,
685 'label_information' => $text,
688 $self->{title} = $title if ($title);
691 print $self->parse_html_template("generic/information", $add_params);
693 $main::lxdebug->leave_sub();
695 $::dispatcher->end_request;
698 sub _store_redirect_info_in_session {
701 return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
703 my ($controller, $params) = ($1, $2);
704 my $form = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
705 $self->{callback} = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
709 $main::lxdebug->enter_sub();
711 my ($self, $msg) = @_;
713 if (!$self->{callback}) {
717 SL::Helper::Flash::flash_later('info', $msg) if $msg;
718 $self->_store_redirect_info_in_session;
719 print $::form->redirect_header($self->{callback});
722 $::dispatcher->end_request;
724 $main::lxdebug->leave_sub();
727 # sort of columns removed - empty sub
729 $main::lxdebug->enter_sub();
731 my ($self, @columns) = @_;
733 $main::lxdebug->leave_sub();
739 $main::lxdebug->enter_sub(2);
741 my ($self, $myconfig, $amount, $places, $dash) = @_;
744 my $neg = $amount < 0;
745 my $force_places = defined $places && $places >= 0;
747 $amount = $self->round_amount($amount, abs $places) if $force_places;
748 $neg = 0 if $amount == 0; # don't show negative zero
749 $amount = sprintf "%.*f", ($force_places ? $places : 10), abs $amount; # 6 is default for %fa
751 # before the sprintf amount was a number, afterwards it's a string. because of the dynamic nature of perl
752 # this is easy to confuse, so keep in mind: before this comment no s///, m//, concat or other strong ops on
753 # $amount. after this comment no +,-,*,/,abs. it will only introduce subtle bugs.
755 $amount =~ s/0*$// unless defined $places && $places == 0; # cull trailing 0s
757 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
758 my @p = split(/\./, $amount); # split amount at decimal point
760 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
762 if ($places || $p[1]) {
765 . (0 x max(abs($places || 0) - length ($p[1]||''), 0)); # pad the fraction
769 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
770 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
771 ($neg ? "-$amount" : "$amount" ) ;
774 $main::lxdebug->leave_sub(2);
778 sub format_amount_units {
779 $main::lxdebug->enter_sub();
784 my $myconfig = \%main::myconfig;
785 my $amount = $params{amount} * 1;
786 my $places = $params{places};
787 my $part_unit_name = $params{part_unit};
788 my $amount_unit_name = $params{amount_unit};
789 my $conv_units = $params{conv_units};
790 my $max_places = $params{max_places};
792 if (!$part_unit_name) {
793 $main::lxdebug->leave_sub();
797 my $all_units = AM->retrieve_all_units;
799 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
800 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
803 if (!scalar @{ $conv_units }) {
804 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
805 $main::lxdebug->leave_sub();
809 my $part_unit = $all_units->{$part_unit_name};
810 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
812 $amount *= $conv_unit->{factor};
817 foreach my $unit (@$conv_units) {
818 my $last = $unit->{name} eq $part_unit->{name};
820 $num = int($amount / $unit->{factor});
821 $amount -= $num * $unit->{factor};
824 if ($last ? $amount : $num) {
825 push @values, { "unit" => $unit->{name},
826 "amount" => $last ? $amount / $unit->{factor} : $num,
827 "places" => $last ? $places : 0 };
834 push @values, { "unit" => $part_unit_name,
839 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
841 $main::lxdebug->leave_sub();
847 $main::lxdebug->enter_sub(2);
852 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
853 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
854 $input =~ s/\#\#/\#/g;
856 $main::lxdebug->leave_sub(2);
864 $main::lxdebug->enter_sub(2);
866 my ($self, $myconfig, $amount) = @_;
868 if (!defined($amount) || ($amount eq '')) {
869 $main::lxdebug->leave_sub(2);
873 if ( ($myconfig->{numberformat} eq '1.000,00')
874 || ($myconfig->{numberformat} eq '1000,00')) {
879 if ($myconfig->{numberformat} eq "1'000.00") {
885 $main::lxdebug->leave_sub(2);
887 # Make sure no code wich is not a math expression ends up in eval().
888 return 0 unless $amount =~ /^ [\s \d \( \) \- \+ \* \/ \. ]* $/x;
890 # Prevent numbers from being parsed as octals;
891 $amount =~ s{ (?<! [\d.] ) 0+ (?= [1-9] ) }{}gx;
893 return scalar(eval($amount)) * 1 ;
897 my ($self, $amount, $places, $adjust) = @_;
899 return 0 if !defined $amount;
904 my $precision = $::instance_conf->get_precision || 0.01;
905 return $self->round_amount( $self->round_amount($amount / $precision, 0) * $precision, $places);
908 # We use Perl's knowledge of string representation for
909 # rounding. First, convert the floating point number to a string
910 # with a high number of places. Then split the string on the decimal
911 # sign and use integer calculation for rounding the decimal places
912 # part. If an overflow occurs then apply that overflow to the part
913 # before the decimal sign as well using integer arithmetic again.
915 my $int_amount = int(abs $amount);
916 my $str_places = max(min(10, 16 - length("$int_amount") - $places), $places);
917 my $amount_str = sprintf '%.*f', $places + $str_places, abs($amount);
919 return $amount unless $amount_str =~ m{^(\d+)\.(\d+)$};
921 my ($pre, $post) = ($1, $2);
922 my $decimals = '1' . substr($post, 0, $places);
924 my $propagation_limit = $Config{i32size} == 4 ? 7 : 18;
925 my $add_for_rounding = substr($post, $places, 1) >= 5 ? 1 : 0;
927 if ($places > $propagation_limit) {
928 $decimals = Math::BigInt->new($decimals)->badd($add_for_rounding);
929 $pre = Math::BigInt->new($decimals)->badd(1) if substr($decimals, 0, 1) eq '2';
932 $decimals += $add_for_rounding;
933 $pre += 1 if substr($decimals, 0, 1) eq '2';
936 $amount = ("${pre}." . substr($decimals, 1)) * ($amount <=> 0);
942 $main::lxdebug->enter_sub();
944 my ($self, $myconfig) = @_;
945 my ($out, $out_mode);
949 my $defaults = SL::DB::Default->get;
950 my $userspath = $::lx_office_conf{paths}->{userspath};
952 $self->{"cwd"} = getcwd();
953 $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
958 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
959 $template_type = 'OpenDocument';
960 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
962 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
963 $template_type = 'LaTeX';
964 $ext_for_format = 'pdf';
966 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
967 $template_type = 'HTML';
968 $ext_for_format = 'html';
970 } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
971 $template_type = 'XML';
972 $ext_for_format = 'xml';
974 } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
975 $template_type = 'XML';
977 } elsif ( $self->{"format"} =~ /excel/i ) {
978 $template_type = 'Excel';
979 $ext_for_format = 'xls';
981 } elsif ( defined $self->{'format'}) {
982 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
984 } elsif ( $self->{'format'} eq '' ) {
985 $self->error("No Outputformat given: $self->{'format'}");
987 } else { #Catch the rest
988 $self->error("Outputformat not defined: $self->{'format'}");
991 my $template = SL::Template::create(type => $template_type,
992 file_name => $self->{IN},
994 myconfig => $myconfig,
995 userspath => $userspath,
996 %{ $self->{TEMPLATE_DRIVER_OPTIONS} || {} });
998 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
999 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" } if exists $self->{ $self->{"formname"} . "notes" };
1001 if (!$self->{employee_id}) {
1002 $self->{"employee_${_}"} = $myconfig->{$_} for qw(email tel fax name signature);
1003 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
1006 $self->{"myconfig_${_}"} = $myconfig->{$_} for grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
1007 $self->{$_} = $defaults->$_ for qw(co_ustid);
1008 $self->{"myconfig_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
1009 $self->{AUTH} = $::auth;
1010 $self->{INSTANCE_CONF} = $::instance_conf;
1011 $self->{LOCALE} = $::locale;
1012 $self->{LXCONFIG} = $::lx_office_conf;
1013 $self->{LXDEBUG} = $::lxdebug;
1014 $self->{MYCONFIG} = \%::myconfig;
1016 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1018 # OUT is used for the media, screen, printer, email
1019 # for postscript we store a copy in a temporary file
1020 my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
1022 my ($temp_fh, $suffix);
1023 $suffix = $self->{IN};
1024 $suffix =~ s/.*\.//;
1025 ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
1026 strftime('kivitendo-print-%Y%m%d%H%M%S-XXXXXX', localtime()),
1027 SUFFIX => '.' . ($suffix || 'tex'),
1029 UNLINK => $keep_temp_files ? 0 : 1,
1032 chmod 0644, $self->{tmpfile} if $keep_temp_files;
1033 (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
1035 $out = $self->{OUT};
1036 $out_mode = $self->{OUT_MODE} || '>';
1037 $self->{OUT} = "$self->{tmpfile}";
1038 $self->{OUT_MODE} = '>';
1041 my $command_formatter = sub {
1042 my ($out_mode, $out) = @_;
1043 return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
1047 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1048 open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
1050 *OUT = ($::dispatcher->get_standard_filehandles)[1];
1054 if (!$template->parse(*OUT)) {
1056 $self->error("$self->{IN} : " . $template->get_error());
1059 close OUT if $self->{OUT};
1060 # check only one flag (webdav_documents)
1061 # therefore copy to webdav, even if we do not have the webdav feature enabled (just archive)
1062 my $copy_to_webdav = $::instance_conf->get_webdav_documents && !$self->{preview} && $self->{tmpdir} && $self->{tmpfile} && $self->{type}
1063 && $self->{type} ne 'statement';
1064 if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
1065 $self->append_general_pdf_attachments(filepath => $self->{tmpdir}."/".$self->{tmpfile},
1066 type => $self->{type});
1068 if ($self->{media} eq 'file') {
1069 copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
1070 Common::copy_file_to_webdav_folder($self) if $copy_to_webdav;
1071 if (!$self->{preview} && $self->doc_storage_enabled)
1073 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1074 $self->store_pdf($self);
1077 chdir("$self->{cwd}");
1079 $::lxdebug->leave_sub();
1084 Common::copy_file_to_webdav_folder($self) if $copy_to_webdav;
1086 if ( !$self->{preview} && $ext_for_format eq 'pdf' && $self->doc_storage_enabled) {
1087 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1088 my $file_obj = $self->store_pdf($self);
1089 $self->{print_file_id} = $file_obj->id if $file_obj;
1091 if ($self->{media} eq 'email') {
1092 if ( getcwd() eq $self->{"tmpdir"} ) {
1093 # in the case of generating pdf we are in the tmpdir, but WHY ???
1094 $self->{tmpfile} = $userspath."/".$self->{tmpfile};
1095 chdir("$self->{cwd}");
1097 $self->send_email(\%::myconfig,$ext_for_format);
1100 $self->{OUT} = $out;
1101 $self->{OUT_MODE} = $out_mode;
1102 $self->output_file($template->get_mime_type,$command_formatter);
1104 delete $self->{print_file_id};
1108 chdir("$self->{cwd}");
1109 $main::lxdebug->leave_sub();
1112 sub get_bcc_defaults {
1113 my ($self, $myconfig, $mybcc) = @_;
1114 if (SL::DB::Default->get->bcc_to_login) {
1115 $mybcc .= ", " if $mybcc;
1116 $mybcc .= $myconfig->{email};
1118 my $otherbcc = SL::DB::Default->get->global_bcc;
1120 $mybcc .= ", " if $mybcc;
1121 $mybcc .= $otherbcc;
1127 $main::lxdebug->enter_sub();
1128 my ($self, $myconfig, $ext_for_format) = @_;
1129 my $mail = Mailer->new;
1131 map { $mail->{$_} = $self->{$_} }
1132 qw(cc subject message version format);
1134 $mail->{bcc} = $self->get_bcc_defaults($myconfig, $self->{bcc});
1135 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1136 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1137 $mail->{fileid} = time() . '.' . $$ . '.';
1138 my $full_signature = $self->create_email_signature();
1139 $full_signature =~ s/\r//g;
1141 $mail->{attachments} = [];
1143 # if we send html or plain text inline
1144 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1145 $mail->{contenttype} = "text/html";
1146 $mail->{message} =~ s/\r//g;
1147 $mail->{message} =~ s/\n/<br>\n/g;
1148 $full_signature =~ s/\n/<br>\n/g;
1149 $mail->{message} .= $full_signature;
1151 open(IN, "<", $self->{tmpfile})
1152 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1153 $mail->{message} .= $_ while <IN>;
1156 } elsif (($self->{attachment_policy} // '') ne 'no_file') {
1157 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1158 $attachment_name =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1160 if (($self->{attachment_policy} // '') eq 'old_file') {
1161 my ( $attfile ) = SL::File->get_all(object_id => $self->{id},
1162 object_type => $self->{formname},
1163 file_type => 'document');
1166 $attfile->{override_file_name} = $attachment_name if $attachment_name;
1167 push @attfiles, $attfile;
1171 push @{ $mail->{attachments} }, { path => $self->{tmpfile},
1172 id => $self->{print_file_id},
1173 type => "application/pdf",
1174 name => $attachment_name };
1180 map { SL::File->get(id => $_) }
1181 @{ $self->{attach_file_ids} // [] };
1183 foreach my $attfile ( @attfiles ) {
1184 push @{ $mail->{attachments} }, {
1185 path => $attfile->get_file,
1187 type => $attfile->mime_type,
1188 name => $attfile->{override_file_name} // $attfile->file_name,
1189 content => $attfile->get_content ? ${ $attfile->get_content } : undef,
1193 $mail->{message} =~ s/\r//g;
1194 $mail->{message} .= $full_signature;
1195 $self->{emailerr} = $mail->send();
1197 if ($self->{emailerr}) {
1199 $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
1202 $self->{email_journal_id} = $mail->{journalentry};
1203 $self->{snumbers} = "emailjournal" . "_" . $self->{email_journal_id};
1204 $self->{what_done} = $::form->{type};
1205 $self->{addition} = "MAILED";
1206 $self->save_history;
1208 #write back for message info and mail journal
1209 $self->{cc} = $mail->{cc};
1210 $self->{bcc} = $mail->{bcc};
1211 $self->{email} = $mail->{to};
1213 $main::lxdebug->leave_sub();
1217 $main::lxdebug->enter_sub();
1219 my ($self,$mimeType,$command_formatter) = @_;
1220 my $numbytes = (-s $self->{tmpfile});
1221 open(IN, "<", $self->{tmpfile})
1222 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1225 $self->{copies} = 1 unless $self->{media} eq 'printer';
1227 chdir("$self->{cwd}");
1228 for my $i (1 .. $self->{copies}) {
1230 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1232 open OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1233 print OUT $_ while <IN>;
1238 my %headers = ('-type' => $mimeType,
1239 '-connection' => 'close',
1240 '-charset' => 'UTF-8');
1242 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1244 if ($self->{attachment_filename}) {
1247 '-attachment' => $self->{attachment_filename},
1248 '-content-length' => $numbytes,
1253 print $::request->cgi->header(%headers);
1255 $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1259 $main::lxdebug->leave_sub();
1262 sub get_formname_translation {
1263 $main::lxdebug->enter_sub();
1264 my ($self, $formname) = @_;
1266 $formname ||= $self->{formname};
1268 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1269 local $::locale = Locale->new($self->{recipient_locale});
1271 my %formname_translations = (
1272 bin_list => $main::locale->text('Bin List'),
1273 credit_note => $main::locale->text('Credit Note'),
1274 invoice => $main::locale->text('Invoice'),
1275 pick_list => $main::locale->text('Pick List'),
1276 proforma => $main::locale->text('Proforma Invoice'),
1277 purchase_order => $main::locale->text('Purchase Order'),
1278 request_quotation => $main::locale->text('RFQ'),
1279 sales_order => $main::locale->text('Confirmation'),
1280 sales_quotation => $main::locale->text('Quotation'),
1281 storno_invoice => $main::locale->text('Storno Invoice'),
1282 sales_delivery_order => $main::locale->text('Delivery Order'),
1283 purchase_delivery_order => $main::locale->text('Delivery Order'),
1284 dunning => $main::locale->text('Dunning'),
1285 dunning1 => $main::locale->text('Payment Reminder'),
1286 dunning2 => $main::locale->text('Dunning'),
1287 dunning3 => $main::locale->text('Last Dunning'),
1288 dunning_invoice => $main::locale->text('Dunning Invoice'),
1289 letter => $main::locale->text('Letter'),
1290 ic_supply => $main::locale->text('Intra-Community supply'),
1291 statement => $main::locale->text('Statement'),
1294 $main::lxdebug->leave_sub();
1295 return $formname_translations{$formname};
1298 sub get_number_prefix_for_type {
1299 $main::lxdebug->enter_sub();
1303 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1304 : ($self->{type} =~ /_quotation$/) ? 'quo'
1305 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1306 : ($self->{type} =~ /letter/) ? 'letter'
1309 # better default like this?
1310 # : ($self->{type} =~ /(sales|purcharse)_order/ : 'ord';
1311 # : 'prefix_undefined';
1313 $main::lxdebug->leave_sub();
1317 sub get_extension_for_format {
1318 $main::lxdebug->enter_sub();
1321 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1322 : $self->{format} =~ /postscript/i ? ".ps"
1323 : $self->{format} =~ /opendocument/i ? ".odt"
1324 : $self->{format} =~ /excel/i ? ".xls"
1325 : $self->{format} =~ /html/i ? ".html"
1328 $main::lxdebug->leave_sub();
1332 sub generate_attachment_filename {
1333 $main::lxdebug->enter_sub();
1336 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1337 my $recipient_locale = Locale->new($self->{recipient_locale});
1339 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1340 my $prefix = $self->get_number_prefix_for_type();
1342 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1343 $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
1345 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1346 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1348 } elsif ($attachment_filename) {
1349 $attachment_filename .= $self->get_extension_for_format();
1352 $attachment_filename = "";
1355 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1356 $attachment_filename =~ s|[\s/\\]+|_|g;
1358 $main::lxdebug->leave_sub();
1359 return $attachment_filename;
1362 sub generate_email_subject {
1363 $main::lxdebug->enter_sub();
1366 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1367 my $prefix = $self->get_number_prefix_for_type();
1369 if ($subject && $self->{"${prefix}number"}) {
1370 $subject .= " " . $self->{"${prefix}number"}
1373 $main::lxdebug->leave_sub();
1377 sub generate_email_body {
1378 $main::lxdebug->enter_sub();
1380 # simple german and english will work grammatically (most european languages as well)
1381 # Dear Mr Alan Greenspan:
1382 # Sehr geehrte Frau Meyer,
1383 # A l’attention de Mme Villeroy,
1384 # Gentile Signora Ferrari,
1387 if ($self->{cp_id}) {
1388 my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
1389 my $name = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
1390 my $gender = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
1391 my $mf = $gender eq 'f' ? 'female' : 'male';
1392 $body = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
1393 $body .= ' ' . $givenname . ' ' . $name if $body;
1395 $body = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
1398 return undef unless $body;
1400 $body .= GenericTranslations->get(translation_type =>"salutation_punctuation_mark", language_id => $self->{language_id}) . "\n";
1401 $body .= GenericTranslations->get(translation_type =>"preset_text_$self->{formname}", language_id => $self->{language_id});
1403 $body = $main::locale->unquote_special_chars('HTML', $body);
1405 $main::lxdebug->leave_sub();
1410 $main::lxdebug->enter_sub();
1412 my ($self, $application) = @_;
1414 my $error_code = $?;
1416 chdir("$self->{tmpdir}");
1419 if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1420 push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1422 } elsif (-f "$self->{tmpfile}.err") {
1423 open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
1428 if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1429 $self->{tmpfile} =~ s|.*/||g;
1431 $self->{tmpfile} =~ s/\.\w+$//g;
1432 my $tmpfile = $self->{tmpfile};
1433 unlink(<$tmpfile.*>);
1436 chdir("$self->{cwd}");
1438 $main::lxdebug->leave_sub();
1444 $main::lxdebug->enter_sub();
1446 my ($self, $date, $myconfig) = @_;
1449 if ($date && $date =~ /\D/) {
1451 if ($myconfig->{dateformat} =~ /^yy/) {
1452 ($yy, $mm, $dd) = split /\D/, $date;
1454 if ($myconfig->{dateformat} =~ /^mm/) {
1455 ($mm, $dd, $yy) = split /\D/, $date;
1457 if ($myconfig->{dateformat} =~ /^dd/) {
1458 ($dd, $mm, $yy) = split /\D/, $date;
1463 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1464 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1466 $dd = "0$dd" if ($dd < 10);
1467 $mm = "0$mm" if ($mm < 10);
1469 $date = "$yy$mm$dd";
1472 $main::lxdebug->leave_sub();
1477 # Database routines used throughout
1478 # DB Handling got moved to SL::DB, these are only shims for compatibility
1481 SL::DB->client->dbh;
1484 sub get_standard_dbh {
1485 my $dbh = SL::DB->client->dbh;
1487 if ($dbh && !$dbh->{Active}) {
1488 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
1489 SL::DB->client->dbh(undef);
1492 SL::DB->client->dbh;
1495 sub disconnect_standard_dbh {
1496 SL::DB->client->dbh->rollback;
1502 $main::lxdebug->enter_sub();
1504 my ($self, $date, $myconfig) = @_;
1505 my $dbh = $self->get_standard_dbh;
1507 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1508 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1510 # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1511 # es ist sicher ein conv_date vorher IMMER auszuführen.
1512 # Testfälle ohne definiertes closedto:
1513 # Leere Datumseingabe i.O.
1514 # SELECT 1 FROM defaults WHERE '' < closedto
1515 # normale Zahlungsbuchung über Rechnungsmaske i.O.
1516 # SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1517 # Testfälle mit definiertem closedto (30.04.2011):
1518 # Leere Datumseingabe i.O.
1519 # SELECT 1 FROM defaults WHERE '' < closedto
1520 # normale Buchung im geschloßenem Zeitraum i.O.
1521 # SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1522 # Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1523 # normale Buchung in aktiver Buchungsperiode i.O.
1524 # SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1526 my ($closed) = $sth->fetchrow_array;
1528 $main::lxdebug->leave_sub();
1533 # prevents bookings to the to far away future
1534 sub date_max_future {
1535 $main::lxdebug->enter_sub();
1537 my ($self, $date, $myconfig) = @_;
1538 my $dbh = $self->get_standard_dbh;
1540 my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
1541 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1543 my ($max_future_booking_interval) = $sth->fetchrow_array;
1545 $main::lxdebug->leave_sub();
1547 return $max_future_booking_interval;
1551 sub update_balance {
1552 $main::lxdebug->enter_sub();
1554 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1556 # if we have a value, go do it
1559 # retrieve balance from table
1560 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1561 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1562 my ($balance) = $sth->fetchrow_array;
1568 $query = "UPDATE $table SET $field = $balance WHERE $where";
1569 do_query($self, $dbh, $query, @values);
1571 $main::lxdebug->leave_sub();
1574 sub update_exchangerate {
1575 $main::lxdebug->enter_sub();
1577 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1579 # some sanity check for currency
1581 $main::lxdebug->leave_sub();
1584 $query = qq|SELECT name AS curr FROM currencies WHERE id=(SELECT currency_id FROM defaults)|;
1586 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1588 if ($curr eq $defaultcurrency) {
1589 $main::lxdebug->leave_sub();
1593 $query = qq|SELECT e.currency_id FROM exchangerate e
1594 WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
1596 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1605 $buy = conv_i($buy, "NULL");
1606 $sell = conv_i($sell, "NULL");
1609 if ($buy != 0 && $sell != 0) {
1610 $set = "buy = $buy, sell = $sell";
1611 } elsif ($buy != 0) {
1612 $set = "buy = $buy";
1613 } elsif ($sell != 0) {
1614 $set = "sell = $sell";
1617 if ($sth->fetchrow_array) {
1618 $query = qq|UPDATE exchangerate
1620 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
1624 $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
1625 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
1628 do_query($self, $dbh, $query, $curr, $transdate);
1630 $main::lxdebug->leave_sub();
1633 sub save_exchangerate {
1634 $main::lxdebug->enter_sub();
1636 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1638 SL::DB->client->with_transaction(sub {
1639 my $dbh = SL::DB->client->dbh;
1643 $buy = $rate if $fld eq 'buy';
1644 $sell = $rate if $fld eq 'sell';
1647 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1649 }) or do { die SL::DB->client->error };
1651 $main::lxdebug->leave_sub();
1654 sub get_exchangerate {
1655 $main::lxdebug->enter_sub();
1657 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1660 unless ($transdate && $curr) {
1661 $main::lxdebug->leave_sub();
1665 $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1667 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1669 if ($curr eq $defaultcurrency) {
1670 $main::lxdebug->leave_sub();
1674 $query = qq|SELECT e.$fld FROM exchangerate e
1675 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1676 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1680 $main::lxdebug->leave_sub();
1682 return $exchangerate;
1685 sub check_exchangerate {
1686 $main::lxdebug->enter_sub();
1688 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1690 if ($fld !~/^buy|sell$/) {
1691 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1694 unless ($transdate) {
1695 $main::lxdebug->leave_sub();
1699 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1701 if ($currency eq $defaultcurrency) {
1702 $main::lxdebug->leave_sub();
1706 my $dbh = $self->get_standard_dbh($myconfig);
1707 my $query = qq|SELECT e.$fld FROM exchangerate e
1708 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1710 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1712 $main::lxdebug->leave_sub();
1714 return $exchangerate;
1717 sub get_all_currencies {
1718 $main::lxdebug->enter_sub();
1721 my $myconfig = shift || \%::myconfig;
1722 my $dbh = $self->get_standard_dbh($myconfig);
1724 my $query = qq|SELECT name FROM currencies|;
1725 my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
1727 $main::lxdebug->leave_sub();
1732 sub get_default_currency {
1733 $main::lxdebug->enter_sub();
1735 my ($self, $myconfig) = @_;
1736 my $dbh = $self->get_standard_dbh($myconfig);
1737 my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1739 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1741 $main::lxdebug->leave_sub();
1743 return $defaultcurrency;
1746 sub set_payment_options {
1747 my ($self, $myconfig, $transdate, $type) = @_;
1749 my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
1752 my $is_invoice = $type =~ m{invoice}i;
1754 $transdate ||= $self->{invdate} || $self->{transdate};
1755 my $due_date = $self->{duedate} || $self->{reqdate};
1757 $self->{$_} = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
1758 $self->{payment_description} = $terms->description;
1759 $self->{netto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
1760 $self->{skonto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
1762 my ($invtotal, $total);
1763 my (%amounts, %formatted_amounts);
1765 if ($self->{type} =~ /_order$/) {
1766 $amounts{invtotal} = $self->{ordtotal};
1767 $amounts{total} = $self->{ordtotal};
1769 } elsif ($self->{type} =~ /_quotation$/) {
1770 $amounts{invtotal} = $self->{quototal};
1771 $amounts{total} = $self->{quototal};
1774 $amounts{invtotal} = $self->{invtotal};
1775 $amounts{total} = $self->{total};
1777 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1779 $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1780 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1781 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1782 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1784 foreach (keys %amounts) {
1785 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1786 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1789 if ($self->{"language_id"}) {
1790 my $language = SL::DB::Language->new(id => $self->{language_id})->load;
1792 $self->{payment_terms} = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
1793 $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
1795 if ($language->output_dateformat) {
1796 foreach my $key (qw(netto_date skonto_date)) {
1797 $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
1801 if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
1802 local $myconfig->{numberformat};
1803 $myconfig->{"numberformat"} = $language->output_numberformat;
1804 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
1808 $self->{payment_terms} = $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
1810 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1811 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1812 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1813 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1814 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1815 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1816 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1817 $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
1818 $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
1819 $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
1820 $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
1822 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1824 $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1828 sub get_template_language {
1829 $main::lxdebug->enter_sub();
1831 my ($self, $myconfig) = @_;
1833 my $template_code = "";
1835 if ($self->{language_id}) {
1836 my $dbh = $self->get_standard_dbh($myconfig);
1837 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1838 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1841 $main::lxdebug->leave_sub();
1843 return $template_code;
1846 sub get_printer_code {
1847 $main::lxdebug->enter_sub();
1849 my ($self, $myconfig) = @_;
1851 my $template_code = "";
1853 if ($self->{printer_id}) {
1854 my $dbh = $self->get_standard_dbh($myconfig);
1855 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1856 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1859 $main::lxdebug->leave_sub();
1861 return $template_code;
1865 $main::lxdebug->enter_sub();
1867 my ($self, $myconfig) = @_;
1869 my $template_code = "";
1871 if ($self->{shipto_id}) {
1872 my $dbh = $self->get_standard_dbh($myconfig);
1873 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1874 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1875 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1877 my $cvars = CVar->get_custom_variables(
1880 trans_id => $self->{shipto_id},
1882 $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
1885 $main::lxdebug->leave_sub();
1889 my ($self, $dbh, $id, $module) = @_;
1894 foreach my $item (qw(name department_1 department_2 street zipcode city country gln
1895 contact cp_gender phone fax email)) {
1896 if ($self->{"shipto$item"}) {
1897 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1899 push(@values, $self->{"shipto${item}"});
1904 my $shipto_id = $self->{shipto_id};
1906 if ($self->{shipto_id}) {
1907 my $query = qq|UPDATE shipto set
1909 shiptodepartment_1 = ?,
1910 shiptodepartment_2 = ?,
1917 shiptocp_gender = ?,
1921 WHERE shipto_id = ?|;
1922 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1924 my $query = qq|SELECT * FROM shipto
1925 WHERE shiptoname = ? AND
1926 shiptodepartment_1 = ? AND
1927 shiptodepartment_2 = ? AND
1928 shiptostreet = ? AND
1929 shiptozipcode = ? AND
1931 shiptocountry = ? AND
1933 shiptocontact = ? AND
1934 shiptocp_gender = ? AND
1940 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1943 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1944 shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
1945 shiptocontact, shiptocp_gender, shiptophone, shiptofax, shiptoemail, module)
1946 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1947 do_query($self, $dbh, $insert_query, $id, @values, $module);
1949 $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1952 $shipto_id = $insert_check->{shipto_id};
1955 return unless $shipto_id;
1957 CVar->save_custom_variables(
1960 trans_id => $shipto_id,
1962 name_prefix => 'shipto',
1967 $main::lxdebug->enter_sub();
1969 my ($self, $dbh) = @_;
1971 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1973 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1974 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1975 $self->{"employee_id"} *= 1;
1977 $main::lxdebug->leave_sub();
1980 sub get_employee_data {
1981 $main::lxdebug->enter_sub();
1985 my $defaults = SL::DB::Default->get;
1987 Common::check_params(\%params, qw(prefix));
1988 Common::check_params_x(\%params, qw(id));
1991 $main::lxdebug->leave_sub();
1995 my $myconfig = \%main::myconfig;
1996 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
1998 my ($login, $deleted) = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
2001 # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
2002 $self->{$params{prefix} . '_login'} = $login;
2003 $self->{$params{prefix} . "_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
2006 # get employee data from auth.user_config
2007 my $user = User->new(login => $login);
2008 $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
2010 # get saved employee data from employee
2011 my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
2012 $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
2013 $self->{$params{prefix} . "_name"} = $employee->name;
2016 $main::lxdebug->leave_sub();
2020 $main::lxdebug->enter_sub();
2022 my ($self, $dbh, $id, $key) = @_;
2024 $key = "all_contacts" unless ($key);
2028 $main::lxdebug->leave_sub();
2033 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2034 qq|FROM contacts | .
2035 qq|WHERE cp_cv_id = ? | .
2036 qq|ORDER BY lower(cp_name)|;
2038 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2040 $main::lxdebug->leave_sub();
2044 $main::lxdebug->enter_sub();
2046 my ($self, $dbh, $key) = @_;
2048 my ($all, $old_id, $where, @values);
2050 if (ref($key) eq "HASH") {
2053 $key = "ALL_PROJECTS";
2055 foreach my $p (keys(%{$params})) {
2057 $all = $params->{$p};
2058 } elsif ($p eq "old_id") {
2059 $old_id = $params->{$p};
2060 } elsif ($p eq "key") {
2061 $key = $params->{$p};
2067 $where = "WHERE active ";
2069 if (ref($old_id) eq "ARRAY") {
2070 my @ids = grep({ $_ } @{$old_id});
2072 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2073 push(@values, @ids);
2076 $where .= " OR (id = ?) ";
2077 push(@values, $old_id);
2083 qq|SELECT id, projectnumber, description, active | .
2086 qq|ORDER BY lower(projectnumber)|;
2088 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2090 $main::lxdebug->leave_sub();
2094 $main::lxdebug->enter_sub();
2096 my ($self, $dbh, $vc_id, $key) = @_;
2098 $key = "all_shipto" unless ($key);
2101 # get shipping addresses
2102 my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2104 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2110 $main::lxdebug->leave_sub();
2114 $main::lxdebug->enter_sub();
2116 my ($self, $dbh, $key) = @_;
2118 $key = "all_printers" unless ($key);
2120 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2122 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2124 $main::lxdebug->leave_sub();
2128 $main::lxdebug->enter_sub();
2130 my ($self, $dbh, $params) = @_;
2133 $key = $params->{key};
2134 $key = "all_charts" unless ($key);
2136 my $transdate = quote_db_date($params->{transdate});
2139 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2141 qq|LEFT JOIN taxkeys tk ON | .
2142 qq|(tk.id = (SELECT id FROM taxkeys | .
2143 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2144 qq| ORDER BY startdate DESC LIMIT 1)) | .
2145 qq|ORDER BY c.accno|;
2147 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2149 $main::lxdebug->leave_sub();
2152 sub _get_taxcharts {
2153 $main::lxdebug->enter_sub();
2155 my ($self, $dbh, $params) = @_;
2157 my $key = "all_taxcharts";
2160 if (ref $params eq 'HASH') {
2161 $key = $params->{key} if ($params->{key});
2162 if ($params->{module} eq 'AR') {
2163 push @where, 'chart_categories ~ \'[ACILQ]\'';
2165 } elsif ($params->{module} eq 'AP') {
2166 push @where, 'chart_categories ~ \'[ACELQ]\'';
2173 my $where = @where ? ' WHERE ' . join(' AND ', map { "($_)" } @where) : '';
2175 my $query = qq|SELECT * FROM tax $where ORDER BY taxkey, rate|;
2177 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2179 $main::lxdebug->leave_sub();
2183 $main::lxdebug->enter_sub();
2185 my ($self, $dbh, $key) = @_;
2187 $key = "all_taxzones" unless ($key);
2189 $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
2191 my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
2193 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2195 $main::lxdebug->leave_sub();
2198 sub _get_employees {
2199 $main::lxdebug->enter_sub();
2201 my ($self, $dbh, $params) = @_;
2206 if (ref $params eq 'HASH') {
2207 $key = $params->{key};
2208 $deleted = $params->{deleted};
2214 $key ||= "all_employees";
2215 my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
2216 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
2218 $main::lxdebug->leave_sub();
2221 sub _get_business_types {
2222 $main::lxdebug->enter_sub();
2224 my ($self, $dbh, $key) = @_;
2226 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2227 $options->{key} ||= "all_business_types";
2230 if (exists $options->{salesman}) {
2231 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2234 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2236 $main::lxdebug->leave_sub();
2239 sub _get_languages {
2240 $main::lxdebug->enter_sub();
2242 my ($self, $dbh, $key) = @_;
2244 $key = "all_languages" unless ($key);
2246 my $query = qq|SELECT * FROM language ORDER BY id|;
2248 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2250 $main::lxdebug->leave_sub();
2253 sub _get_dunning_configs {
2254 $main::lxdebug->enter_sub();
2256 my ($self, $dbh, $key) = @_;
2258 $key = "all_dunning_configs" unless ($key);
2260 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2262 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2264 $main::lxdebug->leave_sub();
2267 sub _get_currencies {
2268 $main::lxdebug->enter_sub();
2270 my ($self, $dbh, $key) = @_;
2272 $key = "all_currencies" unless ($key);
2274 $self->{$key} = [$self->get_all_currencies()];
2276 $main::lxdebug->leave_sub();
2280 $main::lxdebug->enter_sub();
2282 my ($self, $dbh, $key) = @_;
2284 $key = "all_payments" unless ($key);
2286 my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2288 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2290 $main::lxdebug->leave_sub();
2293 sub _get_customers {
2294 $main::lxdebug->enter_sub();
2296 my ($self, $dbh, $key) = @_;
2298 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2299 $options->{key} ||= "all_customers";
2300 my $limit_clause = $options->{limit} ? "LIMIT $options->{limit}" : '';
2303 push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman};
2304 push @where, qq|NOT obsolete| if !$options->{with_obsolete};
2305 my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2307 my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2308 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2310 $main::lxdebug->leave_sub();
2314 $main::lxdebug->enter_sub();
2316 my ($self, $dbh, $key) = @_;
2318 $key = "all_vendors" unless ($key);
2320 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2322 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2324 $main::lxdebug->leave_sub();
2327 sub _get_departments {
2328 $main::lxdebug->enter_sub();
2330 my ($self, $dbh, $key) = @_;
2332 $key = "all_departments" unless ($key);
2334 my $query = qq|SELECT * FROM department ORDER BY description|;
2336 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2338 $main::lxdebug->leave_sub();
2341 sub _get_warehouses {
2342 $main::lxdebug->enter_sub();
2344 my ($self, $dbh, $param) = @_;
2346 my ($key, $bins_key);
2348 if ('' eq ref $param) {
2352 $key = $param->{key};
2353 $bins_key = $param->{bins};
2356 my $query = qq|SELECT w.* FROM warehouse w
2357 WHERE (NOT w.invalid) AND
2358 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2359 ORDER BY w.sortkey|;
2361 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2364 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2365 ORDER BY description|;
2366 my $sth = prepare_query($self, $dbh, $query);
2368 foreach my $warehouse (@{ $self->{$key} }) {
2369 do_statement($self, $sth, $query, $warehouse->{id});
2370 $warehouse->{$bins_key} = [];
2372 while (my $ref = $sth->fetchrow_hashref()) {
2373 push @{ $warehouse->{$bins_key} }, $ref;
2379 $main::lxdebug->leave_sub();
2383 $main::lxdebug->enter_sub();
2385 my ($self, $dbh, $table, $key, $sortkey) = @_;
2387 my $query = qq|SELECT * FROM $table|;
2388 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2390 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2392 $main::lxdebug->leave_sub();
2396 # $main::lxdebug->enter_sub();
2398 # my ($self, $dbh, $key) = @_;
2400 # $key ||= "all_groups";
2402 # my $groups = $main::auth->read_groups();
2404 # $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2406 # $main::lxdebug->leave_sub();
2410 $main::lxdebug->enter_sub();
2415 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2416 my ($sth, $query, $ref);
2419 if ($params{contacts} || $params{shipto}) {
2420 $vc = 'customer' if $self->{"vc"} eq "customer";
2421 $vc = 'vendor' if $self->{"vc"} eq "vendor";
2422 die "invalid use of get_lists, need 'vc'" unless $vc;
2423 $vc_id = $self->{"${vc}_id"};
2426 if ($params{"contacts"}) {
2427 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2430 if ($params{"shipto"}) {
2431 $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2434 if ($params{"projects"} || $params{"all_projects"}) {
2435 $self->_get_projects($dbh, $params{"all_projects"} ?
2436 $params{"all_projects"} : $params{"projects"},
2437 $params{"all_projects"} ? 1 : 0);
2440 if ($params{"printers"}) {
2441 $self->_get_printers($dbh, $params{"printers"});
2444 if ($params{"languages"}) {
2445 $self->_get_languages($dbh, $params{"languages"});
2448 if ($params{"charts"}) {
2449 $self->_get_charts($dbh, $params{"charts"});
2452 if ($params{"taxcharts"}) {
2453 $self->_get_taxcharts($dbh, $params{"taxcharts"});
2456 if ($params{"taxzones"}) {
2457 $self->_get_taxzones($dbh, $params{"taxzones"});
2460 if ($params{"employees"}) {
2461 $self->_get_employees($dbh, $params{"employees"});
2464 if ($params{"salesmen"}) {
2465 $self->_get_employees($dbh, $params{"salesmen"});
2468 if ($params{"business_types"}) {
2469 $self->_get_business_types($dbh, $params{"business_types"});
2472 if ($params{"dunning_configs"}) {
2473 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2476 if($params{"currencies"}) {
2477 $self->_get_currencies($dbh, $params{"currencies"});
2480 if($params{"customers"}) {
2481 $self->_get_customers($dbh, $params{"customers"});
2484 if($params{"vendors"}) {
2485 if (ref $params{"vendors"} eq 'HASH') {
2486 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2488 $self->_get_vendors($dbh, $params{"vendors"});
2492 if($params{"payments"}) {
2493 $self->_get_payments($dbh, $params{"payments"});
2496 if($params{"departments"}) {
2497 $self->_get_departments($dbh, $params{"departments"});
2500 if ($params{price_factors}) {
2501 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2504 if ($params{warehouses}) {
2505 $self->_get_warehouses($dbh, $params{warehouses});
2508 # if ($params{groups}) {
2509 # $self->_get_groups($dbh, $params{groups});
2512 if ($params{partsgroup}) {
2513 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2516 $main::lxdebug->leave_sub();
2519 # this sub gets the id and name from $table
2521 $main::lxdebug->enter_sub();
2523 my ($self, $myconfig, $table) = @_;
2525 # connect to database
2526 my $dbh = $self->get_standard_dbh($myconfig);
2528 $table = $table eq "customer" ? "customer" : "vendor";
2529 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2531 my ($query, @values);
2533 if (!$self->{openinvoices}) {
2535 if ($self->{customernumber} ne "") {
2536 $where = qq|(vc.customernumber ILIKE ?)|;
2537 push(@values, like($self->{customernumber}));
2539 $where = qq|(vc.name ILIKE ?)|;
2540 push(@values, like($self->{$table}));
2544 qq~SELECT vc.id, vc.name,
2545 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2547 WHERE $where AND (NOT vc.obsolete)
2551 qq~SELECT DISTINCT vc.id, vc.name,
2552 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2554 JOIN $table vc ON (a.${table}_id = vc.id)
2555 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2557 push(@values, like($self->{$table}));
2560 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2562 $main::lxdebug->leave_sub();
2564 return scalar(@{ $self->{name_list} });
2569 my ($self, $table, $provided_dbh) = @_;
2571 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
2572 return unless $self->{id};
2573 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2575 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2576 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2577 $ref->{mtime} ||= $ref->{itime};
2578 $self->{lastmtime} = $ref->{mtime};
2582 sub mtime_ischanged {
2583 my ($self, $table, $option) = @_;
2585 return unless $self->{id};
2586 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2588 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2589 my $ref = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
2590 $ref->{mtime} ||= $ref->{itime};
2592 if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
2593 $self->error(($option eq 'mail') ?
2594 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") :
2595 t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
2597 $::dispatcher->end_request;
2601 # language_payment duplicates some of the functionality of all_vc (language,
2602 # printer, payment_terms), and at least in the case of sales invoices both
2603 # all_vc and language_payment are called when adding new invoices
2604 sub language_payment {
2605 $main::lxdebug->enter_sub();
2607 my ($self, $myconfig) = @_;
2609 my $dbh = $self->get_standard_dbh($myconfig);
2611 my $query = qq|SELECT id, description
2615 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2618 $query = qq|SELECT printer_description, id
2620 ORDER BY printer_description|;
2622 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2625 $query = qq|SELECT id, description
2627 WHERE ( obsolete IS FALSE OR id = ? )
2629 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
2631 # get buchungsgruppen
2632 $query = qq|SELECT id, description
2633 FROM buchungsgruppen|;
2635 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2637 $main::lxdebug->leave_sub();
2640 # this is only used for reports
2641 sub all_departments {
2642 $main::lxdebug->enter_sub();
2644 my ($self, $myconfig, $table) = @_;
2646 my $dbh = $self->get_standard_dbh($myconfig);
2648 my $query = qq|SELECT id, description
2650 ORDER BY description|;
2651 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2653 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2655 $main::lxdebug->leave_sub();
2659 $main::lxdebug->enter_sub();
2661 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2664 if ($table eq "customer") {
2673 # get last customers or vendors
2674 my ($query, $sth, $ref);
2676 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2681 my $transdate = "current_date";
2682 if ($self->{transdate}) {
2683 $transdate = $dbh->quote($self->{transdate});
2686 # now get the account numbers
2688 SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
2690 -- find newest entries in taxkeys
2692 SELECT chart_id, MAX(startdate) AS startdate
2694 WHERE (startdate <= $transdate)
2696 ) tk ON (c.id = tk.chart_id)
2697 -- and load all of those entries
2698 INNER JOIN taxkeys tk2
2699 ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
2700 WHERE (c.link LIKE ?)
2703 $sth = $dbh->prepare($query);
2705 do_statement($self, $sth, $query, like($module));
2707 $self->{accounts} = "";
2708 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2710 foreach my $key (split(/:/, $ref->{link})) {
2711 if ($key =~ /\Q$module\E/) {
2713 # cross reference for keys
2714 $xkeyref{ $ref->{accno} } = $key;
2716 push @{ $self->{"${module}_links"}{$key} },
2717 { accno => $ref->{accno},
2718 chart_id => $ref->{chart_id},
2719 description => $ref->{description},
2720 taxkey => $ref->{taxkey_id},
2721 tax_id => $ref->{tax_id} };
2723 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2729 # get taxkeys and description
2730 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2731 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2733 if (($module eq "AP") || ($module eq "AR")) {
2734 # get tax rates and description
2735 $query = qq|SELECT * FROM tax|;
2736 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2739 my $extra_columns = '';
2740 $extra_columns .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
2745 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2746 a.duedate, a.ordnumber, a.taxincluded, (SELECT cu.name FROM currencies cu WHERE cu.id=a.currency_id) AS currency, a.notes,
2748 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2749 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2750 a.globalproject_id, ${extra_columns}
2752 d.description AS department,
2755 JOIN $table c ON (a.${table}_id = c.id)
2756 LEFT JOIN employee e ON (e.id = a.employee_id)
2757 LEFT JOIN department d ON (d.id = a.department_id)
2759 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2761 foreach my $key (keys %$ref) {
2762 $self->{$key} = $ref->{$key};
2764 $self->{mtime} ||= $self->{itime};
2765 $self->{lastmtime} = $self->{mtime};
2766 my $transdate = "current_date";
2767 if ($self->{transdate}) {
2768 $transdate = $dbh->quote($self->{transdate});
2771 # now get the account numbers
2772 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
2774 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2776 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2777 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2780 $sth = $dbh->prepare($query);
2781 do_statement($self, $sth, $query, like($module));
2783 $self->{accounts} = "";
2784 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2786 foreach my $key (split(/:/, $ref->{link})) {
2787 if ($key =~ /\Q$module\E/) {
2789 # cross reference for keys
2790 $xkeyref{ $ref->{accno} } = $key;
2792 push @{ $self->{"${module}_links"}{$key} },
2793 { accno => $ref->{accno},
2794 chart_id => $ref->{chart_id},
2795 description => $ref->{description},
2796 taxkey => $ref->{taxkey_id},
2797 tax_id => $ref->{tax_id} };
2799 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2805 # get amounts from individual entries
2808 c.accno, c.description,
2809 a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
2813 LEFT JOIN chart c ON (c.id = a.chart_id)
2814 LEFT JOIN project p ON (p.id = a.project_id)
2815 LEFT JOIN tax t ON (t.id= a.tax_id)
2816 WHERE a.trans_id = ?
2817 AND a.fx_transaction = '0'
2818 ORDER BY a.acc_trans_id, a.transdate|;
2819 $sth = $dbh->prepare($query);
2820 do_statement($self, $sth, $query, $self->{id});
2822 # get exchangerate for currency
2823 $self->{exchangerate} =
2824 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2827 # store amounts in {acc_trans}{$key} for multiple accounts
2828 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2829 $ref->{exchangerate} =
2830 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2831 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2834 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2835 $ref->{amount} *= -1;
2837 $ref->{index} = $index;
2839 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2846 d.closedto, d.revtrans,
2847 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2848 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2849 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2850 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2851 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2853 $ref = selectfirst_hashref_query($self, $dbh, $query);
2854 map { $self->{$_} = $ref->{$_} } keys %$ref;
2861 current_date AS transdate, d.closedto, d.revtrans,
2862 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2863 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2864 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2865 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2866 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2868 $ref = selectfirst_hashref_query($self, $dbh, $query);
2869 map { $self->{$_} = $ref->{$_} } keys %$ref;
2871 if ($self->{"$self->{vc}_id"}) {
2873 # only setup currency
2874 ($self->{currency}) = $self->{defaultcurrency} if !$self->{currency};
2878 $self->lastname_used($dbh, $myconfig, $table, $module);
2880 # get exchangerate for currency
2881 $self->{exchangerate} =
2882 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2888 $main::lxdebug->leave_sub();
2892 $main::lxdebug->enter_sub();
2894 my ($self, $dbh, $myconfig, $table, $module) = @_;
2898 $table = $table eq "customer" ? "customer" : "vendor";
2899 my %column_map = ("a.${table}_id" => "${table}_id",
2900 "a.department_id" => "department_id",
2901 "d.description" => "department",
2902 "ct.name" => $table,
2903 "cu.name" => "currency",
2906 if ($self->{type} =~ /delivery_order/) {
2907 $arap = 'delivery_orders';
2908 delete $column_map{"cu.currency"};
2910 } elsif ($self->{type} =~ /_order/) {
2912 $where = "quotation = '0'";
2914 } elsif ($self->{type} =~ /_quotation/) {
2916 $where = "quotation = '1'";
2918 } elsif ($table eq 'customer') {
2926 $where = "($where) AND" if ($where);
2927 my $query = qq|SELECT MAX(id) FROM $arap
2928 WHERE $where ${table}_id > 0|;
2929 my ($trans_id) = selectrow_query($self, $dbh, $query);
2932 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2933 $query = qq|SELECT $column_spec
2935 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2936 LEFT JOIN department d ON (a.department_id = d.id)
2937 LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
2939 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2941 map { $self->{$_} = $ref->{$_} } values %column_map;
2943 $main::lxdebug->leave_sub();
2946 sub get_variable_content_types {
2947 my %html_variables = (
2948 longdescription => 'html',
2949 partnotes => 'html',
2951 orignotes => 'html',
2956 header_text => 'html',
2957 footer_text => 'html',
2959 return \%html_variables;
2963 $main::lxdebug->enter_sub();
2966 my $myconfig = shift || \%::myconfig;
2967 my ($thisdate, $days) = @_;
2969 my $dbh = $self->get_standard_dbh($myconfig);
2974 my $dateformat = $myconfig->{dateformat};
2975 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2976 $thisdate = $dbh->quote($thisdate);
2977 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2979 $query = qq|SELECT current_date AS thisdate|;
2982 ($thisdate) = selectrow_query($self, $dbh, $query);
2984 $main::lxdebug->leave_sub();
2990 $main::lxdebug->enter_sub();
2992 my ($self, $flds, $new, $count, $numrows) = @_;
2996 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3001 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3003 my $j = $item->{ndx} - 1;
3004 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3008 for $i ($count + 1 .. $numrows) {
3009 map { delete $self->{"${_}_$i"} } @{$flds};
3012 $main::lxdebug->leave_sub();
3016 $main::lxdebug->enter_sub();
3018 my ($self, $myconfig) = @_;
3022 SL::DB->client->with_transaction(sub {
3023 my $dbh = SL::DB->client->dbh;
3025 my $query = qq|DELETE FROM status
3026 WHERE (formname = ?) AND (trans_id = ?)|;
3027 my $sth = prepare_query($self, $dbh, $query);
3029 if ($self->{formname} =~ /(check|receipt)/) {
3030 for $i (1 .. $self->{rowcount}) {
3031 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3034 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3038 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3039 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3041 my %queued = split / /, $self->{queued};
3044 if ($self->{formname} =~ /(check|receipt)/) {
3046 # this is a check or receipt, add one entry for each lineitem
3047 my ($accno) = split /--/, $self->{account};
3048 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3049 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3050 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3051 $sth = prepare_query($self, $dbh, $query);
3053 for $i (1 .. $self->{rowcount}) {
3054 if ($self->{"checked_$i"}) {
3055 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3061 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3062 VALUES (?, ?, ?, ?, ?)|;
3063 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3064 $queued{$self->{formname}}, $self->{formname});
3067 }) or do { die SL::DB->client->error };
3069 $main::lxdebug->leave_sub();
3073 $main::lxdebug->enter_sub();
3075 my ($self, $dbh) = @_;
3077 my ($query, $printed, $emailed);
3079 my $formnames = $self->{printed};
3080 my $emailforms = $self->{emailed};
3082 $query = qq|DELETE FROM status
3083 WHERE (formname = ?) AND (trans_id = ?)|;
3084 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3086 # this only applies to the forms
3087 # checks and receipts are posted when printed or queued
3089 if ($self->{queued}) {
3090 my %queued = split / /, $self->{queued};
3092 foreach my $formname (keys %queued) {
3093 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3094 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3096 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3097 VALUES (?, ?, ?, ?, ?)|;
3098 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3100 $formnames =~ s/\Q$self->{formname}\E//;
3101 $emailforms =~ s/\Q$self->{formname}\E//;
3106 # save printed, emailed info
3107 $formnames =~ s/^ +//g;
3108 $emailforms =~ s/^ +//g;
3111 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3112 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3114 foreach my $formname (keys %status) {
3115 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3116 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3118 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3119 VALUES (?, ?, ?, ?)|;
3120 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3123 $main::lxdebug->leave_sub();
3127 # $main::locale->text('SAVED')
3128 # $main::locale->text('SCREENED')
3129 # $main::locale->text('DELETED')
3130 # $main::locale->text('ADDED')
3131 # $main::locale->text('PAYMENT POSTED')
3132 # $main::locale->text('POSTED')
3133 # $main::locale->text('POSTED AS NEW')
3134 # $main::locale->text('ELSE')
3135 # $main::locale->text('SAVED FOR DUNNING')
3136 # $main::locale->text('DUNNING STARTED')
3137 # $main::locale->text('PRINTED')
3138 # $main::locale->text('MAILED')
3139 # $main::locale->text('SCREENED')
3140 # $main::locale->text('CANCELED')
3141 # $main::locale->text('IMPORT')
3142 # $main::locale->text('UNIMPORT')
3143 # $main::locale->text('invoice')
3144 # $main::locale->text('proforma')
3145 # $main::locale->text('sales_order')
3146 # $main::locale->text('pick_list')
3147 # $main::locale->text('purchase_order')
3148 # $main::locale->text('bin_list')
3149 # $main::locale->text('sales_quotation')
3150 # $main::locale->text('request_quotation')
3153 $main::lxdebug->enter_sub();
3156 my $dbh = shift || SL::DB->client->dbh;
3157 SL::DB->client->with_transaction(sub {
3159 if(!exists $self->{employee_id}) {
3160 &get_employee($self, $dbh);
3164 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3165 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3166 my @values = (conv_i($self->{id}), $self->{login},
3167 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3168 do_query($self, $dbh, $query, @values);
3170 }) or do { die SL::DB->client->error };
3172 $main::lxdebug->leave_sub();
3176 $main::lxdebug->enter_sub();
3178 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3179 my ($orderBy, $desc) = split(/\-\-/, $order);
3180 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3183 if ($trans_id ne "") {
3185 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 | .
3186 qq|FROM history_erp h | .
3187 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3188 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3191 my $sth = $dbh->prepare($query) || $self->dberror($query);
3193 $sth->execute() || $self->dberror("$query");
3195 while(my $hash_ref = $sth->fetchrow_hashref()) {
3196 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3197 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3198 my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
3199 $hash_ref->{snumbers} = $number;
3200 $hash_ref->{haslink} = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
3201 $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
3202 $tempArray[$i++] = $hash_ref;
3204 $main::lxdebug->leave_sub() and return \@tempArray
3205 if ($i > 0 && $tempArray[0] ne "");
3207 $main::lxdebug->leave_sub();
3211 sub get_partsgroup {
3212 $main::lxdebug->enter_sub();
3214 my ($self, $myconfig, $p) = @_;
3215 my $target = $p->{target} || 'all_partsgroup';
3217 my $dbh = $self->get_standard_dbh($myconfig);
3219 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3221 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3224 if ($p->{searchitems} eq 'part') {
3225 $query .= qq|WHERE p.part_type = 'part'|;
3227 if ($p->{searchitems} eq 'service') {
3228 $query .= qq|WHERE p.part_type = 'service'|;
3230 if ($p->{searchitems} eq 'assembly') {
3231 $query .= qq|WHERE p.part_type = 'assembly'|;
3234 $query .= qq|ORDER BY partsgroup|;
3237 $query = qq|SELECT id, partsgroup FROM partsgroup
3238 ORDER BY partsgroup|;
3241 if ($p->{language_code}) {
3242 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3243 t.description AS translation
3245 JOIN parts p ON (p.partsgroup_id = pg.id)
3246 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3247 ORDER BY translation|;
3248 @values = ($p->{language_code});
3251 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3253 $main::lxdebug->leave_sub();
3256 sub get_pricegroup {
3257 $main::lxdebug->enter_sub();
3259 my ($self, $myconfig, $p) = @_;
3261 my $dbh = $self->get_standard_dbh($myconfig);
3263 my $query = qq|SELECT p.id, p.pricegroup
3266 $query .= qq| ORDER BY pricegroup|;
3269 $query = qq|SELECT id, pricegroup FROM pricegroup
3270 ORDER BY pricegroup|;
3273 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3275 $main::lxdebug->leave_sub();
3279 # usage $form->all_years($myconfig, [$dbh])
3280 # return list of all years where bookings found
3283 $main::lxdebug->enter_sub();
3285 my ($self, $myconfig, $dbh) = @_;
3287 $dbh ||= $self->get_standard_dbh($myconfig);
3290 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3291 (SELECT MAX(transdate) FROM acc_trans)|;
3292 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3294 if ($myconfig->{dateformat} =~ /^yy/) {
3295 ($startdate) = split /\W/, $startdate;
3296 ($enddate) = split /\W/, $enddate;
3298 (@_) = split /\W/, $startdate;
3300 (@_) = split /\W/, $enddate;
3305 $startdate = substr($startdate,0,4);
3306 $enddate = substr($enddate,0,4);
3308 while ($enddate >= $startdate) {
3309 push @all_years, $enddate--;
3314 $main::lxdebug->leave_sub();
3318 $main::lxdebug->enter_sub();
3322 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3324 $main::lxdebug->leave_sub();
3328 $main::lxdebug->enter_sub();
3333 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3335 $main::lxdebug->leave_sub();
3338 sub prepare_for_printing {
3341 my $defaults = SL::DB::Default->get;
3343 $self->{templates} ||= $defaults->templates;
3344 $self->{formname} ||= $self->{type};
3345 $self->{media} ||= 'email';
3347 die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3349 # Several fields that used to reside in %::myconfig (stored in
3350 # auth.user_config) are now stored in defaults. Copy them over for
3352 $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
3354 $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
3356 if (!$self->{employee_id}) {
3357 $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
3358 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
3361 # Load shipping address from database. If shipto_id is set then it's
3362 # one from the customer's/vendor's master data. Otherwise look an a
3363 # customized address linking back to the current record.
3364 my $shipto_module = $self->{type} =~ /_delivery_order$/ ? 'DO'
3365 : $self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/ ? 'OE'
3367 my $shipto = $self->{shipto_id} ? SL::DB::Shipto->new(shipto_id => $self->{shipto_id})->load
3368 : SL::DB::Manager::Shipto->get_first(where => [ module => $shipto_module, trans_id => $self->{id} ]);
3370 $self->{$_} = $shipto->$_ for grep { m{^shipto} } map { $_->name } @{ $shipto->meta->columns };
3371 $self->{"shiptocvar_" . $_->config->name} = $_->value_as_text for @{ $shipto->cvars_by_config };
3374 my $language = $self->{language} ? '_' . $self->{language} : '';
3376 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3377 if ($self->{language_id}) {
3378 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3381 $output_dateformat ||= $::myconfig{dateformat};
3382 $output_numberformat ||= $::myconfig{numberformat};
3383 $output_longdates //= 1;
3385 $self->{myconfig_output_dateformat} = $output_dateformat // $::myconfig{dateformat};
3386 $self->{myconfig_output_longdates} = $output_longdates // 1;
3387 $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
3389 # Retrieve accounts for tax calculation.
3390 IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3392 if ($self->{type} =~ /_delivery_order$/) {
3393 DO->order_details(\%::myconfig, $self);
3394 } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3395 OE->order_details(\%::myconfig, $self);
3397 IS->invoice_details(\%::myconfig, $self, $::locale);
3400 # Chose extension & set source file name
3401 my $extension = 'html';
3402 if ($self->{format} eq 'postscript') {
3403 $self->{postscript} = 1;
3405 } elsif ($self->{"format"} =~ /pdf/) {
3407 $extension = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3408 } elsif ($self->{"format"} =~ /opendocument/) {
3409 $self->{opendocument} = 1;
3411 } elsif ($self->{"format"} =~ /excel/) {
3416 my $printer_code = $self->{printer_code} ? '_' . $self->{printer_code} : '';
3417 my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
3418 $self->{IN} = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3421 $self->format_dates($output_dateformat, $output_longdates,
3422 qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate datepaid
3423 transdate_oe deliverydate_oe employee_startdate employee_enddate),
3424 grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3426 $self->reformat_numbers($output_numberformat, 2,
3427 qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3428 grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3430 $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3432 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3434 if (scalar @{ $cvar_date_fields }) {
3435 $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3438 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3439 $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3442 $self->{template_meta} = {
3443 formname => $self->{formname},
3444 language => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
3445 format => $self->{format},
3446 media => $self->{media},
3447 extension => $extension,
3448 printer => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
3449 today => DateTime->today,
3455 sub calculate_arap {
3456 my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
3458 # this function is used to calculate netamount, total_tax and amount for AP and
3459 # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
3461 # Thus it needs a fully prepared $form to work on.
3462 # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
3464 # The calculated total values are all rounded (default is to 2 places) and
3465 # returned as parameters rather than directly modifying form. The aim is to
3466 # make the calculation of AP and AR behave identically. There is a test-case
3467 # for this function in t/form/arap.t
3469 # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
3470 # modified and formatted and receive the correct sign for writing straight to
3471 # acc_trans, depending on whether they are ar or ap.
3474 die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
3475 die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
3476 die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
3477 $roundplaces = 2 unless $roundplaces;
3479 my $sign = 1; # adjust final results for writing amount to acc_trans
3480 $sign = -1 if $buysell eq 'buy';
3482 my ($netamount,$total_tax,$amount);
3486 # parse and round amounts, setting correct sign for writing to acc_trans
3487 for my $i (1 .. $self->{rowcount}) {
3488 $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
3490 $amount += $self->{"amount_$i"} * $sign;
3493 for my $i (1 .. $self->{rowcount}) {
3494 next unless $self->{"amount_$i"};
3495 ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
3496 my $tax_id = $self->{"tax_id_$i"};
3498 my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
3500 if ( $selected_tax ) {
3502 if ( $buysell eq 'sell' ) {
3503 $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3505 $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3508 $self->{"taxkey_$i"} = $selected_tax->taxkey;
3509 $self->{"taxrate_$i"} = $selected_tax->rate;
3512 ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
3514 $netamount += $self->{"amount_$i"};
3515 $total_tax += $self->{"tax_$i"};
3518 $amount = $netamount + $total_tax;
3520 # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
3521 # but reverse sign of totals for writing amounts to ar
3522 if ( $buysell eq 'buy' ) {
3528 return($netamount,$total_tax,$amount);
3532 my ($self, $dateformat, $longformat, @indices) = @_;
3534 $dateformat ||= $::myconfig{dateformat};
3536 foreach my $idx (@indices) {
3537 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3538 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3539 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3543 next unless defined $self->{$idx};
3545 if (!ref($self->{$idx})) {
3546 $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3548 } elsif (ref($self->{$idx}) eq "ARRAY") {
3549 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3550 $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3556 sub reformat_numbers {
3557 my ($self, $numberformat, $places, @indices) = @_;
3559 return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3561 foreach my $idx (@indices) {
3562 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3563 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3564 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3568 next unless defined $self->{$idx};
3570 if (!ref($self->{$idx})) {
3571 $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3573 } elsif (ref($self->{$idx}) eq "ARRAY") {
3574 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3575 $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3580 my $saved_numberformat = $::myconfig{numberformat};
3581 $::myconfig{numberformat} = $numberformat;
3583 foreach my $idx (@indices) {
3584 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3585 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3586 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3590 next unless defined $self->{$idx};
3592 if (!ref($self->{$idx})) {
3593 $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3595 } elsif (ref($self->{$idx}) eq "ARRAY") {
3596 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3597 $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3602 $::myconfig{numberformat} = $saved_numberformat;
3605 sub create_email_signature {
3607 my $client_signature = $::instance_conf->get_signature;
3608 my $user_signature = $::myconfig{signature};
3611 if ( $client_signature or $user_signature ) {
3612 $signature = "\n\n-- \n";
3613 $signature .= $user_signature . "\n" if $user_signature;
3614 $signature .= $client_signature . "\n" if $client_signature;
3622 $::lxdebug->enter_sub;
3624 my %style_to_script_map = (
3629 my $menu_script = $style_to_script_map{$::myconfig{menustyle}} || '';
3632 require "bin/mozilla/menu$menu_script.pl";
3634 require SL::Controller::FrameHeader;
3637 my $layout = SL::Controller::FrameHeader->new->action_header . ::render();
3639 $::lxdebug->leave_sub;
3644 # this function calculates the net amount and tax for the lines in ar, ap and
3645 # gl and is used for update as well as post. When used with update the return
3646 # value of amount isn't needed
3648 # calculate_tax should always work with positive values, or rather as the user inputs them
3649 # calculate_tax uses db/perl numberformat, i.e. parsed numbers
3650 # convert to negative numbers (when necessary) only when writing to acc_trans
3651 # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
3652 # for post_transaction amount already contains exchangerate and correct sign and is rounded
3653 # calculate_tax doesn't (need to) know anything about exchangerate
3655 my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
3663 # calculate tax (unrounded), subtract from amount, round amount and round tax
3664 $tax = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
3665 $amount = $self->round_amount($amount - $tax, $roundplaces);
3666 $tax = $self->round_amount($tax, $roundplaces);
3668 $tax = $amount * $taxrate;
3669 $tax = $self->round_amount($tax, $roundplaces);
3672 $tax = 0 unless $tax;
3674 return ($amount,$tax);
3683 SL::Form.pm - main data object.
3687 This is the main data object of kivitendo.
3688 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3689 Points of interest for a beginner are:
3691 - $form->error - renders a generic error in html. accepts an error message
3692 - $form->get_standard_dbh - returns a database connection for the
3694 =head1 SPECIAL FUNCTIONS
3696 =head2 C<redirect_header> $url
3698 Generates a HTTP redirection header for the new C<$url>. Constructs an
3699 absolute URL including scheme, host name and port. If C<$url> is a
3700 relative URL then it is considered relative to kivitendo base URL.
3702 This function C<die>s if headers have already been created with
3703 C<$::form-E<gt>header>.
3707 print $::form->redirect_header('oe.pl?action=edit&id=1234');
3708 print $::form->redirect_header('http://www.lx-office.org/');
3712 Generates a general purpose http/html header and includes most of the scripts
3713 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3715 Only one header will be generated. If the method was already called in this
3716 request it will not output anything and return undef. Also if no
3717 HTTP_USER_AGENT is found, no header is generated.
3719 Although header does not accept parameters itself, it will honor special
3720 hashkeys of its Form instance:
3728 If one of these is set, a http-equiv refresh is generated. Missing parameters
3729 default to 3 seconds and the refering url.
3733 Either a scalar or an array ref. Will be inlined into the header. Add
3734 stylesheets with the L<use_stylesheet> function.
3738 If true, a css snippet will be generated that sets the page in landscape mode.
3742 Used to override the default favicon.
3746 A html page title will be generated from this
3748 =item mtime_ischanged
3750 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
3752 Can be used / called with any table, that has itime and mtime attributes.
3753 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
3754 Can be called wit C<option> mail to generate a different error message.
3756 Returns undef if no save operation has been done yet ($self->{id} not present).
3757 Returns undef if no concurrent write process is detected otherwise a error message.