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 #======================================================================
53 use POSIX qw(strftime);
65 use SL::DB::PaymentTerm;
68 use SL::Helper::Flash qw();
71 use SL::Layout::Dispatcher;
73 use SL::Locale::String;
76 use SL::MoreCommon qw(uri_encode uri_decode);
78 use SL::PrefixedNumber;
87 use List::Util qw(first max min sum);
88 use List::MoreUtils qw(all any apply);
90 use SL::Helper::File qw(:all);
91 use SL::Helper::CreatePDF qw(merge_pdfs);
96 SL::Version->get_version;
100 $main::lxdebug->enter_sub();
107 if ($LXDebug::watch_form) {
108 require SL::Watchdog;
109 tie %{ $self }, 'SL::Watchdog';
114 $main::lxdebug->leave_sub();
119 sub _flatten_variables_rec {
120 $main::lxdebug->enter_sub(2);
129 if ('' eq ref $curr->{$key}) {
130 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
132 } elsif ('HASH' eq ref $curr->{$key}) {
133 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
134 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
138 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
139 my $first_array_entry = 1;
141 my $element = $curr->{$key}[$idx];
143 if ('HASH' eq ref $element) {
144 foreach my $hash_key (sort keys %{ $element }) {
145 push @result, $self->_flatten_variables_rec($element, $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
146 $first_array_entry = 0;
149 push @result, { 'key' => $prefix . $key . '[]', 'value' => $element };
154 $main::lxdebug->leave_sub(2);
159 sub flatten_variables {
160 $main::lxdebug->enter_sub(2);
168 push @variables, $self->_flatten_variables_rec($self, '', $_);
171 $main::lxdebug->leave_sub(2);
176 sub flatten_standard_variables {
177 $main::lxdebug->enter_sub(2);
180 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar), @_);
184 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
185 push @variables, $self->_flatten_variables_rec($self, '', $_);
188 $main::lxdebug->leave_sub(2);
194 my ($self, $str) = @_;
196 return uri_encode($str);
200 my ($self, $str) = @_;
202 return uri_decode($str);
206 $main::lxdebug->enter_sub();
207 my ($self, $str) = @_;
209 if ($str && !ref($str)) {
210 $str =~ s/\"/"/g;
213 $main::lxdebug->leave_sub();
219 $main::lxdebug->enter_sub();
220 my ($self, $str) = @_;
222 if ($str && !ref($str)) {
223 $str =~ s/"/\"/g;
226 $main::lxdebug->leave_sub();
232 $main::lxdebug->enter_sub();
236 map({ print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
238 for (sort keys %$self) {
239 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
240 print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
243 $main::lxdebug->leave_sub();
247 my ($self, $code) = @_;
248 local $self->{__ERROR_HANDLER} = sub { SL::X::FormError->throw(error => $_[0]) };
253 $main::lxdebug->enter_sub();
255 $main::lxdebug->show_backtrace();
257 my ($self, $msg) = @_;
259 if ($self->{__ERROR_HANDLER}) {
260 $self->{__ERROR_HANDLER}->($msg);
262 } elsif ($ENV{HTTP_USER_AGENT}) {
264 $self->show_generic_error($msg);
267 confess "Error: $msg\n";
270 $main::lxdebug->leave_sub();
274 $main::lxdebug->enter_sub();
276 my ($self, $msg) = @_;
278 if ($ENV{HTTP_USER_AGENT}) {
280 print $self->parse_html_template('generic/form_info', { message => $msg });
282 } elsif ($self->{info_function}) {
283 &{ $self->{info_function} }($msg);
288 $main::lxdebug->leave_sub();
291 # calculates the number of rows in a textarea based on the content and column number
292 # can be capped with maxrows
294 $main::lxdebug->enter_sub();
295 my ($self, $str, $cols, $maxrows, $minrows) = @_;
299 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
302 $main::lxdebug->leave_sub();
304 return max(min($rows, $maxrows), $minrows);
308 my ($self, $msg) = @_;
310 SL::X::DBError->throw(
312 db_error => $DBI::errstr,
317 $main::lxdebug->enter_sub();
319 my ($self, $name, $msg) = @_;
322 foreach my $part (split m/\./, $name) {
323 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
326 $curr = $curr->{$part};
329 $main::lxdebug->leave_sub();
332 sub _get_request_uri {
335 return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
336 return URI->new if !$ENV{REQUEST_URI}; # for testing
338 my $scheme = $::request->is_https ? 'https' : 'http';
339 my $port = $ENV{SERVER_PORT};
340 $port = undef if (($scheme eq 'http' ) && ($port == 80))
341 || (($scheme eq 'https') && ($port == 443));
343 my $uri = URI->new("${scheme}://");
344 $uri->scheme($scheme);
346 $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
347 $uri->path_query($ENV{REQUEST_URI});
353 sub _add_to_request_uri {
356 my $relative_new_path = shift;
357 my $request_uri = shift || $self->_get_request_uri;
358 my $relative_new_uri = URI->new($relative_new_path);
359 my @request_segments = $request_uri->path_segments;
361 my $new_uri = $request_uri->clone;
362 $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
367 sub create_http_response {
368 $main::lxdebug->enter_sub();
373 my $cgi = $::request->{cgi};
376 if (defined $main::auth) {
377 my $uri = $self->_get_request_uri;
378 my @segments = $uri->path_segments;
380 $uri->path_segments(@segments);
382 my $session_cookie_value = $main::auth->get_session_id();
384 if ($session_cookie_value) {
385 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
386 '-value' => $session_cookie_value,
387 '-path' => $uri->path,
388 '-secure' => $::request->is_https);
392 my %cgi_params = ('-type' => $params{content_type});
393 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
394 $cgi_params{'-cookie'} = $session_cookie if ($session_cookie);
396 map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length status);
398 my $output = $cgi->header(%cgi_params);
400 $main::lxdebug->leave_sub();
406 $::lxdebug->enter_sub;
408 my ($self, %params) = @_;
411 $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
413 if ($params{no_layout}) {
414 $::request->{layout} = SL::Layout::Dispatcher->new(style => 'none');
417 my $layout = $::request->{layout};
419 # standard css for all
420 # this should gradually move to the layouts that need it
421 $layout->use_stylesheet("$_.css") for qw(
422 common main menu list_accounts jquery.autocomplete
423 jquery.multiselect2side
424 ui-lightness/jquery-ui
426 tooltipster themes/tooltipster-light
429 $layout->use_javascript("$_.js") for (qw(
430 jquery jquery-ui jquery.cookie jquery.checkall jquery.download
431 jquery/jquery.form jquery/fixes client_js
432 jquery/jquery.tooltipster.min
433 common part_selection
434 ), "jquery/ui/i18n/jquery.ui.datepicker-$::myconfig{countrycode}");
436 $self->{favicon} ||= "favicon.ico";
437 $self->{titlebar} = join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->read_version if $self->{title} || !$self->{titlebar};
440 if ($self->{refresh_url} || $self->{refresh_time}) {
441 my $refresh_time = $self->{refresh_time} || 3;
442 my $refresh_url = $self->{refresh_url} || $ENV{REFERER};
443 push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
446 my $auto_reload_resources_param = $layout->auto_reload_resources_param;
448 push @header, map { qq|<link rel="stylesheet" href="${_}${auto_reload_resources_param}" type="text/css" title="Stylesheet">| } $layout->stylesheets;
449 push @header, "<style type='text/css'>\@page { size:landscape; }</style> " if $self->{landscape};
450 push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
451 push @header, map { qq|<script type="text/javascript" src="${_}${auto_reload_resources_param}"></script>| } $layout->javascripts;
452 push @header, $self->{javascript} if $self->{javascript};
453 push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
456 strict => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
457 transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
458 frameset => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
459 html5 => qq|<!DOCTYPE html>|,
463 print $self->create_http_response(content_type => 'text/html', charset => 'UTF-8');
464 print $doctypes{$params{doctype} || 'transitional'}, $/;
468 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
469 <title>$self->{titlebar}</title>
471 print " $_\n" for @header;
473 <meta name="robots" content="noindex,nofollow">
478 print $::request->{layout}->pre_content;
479 print $::request->{layout}->start_content;
481 $layout->header_done;
483 $::lxdebug->leave_sub;
487 return unless $::request->{layout}->need_footer;
489 print $::request->{layout}->end_content;
490 print $::request->{layout}->post_content;
492 if (my @inline_scripts = $::request->{layout}->javascripts_inline) {
493 print "<script type='text/javascript'>" . join("; ", @inline_scripts) . "</script>\n";
502 sub ajax_response_header {
503 $main::lxdebug->enter_sub();
507 my $output = $::request->{cgi}->header('-charset' => 'UTF-8');
509 $main::lxdebug->leave_sub();
514 sub redirect_header {
518 my $base_uri = $self->_get_request_uri;
519 my $new_uri = URI->new_abs($new_url, $base_uri);
521 die "Headers already sent" if $self->{header};
524 return $::request->{cgi}->redirect($new_uri);
527 sub set_standard_title {
528 $::lxdebug->enter_sub;
531 $self->{titlebar} = "kivitendo " . $::locale->text('Version') . " " . $self->read_version;
532 $self->{titlebar} .= "- $::myconfig{name}" if $::myconfig{name};
533 $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
535 $::lxdebug->leave_sub;
538 sub _prepare_html_template {
539 $main::lxdebug->enter_sub();
541 my ($self, $file, $additional_params) = @_;
544 if (!%::myconfig || !$::myconfig{"countrycode"}) {
545 $language = $::lx_office_conf{system}->{language};
547 $language = $main::myconfig{"countrycode"};
549 $language = "de" unless ($language);
551 if (-f "templates/webpages/${file}.html") {
552 $file = "templates/webpages/${file}.html";
554 } elsif (ref $file eq 'SCALAR') {
555 # file is a scalarref, use inline mode
557 my $info = "Web page template '${file}' not found.\n";
559 print qq|<pre>$info</pre>|;
560 $::dispatcher->end_request;
563 $additional_params->{AUTH} = $::auth;
564 $additional_params->{INSTANCE_CONF} = $::instance_conf;
565 $additional_params->{LOCALE} = $::locale;
566 $additional_params->{LXCONFIG} = \%::lx_office_conf;
567 $additional_params->{LXDEBUG} = $::lxdebug;
568 $additional_params->{MYCONFIG} = \%::myconfig;
570 $main::lxdebug->leave_sub();
575 sub parse_html_template {
576 $main::lxdebug->enter_sub();
578 my ($self, $file, $additional_params) = @_;
580 $additional_params ||= { };
582 my $real_file = $self->_prepare_html_template($file, $additional_params);
583 my $template = $self->template;
585 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
588 $template->process($real_file, $additional_params, \$output) || die $template->error;
590 $main::lxdebug->leave_sub();
595 sub template { $::request->presenter->get_template }
597 sub show_generic_error {
598 $main::lxdebug->enter_sub();
600 my ($self, $error, %params) = @_;
602 if ($self->{__ERROR_HANDLER}) {
603 $self->{__ERROR_HANDLER}->($error);
604 $main::lxdebug->leave_sub();
608 if ($::request->is_ajax) {
611 ->render(SL::Controller::Base->new);
612 $::dispatcher->end_request;
616 'title_error' => $params{title},
617 'label_error' => $error,
620 $self->{title} = $params{title} if $params{title};
622 for my $bar ($::request->layout->get('actionbar')) {
626 call => [ 'kivi.history_back' ],
627 accesskey => 'enter',
633 print $self->parse_html_template("generic/error", $add_params);
635 print STDERR "Error: $error\n";
637 $main::lxdebug->leave_sub();
639 $::dispatcher->end_request;
642 sub show_generic_information {
643 $main::lxdebug->enter_sub();
645 my ($self, $text, $title) = @_;
648 'title_information' => $title,
649 'label_information' => $text,
652 $self->{title} = $title if ($title);
655 print $self->parse_html_template("generic/information", $add_params);
657 $main::lxdebug->leave_sub();
659 $::dispatcher->end_request;
662 sub _store_redirect_info_in_session {
665 return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
667 my ($controller, $params) = ($1, $2);
668 my $form = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
669 $self->{callback} = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
673 $main::lxdebug->enter_sub();
675 my ($self, $msg) = @_;
677 if (!$self->{callback}) {
681 SL::Helper::Flash::flash_later('info', $msg) if $msg;
682 $self->_store_redirect_info_in_session;
683 print $::form->redirect_header($self->{callback});
686 $::dispatcher->end_request;
688 $main::lxdebug->leave_sub();
691 # sort of columns removed - empty sub
693 $main::lxdebug->enter_sub();
695 my ($self, @columns) = @_;
697 $main::lxdebug->leave_sub();
703 $main::lxdebug->enter_sub(2);
705 my ($self, $myconfig, $amount, $places, $dash) = @_;
708 my $neg = $amount < 0;
709 my $force_places = defined $places && $places >= 0;
711 $amount = $self->round_amount($amount, abs $places) if $force_places;
712 $neg = 0 if $amount == 0; # don't show negative zero
713 $amount = sprintf "%.*f", ($force_places ? $places : 10), abs $amount; # 6 is default for %fa
715 # before the sprintf amount was a number, afterwards it's a string. because of the dynamic nature of perl
716 # this is easy to confuse, so keep in mind: before this comment no s///, m//, concat or other strong ops on
717 # $amount. after this comment no +,-,*,/,abs. it will only introduce subtle bugs.
719 $amount =~ s/0*$// unless defined $places && $places == 0; # cull trailing 0s
721 my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
722 my @p = split(/\./, $amount); # split amount at decimal point
724 $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
726 if ($places || $p[1]) {
729 . (0 x max(abs($places || 0) - length ($p[1]||''), 0)); # pad the fraction
733 ($dash =~ /-/) ? ($neg ? "($amount)" : "$amount" ) :
734 ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
735 ($neg ? "-$amount" : "$amount" ) ;
738 $main::lxdebug->leave_sub(2);
742 sub format_amount_units {
743 $main::lxdebug->enter_sub();
748 my $myconfig = \%main::myconfig;
749 my $amount = $params{amount} * 1;
750 my $places = $params{places};
751 my $part_unit_name = $params{part_unit};
752 my $amount_unit_name = $params{amount_unit};
753 my $conv_units = $params{conv_units};
754 my $max_places = $params{max_places};
756 if (!$part_unit_name) {
757 $main::lxdebug->leave_sub();
761 my $all_units = AM->retrieve_all_units;
763 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
764 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
767 if (!scalar @{ $conv_units }) {
768 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
769 $main::lxdebug->leave_sub();
773 my $part_unit = $all_units->{$part_unit_name};
774 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
776 $amount *= $conv_unit->{factor};
781 foreach my $unit (@$conv_units) {
782 my $last = $unit->{name} eq $part_unit->{name};
784 $num = int($amount / $unit->{factor});
785 $amount -= $num * $unit->{factor};
788 if ($last ? $amount : $num) {
789 push @values, { "unit" => $unit->{name},
790 "amount" => $last ? $amount / $unit->{factor} : $num,
791 "places" => $last ? $places : 0 };
798 push @values, { "unit" => $part_unit_name,
803 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
805 $main::lxdebug->leave_sub();
811 $main::lxdebug->enter_sub(2);
816 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
817 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
818 $input =~ s/\#\#/\#/g;
820 $main::lxdebug->leave_sub(2);
828 $main::lxdebug->enter_sub(2);
830 my ($self, $myconfig, $amount) = @_;
832 if (!defined($amount) || ($amount eq '')) {
833 $main::lxdebug->leave_sub(2);
837 if ( ($myconfig->{numberformat} eq '1.000,00')
838 || ($myconfig->{numberformat} eq '1000,00')) {
843 if ($myconfig->{numberformat} eq "1'000.00") {
849 $main::lxdebug->leave_sub(2);
851 # Make sure no code wich is not a math expression ends up in eval().
852 return 0 unless $amount =~ /^ [\s \d \( \) \- \+ \* \/ \. ]* $/x;
854 # Prevent numbers from being parsed as octals;
855 $amount =~ s{ (?<! [\d.] ) 0+ (?= [1-9] ) }{}gx;
857 return scalar(eval($amount)) * 1 ;
861 my ($self, $amount, $places, $adjust) = @_;
863 return 0 if !defined $amount;
868 my $precision = $::instance_conf->get_precision || 0.01;
869 return $self->round_amount( $self->round_amount($amount / $precision, 0) * $precision, $places);
872 # We use Perl's knowledge of string representation for
873 # rounding. First, convert the floating point number to a string
874 # with a high number of places. Then split the string on the decimal
875 # sign and use integer calculation for rounding the decimal places
876 # part. If an overflow occurs then apply that overflow to the part
877 # before the decimal sign as well using integer arithmetic again.
879 my $int_amount = int(abs $amount);
880 my $str_places = max(min(10, 16 - length("$int_amount") - $places), $places);
881 my $amount_str = sprintf '%.*f', $places + $str_places, abs($amount);
883 return $amount unless $amount_str =~ m{^(\d+)\.(\d+)$};
885 my ($pre, $post) = ($1, $2);
886 my $decimals = '1' . substr($post, 0, $places);
888 my $propagation_limit = $Config{i32size} == 4 ? 7 : 18;
889 my $add_for_rounding = substr($post, $places, 1) >= 5 ? 1 : 0;
891 if ($places > $propagation_limit) {
892 $decimals = Math::BigInt->new($decimals)->badd($add_for_rounding);
893 $pre = Math::BigInt->new($decimals)->badd(1) if substr($decimals, 0, 1) eq '2';
896 $decimals += $add_for_rounding;
897 $pre += 1 if substr($decimals, 0, 1) eq '2';
900 $amount = ("${pre}." . substr($decimals, 1)) * ($amount <=> 0);
906 $main::lxdebug->enter_sub();
908 my ($self, $myconfig) = @_;
909 my ($out, $out_mode);
913 my $defaults = SL::DB::Default->get;
915 my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
916 $self->{cwd} = getcwd();
917 my $temp_dir = File::Temp->newdir(
918 "kivitendo-print-XXXXXX",
919 DIR => $self->{cwd} . "/" . $::lx_office_conf{paths}->{userspath},
920 CLEANUP => !$keep_temp_files,
923 my $userspath = File::Spec->abs2rel($temp_dir->dirname);
924 $self->{tmpdir} = $temp_dir->dirname;
929 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
930 $template_type = 'OpenDocument';
931 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
933 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
934 $template_type = 'LaTeX';
935 $ext_for_format = 'pdf';
937 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
938 $template_type = 'HTML';
939 $ext_for_format = 'html';
941 } elsif ( $self->{"format"} =~ /excel/i ) {
942 $template_type = 'Excel';
943 $ext_for_format = 'xls';
945 } elsif ( defined $self->{'format'}) {
946 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
948 } elsif ( $self->{'format'} eq '' ) {
949 $self->error("No Outputformat given: $self->{'format'}");
951 } else { #Catch the rest
952 $self->error("Outputformat not defined: $self->{'format'}");
955 my $template = SL::Template::create(type => $template_type,
956 file_name => $self->{IN},
958 myconfig => $myconfig,
959 userspath => $userspath,
960 %{ $self->{TEMPLATE_DRIVER_OPTIONS} || {} });
962 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
963 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" } if exists $self->{ $self->{"formname"} . "notes" };
965 if (!$self->{employee_id}) {
966 $self->{"employee_${_}"} = $myconfig->{$_} for qw(email tel fax name signature);
967 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
970 $self->{"myconfig_${_}"} = $myconfig->{$_} for grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
971 $self->{$_} = $defaults->$_ for qw(co_ustid);
972 $self->{"myconfig_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
973 $self->{AUTH} = $::auth;
974 $self->{INSTANCE_CONF} = $::instance_conf;
975 $self->{LOCALE} = $::locale;
976 $self->{LXCONFIG} = $::lx_office_conf;
977 $self->{LXDEBUG} = $::lxdebug;
978 $self->{MYCONFIG} = \%::myconfig;
980 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
982 # OUT is used for the media, screen, printer, email
983 # for postscript we store a copy in a temporary file
985 my ($temp_fh, $suffix);
986 $suffix = $self->{IN};
988 ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
989 strftime('kivitendo-print-%Y%m%d%H%M%S-XXXXXX', localtime()),
990 SUFFIX => '.' . ($suffix || 'tex'),
992 UNLINK => $keep_temp_files ? 0 : 1,
995 chmod 0644, $self->{tmpfile} if $keep_temp_files;
996 (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
999 $out_mode = $self->{OUT_MODE} || '>';
1000 $self->{OUT} = "$self->{tmpfile}";
1001 $self->{OUT_MODE} = '>';
1004 my $command_formatter = sub {
1005 my ($out_mode, $out) = @_;
1006 return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
1010 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1011 open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
1013 *OUT = ($::dispatcher->get_standard_filehandles)[1];
1017 if (!$template->parse(*OUT)) {
1019 $self->error("$self->{IN} : " . $template->get_error());
1022 close OUT if $self->{OUT};
1023 # check only one flag (webdav_documents)
1024 # therefore copy to webdav, even if we do not have the webdav feature enabled (just archive)
1025 my $copy_to_webdav = $::instance_conf->get_webdav_documents && !$self->{preview} && $self->{tmpdir} && $self->{tmpfile} && $self->{type}
1026 && $self->{type} ne 'statement';
1027 if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
1028 $self->append_general_pdf_attachments(filepath => $self->{tmpdir}."/".$self->{tmpfile},
1029 type => $self->{type});
1031 if ($self->{media} eq 'file') {
1032 copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
1034 if ($copy_to_webdav) {
1035 if (my $error = Common::copy_file_to_webdav_folder($self)) {
1036 chdir("$self->{cwd}");
1037 $self->error($error);
1041 if (!$self->{preview} && $self->doc_storage_enabled)
1043 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1044 $self->store_pdf($self);
1047 chdir("$self->{cwd}");
1049 $::lxdebug->leave_sub();
1054 if ($copy_to_webdav) {
1055 if (my $error = Common::copy_file_to_webdav_folder($self)) {
1056 chdir("$self->{cwd}");
1057 $self->error($error);
1061 if ( !$self->{preview} && $ext_for_format eq 'pdf' && $self->doc_storage_enabled) {
1062 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1063 my $file_obj = $self->store_pdf($self);
1064 $self->{print_file_id} = $file_obj->id if $file_obj;
1066 if ($self->{media} eq 'email') {
1067 if ( getcwd() eq $self->{"tmpdir"} ) {
1068 # in the case of generating pdf we are in the tmpdir, but WHY ???
1069 $self->{tmpfile} = $userspath."/".$self->{tmpfile};
1070 chdir("$self->{cwd}");
1072 $self->send_email(\%::myconfig,$ext_for_format);
1075 $self->{OUT} = $out;
1076 $self->{OUT_MODE} = $out_mode;
1077 $self->output_file($template->get_mime_type,$command_formatter);
1079 delete $self->{print_file_id};
1083 chdir("$self->{cwd}");
1084 $main::lxdebug->leave_sub();
1087 sub get_bcc_defaults {
1088 my ($self, $myconfig, $mybcc) = @_;
1089 if (SL::DB::Default->get->bcc_to_login) {
1090 $mybcc .= ", " if $mybcc;
1091 $mybcc .= $myconfig->{email};
1093 my $otherbcc = SL::DB::Default->get->global_bcc;
1095 $mybcc .= ", " if $mybcc;
1096 $mybcc .= $otherbcc;
1102 $main::lxdebug->enter_sub();
1103 my ($self, $myconfig, $ext_for_format) = @_;
1104 my $mail = Mailer->new;
1106 map { $mail->{$_} = $self->{$_} }
1107 qw(cc subject message format);
1109 $mail->{bcc} = $self->get_bcc_defaults($myconfig, $self->{bcc});
1110 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1111 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1112 $mail->{fileid} = time() . '.' . $$ . '.';
1113 my $full_signature = $self->create_email_signature();
1114 $full_signature =~ s/\r//g;
1116 $mail->{attachments} = [];
1118 # if we send html or plain text inline
1119 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1120 $mail->{content_type} = "text/html";
1121 $mail->{message} =~ s/\r//g;
1122 $mail->{message} =~ s{\n}{<br>\n}g;
1123 $full_signature =~ s{\n}{<br>\n}g;
1124 $mail->{message} .= $full_signature;
1126 open(IN, "<", $self->{tmpfile})
1127 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1128 $mail->{message} .= $_ while <IN>;
1131 } elsif (($self->{attachment_policy} // '') ne 'no_file') {
1132 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1133 $attachment_name =~ s{\.(.+?)$}{.${ext_for_format}} if ($ext_for_format);
1135 if (($self->{attachment_policy} // '') eq 'old_file') {
1136 my ( $attfile ) = SL::File->get_all(object_id => $self->{id},
1137 object_type => $self->{formname},
1138 file_type => 'document');
1141 $attfile->{override_file_name} = $attachment_name if $attachment_name;
1142 push @attfiles, $attfile;
1146 push @{ $mail->{attachments} }, { path => $self->{tmpfile},
1147 id => $self->{print_file_id},
1148 type => "application/pdf",
1149 name => $attachment_name };
1155 map { SL::File->get(id => $_) }
1156 @{ $self->{attach_file_ids} // [] };
1158 foreach my $attfile ( @attfiles ) {
1159 push @{ $mail->{attachments} }, {
1160 path => $attfile->get_file,
1162 type => $attfile->mime_type,
1163 name => $attfile->{override_file_name} // $attfile->file_name,
1164 content => $attfile->get_content ? ${ $attfile->get_content } : undef,
1168 $mail->{message} =~ s/\r//g;
1169 $mail->{message} .= $full_signature;
1170 $self->{emailerr} = $mail->send();
1172 if ($self->{emailerr}) {
1174 $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
1177 $self->{email_journal_id} = $mail->{journalentry};
1178 $self->{snumbers} = "emailjournal" . "_" . $self->{email_journal_id};
1179 $self->{what_done} = $::form->{type};
1180 $self->{addition} = "MAILED";
1181 $self->save_history;
1183 #write back for message info and mail journal
1184 $self->{cc} = $mail->{cc};
1185 $self->{bcc} = $mail->{bcc};
1186 $self->{email} = $mail->{to};
1188 $main::lxdebug->leave_sub();
1192 $main::lxdebug->enter_sub();
1194 my ($self,$mimeType,$command_formatter) = @_;
1195 my $numbytes = (-s $self->{tmpfile});
1196 open(IN, "<", $self->{tmpfile})
1197 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1200 $self->{copies} = 1 unless $self->{media} eq 'printer';
1202 chdir("$self->{cwd}");
1203 for my $i (1 .. $self->{copies}) {
1205 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1207 open OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1208 print OUT $_ while <IN>;
1213 my %headers = ('-type' => $mimeType,
1214 '-connection' => 'close',
1215 '-charset' => 'UTF-8');
1217 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1219 if ($self->{attachment_filename}) {
1222 '-attachment' => $self->{attachment_filename},
1223 '-content-length' => $numbytes,
1228 print $::request->cgi->header(%headers);
1230 $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1234 $main::lxdebug->leave_sub();
1237 sub get_formname_translation {
1238 $main::lxdebug->enter_sub();
1239 my ($self, $formname) = @_;
1241 $formname ||= $self->{formname};
1243 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1244 local $::locale = Locale->new($self->{recipient_locale});
1246 my %formname_translations = (
1247 bin_list => $main::locale->text('Bin List'),
1248 credit_note => $main::locale->text('Credit Note'),
1249 invoice => $main::locale->text('Invoice'),
1250 pick_list => $main::locale->text('Pick List'),
1251 proforma => $main::locale->text('Proforma Invoice'),
1252 purchase_order => $main::locale->text('Purchase Order'),
1253 request_quotation => $main::locale->text('RFQ'),
1254 sales_order => $main::locale->text('Confirmation'),
1255 sales_quotation => $main::locale->text('Quotation'),
1256 storno_invoice => $main::locale->text('Storno Invoice'),
1257 sales_delivery_order => $main::locale->text('Delivery Order'),
1258 purchase_delivery_order => $main::locale->text('Delivery Order'),
1259 dunning => $main::locale->text('Dunning'),
1260 dunning1 => $main::locale->text('Payment Reminder'),
1261 dunning2 => $main::locale->text('Dunning'),
1262 dunning3 => $main::locale->text('Last Dunning'),
1263 dunning_invoice => $main::locale->text('Dunning Invoice'),
1264 letter => $main::locale->text('Letter'),
1265 ic_supply => $main::locale->text('Intra-Community supply'),
1266 statement => $main::locale->text('Statement'),
1269 $main::lxdebug->leave_sub();
1270 return $formname_translations{$formname};
1273 sub get_cusordnumber_translation {
1274 $main::lxdebug->enter_sub();
1275 my ($self, $formname) = @_;
1277 $formname ||= $self->{formname};
1279 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1280 local $::locale = Locale->new($self->{recipient_locale});
1283 $main::lxdebug->leave_sub();
1284 return $main::locale->text('Your Order');
1287 sub get_number_prefix_for_type {
1288 $main::lxdebug->enter_sub();
1292 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1293 : ($self->{type} =~ /_quotation$/) ? 'quo'
1294 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1295 : ($self->{type} =~ /letter/) ? 'letter'
1298 # better default like this?
1299 # : ($self->{type} =~ /(sales|purcharse)_order/ : 'ord';
1300 # : 'prefix_undefined';
1302 $main::lxdebug->leave_sub();
1306 sub get_extension_for_format {
1307 $main::lxdebug->enter_sub();
1310 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1311 : $self->{format} =~ /postscript/i ? ".ps"
1312 : $self->{format} =~ /opendocument/i ? ".odt"
1313 : $self->{format} =~ /excel/i ? ".xls"
1314 : $self->{format} =~ /html/i ? ".html"
1317 $main::lxdebug->leave_sub();
1321 sub generate_attachment_filename {
1322 $main::lxdebug->enter_sub();
1325 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1326 my $recipient_locale = Locale->new($self->{recipient_locale});
1328 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1329 my $prefix = $self->get_number_prefix_for_type();
1331 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1332 $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
1334 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1335 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1337 } elsif ($attachment_filename) {
1338 $attachment_filename .= $self->get_extension_for_format();
1341 $attachment_filename = "";
1344 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1345 $attachment_filename =~ s|[\s/\\]+|_|g;
1347 $main::lxdebug->leave_sub();
1348 return $attachment_filename;
1351 sub generate_email_subject {
1352 $main::lxdebug->enter_sub();
1355 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1356 my $prefix = $self->get_number_prefix_for_type();
1358 if ($subject && $self->{"${prefix}number"}) {
1359 $subject .= " " . $self->{"${prefix}number"}
1362 if ($self->{cusordnumber}) {
1363 $subject = $self->get_cusordnumber_translation() . ' ' . $self->{cusordnumber} . ' / ' . $subject;
1366 $main::lxdebug->leave_sub();
1370 sub generate_email_body {
1371 $main::lxdebug->enter_sub();
1372 my ($self, %params) = @_;
1373 # simple german and english will work grammatically (most european languages as well)
1374 # Dear Mr Alan Greenspan:
1375 # Sehr geehrte Frau Meyer,
1376 # A l’attention de Mme Villeroy,
1377 # Gentile Signora Ferrari,
1380 if ($self->{cp_id} && !$params{record_email}) {
1381 my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
1382 my $name = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
1383 my $gender = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
1384 my $mf = $gender eq 'f' ? 'female' : 'male';
1385 $body = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
1386 $body .= ' ' . $givenname . ' ' . $name if $body;
1388 $body = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
1391 return undef unless $body;
1393 my $translation_type = $params{translation_type} // "preset_text_$self->{formname}";
1394 my $main_body = GenericTranslations->get(translation_type => $translation_type, language_id => $self->{language_id});
1395 $main_body = GenericTranslations->get(translation_type => $params{fallback_translation_type}, language_id => $self->{language_id}) if !$main_body && $params{fallback_translation_type};
1396 $body .= GenericTranslations->get(translation_type => "salutation_punctuation_mark", language_id => $self->{language_id}) . "\n\n";
1397 $body .= $main_body;
1399 $body = $main::locale->unquote_special_chars('HTML', $body);
1401 $main::lxdebug->leave_sub();
1406 $main::lxdebug->enter_sub();
1408 my ($self, $application) = @_;
1410 my $error_code = $?;
1412 chdir("$self->{tmpdir}");
1415 if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1416 push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1418 } elsif (-f "$self->{tmpfile}.err") {
1419 open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
1424 if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1425 $self->{tmpfile} =~ s|.*/||g;
1427 $self->{tmpfile} =~ s/\.\w+$//g;
1428 my $tmpfile = $self->{tmpfile};
1429 unlink(<$tmpfile.*>);
1432 chdir("$self->{cwd}");
1434 $main::lxdebug->leave_sub();
1440 $main::lxdebug->enter_sub();
1442 my ($self, $date, $myconfig) = @_;
1445 if ($date && $date =~ /\D/) {
1447 if ($myconfig->{dateformat} =~ /^yy/) {
1448 ($yy, $mm, $dd) = split /\D/, $date;
1450 if ($myconfig->{dateformat} =~ /^mm/) {
1451 ($mm, $dd, $yy) = split /\D/, $date;
1453 if ($myconfig->{dateformat} =~ /^dd/) {
1454 ($dd, $mm, $yy) = split /\D/, $date;
1459 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1460 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1462 $dd = "0$dd" if ($dd < 10);
1463 $mm = "0$mm" if ($mm < 10);
1465 $date = "$yy$mm$dd";
1468 $main::lxdebug->leave_sub();
1473 # Database routines used throughout
1474 # DB Handling got moved to SL::DB, these are only shims for compatibility
1477 SL::DB->client->dbh;
1480 sub get_standard_dbh {
1481 my $dbh = SL::DB->client->dbh;
1483 if ($dbh && !$dbh->{Active}) {
1484 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
1485 SL::DB->client->dbh(undef);
1488 SL::DB->client->dbh;
1491 sub disconnect_standard_dbh {
1492 SL::DB->client->dbh->rollback;
1498 $main::lxdebug->enter_sub();
1500 my ($self, $date, $myconfig) = @_;
1501 my $dbh = $self->get_standard_dbh;
1503 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1504 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1506 # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1507 # es ist sicher ein conv_date vorher IMMER auszuführen.
1508 # Testfälle ohne definiertes closedto:
1509 # Leere Datumseingabe i.O.
1510 # SELECT 1 FROM defaults WHERE '' < closedto
1511 # normale Zahlungsbuchung über Rechnungsmaske i.O.
1512 # SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1513 # Testfälle mit definiertem closedto (30.04.2011):
1514 # Leere Datumseingabe i.O.
1515 # SELECT 1 FROM defaults WHERE '' < closedto
1516 # normale Buchung im geschloßenem Zeitraum i.O.
1517 # SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1518 # Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1519 # normale Buchung in aktiver Buchungsperiode i.O.
1520 # SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1522 my ($closed) = $sth->fetchrow_array;
1524 $main::lxdebug->leave_sub();
1529 # prevents bookings to the to far away future
1530 sub date_max_future {
1531 $main::lxdebug->enter_sub();
1533 my ($self, $date, $myconfig) = @_;
1534 my $dbh = $self->get_standard_dbh;
1536 my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
1537 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1539 my ($max_future_booking_interval) = $sth->fetchrow_array;
1541 $main::lxdebug->leave_sub();
1543 return $max_future_booking_interval;
1547 sub update_balance {
1548 $main::lxdebug->enter_sub();
1550 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1552 # if we have a value, go do it
1555 # retrieve balance from table
1556 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1557 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1558 my ($balance) = $sth->fetchrow_array;
1564 $query = "UPDATE $table SET $field = $balance WHERE $where";
1565 do_query($self, $dbh, $query, @values);
1567 $main::lxdebug->leave_sub();
1570 sub update_exchangerate {
1571 $main::lxdebug->enter_sub();
1573 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1575 # some sanity check for currency
1577 $main::lxdebug->leave_sub();
1580 $query = qq|SELECT name AS curr FROM currencies WHERE id=(SELECT currency_id FROM defaults)|;
1582 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1584 if ($curr eq $defaultcurrency) {
1585 $main::lxdebug->leave_sub();
1589 $query = qq|SELECT e.currency_id FROM exchangerate e
1590 WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
1592 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1601 $buy = conv_i($buy, "NULL");
1602 $sell = conv_i($sell, "NULL");
1605 if ($buy != 0 && $sell != 0) {
1606 $set = "buy = $buy, sell = $sell";
1607 } elsif ($buy != 0) {
1608 $set = "buy = $buy";
1609 } elsif ($sell != 0) {
1610 $set = "sell = $sell";
1613 if ($sth->fetchrow_array) {
1614 $query = qq|UPDATE exchangerate
1616 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
1620 $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
1621 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
1624 do_query($self, $dbh, $query, $curr, $transdate);
1626 $main::lxdebug->leave_sub();
1629 sub save_exchangerate {
1630 $main::lxdebug->enter_sub();
1632 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1634 SL::DB->client->with_transaction(sub {
1635 my $dbh = SL::DB->client->dbh;
1639 $buy = $rate if $fld eq 'buy';
1640 $sell = $rate if $fld eq 'sell';
1643 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1645 }) or do { die SL::DB->client->error };
1647 $main::lxdebug->leave_sub();
1650 sub get_exchangerate {
1651 $main::lxdebug->enter_sub();
1653 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1656 unless ($transdate && $curr) {
1657 $main::lxdebug->leave_sub();
1661 $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1663 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1665 if ($curr eq $defaultcurrency) {
1666 $main::lxdebug->leave_sub();
1670 $query = qq|SELECT e.$fld FROM exchangerate e
1671 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1672 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1676 $main::lxdebug->leave_sub();
1678 return $exchangerate;
1681 sub check_exchangerate {
1682 $main::lxdebug->enter_sub();
1684 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1686 if ($fld !~/^buy|sell$/) {
1687 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1690 unless ($transdate) {
1691 $main::lxdebug->leave_sub();
1695 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1697 if ($currency eq $defaultcurrency) {
1698 $main::lxdebug->leave_sub();
1702 my $dbh = $self->get_standard_dbh($myconfig);
1703 my $query = qq|SELECT e.$fld FROM exchangerate e
1704 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1706 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1708 $main::lxdebug->leave_sub();
1710 return $exchangerate;
1713 sub get_all_currencies {
1714 $main::lxdebug->enter_sub();
1717 my $myconfig = shift || \%::myconfig;
1718 my $dbh = $self->get_standard_dbh($myconfig);
1720 my $query = qq|SELECT name FROM currencies|;
1721 my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
1723 $main::lxdebug->leave_sub();
1728 sub get_default_currency {
1729 $main::lxdebug->enter_sub();
1731 my ($self, $myconfig) = @_;
1732 my $dbh = $self->get_standard_dbh($myconfig);
1733 my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1735 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1737 $main::lxdebug->leave_sub();
1739 return $defaultcurrency;
1742 sub set_payment_options {
1743 my ($self, $myconfig, $transdate, $type) = @_;
1745 my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
1748 my $is_invoice = $type =~ m{invoice}i;
1750 $transdate ||= $self->{invdate} || $self->{transdate};
1751 my $due_date = $self->{duedate} || $self->{reqdate};
1753 $self->{$_} = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
1754 $self->{payment_description} = $terms->description;
1755 $self->{netto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
1756 $self->{skonto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
1758 my ($invtotal, $total);
1759 my (%amounts, %formatted_amounts);
1761 if ($self->{type} =~ /_order$/) {
1762 $amounts{invtotal} = $self->{ordtotal};
1763 $amounts{total} = $self->{ordtotal};
1765 } elsif ($self->{type} =~ /_quotation$/) {
1766 $amounts{invtotal} = $self->{quototal};
1767 $amounts{total} = $self->{quototal};
1770 $amounts{invtotal} = $self->{invtotal};
1771 $amounts{total} = $self->{total};
1773 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1775 $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1776 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1777 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1778 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1780 foreach (keys %amounts) {
1781 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1782 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1785 if ($self->{"language_id"}) {
1786 my $language = SL::DB::Language->new(id => $self->{language_id})->load;
1788 $self->{payment_terms} = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
1789 $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
1791 if ($language->output_dateformat) {
1792 foreach my $key (qw(netto_date skonto_date)) {
1793 $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
1797 if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
1798 local $myconfig->{numberformat};
1799 $myconfig->{"numberformat"} = $language->output_numberformat;
1800 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
1804 $self->{payment_terms} = $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
1806 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1807 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1808 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1809 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1810 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1811 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1812 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1813 $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
1814 $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
1815 $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
1816 $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
1818 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1820 $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1824 sub get_template_language {
1825 $main::lxdebug->enter_sub();
1827 my ($self, $myconfig) = @_;
1829 my $template_code = "";
1831 if ($self->{language_id}) {
1832 my $dbh = $self->get_standard_dbh($myconfig);
1833 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1834 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1837 $main::lxdebug->leave_sub();
1839 return $template_code;
1842 sub get_printer_code {
1843 $main::lxdebug->enter_sub();
1845 my ($self, $myconfig) = @_;
1847 my $template_code = "";
1849 if ($self->{printer_id}) {
1850 my $dbh = $self->get_standard_dbh($myconfig);
1851 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1852 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1855 $main::lxdebug->leave_sub();
1857 return $template_code;
1861 $main::lxdebug->enter_sub();
1863 my ($self, $myconfig) = @_;
1865 my $template_code = "";
1867 if ($self->{shipto_id}) {
1868 my $dbh = $self->get_standard_dbh($myconfig);
1869 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1870 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1871 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1873 my $cvars = CVar->get_custom_variables(
1876 trans_id => $self->{shipto_id},
1878 $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
1881 $main::lxdebug->leave_sub();
1885 my ($self, $dbh, $id, $module) = @_;
1890 foreach my $item (qw(name department_1 department_2 street zipcode city country gln
1891 contact phone fax email)) {
1892 if ($self->{"shipto$item"}) {
1893 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1895 push(@values, $self->{"shipto${item}"});
1900 # shiptocp_gender only makes sense, if any other shipto attribute is set.
1901 # Because shiptocp_gender is set to 'm' by default in forms
1902 # it must not be considered above to decide if shiptos has to be added or
1903 # updated, but must be inserted or updated as well in case.
1904 push(@values, $self->{shiptocp_gender});
1906 my $shipto_id = $self->{shipto_id};
1908 if ($self->{shipto_id}) {
1909 my $query = qq|UPDATE shipto set
1911 shiptodepartment_1 = ?,
1912 shiptodepartment_2 = ?,
1922 shiptocp_gender = ?,
1923 WHERE shipto_id = ?|;
1924 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1926 my $query = qq|SELECT * FROM shipto
1927 WHERE shiptoname = ? AND
1928 shiptodepartment_1 = ? AND
1929 shiptodepartment_2 = ? AND
1930 shiptostreet = ? AND
1931 shiptozipcode = ? AND
1933 shiptocountry = ? AND
1935 shiptocontact = ? AND
1939 shiptocp_gender = ? AND
1942 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1945 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1946 shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
1947 shiptocontact, shiptophone, shiptofax, shiptoemail, shiptocp_gender, module)
1948 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1949 do_query($self, $dbh, $insert_query, $id, @values, $module);
1951 $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1954 $shipto_id = $insert_check->{shipto_id};
1957 return unless $shipto_id;
1959 CVar->save_custom_variables(
1962 trans_id => $shipto_id,
1964 name_prefix => 'shipto',
1969 $main::lxdebug->enter_sub();
1971 my ($self, $dbh) = @_;
1973 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1975 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1976 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1977 $self->{"employee_id"} *= 1;
1979 $main::lxdebug->leave_sub();
1982 sub get_employee_data {
1983 $main::lxdebug->enter_sub();
1987 my $defaults = SL::DB::Default->get;
1989 Common::check_params(\%params, qw(prefix));
1990 Common::check_params_x(\%params, qw(id));
1993 $main::lxdebug->leave_sub();
1997 my $myconfig = \%main::myconfig;
1998 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
2000 my ($login, $deleted) = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
2003 # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
2004 $self->{$params{prefix} . '_login'} = $login;
2005 $self->{$params{prefix} . "_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
2008 # get employee data from auth.user_config
2009 my $user = User->new(login => $login);
2010 $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
2012 # get saved employee data from employee
2013 my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
2014 $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
2015 $self->{$params{prefix} . "_name"} = $employee->name;
2018 $main::lxdebug->leave_sub();
2022 $main::lxdebug->enter_sub();
2024 my ($self, $dbh, $id, $key) = @_;
2026 $key = "all_contacts" unless ($key);
2030 $main::lxdebug->leave_sub();
2035 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2036 qq|FROM contacts | .
2037 qq|WHERE cp_cv_id = ? | .
2038 qq|ORDER BY lower(cp_name)|;
2040 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2042 $main::lxdebug->leave_sub();
2046 $main::lxdebug->enter_sub();
2048 my ($self, $dbh, $key) = @_;
2050 my ($all, $old_id, $where, @values);
2052 if (ref($key) eq "HASH") {
2055 $key = "ALL_PROJECTS";
2057 foreach my $p (keys(%{$params})) {
2059 $all = $params->{$p};
2060 } elsif ($p eq "old_id") {
2061 $old_id = $params->{$p};
2062 } elsif ($p eq "key") {
2063 $key = $params->{$p};
2069 $where = "WHERE active ";
2071 if (ref($old_id) eq "ARRAY") {
2072 my @ids = grep({ $_ } @{$old_id});
2074 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2075 push(@values, @ids);
2078 $where .= " OR (id = ?) ";
2079 push(@values, $old_id);
2085 qq|SELECT id, projectnumber, description, active | .
2088 qq|ORDER BY lower(projectnumber)|;
2090 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2092 $main::lxdebug->leave_sub();
2096 $main::lxdebug->enter_sub();
2098 my ($self, $dbh, $key) = @_;
2100 $key = "all_printers" unless ($key);
2102 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2104 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2106 $main::lxdebug->leave_sub();
2110 $main::lxdebug->enter_sub();
2112 my ($self, $dbh, $params) = @_;
2115 $key = $params->{key};
2116 $key = "all_charts" unless ($key);
2118 my $transdate = quote_db_date($params->{transdate});
2121 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2123 qq|LEFT JOIN taxkeys tk ON | .
2124 qq|(tk.id = (SELECT id FROM taxkeys | .
2125 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2126 qq| ORDER BY startdate DESC LIMIT 1)) | .
2127 qq|ORDER BY c.accno|;
2129 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2131 $main::lxdebug->leave_sub();
2135 $main::lxdebug->enter_sub();
2137 my ($self, $dbh, $key) = @_;
2139 $key = "all_taxzones" unless ($key);
2141 $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
2143 my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
2145 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2147 $main::lxdebug->leave_sub();
2150 sub _get_employees {
2151 $main::lxdebug->enter_sub();
2153 my ($self, $dbh, $params) = @_;
2158 if (ref $params eq 'HASH') {
2159 $key = $params->{key};
2160 $deleted = $params->{deleted};
2166 $key ||= "all_employees";
2167 my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
2168 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
2170 $main::lxdebug->leave_sub();
2173 sub _get_business_types {
2174 $main::lxdebug->enter_sub();
2176 my ($self, $dbh, $key) = @_;
2178 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2179 $options->{key} ||= "all_business_types";
2182 if (exists $options->{salesman}) {
2183 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2186 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2188 $main::lxdebug->leave_sub();
2191 sub _get_languages {
2192 $main::lxdebug->enter_sub();
2194 my ($self, $dbh, $key) = @_;
2196 $key = "all_languages" unless ($key);
2198 my $query = qq|SELECT * FROM language ORDER BY id|;
2200 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2202 $main::lxdebug->leave_sub();
2205 sub _get_dunning_configs {
2206 $main::lxdebug->enter_sub();
2208 my ($self, $dbh, $key) = @_;
2210 $key = "all_dunning_configs" unless ($key);
2212 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2214 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2216 $main::lxdebug->leave_sub();
2219 sub _get_currencies {
2220 $main::lxdebug->enter_sub();
2222 my ($self, $dbh, $key) = @_;
2224 $key = "all_currencies" unless ($key);
2226 $self->{$key} = [$self->get_all_currencies()];
2228 $main::lxdebug->leave_sub();
2232 $main::lxdebug->enter_sub();
2234 my ($self, $dbh, $key) = @_;
2236 $key = "all_payments" unless ($key);
2238 my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2240 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2242 $main::lxdebug->leave_sub();
2245 sub _get_customers {
2246 $main::lxdebug->enter_sub();
2248 my ($self, $dbh, $key) = @_;
2250 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2251 $options->{key} ||= "all_customers";
2252 my $limit_clause = $options->{limit} ? "LIMIT $options->{limit}" : '';
2255 push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman};
2256 push @where, qq|NOT obsolete| if !$options->{with_obsolete};
2257 my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2259 my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2260 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2262 $main::lxdebug->leave_sub();
2266 $main::lxdebug->enter_sub();
2268 my ($self, $dbh, $key) = @_;
2270 $key = "all_vendors" unless ($key);
2272 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2274 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2276 $main::lxdebug->leave_sub();
2279 sub _get_departments {
2280 $main::lxdebug->enter_sub();
2282 my ($self, $dbh, $key) = @_;
2284 $key = "all_departments" unless ($key);
2286 my $query = qq|SELECT * FROM department ORDER BY description|;
2288 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2290 $main::lxdebug->leave_sub();
2293 sub _get_warehouses {
2294 $main::lxdebug->enter_sub();
2296 my ($self, $dbh, $param) = @_;
2298 my ($key, $bins_key);
2300 if ('' eq ref $param) {
2304 $key = $param->{key};
2305 $bins_key = $param->{bins};
2308 my $query = qq|SELECT w.* FROM warehouse w
2309 WHERE (NOT w.invalid) AND
2310 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2311 ORDER BY w.sortkey|;
2313 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2316 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2317 ORDER BY description|;
2318 my $sth = prepare_query($self, $dbh, $query);
2320 foreach my $warehouse (@{ $self->{$key} }) {
2321 do_statement($self, $sth, $query, $warehouse->{id});
2322 $warehouse->{$bins_key} = [];
2324 while (my $ref = $sth->fetchrow_hashref()) {
2325 push @{ $warehouse->{$bins_key} }, $ref;
2331 $main::lxdebug->leave_sub();
2335 $main::lxdebug->enter_sub();
2337 my ($self, $dbh, $table, $key, $sortkey) = @_;
2339 my $query = qq|SELECT * FROM $table|;
2340 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2342 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2344 $main::lxdebug->leave_sub();
2348 $main::lxdebug->enter_sub();
2353 croak "get_lists: shipto is no longer supported" if $params{shipto};
2355 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2356 my ($sth, $query, $ref);
2359 if ($params{contacts}) {
2360 $vc = 'customer' if $self->{"vc"} eq "customer";
2361 $vc = 'vendor' if $self->{"vc"} eq "vendor";
2362 die "invalid use of get_lists, need 'vc'" unless $vc;
2363 $vc_id = $self->{"${vc}_id"};
2366 if ($params{"contacts"}) {
2367 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2370 if ($params{"projects"} || $params{"all_projects"}) {
2371 $self->_get_projects($dbh, $params{"all_projects"} ?
2372 $params{"all_projects"} : $params{"projects"},
2373 $params{"all_projects"} ? 1 : 0);
2376 if ($params{"printers"}) {
2377 $self->_get_printers($dbh, $params{"printers"});
2380 if ($params{"languages"}) {
2381 $self->_get_languages($dbh, $params{"languages"});
2384 if ($params{"charts"}) {
2385 $self->_get_charts($dbh, $params{"charts"});
2388 if ($params{"taxzones"}) {
2389 $self->_get_taxzones($dbh, $params{"taxzones"});
2392 if ($params{"employees"}) {
2393 $self->_get_employees($dbh, $params{"employees"});
2396 if ($params{"salesmen"}) {
2397 $self->_get_employees($dbh, $params{"salesmen"});
2400 if ($params{"business_types"}) {
2401 $self->_get_business_types($dbh, $params{"business_types"});
2404 if ($params{"dunning_configs"}) {
2405 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2408 if($params{"currencies"}) {
2409 $self->_get_currencies($dbh, $params{"currencies"});
2412 if($params{"customers"}) {
2413 $self->_get_customers($dbh, $params{"customers"});
2416 if($params{"vendors"}) {
2417 if (ref $params{"vendors"} eq 'HASH') {
2418 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2420 $self->_get_vendors($dbh, $params{"vendors"});
2424 if($params{"payments"}) {
2425 $self->_get_payments($dbh, $params{"payments"});
2428 if($params{"departments"}) {
2429 $self->_get_departments($dbh, $params{"departments"});
2432 if ($params{price_factors}) {
2433 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2436 if ($params{warehouses}) {
2437 $self->_get_warehouses($dbh, $params{warehouses});
2440 if ($params{partsgroup}) {
2441 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2444 $main::lxdebug->leave_sub();
2447 # this sub gets the id and name from $table
2449 $main::lxdebug->enter_sub();
2451 my ($self, $myconfig, $table) = @_;
2453 # connect to database
2454 my $dbh = $self->get_standard_dbh($myconfig);
2456 $table = $table eq "customer" ? "customer" : "vendor";
2457 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2459 my ($query, @values);
2461 if (!$self->{openinvoices}) {
2463 if ($self->{customernumber} ne "") {
2464 $where = qq|(vc.customernumber ILIKE ?)|;
2465 push(@values, like($self->{customernumber}));
2467 $where = qq|(vc.name ILIKE ?)|;
2468 push(@values, like($self->{$table}));
2472 qq~SELECT vc.id, vc.name,
2473 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2475 WHERE $where AND (NOT vc.obsolete)
2479 qq~SELECT DISTINCT vc.id, vc.name,
2480 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2482 JOIN $table vc ON (a.${table}_id = vc.id)
2483 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2485 push(@values, like($self->{$table}));
2488 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2490 $main::lxdebug->leave_sub();
2492 return scalar(@{ $self->{name_list} });
2497 my ($self, $table, $provided_dbh) = @_;
2499 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
2500 return unless $self->{id};
2501 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2503 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2504 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2505 $ref->{mtime} ||= $ref->{itime};
2506 $self->{lastmtime} = $ref->{mtime};
2510 sub mtime_ischanged {
2511 my ($self, $table, $option) = @_;
2513 return unless $self->{id};
2514 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2516 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2517 my $ref = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
2518 $ref->{mtime} ||= $ref->{itime};
2520 if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
2521 $self->error(($option eq 'mail') ?
2522 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") :
2523 t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
2525 $::dispatcher->end_request;
2529 # language_payment duplicates some of the functionality of all_vc (language,
2530 # printer, payment_terms), and at least in the case of sales invoices both
2531 # all_vc and language_payment are called when adding new invoices
2532 sub language_payment {
2533 $main::lxdebug->enter_sub();
2535 my ($self, $myconfig) = @_;
2537 my $dbh = $self->get_standard_dbh($myconfig);
2539 my $query = qq|SELECT id, description
2543 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2546 $query = qq|SELECT printer_description, id
2548 ORDER BY printer_description|;
2550 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2553 $query = qq|SELECT id, description
2555 WHERE ( obsolete IS FALSE OR id = ? )
2557 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
2559 # get buchungsgruppen
2560 $query = qq|SELECT id, description
2561 FROM buchungsgruppen|;
2563 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2565 $main::lxdebug->leave_sub();
2568 # this is only used for reports
2569 sub all_departments {
2570 $main::lxdebug->enter_sub();
2572 my ($self, $myconfig, $table) = @_;
2574 my $dbh = $self->get_standard_dbh($myconfig);
2576 my $query = qq|SELECT id, description
2578 ORDER BY description|;
2579 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2581 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2583 $main::lxdebug->leave_sub();
2587 $main::lxdebug->enter_sub();
2589 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2592 if ($table eq "customer") {
2601 # get last customers or vendors
2602 my ($query, $sth, $ref);
2604 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2609 my $transdate = "current_date";
2610 if ($self->{transdate}) {
2611 $transdate = $dbh->quote($self->{transdate});
2614 # now get the account numbers
2616 SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
2618 -- find newest entries in taxkeys
2620 SELECT chart_id, MAX(startdate) AS startdate
2622 WHERE (startdate <= $transdate)
2624 ) tk ON (c.id = tk.chart_id)
2625 -- and load all of those entries
2626 INNER JOIN taxkeys tk2
2627 ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
2628 WHERE (c.link LIKE ?)
2631 $sth = $dbh->prepare($query);
2633 do_statement($self, $sth, $query, like($module));
2635 $self->{accounts} = "";
2636 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2638 foreach my $key (split(/:/, $ref->{link})) {
2639 if ($key =~ /\Q$module\E/) {
2641 # cross reference for keys
2642 $xkeyref{ $ref->{accno} } = $key;
2644 push @{ $self->{"${module}_links"}{$key} },
2645 { accno => $ref->{accno},
2646 chart_id => $ref->{chart_id},
2647 description => $ref->{description},
2648 taxkey => $ref->{taxkey_id},
2649 tax_id => $ref->{tax_id} };
2651 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2657 # get taxkeys and description
2658 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2659 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2661 if (($module eq "AP") || ($module eq "AR")) {
2662 # get tax rates and description
2663 $query = qq|SELECT * FROM tax|;
2664 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2667 my $extra_columns = '';
2668 $extra_columns .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
2673 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid, a.deliverydate,
2674 a.duedate, a.ordnumber, a.taxincluded, (SELECT cu.name FROM currencies cu WHERE cu.id=a.currency_id) AS currency, a.notes,
2676 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2677 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2678 a.globalproject_id, ${extra_columns}
2680 d.description AS department,
2683 JOIN $table c ON (a.${table}_id = c.id)
2684 LEFT JOIN employee e ON (e.id = a.employee_id)
2685 LEFT JOIN department d ON (d.id = a.department_id)
2687 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2689 foreach my $key (keys %$ref) {
2690 $self->{$key} = $ref->{$key};
2692 $self->{mtime} ||= $self->{itime};
2693 $self->{lastmtime} = $self->{mtime};
2694 my $transdate = "current_date";
2695 if ($self->{transdate}) {
2696 $transdate = $dbh->quote($self->{transdate});
2699 # now get the account numbers
2700 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
2702 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2704 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2705 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2708 $sth = $dbh->prepare($query);
2709 do_statement($self, $sth, $query, like($module));
2711 $self->{accounts} = "";
2712 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2714 foreach my $key (split(/:/, $ref->{link})) {
2715 if ($key =~ /\Q$module\E/) {
2717 # cross reference for keys
2718 $xkeyref{ $ref->{accno} } = $key;
2720 push @{ $self->{"${module}_links"}{$key} },
2721 { accno => $ref->{accno},
2722 chart_id => $ref->{chart_id},
2723 description => $ref->{description},
2724 taxkey => $ref->{taxkey_id},
2725 tax_id => $ref->{tax_id} };
2727 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2733 # get amounts from individual entries
2736 c.accno, c.description,
2737 a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
2741 LEFT JOIN chart c ON (c.id = a.chart_id)
2742 LEFT JOIN project p ON (p.id = a.project_id)
2743 LEFT JOIN tax t ON (t.id= a.tax_id)
2744 WHERE a.trans_id = ?
2745 AND a.fx_transaction = '0'
2746 ORDER BY a.acc_trans_id, a.transdate|;
2747 $sth = $dbh->prepare($query);
2748 do_statement($self, $sth, $query, $self->{id});
2750 # get exchangerate for currency
2751 $self->{exchangerate} =
2752 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2755 # store amounts in {acc_trans}{$key} for multiple accounts
2756 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2757 $ref->{exchangerate} =
2758 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2759 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2762 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2763 $ref->{amount} *= -1;
2765 $ref->{index} = $index;
2767 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2774 d.closedto, d.revtrans,
2775 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2776 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2777 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2778 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2779 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2781 $ref = selectfirst_hashref_query($self, $dbh, $query);
2782 map { $self->{$_} = $ref->{$_} } keys %$ref;
2789 current_date AS transdate, d.closedto, d.revtrans,
2790 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2791 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2792 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2793 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2794 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2796 $ref = selectfirst_hashref_query($self, $dbh, $query);
2797 map { $self->{$_} = $ref->{$_} } keys %$ref;
2799 if ($self->{"$self->{vc}_id"}) {
2801 # only setup currency
2802 ($self->{currency}) = $self->{defaultcurrency} if !$self->{currency};
2806 $self->lastname_used($dbh, $myconfig, $table, $module);
2808 # get exchangerate for currency
2809 $self->{exchangerate} =
2810 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2816 $main::lxdebug->leave_sub();
2820 $main::lxdebug->enter_sub();
2822 my ($self, $dbh, $myconfig, $table, $module) = @_;
2826 $table = $table eq "customer" ? "customer" : "vendor";
2827 my %column_map = ("a.${table}_id" => "${table}_id",
2828 "a.department_id" => "department_id",
2829 "d.description" => "department",
2830 "ct.name" => $table,
2831 "cu.name" => "currency",
2834 if ($self->{type} =~ /delivery_order/) {
2835 $arap = 'delivery_orders';
2836 delete $column_map{"cu.currency"};
2838 } elsif ($self->{type} =~ /_order/) {
2840 $where = "quotation = '0'";
2842 } elsif ($self->{type} =~ /_quotation/) {
2844 $where = "quotation = '1'";
2846 } elsif ($table eq 'customer') {
2854 $where = "($where) AND" if ($where);
2855 my $query = qq|SELECT MAX(id) FROM $arap
2856 WHERE $where ${table}_id > 0|;
2857 my ($trans_id) = selectrow_query($self, $dbh, $query);
2860 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2861 $query = qq|SELECT $column_spec
2863 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2864 LEFT JOIN department d ON (a.department_id = d.id)
2865 LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
2867 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2869 map { $self->{$_} = $ref->{$_} } values %column_map;
2871 $main::lxdebug->leave_sub();
2874 sub get_variable_content_types {
2875 my %html_variables = (
2876 longdescription => 'html',
2877 partnotes => 'html',
2879 orignotes => 'html',
2884 header_text => 'html',
2885 footer_text => 'html',
2887 return \%html_variables;
2891 $main::lxdebug->enter_sub();
2894 my $myconfig = shift || \%::myconfig;
2895 my ($thisdate, $days) = @_;
2897 my $dbh = $self->get_standard_dbh($myconfig);
2902 my $dateformat = $myconfig->{dateformat};
2903 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2904 $thisdate = $dbh->quote($thisdate);
2905 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2907 $query = qq|SELECT current_date AS thisdate|;
2910 ($thisdate) = selectrow_query($self, $dbh, $query);
2912 $main::lxdebug->leave_sub();
2918 $main::lxdebug->enter_sub();
2920 my ($self, $flds, $new, $count, $numrows) = @_;
2924 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2929 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2931 my $j = $item->{ndx} - 1;
2932 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2936 for $i ($count + 1 .. $numrows) {
2937 map { delete $self->{"${_}_$i"} } @{$flds};
2940 $main::lxdebug->leave_sub();
2944 $main::lxdebug->enter_sub();
2946 my ($self, $myconfig) = @_;
2950 SL::DB->client->with_transaction(sub {
2951 my $dbh = SL::DB->client->dbh;
2953 my $query = qq|DELETE FROM status
2954 WHERE (formname = ?) AND (trans_id = ?)|;
2955 my $sth = prepare_query($self, $dbh, $query);
2957 if ($self->{formname} =~ /(check|receipt)/) {
2958 for $i (1 .. $self->{rowcount}) {
2959 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2962 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2966 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2967 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2969 my %queued = split / /, $self->{queued};
2972 if ($self->{formname} =~ /(check|receipt)/) {
2974 # this is a check or receipt, add one entry for each lineitem
2975 my ($accno) = split /--/, $self->{account};
2976 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2977 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2978 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2979 $sth = prepare_query($self, $dbh, $query);
2981 for $i (1 .. $self->{rowcount}) {
2982 if ($self->{"checked_$i"}) {
2983 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2989 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2990 VALUES (?, ?, ?, ?, ?)|;
2991 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2992 $queued{$self->{formname}}, $self->{formname});
2995 }) or do { die SL::DB->client->error };
2997 $main::lxdebug->leave_sub();
3001 $main::lxdebug->enter_sub();
3003 my ($self, $dbh) = @_;
3005 my ($query, $printed, $emailed);
3007 my $formnames = $self->{printed};
3008 my $emailforms = $self->{emailed};
3010 $query = qq|DELETE FROM status
3011 WHERE (formname = ?) AND (trans_id = ?)|;
3012 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3014 # this only applies to the forms
3015 # checks and receipts are posted when printed or queued
3017 if ($self->{queued}) {
3018 my %queued = split / /, $self->{queued};
3020 foreach my $formname (keys %queued) {
3021 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3022 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3024 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3025 VALUES (?, ?, ?, ?, ?)|;
3026 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3028 $formnames =~ s/\Q$self->{formname}\E//;
3029 $emailforms =~ s/\Q$self->{formname}\E//;
3034 # save printed, emailed info
3035 $formnames =~ s/^ +//g;
3036 $emailforms =~ s/^ +//g;
3039 map { $status{$_}{printed} = 1 } split / +/, $formnames;
3040 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3042 foreach my $formname (keys %status) {
3043 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
3044 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3046 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3047 VALUES (?, ?, ?, ?)|;
3048 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3051 $main::lxdebug->leave_sub();
3055 # $main::locale->text('SAVED')
3056 # $main::locale->text('SCREENED')
3057 # $main::locale->text('DELETED')
3058 # $main::locale->text('ADDED')
3059 # $main::locale->text('PAYMENT POSTED')
3060 # $main::locale->text('POSTED')
3061 # $main::locale->text('POSTED AS NEW')
3062 # $main::locale->text('ELSE')
3063 # $main::locale->text('SAVED FOR DUNNING')
3064 # $main::locale->text('DUNNING STARTED')
3065 # $main::locale->text('PRINTED')
3066 # $main::locale->text('MAILED')
3067 # $main::locale->text('SCREENED')
3068 # $main::locale->text('CANCELED')
3069 # $main::locale->text('IMPORT')
3070 # $main::locale->text('UNIMPORT')
3071 # $main::locale->text('invoice')
3072 # $main::locale->text('proforma')
3073 # $main::locale->text('sales_order')
3074 # $main::locale->text('pick_list')
3075 # $main::locale->text('purchase_order')
3076 # $main::locale->text('bin_list')
3077 # $main::locale->text('sales_quotation')
3078 # $main::locale->text('request_quotation')
3081 $main::lxdebug->enter_sub();
3084 my $dbh = shift || SL::DB->client->dbh;
3085 SL::DB->client->with_transaction(sub {
3087 if(!exists $self->{employee_id}) {
3088 &get_employee($self, $dbh);
3092 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3093 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3094 my @values = (conv_i($self->{id}), $self->{login},
3095 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3096 do_query($self, $dbh, $query, @values);
3098 }) or do { die SL::DB->client->error };
3100 $main::lxdebug->leave_sub();
3104 $main::lxdebug->enter_sub();
3106 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3107 my ($orderBy, $desc) = split(/\-\-/, $order);
3108 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3111 if ($trans_id ne "") {
3113 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 | .
3114 qq|FROM history_erp h | .
3115 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3116 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3119 my $sth = $dbh->prepare($query) || $self->dberror($query);
3121 $sth->execute() || $self->dberror("$query");
3123 while(my $hash_ref = $sth->fetchrow_hashref()) {
3124 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3125 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3126 my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
3127 $hash_ref->{snumbers} = $number;
3128 $hash_ref->{haslink} = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
3129 $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
3130 $tempArray[$i++] = $hash_ref;
3132 $main::lxdebug->leave_sub() and return \@tempArray
3133 if ($i > 0 && $tempArray[0] ne "");
3135 $main::lxdebug->leave_sub();
3139 sub get_partsgroup {
3140 $main::lxdebug->enter_sub();
3142 my ($self, $myconfig, $p) = @_;
3143 my $target = $p->{target} || 'all_partsgroup';
3145 my $dbh = $self->get_standard_dbh($myconfig);
3147 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3149 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3152 if ($p->{searchitems} eq 'part') {
3153 $query .= qq|WHERE p.part_type = 'part'|;
3155 if ($p->{searchitems} eq 'service') {
3156 $query .= qq|WHERE p.part_type = 'service'|;
3158 if ($p->{searchitems} eq 'assembly') {
3159 $query .= qq|WHERE p.part_type = 'assembly'|;
3162 $query .= qq|ORDER BY partsgroup|;
3165 $query = qq|SELECT id, partsgroup FROM partsgroup
3166 ORDER BY partsgroup|;
3169 if ($p->{language_code}) {
3170 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3171 t.description AS translation
3173 JOIN parts p ON (p.partsgroup_id = pg.id)
3174 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3175 ORDER BY translation|;
3176 @values = ($p->{language_code});
3179 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3181 $main::lxdebug->leave_sub();
3184 sub get_pricegroup {
3185 $main::lxdebug->enter_sub();
3187 my ($self, $myconfig, $p) = @_;
3189 my $dbh = $self->get_standard_dbh($myconfig);
3191 my $query = qq|SELECT p.id, p.pricegroup
3194 $query .= qq| ORDER BY pricegroup|;
3197 $query = qq|SELECT id, pricegroup FROM pricegroup
3198 ORDER BY pricegroup|;
3201 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3203 $main::lxdebug->leave_sub();
3207 # usage $form->all_years($myconfig, [$dbh])
3208 # return list of all years where bookings found
3211 $main::lxdebug->enter_sub();
3213 my ($self, $myconfig, $dbh) = @_;
3215 $dbh ||= $self->get_standard_dbh($myconfig);
3218 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3219 (SELECT MAX(transdate) FROM acc_trans)|;
3220 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3222 if ($myconfig->{dateformat} =~ /^yy/) {
3223 ($startdate) = split /\W/, $startdate;
3224 ($enddate) = split /\W/, $enddate;
3226 (@_) = split /\W/, $startdate;
3228 (@_) = split /\W/, $enddate;
3233 $startdate = substr($startdate,0,4);
3234 $enddate = substr($enddate,0,4);
3236 while ($enddate >= $startdate) {
3237 push @all_years, $enddate--;
3242 $main::lxdebug->leave_sub();
3246 $main::lxdebug->enter_sub();
3250 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3252 $main::lxdebug->leave_sub();
3256 $main::lxdebug->enter_sub();
3261 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3263 $main::lxdebug->leave_sub();
3266 sub prepare_for_printing {
3269 my $defaults = SL::DB::Default->get;
3271 $self->{templates} ||= $defaults->templates;
3272 $self->{formname} ||= $self->{type};
3273 $self->{media} ||= 'email';
3275 die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3277 # Several fields that used to reside in %::myconfig (stored in
3278 # auth.user_config) are now stored in defaults. Copy them over for
3280 $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
3282 $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
3284 if (!$self->{employee_id}) {
3285 $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
3286 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
3289 my $language = $self->{language} ? '_' . $self->{language} : '';
3291 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3292 if ($self->{language_id}) {
3293 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3296 $output_dateformat ||= $::myconfig{dateformat};
3297 $output_numberformat ||= $::myconfig{numberformat};
3298 $output_longdates //= 1;
3300 $self->{myconfig_output_dateformat} = $output_dateformat // $::myconfig{dateformat};
3301 $self->{myconfig_output_longdates} = $output_longdates // 1;
3302 $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
3304 # Retrieve accounts for tax calculation.
3305 IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3307 if ($self->{type} =~ /_delivery_order$/) {
3308 DO->order_details(\%::myconfig, $self);
3309 } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3310 OE->order_details(\%::myconfig, $self);
3312 IS->invoice_details(\%::myconfig, $self, $::locale);
3315 # Chose extension & set source file name
3316 my $extension = 'html';
3317 if ($self->{format} eq 'postscript') {
3318 $self->{postscript} = 1;
3320 } elsif ($self->{"format"} =~ /pdf/) {
3322 $extension = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3323 } elsif ($self->{"format"} =~ /opendocument/) {
3324 $self->{opendocument} = 1;
3326 } elsif ($self->{"format"} =~ /excel/) {
3331 my $printer_code = $self->{printer_code} ? '_' . $self->{printer_code} : '';
3332 my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
3333 $self->{IN} = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3336 $self->format_dates($output_dateformat, $output_longdates,
3337 qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate datepaid
3338 transdate_oe deliverydate_oe employee_startdate employee_enddate),
3339 grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3341 $self->reformat_numbers($output_numberformat, 2,
3342 qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3343 grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3345 $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3347 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3349 if (scalar @{ $cvar_date_fields }) {
3350 $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3353 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3354 $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3358 if (($self->{language} // '') ne '') {
3359 my $template_arrays = $self->{TEMPLATE_ARRAYS} || $self;
3360 for my $idx (0..scalar(@{ $template_arrays->{unit} }) - 1) {
3361 $template_arrays->{unit}->[$idx] = AM->translate_units($self, $self->{language}, $template_arrays->{unit}->[$idx], $template_arrays->{qty}->[$idx])
3365 $self->{template_meta} = {
3366 formname => $self->{formname},
3367 language => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
3368 format => $self->{format},
3369 media => $self->{media},
3370 extension => $extension,
3371 printer => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
3372 today => DateTime->today,
3378 sub calculate_arap {
3379 my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
3381 # this function is used to calculate netamount, total_tax and amount for AP and
3382 # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
3384 # Thus it needs a fully prepared $form to work on.
3385 # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
3387 # The calculated total values are all rounded (default is to 2 places) and
3388 # returned as parameters rather than directly modifying form. The aim is to
3389 # make the calculation of AP and AR behave identically. There is a test-case
3390 # for this function in t/form/arap.t
3392 # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
3393 # modified and formatted and receive the correct sign for writing straight to
3394 # acc_trans, depending on whether they are ar or ap.
3397 die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
3398 die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
3399 die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
3400 $roundplaces = 2 unless $roundplaces;
3402 my $sign = 1; # adjust final results for writing amount to acc_trans
3403 $sign = -1 if $buysell eq 'buy';
3405 my ($netamount,$total_tax,$amount);
3409 # parse and round amounts, setting correct sign for writing to acc_trans
3410 for my $i (1 .. $self->{rowcount}) {
3411 $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
3413 $amount += $self->{"amount_$i"} * $sign;
3416 for my $i (1 .. $self->{rowcount}) {
3417 next unless $self->{"amount_$i"};
3418 ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
3419 my $tax_id = $self->{"tax_id_$i"};
3421 my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
3423 if ( $selected_tax ) {
3425 if ( $buysell eq 'sell' ) {
3426 $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3428 $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3431 $self->{"taxkey_$i"} = $selected_tax->taxkey;
3432 $self->{"taxrate_$i"} = $selected_tax->rate;
3435 ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
3437 $netamount += $self->{"amount_$i"};
3438 $total_tax += $self->{"tax_$i"};
3441 $amount = $netamount + $total_tax;
3443 # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
3444 # but reverse sign of totals for writing amounts to ar
3445 if ( $buysell eq 'buy' ) {
3451 return($netamount,$total_tax,$amount);
3455 my ($self, $dateformat, $longformat, @indices) = @_;
3457 $dateformat ||= $::myconfig{dateformat};
3459 foreach my $idx (@indices) {
3460 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3461 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3462 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3466 next unless defined $self->{$idx};
3468 if (!ref($self->{$idx})) {
3469 $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3471 } elsif (ref($self->{$idx}) eq "ARRAY") {
3472 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3473 $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3479 sub reformat_numbers {
3480 my ($self, $numberformat, $places, @indices) = @_;
3482 return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3484 foreach my $idx (@indices) {
3485 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3486 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3487 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3491 next unless defined $self->{$idx};
3493 if (!ref($self->{$idx})) {
3494 $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3496 } elsif (ref($self->{$idx}) eq "ARRAY") {
3497 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3498 $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3503 my $saved_numberformat = $::myconfig{numberformat};
3504 $::myconfig{numberformat} = $numberformat;
3506 foreach my $idx (@indices) {
3507 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3508 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3509 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3513 next unless defined $self->{$idx};
3515 if (!ref($self->{$idx})) {
3516 $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3518 } elsif (ref($self->{$idx}) eq "ARRAY") {
3519 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3520 $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3525 $::myconfig{numberformat} = $saved_numberformat;
3528 sub create_email_signature {
3530 my $client_signature = $::instance_conf->get_signature;
3531 my $user_signature = $::myconfig{signature};
3534 if ( $client_signature or $user_signature ) {
3535 $signature = "\n\n-- \n";
3536 $signature .= $user_signature . "\n" if $user_signature;
3537 $signature .= $client_signature . "\n" if $client_signature;
3544 # this function calculates the net amount and tax for the lines in ar, ap and
3545 # gl and is used for update as well as post. When used with update the return
3546 # value of amount isn't needed
3548 # calculate_tax should always work with positive values, or rather as the user inputs them
3549 # calculate_tax uses db/perl numberformat, i.e. parsed numbers
3550 # convert to negative numbers (when necessary) only when writing to acc_trans
3551 # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
3552 # for post_transaction amount already contains exchangerate and correct sign and is rounded
3553 # calculate_tax doesn't (need to) know anything about exchangerate
3555 my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
3563 # calculate tax (unrounded), subtract from amount, round amount and round tax
3564 $tax = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
3565 $amount = $self->round_amount($amount - $tax, $roundplaces);
3566 $tax = $self->round_amount($tax, $roundplaces);
3568 $tax = $amount * $taxrate;
3569 $tax = $self->round_amount($tax, $roundplaces);
3572 $tax = 0 unless $tax;
3574 return ($amount,$tax);
3583 SL::Form.pm - main data object.
3587 This is the main data object of kivitendo.
3588 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3589 Points of interest for a beginner are:
3591 - $form->error - renders a generic error in html. accepts an error message
3592 - $form->get_standard_dbh - returns a database connection for the
3594 =head1 SPECIAL FUNCTIONS
3596 =head2 C<redirect_header> $url
3598 Generates a HTTP redirection header for the new C<$url>. Constructs an
3599 absolute URL including scheme, host name and port. If C<$url> is a
3600 relative URL then it is considered relative to kivitendo base URL.
3602 This function C<die>s if headers have already been created with
3603 C<$::form-E<gt>header>.
3607 print $::form->redirect_header('oe.pl?action=edit&id=1234');
3608 print $::form->redirect_header('http://www.lx-office.org/');
3612 Generates a general purpose http/html header and includes most of the scripts
3613 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3615 Only one header will be generated. If the method was already called in this
3616 request it will not output anything and return undef. Also if no
3617 HTTP_USER_AGENT is found, no header is generated.
3619 Although header does not accept parameters itself, it will honor special
3620 hashkeys of its Form instance:
3628 If one of these is set, a http-equiv refresh is generated. Missing parameters
3629 default to 3 seconds and the refering url.
3633 Either a scalar or an array ref. Will be inlined into the header. Add
3634 stylesheets with the L<use_stylesheet> function.
3638 If true, a css snippet will be generated that sets the page in landscape mode.
3642 Used to override the default favicon.
3646 A html page title will be generated from this
3648 =item mtime_ischanged
3650 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
3652 Can be used / called with any table, that has itime and mtime attributes.
3653 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
3654 Can be called wit C<option> mail to generate a different error message.
3656 Returns undef if no save operation has been done yet ($self->{id} not present).
3657 Returns undef if no concurrent write process is detected otherwise a error message.