1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
15 # Contributors: Thomas Bayen <bayen@gmx.de>
16 # Antti Kaihola <akaihola@siba.fi>
17 # Moritz Bunkus (tex code)
19 # This program is free software; you can redistribute it and/or modify
20 # it under the terms of the GNU General Public License as published by
21 # the Free Software Foundation; either version 2 of the License, or
22 # (at your option) any later version.
24 # This program is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 # GNU General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, write to the Free Software
30 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
32 #======================================================================
33 # Utilities for parsing forms
34 # and supporting routines for linking account numbers
35 # used in AR, AP and IS, IR modules
37 #======================================================================
52 use POSIX qw(strftime);
64 use SL::DB::PaymentTerm;
67 use SL::Helper::Flash qw();
70 use SL::Layout::Dispatcher;
72 use SL::Locale::String;
75 use SL::MoreCommon qw(uri_encode uri_decode);
77 use SL::PrefixedNumber;
86 use List::Util qw(first max min sum);
87 use List::MoreUtils qw(all any apply);
89 use SL::Helper::File qw(:all);
90 use SL::Helper::Number;
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 '-expires' => '+' . $::auth->{session_timeout} . 'm',
389 '-secure' => $::request->is_https);
393 my %cgi_params = ('-type' => $params{content_type});
394 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
395 $cgi_params{'-cookie'} = $session_cookie if ($session_cookie);
397 map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length status);
399 my $output = $cgi->header(%cgi_params);
401 $main::lxdebug->leave_sub();
407 $::lxdebug->enter_sub;
409 my ($self, %params) = @_;
412 $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
414 if ($params{no_layout}) {
415 $::request->{layout} = SL::Layout::Dispatcher->new(style => 'none');
418 my $layout = $::request->{layout};
420 # standard css for all
421 # this should gradually move to the layouts that need it
422 $layout->use_stylesheet("$_.css") for qw(
423 common main menu list_accounts jquery.autocomplete
424 jquery.multiselect2side
425 ui-lightness/jquery-ui
427 tooltipster themes/tooltipster-light
430 $layout->use_javascript("$_.js") for (qw(
431 jquery jquery-ui jquery.cookie jquery.checkall jquery.download
432 jquery/jquery.form jquery/fixes client_js
433 jquery/jquery.tooltipster.min
434 common part_selection
435 ), "jquery/ui/i18n/jquery.ui.datepicker-$::myconfig{countrycode}");
437 $self->{favicon} ||= "favicon.ico";
438 $self->{titlebar} = join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->read_version if $self->{title} || !$self->{titlebar};
441 if ($self->{refresh_url} || $self->{refresh_time}) {
442 my $refresh_time = $self->{refresh_time} || 3;
443 my $refresh_url = $self->{refresh_url} || $ENV{REFERER};
444 push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
447 my $auto_reload_resources_param = $layout->auto_reload_resources_param;
449 push @header, map { qq|<link rel="stylesheet" href="${_}${auto_reload_resources_param}" type="text/css" title="Stylesheet">| } $layout->stylesheets;
450 push @header, "<style type='text/css'>\@page { size:landscape; }</style> " if $self->{landscape};
451 push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
452 push @header, map { qq|<script type="text/javascript" src="${_}${auto_reload_resources_param}"></script>| } $layout->javascripts;
453 push @header, '<meta name="viewport" content="width=device-width, initial-scale=1">';
454 push @header, $self->{javascript} if $self->{javascript};
455 push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
458 strict => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
459 transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
460 frameset => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
461 html5 => qq|<!DOCTYPE html>|,
465 print $self->create_http_response(content_type => 'text/html', charset => 'UTF-8');
466 print $doctypes{$params{doctype} || 'transitional'}, $/;
470 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
471 <title>$self->{titlebar}</title>
473 print " $_\n" for @header;
475 <meta name="robots" content="noindex,nofollow">
480 print $::request->{layout}->pre_content;
481 print $::request->{layout}->start_content;
483 $layout->header_done;
485 $::lxdebug->leave_sub;
489 return unless $::request->{layout}->need_footer;
491 print $::request->{layout}->end_content;
492 print $::request->{layout}->post_content;
494 if (my @inline_scripts = $::request->{layout}->javascripts_inline) {
495 print "<script type='text/javascript'>" . join("; ", @inline_scripts) . "</script>\n";
504 sub ajax_response_header {
505 $main::lxdebug->enter_sub();
509 my $output = $::request->{cgi}->header('-charset' => 'UTF-8');
511 $main::lxdebug->leave_sub();
516 sub redirect_header {
520 my $base_uri = $self->_get_request_uri;
521 my $new_uri = URI->new_abs($new_url, $base_uri);
523 die "Headers already sent" if $self->{header};
526 return $::request->{cgi}->redirect($new_uri);
529 sub set_standard_title {
530 $::lxdebug->enter_sub;
533 $self->{titlebar} = "kivitendo " . $::locale->text('Version') . " " . $self->read_version;
534 $self->{titlebar} .= "- $::myconfig{name}" if $::myconfig{name};
535 $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
537 $::lxdebug->leave_sub;
540 sub _prepare_html_template {
541 $main::lxdebug->enter_sub();
543 my ($self, $file, $additional_params) = @_;
546 if (!%::myconfig || !$::myconfig{"countrycode"}) {
547 $language = $::lx_office_conf{system}->{language};
549 $language = $main::myconfig{"countrycode"};
551 $language = "de" unless ($language);
553 my $webpages_path = $::request->layout->webpages_path;
555 if (-f "${webpages_path}/${file}.html") {
556 $file = "${webpages_path}/${file}.html";
558 } elsif (ref $file eq 'SCALAR') {
559 # file is a scalarref, use inline mode
561 my $info = "Web page template '${file}' not found.\n";
563 print qq|<pre>$info</pre>|;
564 $::dispatcher->end_request;
567 $additional_params->{AUTH} = $::auth;
568 $additional_params->{INSTANCE_CONF} = $::instance_conf;
569 $additional_params->{LOCALE} = $::locale;
570 $additional_params->{LXCONFIG} = \%::lx_office_conf;
571 $additional_params->{LXDEBUG} = $::lxdebug;
572 $additional_params->{MYCONFIG} = \%::myconfig;
574 $main::lxdebug->leave_sub();
579 sub parse_html_template {
580 $main::lxdebug->enter_sub();
582 my ($self, $file, $additional_params) = @_;
584 $additional_params ||= { };
586 my $real_file = $self->_prepare_html_template($file, $additional_params);
587 my $template = $self->template;
589 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
592 $template->process($real_file, $additional_params, \$output) || die $template->error;
594 $main::lxdebug->leave_sub();
599 sub template { $::request->presenter->get_template }
601 sub show_generic_error {
602 $main::lxdebug->enter_sub();
604 my ($self, $error, %params) = @_;
606 if ($self->{__ERROR_HANDLER}) {
607 $self->{__ERROR_HANDLER}->($error);
608 $main::lxdebug->leave_sub();
612 if ($::request->is_ajax) {
615 ->render(SL::Controller::Base->new);
616 $::dispatcher->end_request;
620 'title_error' => $params{title},
621 'label_error' => $error,
624 $self->{title} = $params{title} if $params{title};
626 for my $bar ($::request->layout->get('actionbar')) {
630 call => [ 'kivi.history_back' ],
631 accesskey => 'enter',
637 print $self->parse_html_template("generic/error", $add_params);
639 print STDERR "Error: $error\n";
641 $main::lxdebug->leave_sub();
643 $::dispatcher->end_request;
646 sub show_generic_information {
647 $main::lxdebug->enter_sub();
649 my ($self, $text, $title) = @_;
652 'title_information' => $title,
653 'label_information' => $text,
656 $self->{title} = $title if ($title);
659 print $self->parse_html_template("generic/information", $add_params);
661 $main::lxdebug->leave_sub();
663 $::dispatcher->end_request;
666 sub _store_redirect_info_in_session {
669 return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
671 my ($controller, $params) = ($1, $2);
672 my $form = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
673 $self->{callback} = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
677 $main::lxdebug->enter_sub();
679 my ($self, $msg) = @_;
681 if (!$self->{callback}) {
685 SL::Helper::Flash::flash_later('info', $msg) if $msg;
686 $self->_store_redirect_info_in_session;
687 print $::form->redirect_header($self->{callback});
690 $::dispatcher->end_request;
692 $main::lxdebug->leave_sub();
695 # sort of columns removed - empty sub
697 $main::lxdebug->enter_sub();
699 my ($self, @columns) = @_;
701 $main::lxdebug->leave_sub();
708 my ($self, $myconfig, $amount, $places, $dash) = @_;
709 SL::Helper::Number::_format_number($amount, $places, %$myconfig, dash => $dash);
713 $main::lxdebug->enter_sub(2);
718 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
719 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
720 $input =~ s/\#\#/\#/g;
722 $main::lxdebug->leave_sub(2);
730 my ($self, $myconfig, $amount) = @_;
731 SL::Helper::Number::_parse_number($amount, %$myconfig);
734 sub round_amount { shift; goto &SL::Helper::Number::_round_number; }
737 $main::lxdebug->enter_sub();
739 my ($self, $myconfig) = @_;
740 my ($out, $out_mode);
744 my $defaults = SL::DB::Default->get;
746 my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
747 $self->{cwd} = getcwd();
748 my $temp_dir = File::Temp->newdir(
749 "kivitendo-print-XXXXXX",
750 DIR => $self->{cwd} . "/" . $::lx_office_conf{paths}->{userspath},
751 CLEANUP => !$keep_temp_files,
754 my $userspath = File::Spec->abs2rel($temp_dir->dirname);
755 $self->{tmpdir} = $temp_dir->dirname;
760 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
761 $template_type = 'OpenDocument';
762 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
764 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
765 $template_type = 'LaTeX';
766 $ext_for_format = 'pdf';
768 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
769 $template_type = 'HTML';
770 $ext_for_format = 'html';
772 } elsif ( $self->{"format"} =~ /excel/i ) {
773 $template_type = 'Excel';
774 $ext_for_format = 'xls';
776 } elsif ( defined $self->{'format'}) {
777 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
779 } elsif ( $self->{'format'} eq '' ) {
780 $self->error("No Outputformat given: $self->{'format'}");
782 } else { #Catch the rest
783 $self->error("Outputformat not defined: $self->{'format'}");
786 my $template = SL::Template::create(type => $template_type,
787 file_name => $self->{IN},
789 myconfig => $myconfig,
790 userspath => $userspath,
791 %{ $self->{TEMPLATE_DRIVER_OPTIONS} || {} });
793 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
794 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" } if exists $self->{ $self->{"formname"} . "notes" };
796 if (!$self->{employee_id}) {
797 $self->{"employee_${_}"} = $myconfig->{$_} for qw(email tel fax name signature);
798 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
801 $self->{"myconfig_${_}"} = $myconfig->{$_} for grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
802 $self->{$_} = $defaults->$_ for qw(co_ustid);
803 $self->{"myconfig_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
804 $self->{AUTH} = $::auth;
805 $self->{INSTANCE_CONF} = $::instance_conf;
806 $self->{LOCALE} = $::locale;
807 $self->{LXCONFIG} = $::lx_office_conf;
808 $self->{LXDEBUG} = $::lxdebug;
809 $self->{MYCONFIG} = \%::myconfig;
811 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
813 # OUT is used for the media, screen, printer, email
814 # for postscript we store a copy in a temporary file
816 my ($temp_fh, $suffix);
817 $suffix = $self->{IN};
819 ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
820 strftime('kivitendo-print-%Y%m%d%H%M%S-XXXXXX', localtime()),
821 SUFFIX => '.' . ($suffix || 'tex'),
823 UNLINK => $keep_temp_files ? 0 : 1,
826 chmod 0644, $self->{tmpfile} if $keep_temp_files;
827 (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
830 $out_mode = $self->{OUT_MODE} || '>';
831 $self->{OUT} = "$self->{tmpfile}";
832 $self->{OUT_MODE} = '>';
835 my $command_formatter = sub {
836 my ($out_mode, $out) = @_;
837 return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
841 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
842 open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
844 *OUT = ($::dispatcher->get_standard_filehandles)[1];
848 if (!$template->parse(*OUT)) {
850 $self->error("$self->{IN} : " . $template->get_error());
853 close OUT if $self->{OUT};
854 # check only one flag (webdav_documents)
855 # therefore copy to webdav, even if we do not have the webdav feature enabled (just archive)
856 my $copy_to_webdav = $::instance_conf->get_webdav_documents && !$self->{preview} && $self->{tmpdir} && $self->{tmpfile} && $self->{type}
857 && $self->{type} ne 'statement';
858 if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
859 $self->append_general_pdf_attachments(filepath => $self->{tmpdir}."/".$self->{tmpfile},
860 type => $self->{type});
862 if ($self->{media} eq 'file') {
863 copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
865 if ($copy_to_webdav) {
866 if (my $error = Common::copy_file_to_webdav_folder($self)) {
867 chdir("$self->{cwd}");
868 $self->error($error);
872 if (!$self->{preview} && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled)
874 $self->{attachment_filename} ||= $self->generate_attachment_filename;
875 $self->store_pdf($self);
878 chdir("$self->{cwd}");
880 $::lxdebug->leave_sub();
885 if ($copy_to_webdav) {
886 if (my $error = Common::copy_file_to_webdav_folder($self)) {
887 chdir("$self->{cwd}");
888 $self->error($error);
892 if ( !$self->{preview} && $ext_for_format eq 'pdf' && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled) {
893 $self->{attachment_filename} ||= $self->generate_attachment_filename;
894 my $file_obj = $self->store_pdf($self);
895 $self->{print_file_id} = $file_obj->id if $file_obj;
897 if ($self->{media} eq 'email') {
898 if ( getcwd() eq $self->{"tmpdir"} ) {
899 # in the case of generating pdf we are in the tmpdir, but WHY ???
900 $self->{tmpfile} = $userspath."/".$self->{tmpfile};
901 chdir("$self->{cwd}");
903 $self->send_email(\%::myconfig,$ext_for_format);
907 $self->{OUT_MODE} = $out_mode;
908 $self->output_file($template->get_mime_type,$command_formatter);
910 delete $self->{print_file_id};
914 chdir("$self->{cwd}");
915 $main::lxdebug->leave_sub();
918 sub get_bcc_defaults {
919 my ($self, $myconfig, $mybcc) = @_;
920 if (SL::DB::Default->get->bcc_to_login) {
921 $mybcc .= ", " if $mybcc;
922 $mybcc .= $myconfig->{email};
924 my $otherbcc = SL::DB::Default->get->global_bcc;
926 $mybcc .= ", " if $mybcc;
933 $main::lxdebug->enter_sub();
934 my ($self, $myconfig, $ext_for_format) = @_;
935 my $mail = Mailer->new;
937 map { $mail->{$_} = $self->{$_} }
938 qw(cc subject message format);
940 if ($self->{cc_employee}) {
941 my ($user, $my_emp_cc);
942 $user = SL::DB::Manager::AuthUser->find_by(login => $self->{cc_employee});
943 $my_emp_cc = $user->get_config_value('email') if ref $user eq 'SL::DB::AuthUser';
944 $mail->{cc} .= ", " if $mail->{cc};
945 $mail->{cc} .= $my_emp_cc if $my_emp_cc;
948 $mail->{bcc} = $self->get_bcc_defaults($myconfig, $self->{bcc});
949 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
950 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
951 $mail->{fileid} = time() . '.' . $$ . '.';
952 my $full_signature = $self->create_email_signature();
953 $full_signature =~ s/\r//g;
955 $mail->{attachments} = [];
957 # if we send html or plain text inline
958 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
959 $mail->{content_type} = "text/html";
960 $mail->{message} =~ s/\r//g;
961 $mail->{message} =~ s{\n}{<br>\n}g;
962 $full_signature =~ s{\n}{<br>\n}g;
963 $mail->{message} .= $full_signature;
965 open(IN, "<", $self->{tmpfile})
966 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
967 $mail->{message} .= $_ while <IN>;
970 } elsif (($self->{attachment_policy} // '') ne 'no_file') {
971 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
972 $attachment_name =~ s{\.(.+?)$}{.${ext_for_format}} if ($ext_for_format);
974 if (($self->{attachment_policy} // '') eq 'old_file') {
975 my ( $attfile ) = SL::File->get_all(object_id => $self->{id},
976 object_type => $self->{formname},
977 file_type => 'document');
980 $attfile->{override_file_name} = $attachment_name if $attachment_name;
981 push @attfiles, $attfile;
985 push @{ $mail->{attachments} }, { path => $self->{tmpfile},
986 id => $self->{print_file_id},
987 type => "application/pdf",
988 name => $attachment_name };
994 map { SL::File->get(id => $_) }
995 @{ $self->{attach_file_ids} // [] };
997 foreach my $attfile ( @attfiles ) {
998 push @{ $mail->{attachments} }, {
999 path => $attfile->get_file,
1001 type => $attfile->mime_type,
1002 name => $attfile->{override_file_name} // $attfile->file_name,
1003 content => $attfile->get_content ? ${ $attfile->get_content } : undef,
1007 $mail->{message} =~ s/\r//g;
1008 $mail->{message} .= $full_signature;
1009 $self->{emailerr} = $mail->send();
1011 if ($self->{emailerr}) {
1013 $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
1016 $self->{email_journal_id} = $mail->{journalentry};
1017 $self->{snumbers} = "emailjournal" . "_" . $self->{email_journal_id};
1018 $self->{what_done} = $::form->{type};
1019 $self->{addition} = "MAILED";
1020 $self->save_history;
1022 #write back for message info and mail journal
1023 $self->{cc} = $mail->{cc};
1024 $self->{bcc} = $mail->{bcc};
1025 $self->{email} = $mail->{to};
1027 $main::lxdebug->leave_sub();
1031 $main::lxdebug->enter_sub();
1033 my ($self,$mimeType,$command_formatter) = @_;
1034 my $numbytes = (-s $self->{tmpfile});
1035 open(IN, "<", $self->{tmpfile})
1036 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1039 $self->{copies} = 1 unless $self->{media} eq 'printer';
1041 chdir("$self->{cwd}");
1042 for my $i (1 .. $self->{copies}) {
1044 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1046 open OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1047 print OUT $_ while <IN>;
1052 my %headers = ('-type' => $mimeType,
1053 '-connection' => 'close',
1054 '-charset' => 'UTF-8');
1056 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1058 if ($self->{attachment_filename}) {
1061 '-attachment' => $self->{attachment_filename},
1062 '-content-length' => $numbytes,
1067 print $::request->cgi->header(%headers);
1069 $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1073 $main::lxdebug->leave_sub();
1076 sub get_formname_translation {
1077 $main::lxdebug->enter_sub();
1078 my ($self, $formname) = @_;
1080 $formname ||= $self->{formname};
1082 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1083 local $::locale = Locale->new($self->{recipient_locale});
1085 my %formname_translations = (
1086 bin_list => $main::locale->text('Bin List'),
1087 credit_note => $main::locale->text('Credit Note'),
1088 invoice => $main::locale->text('Invoice'),
1089 invoice_copy => $main::locale->text('Invoice Copy'),
1090 pick_list => $main::locale->text('Pick List'),
1091 proforma => $main::locale->text('Proforma Invoice'),
1092 purchase_order => $main::locale->text('Purchase Order'),
1093 request_quotation => $main::locale->text('RFQ'),
1094 sales_order => $main::locale->text('Confirmation'),
1095 sales_quotation => $main::locale->text('Quotation'),
1096 storno_invoice => $main::locale->text('Storno Invoice'),
1097 sales_delivery_order => $main::locale->text('Delivery Order'),
1098 purchase_delivery_order => $main::locale->text('Delivery Order'),
1099 dunning => $main::locale->text('Dunning'),
1100 dunning1 => $main::locale->text('Payment Reminder'),
1101 dunning2 => $main::locale->text('Dunning'),
1102 dunning3 => $main::locale->text('Last Dunning'),
1103 dunning_invoice => $main::locale->text('Dunning Invoice'),
1104 letter => $main::locale->text('Letter'),
1105 ic_supply => $main::locale->text('Intra-Community supply'),
1106 statement => $main::locale->text('Statement'),
1109 $main::lxdebug->leave_sub();
1110 return $formname_translations{$formname};
1113 sub get_cusordnumber_translation {
1114 $main::lxdebug->enter_sub();
1115 my ($self, $formname) = @_;
1117 $formname ||= $self->{formname};
1119 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1120 local $::locale = Locale->new($self->{recipient_locale});
1123 $main::lxdebug->leave_sub();
1124 return $main::locale->text('Your Order');
1127 sub get_number_prefix_for_type {
1128 $main::lxdebug->enter_sub();
1132 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1133 : ($self->{type} =~ /_quotation$/) ? 'quo'
1134 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1135 : ($self->{type} =~ /letter/) ? 'letter'
1138 # better default like this?
1139 # : ($self->{type} =~ /(sales|purcharse)_order/ : 'ord';
1140 # : 'prefix_undefined';
1142 $main::lxdebug->leave_sub();
1146 sub get_extension_for_format {
1147 $main::lxdebug->enter_sub();
1150 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1151 : $self->{format} =~ /postscript/i ? ".ps"
1152 : $self->{format} =~ /opendocument/i ? ".odt"
1153 : $self->{format} =~ /excel/i ? ".xls"
1154 : $self->{format} =~ /html/i ? ".html"
1157 $main::lxdebug->leave_sub();
1161 sub generate_attachment_filename {
1162 $main::lxdebug->enter_sub();
1165 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1166 my $recipient_locale = Locale->new($self->{recipient_locale});
1168 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1169 my $prefix = $self->get_number_prefix_for_type();
1171 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1172 $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
1174 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1175 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1177 } elsif ($attachment_filename) {
1178 $attachment_filename .= $self->get_extension_for_format();
1181 $attachment_filename = "";
1184 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1185 $attachment_filename =~ s|[\s/\\]+|_|g;
1187 $main::lxdebug->leave_sub();
1188 return $attachment_filename;
1191 sub generate_email_subject {
1192 $main::lxdebug->enter_sub();
1195 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1196 my $prefix = $self->get_number_prefix_for_type();
1198 if ($subject && $self->{"${prefix}number"}) {
1199 $subject .= " " . $self->{"${prefix}number"}
1202 if ($self->{cusordnumber}) {
1203 $subject = $self->get_cusordnumber_translation() . ' ' . $self->{cusordnumber} . ' / ' . $subject;
1206 $main::lxdebug->leave_sub();
1210 sub generate_email_body {
1211 $main::lxdebug->enter_sub();
1212 my ($self, %params) = @_;
1213 # simple german and english will work grammatically (most european languages as well)
1214 # Dear Mr Alan Greenspan:
1215 # Sehr geehrte Frau Meyer,
1216 # A l’attention de Mme Villeroy,
1217 # Gentile Signora Ferrari,
1220 if ($self->{cp_id} && !$params{record_email}) {
1221 my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
1222 my $name = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
1223 my $gender = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
1224 my $mf = $gender eq 'f' ? 'female' : 'male';
1225 $body = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
1226 $body .= ' ' . $givenname . ' ' . $name if $body;
1228 $body = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
1231 return undef unless $body;
1233 my $translation_type = $params{translation_type} // "preset_text_$self->{formname}";
1234 my $main_body = GenericTranslations->get(translation_type => $translation_type, language_id => $self->{language_id});
1235 $main_body = GenericTranslations->get(translation_type => $params{fallback_translation_type}, language_id => $self->{language_id}) if !$main_body && $params{fallback_translation_type};
1236 $body .= GenericTranslations->get(translation_type => "salutation_punctuation_mark", language_id => $self->{language_id}) . "\n\n";
1237 $body .= $main_body;
1239 $body = $main::locale->unquote_special_chars('HTML', $body);
1241 $main::lxdebug->leave_sub();
1246 $main::lxdebug->enter_sub();
1248 my ($self, $application) = @_;
1250 my $error_code = $?;
1252 chdir("$self->{tmpdir}");
1255 if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1256 push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1258 } elsif (-f "$self->{tmpfile}.err") {
1259 open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
1264 if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1265 $self->{tmpfile} =~ s|.*/||g;
1267 $self->{tmpfile} =~ s/\.\w+$//g;
1268 my $tmpfile = $self->{tmpfile};
1269 unlink(<$tmpfile.*>);
1272 chdir("$self->{cwd}");
1274 $main::lxdebug->leave_sub();
1280 $main::lxdebug->enter_sub();
1282 my ($self, $date, $myconfig) = @_;
1285 if ($date && $date =~ /\D/) {
1287 if ($myconfig->{dateformat} =~ /^yy/) {
1288 ($yy, $mm, $dd) = split /\D/, $date;
1290 if ($myconfig->{dateformat} =~ /^mm/) {
1291 ($mm, $dd, $yy) = split /\D/, $date;
1293 if ($myconfig->{dateformat} =~ /^dd/) {
1294 ($dd, $mm, $yy) = split /\D/, $date;
1299 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1300 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1302 $dd = "0$dd" if ($dd < 10);
1303 $mm = "0$mm" if ($mm < 10);
1305 $date = "$yy$mm$dd";
1308 $main::lxdebug->leave_sub();
1313 # Database routines used throughout
1314 # DB Handling got moved to SL::DB, these are only shims for compatibility
1317 SL::DB->client->dbh;
1320 sub get_standard_dbh {
1321 my $dbh = SL::DB->client->dbh;
1323 if ($dbh && !$dbh->{Active}) {
1324 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
1325 SL::DB->client->dbh(undef);
1328 SL::DB->client->dbh;
1331 sub disconnect_standard_dbh {
1332 SL::DB->client->dbh->rollback;
1338 $main::lxdebug->enter_sub();
1340 my ($self, $date, $myconfig) = @_;
1341 my $dbh = $self->get_standard_dbh;
1343 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1344 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1346 # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1347 # es ist sicher ein conv_date vorher IMMER auszuführen.
1348 # Testfälle ohne definiertes closedto:
1349 # Leere Datumseingabe i.O.
1350 # SELECT 1 FROM defaults WHERE '' < closedto
1351 # normale Zahlungsbuchung über Rechnungsmaske i.O.
1352 # SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1353 # Testfälle mit definiertem closedto (30.04.2011):
1354 # Leere Datumseingabe i.O.
1355 # SELECT 1 FROM defaults WHERE '' < closedto
1356 # normale Buchung im geschloßenem Zeitraum i.O.
1357 # SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1358 # Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1359 # normale Buchung in aktiver Buchungsperiode i.O.
1360 # SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1362 my ($closed) = $sth->fetchrow_array;
1364 $main::lxdebug->leave_sub();
1369 # prevents bookings to the to far away future
1370 sub date_max_future {
1371 $main::lxdebug->enter_sub();
1373 my ($self, $date, $myconfig) = @_;
1374 my $dbh = $self->get_standard_dbh;
1376 my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
1377 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1379 my ($max_future_booking_interval) = $sth->fetchrow_array;
1381 $main::lxdebug->leave_sub();
1383 return $max_future_booking_interval;
1387 sub update_balance {
1388 $main::lxdebug->enter_sub();
1390 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1392 # if we have a value, go do it
1395 # retrieve balance from table
1396 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1397 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1398 my ($balance) = $sth->fetchrow_array;
1404 $query = "UPDATE $table SET $field = $balance WHERE $where";
1405 do_query($self, $dbh, $query, @values);
1407 $main::lxdebug->leave_sub();
1410 sub update_exchangerate {
1411 $main::lxdebug->enter_sub();
1413 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1415 # some sanity check for currency
1417 $main::lxdebug->leave_sub();
1420 $query = qq|SELECT name AS curr FROM currencies WHERE id=(SELECT currency_id FROM defaults)|;
1422 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1424 if ($curr eq $defaultcurrency) {
1425 $main::lxdebug->leave_sub();
1429 $query = qq|SELECT e.currency_id FROM exchangerate e
1430 WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
1432 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1441 $buy = conv_i($buy, "NULL");
1442 $sell = conv_i($sell, "NULL");
1445 if ($buy != 0 && $sell != 0) {
1446 $set = "buy = $buy, sell = $sell";
1447 } elsif ($buy != 0) {
1448 $set = "buy = $buy";
1449 } elsif ($sell != 0) {
1450 $set = "sell = $sell";
1453 if ($sth->fetchrow_array) {
1454 $query = qq|UPDATE exchangerate
1456 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
1460 $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
1461 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
1464 do_query($self, $dbh, $query, $curr, $transdate);
1466 $main::lxdebug->leave_sub();
1469 sub save_exchangerate {
1470 $main::lxdebug->enter_sub();
1472 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1474 SL::DB->client->with_transaction(sub {
1475 my $dbh = SL::DB->client->dbh;
1479 $buy = $rate if $fld eq 'buy';
1480 $sell = $rate if $fld eq 'sell';
1483 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1485 }) or do { die SL::DB->client->error };
1487 $main::lxdebug->leave_sub();
1490 sub get_exchangerate {
1491 $main::lxdebug->enter_sub();
1493 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1496 unless ($transdate && $curr) {
1497 $main::lxdebug->leave_sub();
1501 $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1503 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1505 if ($curr eq $defaultcurrency) {
1506 $main::lxdebug->leave_sub();
1510 $query = qq|SELECT e.$fld FROM exchangerate e
1511 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1512 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1516 $main::lxdebug->leave_sub();
1518 return $exchangerate;
1521 sub check_exchangerate {
1522 $main::lxdebug->enter_sub();
1524 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1526 if ($fld !~/^buy|sell$/) {
1527 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1530 unless ($transdate) {
1531 $main::lxdebug->leave_sub();
1535 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1537 if ($currency eq $defaultcurrency) {
1538 $main::lxdebug->leave_sub();
1542 my $dbh = $self->get_standard_dbh($myconfig);
1543 my $query = qq|SELECT e.$fld FROM exchangerate e
1544 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1546 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1548 $main::lxdebug->leave_sub();
1550 return $exchangerate;
1553 sub get_all_currencies {
1554 $main::lxdebug->enter_sub();
1557 my $myconfig = shift || \%::myconfig;
1558 my $dbh = $self->get_standard_dbh($myconfig);
1560 my $query = qq|SELECT name FROM currencies|;
1561 my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
1563 $main::lxdebug->leave_sub();
1568 sub get_default_currency {
1569 $main::lxdebug->enter_sub();
1571 my ($self, $myconfig) = @_;
1572 my $dbh = $self->get_standard_dbh($myconfig);
1573 my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1575 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1577 $main::lxdebug->leave_sub();
1579 return $defaultcurrency;
1582 sub set_payment_options {
1583 my ($self, $myconfig, $transdate, $type) = @_;
1585 my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
1588 my $is_invoice = $type =~ m{invoice}i;
1590 $transdate ||= $self->{invdate} || $self->{transdate};
1591 my $due_date = $self->{duedate} || $self->{reqdate};
1593 $self->{$_} = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
1594 $self->{payment_description} = $terms->description;
1595 $self->{netto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
1596 $self->{skonto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
1598 my ($invtotal, $total);
1599 my (%amounts, %formatted_amounts);
1601 if ($self->{type} =~ /_order$/) {
1602 $amounts{invtotal} = $self->{ordtotal};
1603 $amounts{total} = $self->{ordtotal};
1605 } elsif ($self->{type} =~ /_quotation$/) {
1606 $amounts{invtotal} = $self->{quototal};
1607 $amounts{total} = $self->{quototal};
1610 $amounts{invtotal} = $self->{invtotal};
1611 $amounts{total} = $self->{total};
1613 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1615 $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1616 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1617 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1618 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1620 foreach (keys %amounts) {
1621 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1622 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1625 if ($self->{"language_id"}) {
1626 my $language = SL::DB::Language->new(id => $self->{language_id})->load;
1628 $self->{payment_terms} = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
1629 $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
1631 if ($language->output_dateformat) {
1632 foreach my $key (qw(netto_date skonto_date)) {
1633 $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
1637 if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
1638 local $myconfig->{numberformat};
1639 $myconfig->{"numberformat"} = $language->output_numberformat;
1640 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
1644 $self->{payment_terms} = $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
1646 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1647 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1648 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1649 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1650 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1651 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1652 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1653 $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
1654 $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
1655 $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
1656 $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
1658 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1660 $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1664 sub get_template_language {
1665 $main::lxdebug->enter_sub();
1667 my ($self, $myconfig) = @_;
1669 my $template_code = "";
1671 if ($self->{language_id}) {
1672 my $dbh = $self->get_standard_dbh($myconfig);
1673 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1674 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1677 $main::lxdebug->leave_sub();
1679 return $template_code;
1682 sub get_printer_code {
1683 $main::lxdebug->enter_sub();
1685 my ($self, $myconfig) = @_;
1687 my $template_code = "";
1689 if ($self->{printer_id}) {
1690 my $dbh = $self->get_standard_dbh($myconfig);
1691 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1692 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1695 $main::lxdebug->leave_sub();
1697 return $template_code;
1701 $main::lxdebug->enter_sub();
1703 my ($self, $myconfig) = @_;
1705 my $template_code = "";
1707 if ($self->{shipto_id}) {
1708 my $dbh = $self->get_standard_dbh($myconfig);
1709 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1710 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1711 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1713 my $cvars = CVar->get_custom_variables(
1716 trans_id => $self->{shipto_id},
1718 $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
1721 $main::lxdebug->leave_sub();
1725 my ($self, $dbh, $id, $module) = @_;
1730 foreach my $item (qw(name department_1 department_2 street zipcode city country gln
1731 contact phone fax email)) {
1732 if ($self->{"shipto$item"}) {
1733 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1735 push(@values, $self->{"shipto${item}"});
1740 # shiptocp_gender only makes sense, if any other shipto attribute is set.
1741 # Because shiptocp_gender is set to 'm' by default in forms
1742 # it must not be considered above to decide if shiptos has to be added or
1743 # updated, but must be inserted or updated as well in case.
1744 push(@values, $self->{shiptocp_gender});
1746 my $shipto_id = $self->{shipto_id};
1748 if ($self->{shipto_id}) {
1749 my $query = qq|UPDATE shipto set
1751 shiptodepartment_1 = ?,
1752 shiptodepartment_2 = ?,
1762 shiptocp_gender = ?,
1763 WHERE shipto_id = ?|;
1764 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1766 my $query = qq|SELECT * FROM shipto
1767 WHERE shiptoname = ? AND
1768 shiptodepartment_1 = ? AND
1769 shiptodepartment_2 = ? AND
1770 shiptostreet = ? AND
1771 shiptozipcode = ? AND
1773 shiptocountry = ? AND
1775 shiptocontact = ? AND
1779 shiptocp_gender = ? AND
1782 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1785 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1786 shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
1787 shiptocontact, shiptophone, shiptofax, shiptoemail, shiptocp_gender, module)
1788 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1789 do_query($self, $dbh, $insert_query, $id, @values, $module);
1791 $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1794 $shipto_id = $insert_check->{shipto_id};
1797 return unless $shipto_id;
1799 CVar->save_custom_variables(
1802 trans_id => $shipto_id,
1804 name_prefix => 'shipto',
1809 $main::lxdebug->enter_sub();
1811 my ($self, $dbh) = @_;
1813 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1815 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1816 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1817 $self->{"employee_id"} *= 1;
1819 $main::lxdebug->leave_sub();
1822 sub get_employee_data {
1823 $main::lxdebug->enter_sub();
1827 my $defaults = SL::DB::Default->get;
1829 Common::check_params(\%params, qw(prefix));
1830 Common::check_params_x(\%params, qw(id));
1833 $main::lxdebug->leave_sub();
1837 my $myconfig = \%main::myconfig;
1838 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
1840 my ($login, $deleted) = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
1843 # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
1844 $self->{$params{prefix} . '_login'} = $login;
1845 $self->{$params{prefix} . "_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
1848 # get employee data from auth.user_config
1849 my $user = User->new(login => $login);
1850 $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
1852 # get saved employee data from employee
1853 my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
1854 $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
1855 $self->{$params{prefix} . "_name"} = $employee->name;
1858 $main::lxdebug->leave_sub();
1862 $main::lxdebug->enter_sub();
1864 my ($self, $dbh, $id, $key) = @_;
1866 $key = "all_contacts" unless ($key);
1870 $main::lxdebug->leave_sub();
1875 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1876 qq|FROM contacts | .
1877 qq|WHERE cp_cv_id = ? | .
1878 qq|ORDER BY lower(cp_name)|;
1880 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1882 $main::lxdebug->leave_sub();
1886 $main::lxdebug->enter_sub();
1888 my ($self, $dbh, $key) = @_;
1890 my ($all, $old_id, $where, @values);
1892 if (ref($key) eq "HASH") {
1895 $key = "ALL_PROJECTS";
1897 foreach my $p (keys(%{$params})) {
1899 $all = $params->{$p};
1900 } elsif ($p eq "old_id") {
1901 $old_id = $params->{$p};
1902 } elsif ($p eq "key") {
1903 $key = $params->{$p};
1909 $where = "WHERE active ";
1911 if (ref($old_id) eq "ARRAY") {
1912 my @ids = grep({ $_ } @{$old_id});
1914 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1915 push(@values, @ids);
1918 $where .= " OR (id = ?) ";
1919 push(@values, $old_id);
1925 qq|SELECT id, projectnumber, description, active | .
1928 qq|ORDER BY lower(projectnumber)|;
1930 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1932 $main::lxdebug->leave_sub();
1936 $main::lxdebug->enter_sub();
1938 my ($self, $dbh, $key) = @_;
1940 $key = "all_printers" unless ($key);
1942 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1944 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1946 $main::lxdebug->leave_sub();
1950 $main::lxdebug->enter_sub();
1952 my ($self, $dbh, $params) = @_;
1955 $key = $params->{key};
1956 $key = "all_charts" unless ($key);
1958 my $transdate = quote_db_date($params->{transdate});
1961 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
1963 qq|LEFT JOIN taxkeys tk ON | .
1964 qq|(tk.id = (SELECT id FROM taxkeys | .
1965 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1966 qq| ORDER BY startdate DESC LIMIT 1)) | .
1967 qq|ORDER BY c.accno|;
1969 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1971 $main::lxdebug->leave_sub();
1975 $main::lxdebug->enter_sub();
1977 my ($self, $dbh, $key) = @_;
1979 $key = "all_taxzones" unless ($key);
1981 $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
1983 my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
1985 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1987 $main::lxdebug->leave_sub();
1990 sub _get_employees {
1991 $main::lxdebug->enter_sub();
1993 my ($self, $dbh, $params) = @_;
1998 if (ref $params eq 'HASH') {
1999 $key = $params->{key};
2000 $deleted = $params->{deleted};
2006 $key ||= "all_employees";
2007 my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
2008 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
2010 $main::lxdebug->leave_sub();
2013 sub _get_business_types {
2014 $main::lxdebug->enter_sub();
2016 my ($self, $dbh, $key) = @_;
2018 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2019 $options->{key} ||= "all_business_types";
2022 if (exists $options->{salesman}) {
2023 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2026 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2028 $main::lxdebug->leave_sub();
2031 sub _get_languages {
2032 $main::lxdebug->enter_sub();
2034 my ($self, $dbh, $key) = @_;
2036 $key = "all_languages" unless ($key);
2038 my $query = qq|SELECT * FROM language ORDER BY id|;
2040 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2042 $main::lxdebug->leave_sub();
2045 sub _get_dunning_configs {
2046 $main::lxdebug->enter_sub();
2048 my ($self, $dbh, $key) = @_;
2050 $key = "all_dunning_configs" unless ($key);
2052 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2054 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2056 $main::lxdebug->leave_sub();
2059 sub _get_currencies {
2060 $main::lxdebug->enter_sub();
2062 my ($self, $dbh, $key) = @_;
2064 $key = "all_currencies" unless ($key);
2066 $self->{$key} = [$self->get_all_currencies()];
2068 $main::lxdebug->leave_sub();
2072 $main::lxdebug->enter_sub();
2074 my ($self, $dbh, $key) = @_;
2076 $key = "all_payments" unless ($key);
2078 my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2080 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2082 $main::lxdebug->leave_sub();
2085 sub _get_customers {
2086 $main::lxdebug->enter_sub();
2088 my ($self, $dbh, $key) = @_;
2090 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2091 $options->{key} ||= "all_customers";
2092 my $limit_clause = $options->{limit} ? "LIMIT $options->{limit}" : '';
2095 push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman};
2096 push @where, qq|NOT obsolete| if !$options->{with_obsolete};
2097 my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2099 my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2100 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2102 $main::lxdebug->leave_sub();
2106 $main::lxdebug->enter_sub();
2108 my ($self, $dbh, $key) = @_;
2110 $key = "all_vendors" unless ($key);
2112 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2114 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2116 $main::lxdebug->leave_sub();
2119 sub _get_departments {
2120 $main::lxdebug->enter_sub();
2122 my ($self, $dbh, $key) = @_;
2124 $key = "all_departments" unless ($key);
2126 my $query = qq|SELECT * FROM department ORDER BY description|;
2128 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2130 $main::lxdebug->leave_sub();
2133 sub _get_warehouses {
2134 $main::lxdebug->enter_sub();
2136 my ($self, $dbh, $param) = @_;
2138 my ($key, $bins_key);
2140 if ('' eq ref $param) {
2144 $key = $param->{key};
2145 $bins_key = $param->{bins};
2148 my $query = qq|SELECT w.* FROM warehouse w
2149 WHERE (NOT w.invalid) AND
2150 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2151 ORDER BY w.sortkey|;
2153 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2156 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2157 ORDER BY description|;
2158 my $sth = prepare_query($self, $dbh, $query);
2160 foreach my $warehouse (@{ $self->{$key} }) {
2161 do_statement($self, $sth, $query, $warehouse->{id});
2162 $warehouse->{$bins_key} = [];
2164 while (my $ref = $sth->fetchrow_hashref()) {
2165 push @{ $warehouse->{$bins_key} }, $ref;
2171 $main::lxdebug->leave_sub();
2175 $main::lxdebug->enter_sub();
2177 my ($self, $dbh, $table, $key, $sortkey) = @_;
2179 my $query = qq|SELECT * FROM $table|;
2180 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2182 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2184 $main::lxdebug->leave_sub();
2188 $main::lxdebug->enter_sub();
2193 croak "get_lists: shipto is no longer supported" if $params{shipto};
2195 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2196 my ($sth, $query, $ref);
2199 if ($params{contacts}) {
2200 $vc = 'customer' if $self->{"vc"} eq "customer";
2201 $vc = 'vendor' if $self->{"vc"} eq "vendor";
2202 die "invalid use of get_lists, need 'vc'" unless $vc;
2203 $vc_id = $self->{"${vc}_id"};
2206 if ($params{"contacts"}) {
2207 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2210 if ($params{"projects"} || $params{"all_projects"}) {
2211 $self->_get_projects($dbh, $params{"all_projects"} ?
2212 $params{"all_projects"} : $params{"projects"},
2213 $params{"all_projects"} ? 1 : 0);
2216 if ($params{"printers"}) {
2217 $self->_get_printers($dbh, $params{"printers"});
2220 if ($params{"languages"}) {
2221 $self->_get_languages($dbh, $params{"languages"});
2224 if ($params{"charts"}) {
2225 $self->_get_charts($dbh, $params{"charts"});
2228 if ($params{"taxzones"}) {
2229 $self->_get_taxzones($dbh, $params{"taxzones"});
2232 if ($params{"employees"}) {
2233 $self->_get_employees($dbh, $params{"employees"});
2236 if ($params{"salesmen"}) {
2237 $self->_get_employees($dbh, $params{"salesmen"});
2240 if ($params{"business_types"}) {
2241 $self->_get_business_types($dbh, $params{"business_types"});
2244 if ($params{"dunning_configs"}) {
2245 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2248 if($params{"currencies"}) {
2249 $self->_get_currencies($dbh, $params{"currencies"});
2252 if($params{"customers"}) {
2253 $self->_get_customers($dbh, $params{"customers"});
2256 if($params{"vendors"}) {
2257 if (ref $params{"vendors"} eq 'HASH') {
2258 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2260 $self->_get_vendors($dbh, $params{"vendors"});
2264 if($params{"payments"}) {
2265 $self->_get_payments($dbh, $params{"payments"});
2268 if($params{"departments"}) {
2269 $self->_get_departments($dbh, $params{"departments"});
2272 if ($params{price_factors}) {
2273 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2276 if ($params{warehouses}) {
2277 $self->_get_warehouses($dbh, $params{warehouses});
2280 if ($params{partsgroup}) {
2281 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2284 $main::lxdebug->leave_sub();
2287 # this sub gets the id and name from $table
2289 $main::lxdebug->enter_sub();
2291 my ($self, $myconfig, $table) = @_;
2293 # connect to database
2294 my $dbh = $self->get_standard_dbh($myconfig);
2296 $table = $table eq "customer" ? "customer" : "vendor";
2297 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2299 my ($query, @values);
2301 if (!$self->{openinvoices}) {
2303 if ($self->{customernumber} ne "") {
2304 $where = qq|(vc.customernumber ILIKE ?)|;
2305 push(@values, like($self->{customernumber}));
2307 $where = qq|(vc.name ILIKE ?)|;
2308 push(@values, like($self->{$table}));
2312 qq~SELECT vc.id, vc.name,
2313 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2315 WHERE $where AND (NOT vc.obsolete)
2319 qq~SELECT DISTINCT vc.id, vc.name,
2320 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2322 JOIN $table vc ON (a.${table}_id = vc.id)
2323 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2325 push(@values, like($self->{$table}));
2328 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2330 $main::lxdebug->leave_sub();
2332 return scalar(@{ $self->{name_list} });
2337 my ($self, $table, $provided_dbh) = @_;
2339 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
2340 return unless $self->{id};
2341 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2343 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2344 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2345 $ref->{mtime} ||= $ref->{itime};
2346 $self->{lastmtime} = $ref->{mtime};
2350 sub mtime_ischanged {
2351 my ($self, $table, $option) = @_;
2353 return unless $self->{id};
2354 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2356 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2357 my $ref = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
2358 $ref->{mtime} ||= $ref->{itime};
2360 if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
2361 $self->error(($option eq 'mail') ?
2362 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") :
2363 t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
2365 $::dispatcher->end_request;
2369 # language_payment duplicates some of the functionality of all_vc (language,
2370 # printer, payment_terms), and at least in the case of sales invoices both
2371 # all_vc and language_payment are called when adding new invoices
2372 sub language_payment {
2373 $main::lxdebug->enter_sub();
2375 my ($self, $myconfig) = @_;
2377 my $dbh = $self->get_standard_dbh($myconfig);
2379 my $query = qq|SELECT id, description
2383 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2386 $query = qq|SELECT printer_description, id
2388 ORDER BY printer_description|;
2390 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2393 $query = qq|SELECT id, description
2395 WHERE ( obsolete IS FALSE OR id = ? )
2397 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
2399 # get buchungsgruppen
2400 $query = qq|SELECT id, description
2401 FROM buchungsgruppen|;
2403 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2405 $main::lxdebug->leave_sub();
2408 # this is only used for reports
2409 sub all_departments {
2410 $main::lxdebug->enter_sub();
2412 my ($self, $myconfig, $table) = @_;
2414 my $dbh = $self->get_standard_dbh($myconfig);
2416 my $query = qq|SELECT id, description
2418 ORDER BY description|;
2419 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2421 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2423 $main::lxdebug->leave_sub();
2427 $main::lxdebug->enter_sub();
2429 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2432 if ($table eq "customer") {
2441 # get last customers or vendors
2442 my ($query, $sth, $ref);
2444 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2449 my $transdate = "current_date";
2450 if ($self->{transdate}) {
2451 $transdate = $dbh->quote($self->{transdate});
2454 # now get the account numbers
2456 SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
2458 -- find newest entries in taxkeys
2460 SELECT chart_id, MAX(startdate) AS startdate
2462 WHERE (startdate <= $transdate)
2464 ) tk ON (c.id = tk.chart_id)
2465 -- and load all of those entries
2466 INNER JOIN taxkeys tk2
2467 ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
2468 WHERE (c.link LIKE ?)
2471 $sth = $dbh->prepare($query);
2473 do_statement($self, $sth, $query, like($module));
2475 $self->{accounts} = "";
2476 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2478 foreach my $key (split(/:/, $ref->{link})) {
2479 if ($key =~ /\Q$module\E/) {
2481 # cross reference for keys
2482 $xkeyref{ $ref->{accno} } = $key;
2484 push @{ $self->{"${module}_links"}{$key} },
2485 { accno => $ref->{accno},
2486 chart_id => $ref->{chart_id},
2487 description => $ref->{description},
2488 taxkey => $ref->{taxkey_id},
2489 tax_id => $ref->{tax_id} };
2491 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2497 # get taxkeys and description
2498 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2499 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2501 if (($module eq "AP") || ($module eq "AR")) {
2502 # get tax rates and description
2503 $query = qq|SELECT * FROM tax|;
2504 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2507 my $extra_columns = '';
2508 $extra_columns .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
2513 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid, a.deliverydate,
2514 a.duedate, a.tax_point, a.ordnumber, a.taxincluded, (SELECT cu.name FROM currencies cu WHERE cu.id=a.currency_id) AS currency, a.notes,
2516 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2517 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2518 a.globalproject_id, ${extra_columns}
2520 d.description AS department,
2523 JOIN $table c ON (a.${table}_id = c.id)
2524 LEFT JOIN employee e ON (e.id = a.employee_id)
2525 LEFT JOIN department d ON (d.id = a.department_id)
2527 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2529 foreach my $key (keys %$ref) {
2530 $self->{$key} = $ref->{$key};
2532 $self->{mtime} ||= $self->{itime};
2533 $self->{lastmtime} = $self->{mtime};
2534 my $transdate = "current_date";
2535 if ($self->{transdate}) {
2536 $transdate = $dbh->quote($self->{transdate});
2539 # now get the account numbers
2540 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
2542 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2544 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2545 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2548 $sth = $dbh->prepare($query);
2549 do_statement($self, $sth, $query, like($module));
2551 $self->{accounts} = "";
2552 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2554 foreach my $key (split(/:/, $ref->{link})) {
2555 if ($key =~ /\Q$module\E/) {
2557 # cross reference for keys
2558 $xkeyref{ $ref->{accno} } = $key;
2560 push @{ $self->{"${module}_links"}{$key} },
2561 { accno => $ref->{accno},
2562 chart_id => $ref->{chart_id},
2563 description => $ref->{description},
2564 taxkey => $ref->{taxkey_id},
2565 tax_id => $ref->{tax_id} };
2567 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2573 # get amounts from individual entries
2576 c.accno, c.description,
2577 a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
2581 LEFT JOIN chart c ON (c.id = a.chart_id)
2582 LEFT JOIN project p ON (p.id = a.project_id)
2583 LEFT JOIN tax t ON (t.id= a.tax_id)
2584 WHERE a.trans_id = ?
2585 AND a.fx_transaction = '0'
2586 ORDER BY a.acc_trans_id, a.transdate|;
2587 $sth = $dbh->prepare($query);
2588 do_statement($self, $sth, $query, $self->{id});
2590 # get exchangerate for currency
2591 $self->{exchangerate} =
2592 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2595 # store amounts in {acc_trans}{$key} for multiple accounts
2596 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2597 $ref->{exchangerate} =
2598 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2599 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2602 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2603 $ref->{amount} *= -1;
2605 $ref->{index} = $index;
2607 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2614 d.closedto, d.revtrans,
2615 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2616 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2617 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2618 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2619 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2621 $ref = selectfirst_hashref_query($self, $dbh, $query);
2622 map { $self->{$_} = $ref->{$_} } keys %$ref;
2629 current_date AS transdate, d.closedto, d.revtrans,
2630 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2631 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2632 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2633 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2634 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2636 $ref = selectfirst_hashref_query($self, $dbh, $query);
2637 map { $self->{$_} = $ref->{$_} } keys %$ref;
2639 if ($self->{"$self->{vc}_id"}) {
2641 # only setup currency
2642 ($self->{currency}) = $self->{defaultcurrency} if !$self->{currency};
2646 $self->lastname_used($dbh, $myconfig, $table, $module);
2648 # get exchangerate for currency
2649 $self->{exchangerate} =
2650 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2656 $main::lxdebug->leave_sub();
2660 $main::lxdebug->enter_sub();
2662 my ($self, $dbh, $myconfig, $table, $module) = @_;
2666 $table = $table eq "customer" ? "customer" : "vendor";
2667 my %column_map = ("a.${table}_id" => "${table}_id",
2668 "a.department_id" => "department_id",
2669 "d.description" => "department",
2670 "ct.name" => $table,
2671 "cu.name" => "currency",
2674 if ($self->{type} =~ /delivery_order/) {
2675 $arap = 'delivery_orders';
2676 delete $column_map{"cu.currency"};
2678 } elsif ($self->{type} =~ /_order/) {
2680 $where = "quotation = '0'";
2682 } elsif ($self->{type} =~ /_quotation/) {
2684 $where = "quotation = '1'";
2686 } elsif ($table eq 'customer') {
2694 $where = "($where) AND" if ($where);
2695 my $query = qq|SELECT MAX(id) FROM $arap
2696 WHERE $where ${table}_id > 0|;
2697 my ($trans_id) = selectrow_query($self, $dbh, $query);
2700 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2701 $query = qq|SELECT $column_spec
2703 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2704 LEFT JOIN department d ON (a.department_id = d.id)
2705 LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
2707 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2709 map { $self->{$_} = $ref->{$_} } values %column_map;
2711 $main::lxdebug->leave_sub();
2714 sub get_variable_content_types {
2715 my %html_variables = (
2716 longdescription => 'html',
2717 partnotes => 'html',
2719 orignotes => 'html',
2724 header_text => 'html',
2725 footer_text => 'html',
2727 return \%html_variables;
2731 $main::lxdebug->enter_sub();
2734 my $myconfig = shift || \%::myconfig;
2735 my ($thisdate, $days) = @_;
2737 my $dbh = $self->get_standard_dbh($myconfig);
2742 my $dateformat = $myconfig->{dateformat};
2743 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2744 $thisdate = $dbh->quote($thisdate);
2745 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2747 $query = qq|SELECT current_date AS thisdate|;
2750 ($thisdate) = selectrow_query($self, $dbh, $query);
2752 $main::lxdebug->leave_sub();
2758 $main::lxdebug->enter_sub();
2760 my ($self, $flds, $new, $count, $numrows) = @_;
2764 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2769 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2771 my $j = $item->{ndx} - 1;
2772 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2776 for $i ($count + 1 .. $numrows) {
2777 map { delete $self->{"${_}_$i"} } @{$flds};
2780 $main::lxdebug->leave_sub();
2784 $main::lxdebug->enter_sub();
2786 my ($self, $myconfig) = @_;
2790 SL::DB->client->with_transaction(sub {
2791 my $dbh = SL::DB->client->dbh;
2793 my $query = qq|DELETE FROM status
2794 WHERE (formname = ?) AND (trans_id = ?)|;
2795 my $sth = prepare_query($self, $dbh, $query);
2797 if ($self->{formname} =~ /(check|receipt)/) {
2798 for $i (1 .. $self->{rowcount}) {
2799 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2802 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2806 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2807 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2809 my %queued = split / /, $self->{queued};
2812 if ($self->{formname} =~ /(check|receipt)/) {
2814 # this is a check or receipt, add one entry for each lineitem
2815 my ($accno) = split /--/, $self->{account};
2816 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2817 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2818 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2819 $sth = prepare_query($self, $dbh, $query);
2821 for $i (1 .. $self->{rowcount}) {
2822 if ($self->{"checked_$i"}) {
2823 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2829 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2830 VALUES (?, ?, ?, ?, ?)|;
2831 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2832 $queued{$self->{formname}}, $self->{formname});
2835 }) or do { die SL::DB->client->error };
2837 $main::lxdebug->leave_sub();
2841 $main::lxdebug->enter_sub();
2843 my ($self, $dbh) = @_;
2845 my ($query, $printed, $emailed);
2847 my $formnames = $self->{printed};
2848 my $emailforms = $self->{emailed};
2850 $query = qq|DELETE FROM status
2851 WHERE (formname = ?) AND (trans_id = ?)|;
2852 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2854 # this only applies to the forms
2855 # checks and receipts are posted when printed or queued
2857 if ($self->{queued}) {
2858 my %queued = split / /, $self->{queued};
2860 foreach my $formname (keys %queued) {
2861 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2862 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2864 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2865 VALUES (?, ?, ?, ?, ?)|;
2866 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2868 $formnames =~ s/\Q$self->{formname}\E//;
2869 $emailforms =~ s/\Q$self->{formname}\E//;
2874 # save printed, emailed info
2875 $formnames =~ s/^ +//g;
2876 $emailforms =~ s/^ +//g;
2879 map { $status{$_}{printed} = 1 } split / +/, $formnames;
2880 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2882 foreach my $formname (keys %status) {
2883 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
2884 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
2886 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2887 VALUES (?, ?, ?, ?)|;
2888 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2891 $main::lxdebug->leave_sub();
2895 # $main::locale->text('SAVED')
2896 # $main::locale->text('SCREENED')
2897 # $main::locale->text('DELETED')
2898 # $main::locale->text('ADDED')
2899 # $main::locale->text('PAYMENT POSTED')
2900 # $main::locale->text('POSTED')
2901 # $main::locale->text('POSTED AS NEW')
2902 # $main::locale->text('ELSE')
2903 # $main::locale->text('SAVED FOR DUNNING')
2904 # $main::locale->text('DUNNING STARTED')
2905 # $main::locale->text('PREVIEWED')
2906 # $main::locale->text('PRINTED')
2907 # $main::locale->text('MAILED')
2908 # $main::locale->text('SCREENED')
2909 # $main::locale->text('CANCELED')
2910 # $main::locale->text('IMPORT')
2911 # $main::locale->text('UNDO TRANSFER')
2912 # $main::locale->text('UNIMPORT')
2913 # $main::locale->text('invoice')
2914 # $main::locale->text('proforma')
2915 # $main::locale->text('sales_order')
2916 # $main::locale->text('pick_list')
2917 # $main::locale->text('purchase_order')
2918 # $main::locale->text('bin_list')
2919 # $main::locale->text('sales_quotation')
2920 # $main::locale->text('request_quotation')
2923 $main::lxdebug->enter_sub();
2926 my $dbh = shift || SL::DB->client->dbh;
2927 SL::DB->client->with_transaction(sub {
2929 if(!exists $self->{employee_id}) {
2930 &get_employee($self, $dbh);
2934 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2935 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
2936 my @values = (conv_i($self->{id}), $self->{login},
2937 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
2938 do_query($self, $dbh, $query, @values);
2940 }) or do { die SL::DB->client->error };
2942 $main::lxdebug->leave_sub();
2946 $main::lxdebug->enter_sub();
2948 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
2949 my ($orderBy, $desc) = split(/\-\-/, $order);
2950 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
2953 if ($trans_id ne "") {
2955 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 | .
2956 qq|FROM history_erp h | .
2957 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
2958 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
2961 my $sth = $dbh->prepare($query) || $self->dberror($query);
2963 $sth->execute() || $self->dberror("$query");
2965 while(my $hash_ref = $sth->fetchrow_hashref()) {
2966 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
2967 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
2968 my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
2969 $hash_ref->{snumbers} = $number;
2970 $hash_ref->{haslink} = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
2971 $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
2972 $tempArray[$i++] = $hash_ref;
2974 $main::lxdebug->leave_sub() and return \@tempArray
2975 if ($i > 0 && $tempArray[0] ne "");
2977 $main::lxdebug->leave_sub();
2981 sub get_partsgroup {
2982 $main::lxdebug->enter_sub();
2984 my ($self, $myconfig, $p) = @_;
2985 my $target = $p->{target} || 'all_partsgroup';
2987 my $dbh = $self->get_standard_dbh($myconfig);
2989 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2991 JOIN parts p ON (p.partsgroup_id = pg.id) |;
2994 if ($p->{searchitems} eq 'part') {
2995 $query .= qq|WHERE p.part_type = 'part'|;
2997 if ($p->{searchitems} eq 'service') {
2998 $query .= qq|WHERE p.part_type = 'service'|;
3000 if ($p->{searchitems} eq 'assembly') {
3001 $query .= qq|WHERE p.part_type = 'assembly'|;
3004 $query .= qq|ORDER BY partsgroup|;
3007 $query = qq|SELECT id, partsgroup FROM partsgroup
3008 ORDER BY partsgroup|;
3011 if ($p->{language_code}) {
3012 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3013 t.description AS translation
3015 JOIN parts p ON (p.partsgroup_id = pg.id)
3016 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3017 ORDER BY translation|;
3018 @values = ($p->{language_code});
3021 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3023 $main::lxdebug->leave_sub();
3026 sub get_pricegroup {
3027 $main::lxdebug->enter_sub();
3029 my ($self, $myconfig, $p) = @_;
3031 my $dbh = $self->get_standard_dbh($myconfig);
3033 my $query = qq|SELECT p.id, p.pricegroup
3036 $query .= qq| ORDER BY pricegroup|;
3039 $query = qq|SELECT id, pricegroup FROM pricegroup
3040 ORDER BY pricegroup|;
3043 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3045 $main::lxdebug->leave_sub();
3049 # usage $form->all_years($myconfig, [$dbh])
3050 # return list of all years where bookings found
3053 $main::lxdebug->enter_sub();
3055 my ($self, $myconfig, $dbh) = @_;
3057 $dbh ||= $self->get_standard_dbh($myconfig);
3060 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3061 (SELECT MAX(transdate) FROM acc_trans)|;
3062 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3064 if ($myconfig->{dateformat} =~ /^yy/) {
3065 ($startdate) = split /\W/, $startdate;
3066 ($enddate) = split /\W/, $enddate;
3068 (@_) = split /\W/, $startdate;
3070 (@_) = split /\W/, $enddate;
3075 $startdate = substr($startdate,0,4);
3076 $enddate = substr($enddate,0,4);
3078 while ($enddate >= $startdate) {
3079 push @all_years, $enddate--;
3084 $main::lxdebug->leave_sub();
3088 $main::lxdebug->enter_sub();
3092 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3094 $main::lxdebug->leave_sub();
3098 $main::lxdebug->enter_sub();
3103 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3105 $main::lxdebug->leave_sub();
3108 sub prepare_for_printing {
3111 my $defaults = SL::DB::Default->get;
3113 $self->{templates} ||= $defaults->templates;
3114 $self->{formname} ||= $self->{type};
3115 $self->{media} ||= 'email';
3117 die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3119 # Several fields that used to reside in %::myconfig (stored in
3120 # auth.user_config) are now stored in defaults. Copy them over for
3122 $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
3124 $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
3126 if (!$self->{employee_id}) {
3127 $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
3128 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
3131 my $language = $self->{language} ? '_' . $self->{language} : '';
3133 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3134 if ($self->{language_id}) {
3135 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3138 $output_dateformat ||= $::myconfig{dateformat};
3139 $output_numberformat ||= $::myconfig{numberformat};
3140 $output_longdates //= 1;
3142 $self->{myconfig_output_dateformat} = $output_dateformat // $::myconfig{dateformat};
3143 $self->{myconfig_output_longdates} = $output_longdates // 1;
3144 $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
3146 # Retrieve accounts for tax calculation.
3147 IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3149 if ($self->{type} =~ /_delivery_order$/) {
3150 DO->order_details(\%::myconfig, $self);
3151 } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3152 OE->order_details(\%::myconfig, $self);
3154 IS->invoice_details(\%::myconfig, $self, $::locale);
3157 # Chose extension & set source file name
3158 my $extension = 'html';
3159 if ($self->{format} eq 'postscript') {
3160 $self->{postscript} = 1;
3162 } elsif ($self->{"format"} =~ /pdf/) {
3164 $extension = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3165 } elsif ($self->{"format"} =~ /opendocument/) {
3166 $self->{opendocument} = 1;
3168 } elsif ($self->{"format"} =~ /excel/) {
3173 my $printer_code = $self->{printer_code} ? '_' . $self->{printer_code} : '';
3174 my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
3175 $self->{IN} = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3178 $self->format_dates($output_dateformat, $output_longdates,
3179 qw(invdate orddate quodate pldate duedate reqdate transdate tax_point shippingdate deliverydate validitydate paymentdate datepaid
3180 transdate_oe deliverydate_oe employee_startdate employee_enddate),
3181 grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3183 $self->reformat_numbers($output_numberformat, 2,
3184 qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3185 grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3187 $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3189 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3191 if (scalar @{ $cvar_date_fields }) {
3192 $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3195 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3196 $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3200 if (($self->{language} // '') ne '') {
3201 my $template_arrays = $self->{TEMPLATE_ARRAYS} || $self;
3202 for my $idx (0..scalar(@{ $template_arrays->{unit} }) - 1) {
3203 $template_arrays->{unit}->[$idx] = AM->translate_units($self, $self->{language}, $template_arrays->{unit}->[$idx], $template_arrays->{qty}->[$idx])
3207 $self->{template_meta} = {
3208 formname => $self->{formname},
3209 language => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
3210 format => $self->{format},
3211 media => $self->{media},
3212 extension => $extension,
3213 printer => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
3214 today => DateTime->today,
3217 if ($defaults->print_interpolate_variables_in_positions) {
3218 $self->substitute_placeholders_in_template_arrays({ field => 'description', type => 'text' }, { field => 'longdescription', type => 'html' });
3224 sub substitute_placeholders_in_template_arrays {
3225 my ($self, @fields) = @_;
3227 foreach my $spec (@fields) {
3228 $spec = { field => $spec, type => 'text' } if !ref($spec);
3229 my $field = $spec->{field};
3231 next unless exists $self->{TEMPLATE_ARRAYS} && exists $self->{TEMPLATE_ARRAYS}->{$field};
3233 my $tag_start = $spec->{type} eq 'html' ? '<%' : '<%';
3234 my $tag_end = $spec->{type} eq 'html' ? '%>' : '%>';
3235 my $formatter = $spec->{type} eq 'html' ? sub { $::locale->quote_special_chars('html', $_[0] // '') } : sub { $_[0] };
3237 $self->{TEMPLATE_ARRAYS}->{$field} = [
3238 apply { s{${tag_start}(.+?)${tag_end}}{ $formatter->($self->{$1}) }eg }
3239 @{ $self->{TEMPLATE_ARRAYS}->{$field} }
3246 sub calculate_arap {
3247 my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
3249 # this function is used to calculate netamount, total_tax and amount for AP and
3250 # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
3252 # Thus it needs a fully prepared $form to work on.
3253 # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
3255 # The calculated total values are all rounded (default is to 2 places) and
3256 # returned as parameters rather than directly modifying form. The aim is to
3257 # make the calculation of AP and AR behave identically. There is a test-case
3258 # for this function in t/form/arap.t
3260 # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
3261 # modified and formatted and receive the correct sign for writing straight to
3262 # acc_trans, depending on whether they are ar or ap.
3265 die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
3266 die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
3267 die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
3268 $roundplaces = 2 unless $roundplaces;
3270 my $sign = 1; # adjust final results for writing amount to acc_trans
3271 $sign = -1 if $buysell eq 'buy';
3273 my ($netamount,$total_tax,$amount);
3277 # parse and round amounts, setting correct sign for writing to acc_trans
3278 for my $i (1 .. $self->{rowcount}) {
3279 $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
3281 $amount += $self->{"amount_$i"} * $sign;
3284 for my $i (1 .. $self->{rowcount}) {
3285 next unless $self->{"amount_$i"};
3286 ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
3287 my $tax_id = $self->{"tax_id_$i"};
3289 my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
3291 if ( $selected_tax ) {
3293 if ( $buysell eq 'sell' ) {
3294 $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3296 $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3299 $self->{"taxkey_$i"} = $selected_tax->taxkey;
3300 $self->{"taxrate_$i"} = $selected_tax->rate;
3303 ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
3305 $netamount += $self->{"amount_$i"};
3306 $total_tax += $self->{"tax_$i"};
3309 $amount = $netamount + $total_tax;
3311 # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
3312 # but reverse sign of totals for writing amounts to ar
3313 if ( $buysell eq 'buy' ) {
3319 return($netamount,$total_tax,$amount);
3323 my ($self, $dateformat, $longformat, @indices) = @_;
3325 $dateformat ||= $::myconfig{dateformat};
3327 foreach my $idx (@indices) {
3328 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3329 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3330 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3334 next unless defined $self->{$idx};
3336 if (!ref($self->{$idx})) {
3337 $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3339 } elsif (ref($self->{$idx}) eq "ARRAY") {
3340 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3341 $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3347 sub reformat_numbers {
3348 my ($self, $numberformat, $places, @indices) = @_;
3350 return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3352 foreach my $idx (@indices) {
3353 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3354 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3355 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3359 next unless defined $self->{$idx};
3361 if (!ref($self->{$idx})) {
3362 $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3364 } elsif (ref($self->{$idx}) eq "ARRAY") {
3365 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3366 $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3371 my $saved_numberformat = $::myconfig{numberformat};
3372 $::myconfig{numberformat} = $numberformat;
3374 foreach my $idx (@indices) {
3375 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3376 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3377 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3381 next unless defined $self->{$idx};
3383 if (!ref($self->{$idx})) {
3384 $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3386 } elsif (ref($self->{$idx}) eq "ARRAY") {
3387 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3388 $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3393 $::myconfig{numberformat} = $saved_numberformat;
3396 sub create_email_signature {
3398 my $client_signature = $::instance_conf->get_signature;
3399 my $user_signature = $::myconfig{signature};
3402 if ( $client_signature or $user_signature ) {
3403 $signature = "\n\n-- \n";
3404 $signature .= $user_signature . "\n" if $user_signature;
3405 $signature .= $client_signature . "\n" if $client_signature;
3412 # this function calculates the net amount and tax for the lines in ar, ap and
3413 # gl and is used for update as well as post. When used with update the return
3414 # value of amount isn't needed
3416 # calculate_tax should always work with positive values, or rather as the user inputs them
3417 # calculate_tax uses db/perl numberformat, i.e. parsed numbers
3418 # convert to negative numbers (when necessary) only when writing to acc_trans
3419 # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
3420 # for post_transaction amount already contains exchangerate and correct sign and is rounded
3421 # calculate_tax doesn't (need to) know anything about exchangerate
3423 my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
3431 # calculate tax (unrounded), subtract from amount, round amount and round tax
3432 $tax = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
3433 $amount = $self->round_amount($amount - $tax, $roundplaces);
3434 $tax = $self->round_amount($tax, $roundplaces);
3436 $tax = $amount * $taxrate;
3437 $tax = $self->round_amount($tax, $roundplaces);
3440 $tax = 0 unless $tax;
3442 return ($amount,$tax);
3451 SL::Form.pm - main data object.
3455 This is the main data object of kivitendo.
3456 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3457 Points of interest for a beginner are:
3459 - $form->error - renders a generic error in html. accepts an error message
3460 - $form->get_standard_dbh - returns a database connection for the
3462 =head1 SPECIAL FUNCTIONS
3464 =head2 C<redirect_header> $url
3466 Generates a HTTP redirection header for the new C<$url>. Constructs an
3467 absolute URL including scheme, host name and port. If C<$url> is a
3468 relative URL then it is considered relative to kivitendo base URL.
3470 This function C<die>s if headers have already been created with
3471 C<$::form-E<gt>header>.
3475 print $::form->redirect_header('oe.pl?action=edit&id=1234');
3476 print $::form->redirect_header('http://www.lx-office.org/');
3480 Generates a general purpose http/html header and includes most of the scripts
3481 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3483 Only one header will be generated. If the method was already called in this
3484 request it will not output anything and return undef. Also if no
3485 HTTP_USER_AGENT is found, no header is generated.
3487 Although header does not accept parameters itself, it will honor special
3488 hashkeys of its Form instance:
3496 If one of these is set, a http-equiv refresh is generated. Missing parameters
3497 default to 3 seconds and the refering url.
3501 Either a scalar or an array ref. Will be inlined into the header. Add
3502 stylesheets with the L<use_stylesheet> function.
3506 If true, a css snippet will be generated that sets the page in landscape mode.
3510 Used to override the default favicon.
3514 A html page title will be generated from this
3516 =item mtime_ischanged
3518 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
3520 Can be used / called with any table, that has itime and mtime attributes.
3521 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
3522 Can be called wit C<option> mail to generate a different error message.
3524 Returns undef if no save operation has been done yet ($self->{id} not present).
3525 Returns undef if no concurrent write process is detected otherwise a error message.