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);
62 use SL::DB::AdditionalBillingAddress;
64 use SL::DB::CustomVariableConfig;
66 use SL::DB::PaymentTerm;
69 use SL::Helper::Flash qw();
72 use SL::Layout::Dispatcher;
74 use SL::Locale::String;
77 use SL::MoreCommon qw(uri_encode uri_decode);
79 use SL::PrefixedNumber;
88 use List::Util qw(first max min sum);
89 use List::MoreUtils qw(all any apply);
91 use SL::Helper::File qw(:all);
92 use SL::Helper::Number;
93 use SL::Helper::CreatePDF qw(merge_pdfs);
98 SL::Version->get_version;
102 $main::lxdebug->enter_sub();
109 if ($LXDebug::watch_form) {
110 require SL::Watchdog;
111 tie %{ $self }, 'SL::Watchdog';
116 $main::lxdebug->leave_sub();
121 sub _flatten_variables_rec {
122 $main::lxdebug->enter_sub(2);
131 if ('' eq ref $curr->{$key}) {
132 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
134 } elsif ('HASH' eq ref $curr->{$key}) {
135 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
136 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
140 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
141 my $first_array_entry = 1;
143 my $element = $curr->{$key}[$idx];
145 if ('HASH' eq ref $element) {
146 foreach my $hash_key (sort keys %{ $element }) {
147 push @result, $self->_flatten_variables_rec($element, $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
148 $first_array_entry = 0;
151 push @result, { 'key' => $prefix . $key . '[]', 'value' => $element };
156 $main::lxdebug->leave_sub(2);
161 sub flatten_variables {
162 $main::lxdebug->enter_sub(2);
170 push @variables, $self->_flatten_variables_rec($self, '', $_);
173 $main::lxdebug->leave_sub(2);
178 sub flatten_standard_variables {
179 $main::lxdebug->enter_sub(2);
182 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar), @_);
186 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
187 push @variables, $self->_flatten_variables_rec($self, '', $_);
190 $main::lxdebug->leave_sub(2);
196 my ($self, $str) = @_;
198 return uri_encode($str);
202 my ($self, $str) = @_;
204 return uri_decode($str);
208 $main::lxdebug->enter_sub();
209 my ($self, $str) = @_;
211 if ($str && !ref($str)) {
212 $str =~ s/\"/"/g;
215 $main::lxdebug->leave_sub();
221 $main::lxdebug->enter_sub();
222 my ($self, $str) = @_;
224 if ($str && !ref($str)) {
225 $str =~ s/"/\"/g;
228 $main::lxdebug->leave_sub();
234 $main::lxdebug->enter_sub();
238 map({ print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
240 for (sort keys %$self) {
241 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
242 print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
245 $main::lxdebug->leave_sub();
249 my ($self, $code) = @_;
250 local $self->{__ERROR_HANDLER} = sub { SL::X::FormError->throw(error => $_[0]) };
255 $main::lxdebug->enter_sub();
257 $main::lxdebug->show_backtrace();
259 my ($self, $msg) = @_;
261 if ($self->{__ERROR_HANDLER}) {
262 $self->{__ERROR_HANDLER}->($msg);
264 } elsif ($ENV{HTTP_USER_AGENT}) {
266 $self->show_generic_error($msg);
269 confess "Error: $msg\n";
272 $main::lxdebug->leave_sub();
276 $main::lxdebug->enter_sub();
278 my ($self, $msg) = @_;
280 if ($ENV{HTTP_USER_AGENT}) {
282 print $self->parse_html_template('generic/form_info', { message => $msg });
284 } elsif ($self->{info_function}) {
285 &{ $self->{info_function} }($msg);
290 $main::lxdebug->leave_sub();
293 # calculates the number of rows in a textarea based on the content and column number
294 # can be capped with maxrows
296 $main::lxdebug->enter_sub();
297 my ($self, $str, $cols, $maxrows, $minrows) = @_;
301 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
304 $main::lxdebug->leave_sub();
306 return max(min($rows, $maxrows), $minrows);
310 my ($self, $msg) = @_;
312 SL::X::DBError->throw(
314 db_error => $DBI::errstr,
319 $main::lxdebug->enter_sub();
321 my ($self, $name, $msg) = @_;
324 foreach my $part (split m/\./, $name) {
325 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
328 $curr = $curr->{$part};
331 $main::lxdebug->leave_sub();
334 sub _get_request_uri {
337 return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
338 return URI->new if !$ENV{REQUEST_URI}; # for testing
340 my $scheme = $::request->is_https ? 'https' : 'http';
341 my $port = $ENV{SERVER_PORT};
342 $port = undef if (($scheme eq 'http' ) && ($port == 80))
343 || (($scheme eq 'https') && ($port == 443));
345 my $uri = URI->new("${scheme}://");
346 $uri->scheme($scheme);
348 $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
349 $uri->path_query($ENV{REQUEST_URI});
355 sub _add_to_request_uri {
358 my $relative_new_path = shift;
359 my $request_uri = shift || $self->_get_request_uri;
360 my $relative_new_uri = URI->new($relative_new_path);
361 my @request_segments = $request_uri->path_segments;
363 my $new_uri = $request_uri->clone;
364 $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
369 sub create_http_response {
370 $main::lxdebug->enter_sub();
375 my $cgi = $::request->{cgi};
378 if (defined $main::auth) {
379 my $uri = $self->_get_request_uri;
380 my @segments = $uri->path_segments;
382 $uri->path_segments(@segments);
384 my $session_cookie_value = $main::auth->get_session_id();
386 if ($session_cookie_value) {
387 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
388 '-value' => $session_cookie_value,
389 '-path' => $uri->path,
390 '-expires' => '+' . $::auth->{session_timeout} . 'm',
391 '-secure' => $::request->is_https);
392 $session_cookie = "$session_cookie; SameSite=strict";
396 my %cgi_params = ('-type' => $params{content_type});
397 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
398 $cgi_params{'-cookie'} = $session_cookie if ($session_cookie);
400 map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length status);
402 my $output = $cgi->header(%cgi_params);
404 $main::lxdebug->leave_sub();
410 $::lxdebug->enter_sub;
412 my ($self, %params) = @_;
415 $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
417 if ($params{no_layout}) {
418 $::request->{layout} = SL::Layout::Dispatcher->new(style => 'none');
421 my $layout = $::request->{layout};
423 # standard css for all
424 # this should gradually move to the layouts that need it
425 $layout->use_stylesheet("$_.css") for qw(
426 common main menu list_accounts jquery.autocomplete
427 jquery.multiselect2side
428 ui-lightness/jquery-ui
430 tooltipster themes/tooltipster-light
433 $layout->use_javascript("$_.js") for (qw(
434 jquery jquery-ui jquery.cookie jquery.checkall jquery.download
435 jquery/jquery.form jquery/fixes client_js
436 jquery/jquery.tooltipster.min
437 common part_selection
438 ), "jquery/ui/i18n/jquery.ui.datepicker-$::myconfig{countrycode}");
440 $layout->use_javascript("$_.js") for @{ $params{use_javascripts} // [] };
442 $self->{favicon} ||= "favicon.ico";
443 $self->{titlebar} = join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->read_version if $self->{title} || !$self->{titlebar};
446 if ($self->{refresh_url} || $self->{refresh_time}) {
447 my $refresh_time = $self->{refresh_time} || 3;
448 my $refresh_url = $self->{refresh_url} || $ENV{REFERER};
449 push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
452 my $auto_reload_resources_param = $layout->auto_reload_resources_param;
454 push @header, map { qq|<link rel="stylesheet" href="${_}${auto_reload_resources_param}" type="text/css" title="Stylesheet">| } $layout->stylesheets;
455 push @header, "<style type='text/css'>\@page { size:landscape; }</style> " if $self->{landscape};
456 push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
457 push @header, map { qq|<script type="text/javascript" src="${_}${auto_reload_resources_param}"></script>| } $layout->javascripts;
458 push @header, '<meta name="viewport" content="width=device-width, initial-scale=1">';
459 push @header, $self->{javascript} if $self->{javascript};
460 push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
463 strict => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
464 transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
465 frameset => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
466 html5 => qq|<!DOCTYPE html>|,
470 print $self->create_http_response(content_type => 'text/html', charset => 'UTF-8');
471 print $doctypes{$params{doctype} || 'transitional'}, $/;
475 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
476 <title>$self->{titlebar}</title>
478 print " $_\n" for @header;
480 <meta name="robots" content="noindex,nofollow">
485 print $::request->{layout}->pre_content;
486 print $::request->{layout}->start_content;
488 $layout->header_done;
490 $::lxdebug->leave_sub;
494 return unless $::request->{layout}->need_footer;
496 print $::request->{layout}->end_content;
497 print $::request->{layout}->post_content;
499 if (my @inline_scripts = $::request->{layout}->javascripts_inline) {
500 print "<script type='text/javascript'>" . join("; ", @inline_scripts) . "</script>\n";
509 sub ajax_response_header {
510 $main::lxdebug->enter_sub();
514 my $output = $::request->{cgi}->header('-charset' => 'UTF-8');
516 $main::lxdebug->leave_sub();
521 sub redirect_header {
525 my $base_uri = $self->_get_request_uri;
526 my $new_uri = URI->new_abs($new_url, $base_uri);
528 die "Headers already sent" if $self->{header};
531 return $::request->{cgi}->redirect($new_uri);
534 sub set_standard_title {
535 $::lxdebug->enter_sub;
538 $self->{titlebar} = "kivitendo " . $::locale->text('Version') . " " . $self->read_version;
539 $self->{titlebar} .= "- $::myconfig{name}" if $::myconfig{name};
540 $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
542 $::lxdebug->leave_sub;
545 sub _prepare_html_template {
546 $main::lxdebug->enter_sub();
548 my ($self, $file, $additional_params) = @_;
551 if (!%::myconfig || !$::myconfig{"countrycode"}) {
552 $language = $::lx_office_conf{system}->{language};
554 $language = $main::myconfig{"countrycode"};
556 $language = "de" unless ($language);
558 my $webpages_path = $::request->layout->webpages_path;
560 if (-f "${webpages_path}/${file}.html") {
561 $file = "${webpages_path}/${file}.html";
563 } elsif (ref $file eq 'SCALAR') {
564 # file is a scalarref, use inline mode
566 my $info = "Web page template '${file}' not found.\n";
568 print qq|<pre>$info</pre>|;
569 $::dispatcher->end_request;
572 $additional_params->{AUTH} = $::auth;
573 $additional_params->{INSTANCE_CONF} = $::instance_conf;
574 $additional_params->{LOCALE} = $::locale;
575 $additional_params->{LXCONFIG} = \%::lx_office_conf;
576 $additional_params->{LXDEBUG} = $::lxdebug;
577 $additional_params->{MYCONFIG} = \%::myconfig;
579 $main::lxdebug->leave_sub();
584 sub parse_html_template {
585 $main::lxdebug->enter_sub();
587 my ($self, $file, $additional_params) = @_;
589 $additional_params ||= { };
591 my $real_file = $self->_prepare_html_template($file, $additional_params);
592 my $template = $self->template;
594 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
597 $template->process($real_file, $additional_params, \$output) || die $template->error;
599 $main::lxdebug->leave_sub();
604 sub template { $::request->presenter->get_template }
606 sub show_generic_error {
607 $main::lxdebug->enter_sub();
609 my ($self, $error, %params) = @_;
611 if ($self->{__ERROR_HANDLER}) {
612 $self->{__ERROR_HANDLER}->($error);
613 $main::lxdebug->leave_sub();
617 if ($::request->is_ajax) {
620 ->render(SL::Controller::Base->new);
621 $::dispatcher->end_request;
625 'title_error' => $params{title},
626 'label_error' => $error,
629 $self->{title} = $params{title} if $params{title};
631 for my $bar ($::request->layout->get('actionbar')) {
635 call => [ 'kivi.history_back' ],
636 accesskey => 'enter',
642 print $self->parse_html_template("generic/error", $add_params);
644 print STDERR "Error: $error\n";
646 $main::lxdebug->leave_sub();
648 $::dispatcher->end_request;
651 sub show_generic_information {
652 $main::lxdebug->enter_sub();
654 my ($self, $text, $title) = @_;
657 'title_information' => $title,
658 'label_information' => $text,
661 $self->{title} = $title if ($title);
664 print $self->parse_html_template("generic/information", $add_params);
666 $main::lxdebug->leave_sub();
668 $::dispatcher->end_request;
671 sub _store_redirect_info_in_session {
674 return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
676 my ($controller, $params) = ($1, $2);
677 my $form = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
678 $self->{callback} = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
682 $main::lxdebug->enter_sub();
684 my ($self, $msg) = @_;
686 if (!$self->{callback}) {
690 SL::Helper::Flash::flash_later('info', $msg) if $msg;
691 $self->_store_redirect_info_in_session;
692 print $::form->redirect_header($self->{callback});
695 $::dispatcher->end_request;
697 $main::lxdebug->leave_sub();
700 # sort of columns removed - empty sub
702 $main::lxdebug->enter_sub();
704 my ($self, @columns) = @_;
706 $main::lxdebug->leave_sub();
713 my ($self, $myconfig, $amount, $places, $dash) = @_;
714 SL::Helper::Number::_format_number($amount, $places, %$myconfig, dash => $dash);
718 $main::lxdebug->enter_sub(2);
723 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
724 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
725 $input =~ s/\#\#/\#/g;
727 $main::lxdebug->leave_sub(2);
735 my ($self, $myconfig, $amount) = @_;
736 SL::Helper::Number::_parse_number($amount, %$myconfig);
739 sub round_amount { shift; goto &SL::Helper::Number::_round_number; }
742 $main::lxdebug->enter_sub();
744 my ($self, $myconfig) = @_;
745 my ($out, $out_mode);
749 my $defaults = SL::DB::Default->get;
751 my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
752 $self->{cwd} = getcwd();
753 my $temp_dir = File::Temp->newdir(
754 "kivitendo-print-XXXXXX",
755 DIR => $self->{cwd} . "/" . $::lx_office_conf{paths}->{userspath},
756 CLEANUP => !$keep_temp_files,
759 my $userspath = File::Spec->abs2rel($temp_dir->dirname);
760 $self->{tmpdir} = $temp_dir->dirname;
765 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
766 $template_type = 'OpenDocument';
767 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
769 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
770 $template_type = 'LaTeX';
771 $ext_for_format = 'pdf';
773 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
774 $template_type = 'HTML';
775 $ext_for_format = 'html';
777 } elsif ( $self->{"format"} =~ /excel/i ) {
778 $template_type = 'Excel';
779 $ext_for_format = 'xls';
781 } elsif ( defined $self->{'format'}) {
782 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
784 } elsif ( $self->{'format'} eq '' ) {
785 $self->error("No Outputformat given: $self->{'format'}");
787 } else { #Catch the rest
788 $self->error("Outputformat not defined: $self->{'format'}");
791 my $template = SL::Template::create(type => $template_type,
792 file_name => $self->{IN},
794 myconfig => $myconfig,
795 userspath => $userspath,
796 %{ $self->{TEMPLATE_DRIVER_OPTIONS} || {} });
798 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
799 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" } if exists $self->{ $self->{"formname"} . "notes" };
801 if (!$self->{employee_id}) {
802 $self->{"employee_${_}"} = $myconfig->{$_} for qw(email tel fax name signature);
803 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
806 $self->{"myconfig_${_}"} = $myconfig->{$_} for grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
807 $self->{$_} = $defaults->$_ for qw(co_ustid);
808 $self->{"myconfig_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
809 $self->{AUTH} = $::auth;
810 $self->{INSTANCE_CONF} = $::instance_conf;
811 $self->{LOCALE} = $::locale;
812 $self->{LXCONFIG} = $::lx_office_conf;
813 $self->{LXDEBUG} = $::lxdebug;
814 $self->{MYCONFIG} = \%::myconfig;
816 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
818 # OUT is used for the media, screen, printer, email
819 # for postscript we store a copy in a temporary file
821 my ($temp_fh, $suffix);
822 $suffix = $self->{IN};
824 ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
825 strftime('kivitendo-print-%Y%m%d%H%M%S-XXXXXX', localtime()),
826 SUFFIX => '.' . ($suffix || 'tex'),
828 UNLINK => $keep_temp_files ? 0 : 1,
831 chmod 0644, $self->{tmpfile} if $keep_temp_files;
832 (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
835 $out_mode = $self->{OUT_MODE} || '>';
836 $self->{OUT} = "$self->{tmpfile}";
837 $self->{OUT_MODE} = '>';
840 my $command_formatter = sub {
841 my ($out_mode, $out) = @_;
842 return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
846 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
847 open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
849 *OUT = ($::dispatcher->get_standard_filehandles)[1];
853 if (!$template->parse(*OUT)) {
855 $self->error("$self->{IN} : " . $template->get_error());
858 close OUT if $self->{OUT};
859 # check only one flag (webdav_documents)
860 # therefore copy to webdav, even if we do not have the webdav feature enabled (just archive)
861 my $copy_to_webdav = $::instance_conf->get_webdav_documents && !$self->{preview} && $self->{tmpdir} && $self->{tmpfile} && $self->{type}
862 && $self->{type} ne 'statement';
864 $self->{attachment_filename} ||= $self->generate_attachment_filename;
866 if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
867 $self->append_general_pdf_attachments(filepath => $self->{tmpdir}."/".$self->{tmpfile},
868 type => $self->{type});
870 if ($self->{media} eq 'file') {
871 copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
873 if ($copy_to_webdav) {
874 if (my $error = Common::copy_file_to_webdav_folder($self)) {
875 chdir("$self->{cwd}");
876 $self->error($error);
880 if (!$self->{preview} && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled)
882 $self->store_pdf($self);
885 chdir("$self->{cwd}");
887 $::lxdebug->leave_sub();
892 if ($copy_to_webdav) {
893 if (my $error = Common::copy_file_to_webdav_folder($self)) {
894 chdir("$self->{cwd}");
895 $self->error($error);
899 if ( !$self->{preview} && $ext_for_format eq 'pdf' && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled) {
900 my $file_obj = $self->store_pdf($self);
901 $self->{print_file_id} = $file_obj->id if $file_obj;
903 if ($self->{media} eq 'email') {
904 if ( getcwd() eq $self->{"tmpdir"} ) {
905 # in the case of generating pdf we are in the tmpdir, but WHY ???
906 $self->{tmpfile} = $userspath."/".$self->{tmpfile};
907 chdir("$self->{cwd}");
909 $self->send_email(\%::myconfig,$ext_for_format);
913 $self->{OUT_MODE} = $out_mode;
914 $self->output_file($template->get_mime_type,$command_formatter);
916 delete $self->{print_file_id};
920 chdir("$self->{cwd}");
921 $main::lxdebug->leave_sub();
924 sub get_bcc_defaults {
925 my ($self, $myconfig, $mybcc) = @_;
926 if (SL::DB::Default->get->bcc_to_login) {
927 $mybcc .= ", " if $mybcc;
928 $mybcc .= $myconfig->{email};
930 my $otherbcc = SL::DB::Default->get->global_bcc;
932 $mybcc .= ", " if $mybcc;
939 $main::lxdebug->enter_sub();
940 my ($self, $myconfig, $ext_for_format) = @_;
941 my $mail = Mailer->new;
943 map { $mail->{$_} = $self->{$_} }
944 qw(cc subject message format);
946 if ($self->{cc_employee}) {
947 my ($user, $my_emp_cc);
948 $user = SL::DB::Manager::AuthUser->find_by(login => $self->{cc_employee});
949 $my_emp_cc = $user->get_config_value('email') if ref $user eq 'SL::DB::AuthUser';
950 $mail->{cc} .= ", " if $mail->{cc};
951 $mail->{cc} .= $my_emp_cc if $my_emp_cc;
954 $mail->{bcc} = $self->get_bcc_defaults($myconfig, $self->{bcc});
955 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
956 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
957 $mail->{fileid} = time() . '.' . $$ . '.';
958 $mail->{content_type} = "text/html";
959 my $full_signature = $self->create_email_signature();
961 $mail->{attachments} = [];
963 # if we send html or plain text inline
964 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
965 $mail->{message} =~ s/\r//g;
966 $mail->{message} =~ s{\n}{<br>\n}g;
967 $mail->{message} .= $full_signature;
969 open(IN, "<", $self->{tmpfile})
970 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
971 $mail->{message} .= $_ while <IN>;
974 } elsif (($self->{attachment_policy} // '') ne 'no_file') {
975 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
976 $attachment_name =~ s{\.(.+?)$}{.${ext_for_format}} if ($ext_for_format);
978 if (($self->{attachment_policy} // '') eq 'old_file') {
979 my ( $attfile ) = SL::File->get_all(object_id => $self->{id},
980 object_type => $self->{type},
981 file_type => 'document',
982 print_variant => $self->{formname},);
985 $attfile->{override_file_name} = $attachment_name if $attachment_name;
986 push @attfiles, $attfile;
990 push @{ $mail->{attachments} }, { path => $self->{tmpfile},
991 id => $self->{print_file_id},
992 type => "application/pdf",
993 name => $attachment_name };
999 map { SL::File->get(id => $_) }
1000 @{ $self->{attach_file_ids} // [] };
1002 foreach my $attfile ( @attfiles ) {
1003 push @{ $mail->{attachments} }, {
1004 path => $attfile->get_file,
1006 type => $attfile->mime_type,
1007 name => $attfile->{override_file_name} // $attfile->file_name,
1008 content => $attfile->get_content ? ${ $attfile->get_content } : undef,
1012 $mail->{message} =~ s/\r//g;
1013 $mail->{message} .= $full_signature;
1014 $self->{emailerr} = $mail->send();
1016 if ($self->{emailerr}) {
1018 $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
1021 $self->{email_journal_id} = $mail->{journalentry};
1022 $self->{snumbers} = "emailjournal" . "_" . $self->{email_journal_id};
1023 $self->{what_done} = $::form->{type};
1024 $self->{addition} = "MAILED";
1025 $self->save_history;
1027 #write back for message info and mail journal
1028 $self->{cc} = $mail->{cc};
1029 $self->{bcc} = $mail->{bcc};
1030 $self->{email} = $mail->{to};
1032 $main::lxdebug->leave_sub();
1036 $main::lxdebug->enter_sub();
1038 my ($self,$mimeType,$command_formatter) = @_;
1039 my $numbytes = (-s $self->{tmpfile});
1040 open(IN, "<", $self->{tmpfile})
1041 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1044 $self->{copies} = 1 unless $self->{media} eq 'printer';
1046 chdir("$self->{cwd}");
1047 for my $i (1 .. $self->{copies}) {
1049 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1051 open OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1052 print OUT $_ while <IN>;
1057 my %headers = ('-type' => $mimeType,
1058 '-connection' => 'close',
1059 '-charset' => 'UTF-8');
1061 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1063 if ($self->{attachment_filename}) {
1066 '-attachment' => $self->{attachment_filename},
1067 '-content-length' => $numbytes,
1072 print $::request->cgi->header(%headers);
1074 $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1078 $main::lxdebug->leave_sub();
1081 sub get_formname_translation {
1082 $main::lxdebug->enter_sub();
1083 my ($self, $formname) = @_;
1085 $formname ||= $self->{formname};
1087 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1088 local $::locale = Locale->new($self->{recipient_locale});
1090 my %formname_translations = (
1091 bin_list => $main::locale->text('Bin List'),
1092 credit_note => $main::locale->text('Credit Note'),
1093 invoice => $main::locale->text('Invoice'),
1094 invoice_copy => $main::locale->text('Invoice Copy'),
1095 invoice_for_advance_payment => $main::locale->text('Invoice for Advance Payment'),
1096 final_invoice => $main::locale->text('Final Invoice'),
1097 pick_list => $main::locale->text('Pick List'),
1098 proforma => $main::locale->text('Proforma Invoice'),
1099 purchase_order => $main::locale->text('Purchase Order'),
1100 request_quotation => $main::locale->text('RFQ'),
1101 sales_order => $main::locale->text('Confirmation'),
1102 sales_quotation => $main::locale->text('Quotation'),
1103 storno_invoice => $main::locale->text('Storno Invoice'),
1104 sales_delivery_order => $main::locale->text('Delivery Order'),
1105 purchase_delivery_order => $main::locale->text('Delivery Order'),
1106 supplier_delivery_order => $main::locale->text('Supplier Delivery Order'),
1107 rma_delivery_order => $main::locale->text('RMA Delivery Order'),
1108 dunning => $main::locale->text('Dunning'),
1109 dunning1 => $main::locale->text('Payment Reminder'),
1110 dunning2 => $main::locale->text('Dunning'),
1111 dunning3 => $main::locale->text('Last Dunning'),
1112 dunning_invoice => $main::locale->text('Dunning Invoice'),
1113 letter => $main::locale->text('Letter'),
1114 ic_supply => $main::locale->text('Intra-Community supply'),
1115 statement => $main::locale->text('Statement'),
1118 $main::lxdebug->leave_sub();
1119 return $formname_translations{$formname};
1122 sub get_cusordnumber_translation {
1123 $main::lxdebug->enter_sub();
1124 my ($self, $formname) = @_;
1126 $formname ||= $self->{formname};
1128 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1129 local $::locale = Locale->new($self->{recipient_locale});
1132 $main::lxdebug->leave_sub();
1133 return $main::locale->text('Your Order');
1136 sub get_number_prefix_for_type {
1137 $main::lxdebug->enter_sub();
1141 (first { $self->{type} eq $_ } qw(invoice invoice_for_advance_payment final_invoice credit_note)) ? 'inv'
1142 : ($self->{type} =~ /_quotation$/) ? 'quo'
1143 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1144 : ($self->{type} =~ /letter/) ? 'letter'
1147 # better default like this?
1148 # : ($self->{type} =~ /(sales|purcharse)_order/ : 'ord';
1149 # : 'prefix_undefined';
1151 $main::lxdebug->leave_sub();
1155 sub get_extension_for_format {
1156 $main::lxdebug->enter_sub();
1159 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1160 : $self->{format} =~ /postscript/i ? ".ps"
1161 : $self->{format} =~ /opendocument/i ? ".odt"
1162 : $self->{format} =~ /excel/i ? ".xls"
1163 : $self->{format} =~ /html/i ? ".html"
1166 $main::lxdebug->leave_sub();
1170 sub generate_attachment_filename {
1171 $main::lxdebug->enter_sub();
1174 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1175 my $recipient_locale = Locale->new($self->{recipient_locale});
1177 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1178 my $prefix = $self->get_number_prefix_for_type();
1180 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice invoice_for_advance_payment final_invoice credit_note))) {
1181 $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
1183 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1184 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1186 } elsif ($attachment_filename) {
1187 $attachment_filename .= $self->get_extension_for_format();
1190 $attachment_filename = "";
1193 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1194 $attachment_filename =~ s|[\s/\\]+|_|g;
1196 $main::lxdebug->leave_sub();
1197 return $attachment_filename;
1200 sub generate_email_subject {
1201 $main::lxdebug->enter_sub();
1204 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1205 my $prefix = $self->get_number_prefix_for_type();
1207 if ($subject && $self->{"${prefix}number"}) {
1208 $subject .= " " . $self->{"${prefix}number"}
1211 if ($self->{cusordnumber}) {
1212 $subject = $self->get_cusordnumber_translation() . ' ' . $self->{cusordnumber} . ' / ' . $subject;
1215 $main::lxdebug->leave_sub();
1219 sub generate_email_body {
1220 $main::lxdebug->enter_sub();
1221 my ($self, %params) = @_;
1222 # simple german and english will work grammatically (most european languages as well)
1223 # Dear Mr Alan Greenspan:
1224 # Sehr geehrte Frau Meyer,
1225 # A l’attention de Mme Villeroy,
1226 # Gentile Signora Ferrari,
1229 if ($self->{cp_id} && !$params{record_email}) {
1230 my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
1231 my $name = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
1232 my $gender = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
1233 my $mf = $gender eq 'f' ? 'female' : 'male';
1234 $body = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
1235 $body .= ' ' . $givenname . ' ' . $name if $body;
1237 $body = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
1240 return undef unless $body;
1242 $body .= GenericTranslations->get(translation_type => "salutation_punctuation_mark", language_id => $self->{language_id});
1243 $body = '<p>' . $::locale->quote_special_chars('HTML', $body) . '</p>';
1245 my $translation_type = $params{translation_type} // "preset_text_$self->{formname}";
1246 my $main_body = GenericTranslations->get(translation_type => $translation_type, language_id => $self->{language_id});
1247 $main_body = GenericTranslations->get(translation_type => $params{fallback_translation_type}, language_id => $self->{language_id}) if !$main_body && $params{fallback_translation_type};
1248 $body .= $main_body;
1250 $body = $main::locale->unquote_special_chars('HTML', $body);
1252 $main::lxdebug->leave_sub();
1257 $main::lxdebug->enter_sub();
1259 my ($self, $application) = @_;
1261 my $error_code = $?;
1263 chdir("$self->{tmpdir}");
1266 if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1267 push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1269 } elsif (-f "$self->{tmpfile}.err") {
1270 open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
1275 if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1276 $self->{tmpfile} =~ s|.*/||g;
1278 $self->{tmpfile} =~ s/\.\w+$//g;
1279 my $tmpfile = $self->{tmpfile};
1280 unlink(<$tmpfile.*>);
1283 chdir("$self->{cwd}");
1285 $main::lxdebug->leave_sub();
1291 $main::lxdebug->enter_sub();
1293 my ($self, $date, $myconfig) = @_;
1296 if ($date && $date =~ /\D/) {
1298 if ($myconfig->{dateformat} =~ /^yy/) {
1299 ($yy, $mm, $dd) = split /\D/, $date;
1301 if ($myconfig->{dateformat} =~ /^mm/) {
1302 ($mm, $dd, $yy) = split /\D/, $date;
1304 if ($myconfig->{dateformat} =~ /^dd/) {
1305 ($dd, $mm, $yy) = split /\D/, $date;
1310 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1311 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1313 $dd = "0$dd" if ($dd < 10);
1314 $mm = "0$mm" if ($mm < 10);
1316 $date = "$yy$mm$dd";
1319 $main::lxdebug->leave_sub();
1324 # Database routines used throughout
1325 # DB Handling got moved to SL::DB, these are only shims for compatibility
1328 SL::DB->client->dbh;
1331 sub get_standard_dbh {
1332 my $dbh = SL::DB->client->dbh;
1334 if ($dbh && !$dbh->{Active}) {
1335 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
1336 SL::DB->client->dbh(undef);
1339 SL::DB->client->dbh;
1342 sub disconnect_standard_dbh {
1343 SL::DB->client->dbh->rollback;
1349 $main::lxdebug->enter_sub();
1351 my ($self, $date, $myconfig) = @_;
1352 my $dbh = $self->get_standard_dbh;
1354 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1355 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1357 # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1358 # es ist sicher ein conv_date vorher IMMER auszuführen.
1359 # Testfälle ohne definiertes closedto:
1360 # Leere Datumseingabe i.O.
1361 # SELECT 1 FROM defaults WHERE '' < closedto
1362 # normale Zahlungsbuchung über Rechnungsmaske i.O.
1363 # SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1364 # Testfälle mit definiertem closedto (30.04.2011):
1365 # Leere Datumseingabe i.O.
1366 # SELECT 1 FROM defaults WHERE '' < closedto
1367 # normale Buchung im geschloßenem Zeitraum i.O.
1368 # SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1369 # Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1370 # normale Buchung in aktiver Buchungsperiode i.O.
1371 # SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1373 my ($closed) = $sth->fetchrow_array;
1375 $main::lxdebug->leave_sub();
1380 # prevents bookings to the to far away future
1381 sub date_max_future {
1382 $main::lxdebug->enter_sub();
1384 my ($self, $date, $myconfig) = @_;
1385 my $dbh = $self->get_standard_dbh;
1387 my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
1388 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1390 my ($max_future_booking_interval) = $sth->fetchrow_array;
1392 $main::lxdebug->leave_sub();
1394 return $max_future_booking_interval;
1398 sub update_balance {
1399 $main::lxdebug->enter_sub();
1401 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1403 # if we have a value, go do it
1406 # retrieve balance from table
1407 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1408 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1409 my ($balance) = $sth->fetchrow_array;
1415 $query = "UPDATE $table SET $field = $balance WHERE $where";
1416 do_query($self, $dbh, $query, @values);
1418 $main::lxdebug->leave_sub();
1421 sub update_exchangerate {
1422 $main::lxdebug->enter_sub();
1424 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1426 # some sanity check for currency
1428 $main::lxdebug->leave_sub();
1431 $query = qq|SELECT name AS curr FROM currencies WHERE id=(SELECT currency_id FROM defaults)|;
1433 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1435 if ($curr eq $defaultcurrency) {
1436 $main::lxdebug->leave_sub();
1440 $query = qq|SELECT e.currency_id FROM exchangerate e
1441 WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
1443 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1452 $buy = conv_i($buy, "NULL");
1453 $sell = conv_i($sell, "NULL");
1456 if ($buy != 0 && $sell != 0) {
1457 $set = "buy = $buy, sell = $sell";
1458 } elsif ($buy != 0) {
1459 $set = "buy = $buy";
1460 } elsif ($sell != 0) {
1461 $set = "sell = $sell";
1464 if ($sth->fetchrow_array) {
1465 $query = qq|UPDATE exchangerate
1467 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
1471 $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
1472 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
1475 do_query($self, $dbh, $query, $curr, $transdate);
1477 $main::lxdebug->leave_sub();
1480 sub save_exchangerate {
1481 $main::lxdebug->enter_sub();
1483 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1485 SL::DB->client->with_transaction(sub {
1486 my $dbh = SL::DB->client->dbh;
1490 $buy = $rate if $fld eq 'buy';
1491 $sell = $rate if $fld eq 'sell';
1494 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1496 }) or do { die SL::DB->client->error };
1498 $main::lxdebug->leave_sub();
1501 sub get_exchangerate {
1502 $main::lxdebug->enter_sub();
1504 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1507 unless ($transdate && $curr) {
1508 $main::lxdebug->leave_sub();
1512 $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1514 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1516 if ($curr eq $defaultcurrency) {
1517 $main::lxdebug->leave_sub();
1521 $query = qq|SELECT e.$fld FROM exchangerate e
1522 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1523 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1527 $main::lxdebug->leave_sub();
1529 return $exchangerate;
1532 sub check_exchangerate {
1533 $main::lxdebug->enter_sub();
1535 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1537 if ($fld !~/^buy|sell$/) {
1538 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1541 unless ($transdate) {
1542 $main::lxdebug->leave_sub();
1546 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1548 if ($currency eq $defaultcurrency) {
1549 $main::lxdebug->leave_sub();
1553 my $dbh = $self->get_standard_dbh($myconfig);
1554 my $query = qq|SELECT e.$fld FROM exchangerate e
1555 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1557 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1559 $main::lxdebug->leave_sub();
1561 return $exchangerate;
1564 sub get_all_currencies {
1565 $main::lxdebug->enter_sub();
1568 my $myconfig = shift || \%::myconfig;
1569 my $dbh = $self->get_standard_dbh($myconfig);
1571 my $query = qq|SELECT name FROM currencies|;
1572 my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
1574 $main::lxdebug->leave_sub();
1579 sub get_default_currency {
1580 $main::lxdebug->enter_sub();
1582 my ($self, $myconfig) = @_;
1583 my $dbh = $self->get_standard_dbh($myconfig);
1584 my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1586 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1588 $main::lxdebug->leave_sub();
1590 return $defaultcurrency;
1593 sub set_payment_options {
1594 my ($self, $myconfig, $transdate, $type) = @_;
1596 my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
1599 my $is_invoice = $type =~ m{invoice}i;
1601 $transdate ||= $self->{invdate} || $self->{transdate};
1602 my $due_date = $self->{duedate} || $self->{reqdate};
1604 $self->{$_} = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
1605 $self->{payment_description} = $terms->description;
1606 $self->{netto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
1607 $self->{skonto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
1609 my ($invtotal, $total);
1610 my (%amounts, %formatted_amounts);
1612 if ($self->{type} =~ /_order$/) {
1613 $amounts{invtotal} = $self->{ordtotal};
1614 $amounts{total} = $self->{ordtotal};
1616 } elsif ($self->{type} =~ /_quotation$/) {
1617 $amounts{invtotal} = $self->{quototal};
1618 $amounts{total} = $self->{quototal};
1621 $amounts{invtotal} = $self->{invtotal};
1622 $amounts{total} = $self->{total};
1624 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1626 $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1627 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1628 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1629 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1631 foreach (keys %amounts) {
1632 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1633 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1636 if ($self->{"language_id"}) {
1637 my $language = SL::DB::Language->new(id => $self->{language_id})->load;
1639 $self->{payment_terms} = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
1640 $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
1642 if ($language->output_dateformat) {
1643 foreach my $key (qw(netto_date skonto_date)) {
1644 $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
1648 if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
1649 local $myconfig->{numberformat};
1650 $myconfig->{"numberformat"} = $language->output_numberformat;
1651 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
1655 $self->{payment_terms} = $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
1657 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1658 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1659 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1660 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1661 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1662 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1663 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1664 $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
1665 $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
1666 $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
1667 $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
1669 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1671 $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1675 sub get_template_language {
1676 $main::lxdebug->enter_sub();
1678 my ($self, $myconfig) = @_;
1680 my $template_code = "";
1682 if ($self->{language_id}) {
1683 my $dbh = $self->get_standard_dbh($myconfig);
1684 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1685 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1688 $main::lxdebug->leave_sub();
1690 return $template_code;
1693 sub get_printer_code {
1694 $main::lxdebug->enter_sub();
1696 my ($self, $myconfig) = @_;
1698 my $template_code = "";
1700 if ($self->{printer_id}) {
1701 my $dbh = $self->get_standard_dbh($myconfig);
1702 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1703 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1706 $main::lxdebug->leave_sub();
1708 return $template_code;
1712 $main::lxdebug->enter_sub();
1714 my ($self, $myconfig) = @_;
1716 my $template_code = "";
1718 if ($self->{shipto_id}) {
1719 my $dbh = $self->get_standard_dbh($myconfig);
1720 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1721 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1722 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1724 my $cvars = CVar->get_custom_variables(
1727 trans_id => $self->{shipto_id},
1729 $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
1732 $main::lxdebug->leave_sub();
1736 my ($self, $dbh, $id, $module) = @_;
1741 foreach my $item (qw(name department_1 department_2 street zipcode city country gln
1742 contact phone fax email)) {
1743 if ($self->{"shipto$item"}) {
1744 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1746 push(@values, $self->{"shipto${item}"});
1751 # shiptocp_gender only makes sense, if any other shipto attribute is set.
1752 # Because shiptocp_gender is set to 'm' by default in forms
1753 # it must not be considered above to decide if shiptos has to be added or
1754 # updated, but must be inserted or updated as well in case.
1755 push(@values, $self->{shiptocp_gender});
1757 my $shipto_id = $self->{shipto_id};
1759 if ($self->{shipto_id}) {
1760 my $query = qq|UPDATE shipto set
1762 shiptodepartment_1 = ?,
1763 shiptodepartment_2 = ?,
1773 shiptocp_gender = ?,
1774 WHERE shipto_id = ?|;
1775 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1777 my $query = qq|SELECT * FROM shipto
1778 WHERE shiptoname = ? AND
1779 shiptodepartment_1 = ? AND
1780 shiptodepartment_2 = ? AND
1781 shiptostreet = ? AND
1782 shiptozipcode = ? AND
1784 shiptocountry = ? AND
1786 shiptocontact = ? AND
1790 shiptocp_gender = ? AND
1793 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1796 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1797 shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
1798 shiptocontact, shiptophone, shiptofax, shiptoemail, shiptocp_gender, module)
1799 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1800 do_query($self, $dbh, $insert_query, $id, @values, $module);
1802 $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1805 $shipto_id = $insert_check->{shipto_id};
1808 return unless $shipto_id;
1810 CVar->save_custom_variables(
1813 trans_id => $shipto_id,
1815 name_prefix => 'shipto',
1820 $main::lxdebug->enter_sub();
1822 my ($self, $dbh) = @_;
1824 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1826 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1827 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1828 $self->{"employee_id"} *= 1;
1830 $main::lxdebug->leave_sub();
1833 sub get_employee_data {
1834 $main::lxdebug->enter_sub();
1838 my $defaults = SL::DB::Default->get;
1840 Common::check_params(\%params, qw(prefix));
1841 Common::check_params_x(\%params, qw(id));
1844 $main::lxdebug->leave_sub();
1848 my $myconfig = \%main::myconfig;
1849 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
1851 my ($login, $deleted) = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
1854 # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
1855 $self->{$params{prefix} . '_login'} = $login;
1856 $self->{$params{prefix} . "_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
1859 # get employee data from auth.user_config
1860 my $user = User->new(login => $login);
1861 $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
1863 # get saved employee data from employee
1864 my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
1865 $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
1866 $self->{$params{prefix} . "_name"} = $employee->name;
1869 $main::lxdebug->leave_sub();
1873 $main::lxdebug->enter_sub();
1875 my ($self, $dbh, $id, $key) = @_;
1877 $key = "all_contacts" unless ($key);
1881 $main::lxdebug->leave_sub();
1886 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1887 qq|FROM contacts | .
1888 qq|WHERE cp_cv_id = ? | .
1889 qq|ORDER BY lower(cp_name)|;
1891 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1893 $main::lxdebug->leave_sub();
1897 $main::lxdebug->enter_sub();
1899 my ($self, $dbh, $key) = @_;
1901 my ($all, $old_id, $where, @values);
1903 if (ref($key) eq "HASH") {
1906 $key = "ALL_PROJECTS";
1908 foreach my $p (keys(%{$params})) {
1910 $all = $params->{$p};
1911 } elsif ($p eq "old_id") {
1912 $old_id = $params->{$p};
1913 } elsif ($p eq "key") {
1914 $key = $params->{$p};
1920 $where = "WHERE active ";
1922 if (ref($old_id) eq "ARRAY") {
1923 my @ids = grep({ $_ } @{$old_id});
1925 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1926 push(@values, @ids);
1929 $where .= " OR (id = ?) ";
1930 push(@values, $old_id);
1936 qq|SELECT id, projectnumber, description, active | .
1939 qq|ORDER BY lower(projectnumber)|;
1941 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1943 $main::lxdebug->leave_sub();
1947 $main::lxdebug->enter_sub();
1949 my ($self, $dbh, $key) = @_;
1951 $key = "all_printers" unless ($key);
1953 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1955 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1957 $main::lxdebug->leave_sub();
1961 $main::lxdebug->enter_sub();
1963 my ($self, $dbh, $params) = @_;
1966 $key = $params->{key};
1967 $key = "all_charts" unless ($key);
1969 my $transdate = quote_db_date($params->{transdate});
1972 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
1974 qq|LEFT JOIN taxkeys tk ON | .
1975 qq|(tk.id = (SELECT id FROM taxkeys | .
1976 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1977 qq| ORDER BY startdate DESC LIMIT 1)) | .
1978 qq|ORDER BY c.accno|;
1980 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1982 $main::lxdebug->leave_sub();
1986 $main::lxdebug->enter_sub();
1988 my ($self, $dbh, $key) = @_;
1990 $key = "all_taxzones" unless ($key);
1992 $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
1994 my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
1996 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1998 $main::lxdebug->leave_sub();
2001 sub _get_employees {
2002 $main::lxdebug->enter_sub();
2004 my ($self, $dbh, $params) = @_;
2009 if (ref $params eq 'HASH') {
2010 $key = $params->{key};
2011 $deleted = $params->{deleted};
2017 $key ||= "all_employees";
2018 my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
2019 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
2021 $main::lxdebug->leave_sub();
2024 sub _get_business_types {
2025 $main::lxdebug->enter_sub();
2027 my ($self, $dbh, $key) = @_;
2029 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2030 $options->{key} ||= "all_business_types";
2033 if (exists $options->{salesman}) {
2034 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2037 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2039 $main::lxdebug->leave_sub();
2042 sub _get_languages {
2043 $main::lxdebug->enter_sub();
2045 my ($self, $dbh, $key) = @_;
2047 $key = "all_languages" unless ($key);
2049 my $query = qq|SELECT * FROM language ORDER BY id|;
2051 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2053 $main::lxdebug->leave_sub();
2056 sub _get_dunning_configs {
2057 $main::lxdebug->enter_sub();
2059 my ($self, $dbh, $key) = @_;
2061 $key = "all_dunning_configs" unless ($key);
2063 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2065 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2067 $main::lxdebug->leave_sub();
2070 sub _get_currencies {
2071 $main::lxdebug->enter_sub();
2073 my ($self, $dbh, $key) = @_;
2075 $key = "all_currencies" unless ($key);
2077 $self->{$key} = [$self->get_all_currencies()];
2079 $main::lxdebug->leave_sub();
2083 $main::lxdebug->enter_sub();
2085 my ($self, $dbh, $key) = @_;
2087 $key = "all_payments" unless ($key);
2089 my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2091 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2093 $main::lxdebug->leave_sub();
2096 sub _get_customers {
2097 $main::lxdebug->enter_sub();
2099 my ($self, $dbh, $key) = @_;
2101 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2102 $options->{key} ||= "all_customers";
2103 my $limit_clause = $options->{limit} ? "LIMIT $options->{limit}" : '';
2106 push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman};
2107 push @where, qq|NOT obsolete| if !$options->{with_obsolete};
2108 my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2110 my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2111 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2113 $main::lxdebug->leave_sub();
2117 $main::lxdebug->enter_sub();
2119 my ($self, $dbh, $key) = @_;
2121 $key = "all_vendors" unless ($key);
2123 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2125 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2127 $main::lxdebug->leave_sub();
2130 sub _get_departments {
2131 $main::lxdebug->enter_sub();
2133 my ($self, $dbh, $key) = @_;
2135 $key = "all_departments" unless ($key);
2137 my $query = qq|SELECT * FROM department ORDER BY description|;
2139 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2141 $main::lxdebug->leave_sub();
2144 sub _get_warehouses {
2145 $main::lxdebug->enter_sub();
2147 my ($self, $dbh, $param) = @_;
2149 my ($key, $bins_key);
2151 if ('' eq ref $param) {
2155 $key = $param->{key};
2156 $bins_key = $param->{bins};
2159 my $query = qq|SELECT w.* FROM warehouse w
2160 WHERE (NOT w.invalid) AND
2161 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2162 ORDER BY w.sortkey|;
2164 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2167 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2168 ORDER BY description|;
2169 my $sth = prepare_query($self, $dbh, $query);
2171 foreach my $warehouse (@{ $self->{$key} }) {
2172 do_statement($self, $sth, $query, $warehouse->{id});
2173 $warehouse->{$bins_key} = [];
2175 while (my $ref = $sth->fetchrow_hashref()) {
2176 push @{ $warehouse->{$bins_key} }, $ref;
2182 $main::lxdebug->leave_sub();
2186 $main::lxdebug->enter_sub();
2188 my ($self, $dbh, $table, $key, $sortkey) = @_;
2190 my $query = qq|SELECT * FROM $table|;
2191 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2193 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2195 $main::lxdebug->leave_sub();
2199 $main::lxdebug->enter_sub();
2204 croak "get_lists: shipto is no longer supported" if $params{shipto};
2206 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2207 my ($sth, $query, $ref);
2210 if ($params{contacts}) {
2211 $vc = 'customer' if $self->{"vc"} eq "customer";
2212 $vc = 'vendor' if $self->{"vc"} eq "vendor";
2213 die "invalid use of get_lists, need 'vc'" unless $vc;
2214 $vc_id = $self->{"${vc}_id"};
2217 if ($params{"contacts"}) {
2218 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2221 if ($params{"projects"} || $params{"all_projects"}) {
2222 $self->_get_projects($dbh, $params{"all_projects"} ?
2223 $params{"all_projects"} : $params{"projects"},
2224 $params{"all_projects"} ? 1 : 0);
2227 if ($params{"printers"}) {
2228 $self->_get_printers($dbh, $params{"printers"});
2231 if ($params{"languages"}) {
2232 $self->_get_languages($dbh, $params{"languages"});
2235 if ($params{"charts"}) {
2236 $self->_get_charts($dbh, $params{"charts"});
2239 if ($params{"taxzones"}) {
2240 $self->_get_taxzones($dbh, $params{"taxzones"});
2243 if ($params{"employees"}) {
2244 $self->_get_employees($dbh, $params{"employees"});
2247 if ($params{"salesmen"}) {
2248 $self->_get_employees($dbh, $params{"salesmen"});
2251 if ($params{"business_types"}) {
2252 $self->_get_business_types($dbh, $params{"business_types"});
2255 if ($params{"dunning_configs"}) {
2256 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2259 if($params{"currencies"}) {
2260 $self->_get_currencies($dbh, $params{"currencies"});
2263 if($params{"customers"}) {
2264 $self->_get_customers($dbh, $params{"customers"});
2267 if($params{"vendors"}) {
2268 if (ref $params{"vendors"} eq 'HASH') {
2269 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2271 $self->_get_vendors($dbh, $params{"vendors"});
2275 if($params{"payments"}) {
2276 $self->_get_payments($dbh, $params{"payments"});
2279 if($params{"departments"}) {
2280 $self->_get_departments($dbh, $params{"departments"});
2283 if ($params{price_factors}) {
2284 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2287 if ($params{warehouses}) {
2288 $self->_get_warehouses($dbh, $params{warehouses});
2291 if ($params{partsgroup}) {
2292 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2295 $main::lxdebug->leave_sub();
2298 # this sub gets the id and name from $table
2300 $main::lxdebug->enter_sub();
2302 my ($self, $myconfig, $table) = @_;
2304 # connect to database
2305 my $dbh = $self->get_standard_dbh($myconfig);
2307 $table = $table eq "customer" ? "customer" : "vendor";
2308 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2310 my ($query, @values);
2312 if (!$self->{openinvoices}) {
2314 if ($self->{customernumber} ne "") {
2315 $where = qq|(vc.customernumber ILIKE ?)|;
2316 push(@values, like($self->{customernumber}));
2318 $where = qq|(vc.name ILIKE ?)|;
2319 push(@values, like($self->{$table}));
2323 qq~SELECT vc.id, vc.name,
2324 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2326 WHERE $where AND (NOT vc.obsolete)
2330 qq~SELECT DISTINCT vc.id, vc.name,
2331 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2333 JOIN $table vc ON (a.${table}_id = vc.id)
2334 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2336 push(@values, like($self->{$table}));
2339 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2341 $main::lxdebug->leave_sub();
2343 return scalar(@{ $self->{name_list} });
2348 my ($self, $table, $provided_dbh) = @_;
2350 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
2351 return unless $self->{id};
2352 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2354 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2355 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2356 $ref->{mtime} ||= $ref->{itime};
2357 $self->{lastmtime} = $ref->{mtime};
2361 sub mtime_ischanged {
2362 my ($self, $table, $option) = @_;
2364 return unless $self->{id};
2365 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2367 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2368 my $ref = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
2369 $ref->{mtime} ||= $ref->{itime};
2371 if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
2372 $self->error(($option eq 'mail') ?
2373 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") :
2374 t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
2376 $::dispatcher->end_request;
2380 # language_payment duplicates some of the functionality of all_vc (language,
2381 # printer, payment_terms), and at least in the case of sales invoices both
2382 # all_vc and language_payment are called when adding new invoices
2383 sub language_payment {
2384 $main::lxdebug->enter_sub();
2386 my ($self, $myconfig) = @_;
2388 my $dbh = $self->get_standard_dbh($myconfig);
2390 my $query = qq|SELECT id, description
2394 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2397 $query = qq|SELECT printer_description, id
2399 ORDER BY printer_description|;
2401 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2404 $query = qq|SELECT id, description
2406 WHERE ( obsolete IS FALSE OR id = ? )
2408 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
2410 # get buchungsgruppen
2411 $query = qq|SELECT id, description
2412 FROM buchungsgruppen|;
2414 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2416 $main::lxdebug->leave_sub();
2419 # this is only used for reports
2420 sub all_departments {
2421 $main::lxdebug->enter_sub();
2423 my ($self, $myconfig, $table) = @_;
2425 my $dbh = $self->get_standard_dbh($myconfig);
2427 my $query = qq|SELECT id, description
2429 ORDER BY description|;
2430 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2432 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2434 $main::lxdebug->leave_sub();
2438 $main::lxdebug->enter_sub();
2440 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2443 if ($table eq "customer") {
2452 # get last customers or vendors
2453 my ($query, $sth, $ref);
2455 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2460 my $transdate = "current_date";
2461 if ($self->{transdate}) {
2462 $transdate = $dbh->quote($self->{transdate});
2465 # now get the account numbers
2467 SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
2469 -- find newest entries in taxkeys
2471 SELECT chart_id, MAX(startdate) AS startdate
2473 WHERE (startdate <= $transdate)
2475 ) tk ON (c.id = tk.chart_id)
2476 -- and load all of those entries
2477 INNER JOIN taxkeys tk2
2478 ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
2479 WHERE (c.link LIKE ?)
2482 $sth = $dbh->prepare($query);
2484 do_statement($self, $sth, $query, like($module));
2486 $self->{accounts} = "";
2487 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2489 foreach my $key (split(/:/, $ref->{link})) {
2490 if ($key =~ /\Q$module\E/) {
2492 # cross reference for keys
2493 $xkeyref{ $ref->{accno} } = $key;
2495 push @{ $self->{"${module}_links"}{$key} },
2496 { accno => $ref->{accno},
2497 chart_id => $ref->{chart_id},
2498 description => $ref->{description},
2499 taxkey => $ref->{taxkey_id},
2500 tax_id => $ref->{tax_id} };
2502 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2508 # get taxkeys and description
2509 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2510 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2512 if (($module eq "AP") || ($module eq "AR")) {
2513 # get tax rates and description
2514 $query = qq|SELECT * FROM tax|;
2515 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2518 my $extra_columns = '';
2519 $extra_columns .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
2524 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid, a.deliverydate,
2525 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,
2527 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2528 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2529 a.globalproject_id, a.transaction_description, ${extra_columns}
2531 d.description AS department,
2534 JOIN $table c ON (a.${table}_id = c.id)
2535 LEFT JOIN employee e ON (e.id = a.employee_id)
2536 LEFT JOIN department d ON (d.id = a.department_id)
2538 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2540 foreach my $key (keys %$ref) {
2541 $self->{$key} = $ref->{$key};
2543 $self->{mtime} ||= $self->{itime};
2544 $self->{lastmtime} = $self->{mtime};
2545 my $transdate = "current_date";
2546 if ($self->{transdate}) {
2547 $transdate = $dbh->quote($self->{transdate});
2550 # now get the account numbers
2551 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
2553 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2555 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2556 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2559 $sth = $dbh->prepare($query);
2560 do_statement($self, $sth, $query, like($module));
2562 $self->{accounts} = "";
2563 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2565 foreach my $key (split(/:/, $ref->{link})) {
2566 if ($key =~ /\Q$module\E/) {
2568 # cross reference for keys
2569 $xkeyref{ $ref->{accno} } = $key;
2571 push @{ $self->{"${module}_links"}{$key} },
2572 { accno => $ref->{accno},
2573 chart_id => $ref->{chart_id},
2574 description => $ref->{description},
2575 taxkey => $ref->{taxkey_id},
2576 tax_id => $ref->{tax_id} };
2578 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2584 # get amounts from individual entries
2587 c.accno, c.description,
2588 a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
2592 LEFT JOIN chart c ON (c.id = a.chart_id)
2593 LEFT JOIN project p ON (p.id = a.project_id)
2594 LEFT JOIN tax t ON (t.id= a.tax_id)
2595 WHERE a.trans_id = ?
2596 AND a.fx_transaction = '0'
2597 ORDER BY a.acc_trans_id, a.transdate|;
2598 $sth = $dbh->prepare($query);
2599 do_statement($self, $sth, $query, $self->{id});
2601 # get exchangerate for currency
2602 $self->{exchangerate} =
2603 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2606 # store amounts in {acc_trans}{$key} for multiple accounts
2607 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2608 $ref->{exchangerate} =
2609 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2610 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2613 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2614 $ref->{amount} *= -1;
2616 $ref->{index} = $index;
2618 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2625 d.closedto, d.revtrans,
2626 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2627 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2628 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2629 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2630 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2632 $ref = selectfirst_hashref_query($self, $dbh, $query);
2633 map { $self->{$_} = $ref->{$_} } keys %$ref;
2640 current_date AS transdate, d.closedto, d.revtrans,
2641 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2642 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2643 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2644 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2645 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2647 $ref = selectfirst_hashref_query($self, $dbh, $query);
2648 map { $self->{$_} = $ref->{$_} } keys %$ref;
2650 if ($self->{"$self->{vc}_id"}) {
2652 # only setup currency
2653 ($self->{currency}) = $self->{defaultcurrency} if !$self->{currency};
2657 $self->lastname_used($dbh, $myconfig, $table, $module);
2659 # get exchangerate for currency
2660 $self->{exchangerate} =
2661 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2667 $main::lxdebug->leave_sub();
2671 $main::lxdebug->enter_sub();
2673 my ($self, $dbh, $myconfig, $table, $module) = @_;
2677 $table = $table eq "customer" ? "customer" : "vendor";
2678 my %column_map = ("a.${table}_id" => "${table}_id",
2679 "a.department_id" => "department_id",
2680 "d.description" => "department",
2681 "ct.name" => $table,
2682 "cu.name" => "currency",
2685 if ($self->{type} =~ /delivery_order/) {
2686 $arap = 'delivery_orders';
2687 delete $column_map{"cu.currency"};
2689 } elsif ($self->{type} =~ /_order/) {
2691 $where = "quotation = '0'";
2693 } elsif ($self->{type} =~ /_quotation/) {
2695 $where = "quotation = '1'";
2697 } elsif ($table eq 'customer') {
2705 $where = "($where) AND" if ($where);
2706 my $query = qq|SELECT MAX(id) FROM $arap
2707 WHERE $where ${table}_id > 0|;
2708 my ($trans_id) = selectrow_query($self, $dbh, $query);
2711 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2712 $query = qq|SELECT $column_spec
2714 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2715 LEFT JOIN department d ON (a.department_id = d.id)
2716 LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
2718 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2720 map { $self->{$_} = $ref->{$_} } values %column_map;
2722 $main::lxdebug->leave_sub();
2725 sub get_variable_content_types {
2728 my %html_variables = (
2729 longdescription => 'html',
2730 partnotes => 'html',
2732 orignotes => 'html',
2737 header_text => 'html',
2738 footer_text => 'html',
2743 $self->get_variable_content_types_for_cvars,
2747 sub get_variable_content_types_for_cvars {
2749 my $html_configs = SL::DB::Manager::CustomVariableConfig->get_all(where => [ type => 'htmlfield' ]);
2752 if (@{ $html_configs }) {
2753 my %prefix_by_module = (
2754 Contacts => 'cp_cvar_',
2757 Projects => 'project_cvar_',
2758 ShipTo => 'shiptocvar_',
2761 foreach my $cfg (@{ $html_configs }) {
2762 my $prefix = $prefix_by_module{$cfg->module};
2763 $types{$prefix . $cfg->name} = 'html' if $prefix;
2771 $main::lxdebug->enter_sub();
2774 my $myconfig = shift || \%::myconfig;
2775 my ($thisdate, $days) = @_;
2777 my $dbh = $self->get_standard_dbh($myconfig);
2782 my $dateformat = $myconfig->{dateformat};
2783 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2784 $thisdate = $dbh->quote($thisdate);
2785 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2787 $query = qq|SELECT current_date AS thisdate|;
2790 ($thisdate) = selectrow_query($self, $dbh, $query);
2792 $main::lxdebug->leave_sub();
2798 $main::lxdebug->enter_sub();
2800 my ($self, $flds, $new, $count, $numrows) = @_;
2804 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2809 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2811 my $j = $item->{ndx} - 1;
2812 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2816 for $i ($count + 1 .. $numrows) {
2817 map { delete $self->{"${_}_$i"} } @{$flds};
2820 $main::lxdebug->leave_sub();
2824 $main::lxdebug->enter_sub();
2826 my ($self, $myconfig) = @_;
2830 SL::DB->client->with_transaction(sub {
2831 my $dbh = SL::DB->client->dbh;
2833 my $query = qq|DELETE FROM status
2834 WHERE (formname = ?) AND (trans_id = ?)|;
2835 my $sth = prepare_query($self, $dbh, $query);
2837 if ($self->{formname} =~ /(check|receipt)/) {
2838 for $i (1 .. $self->{rowcount}) {
2839 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2842 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2846 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2847 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2849 my %queued = split / /, $self->{queued};
2852 if ($self->{formname} =~ /(check|receipt)/) {
2854 # this is a check or receipt, add one entry for each lineitem
2855 my ($accno) = split /--/, $self->{account};
2856 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2857 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2858 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2859 $sth = prepare_query($self, $dbh, $query);
2861 for $i (1 .. $self->{rowcount}) {
2862 if ($self->{"checked_$i"}) {
2863 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2869 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2870 VALUES (?, ?, ?, ?, ?)|;
2871 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2872 $queued{$self->{formname}}, $self->{formname});
2875 }) or do { die SL::DB->client->error };
2877 $main::lxdebug->leave_sub();
2881 $main::lxdebug->enter_sub();
2883 my ($self, $dbh) = @_;
2885 my ($query, $printed, $emailed);
2887 my $formnames = $self->{printed};
2888 my $emailforms = $self->{emailed};
2890 $query = qq|DELETE FROM status
2891 WHERE (formname = ?) AND (trans_id = ?)|;
2892 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2894 # this only applies to the forms
2895 # checks and receipts are posted when printed or queued
2897 if ($self->{queued}) {
2898 my %queued = split / /, $self->{queued};
2900 foreach my $formname (keys %queued) {
2901 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2902 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2904 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2905 VALUES (?, ?, ?, ?, ?)|;
2906 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2908 $formnames =~ s/\Q$self->{formname}\E//;
2909 $emailforms =~ s/\Q$self->{formname}\E//;
2914 # save printed, emailed info
2915 $formnames =~ s/^ +//g;
2916 $emailforms =~ s/^ +//g;
2919 map { $status{$_}{printed} = 1 } split / +/, $formnames;
2920 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2922 foreach my $formname (keys %status) {
2923 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
2924 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
2926 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2927 VALUES (?, ?, ?, ?)|;
2928 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2931 $main::lxdebug->leave_sub();
2935 # $main::locale->text('SAVED')
2936 # $main::locale->text('SCREENED')
2937 # $main::locale->text('DELETED')
2938 # $main::locale->text('ADDED')
2939 # $main::locale->text('PAYMENT POSTED')
2940 # $main::locale->text('POSTED')
2941 # $main::locale->text('POSTED AS NEW')
2942 # $main::locale->text('ELSE')
2943 # $main::locale->text('SAVED FOR DUNNING')
2944 # $main::locale->text('DUNNING STARTED')
2945 # $main::locale->text('PREVIEWED')
2946 # $main::locale->text('PRINTED')
2947 # $main::locale->text('MAILED')
2948 # $main::locale->text('SCREENED')
2949 # $main::locale->text('CANCELED')
2950 # $main::locale->text('IMPORT')
2951 # $main::locale->text('UNDO TRANSFER')
2952 # $main::locale->text('UNIMPORT')
2953 # $main::locale->text('invoice')
2954 # $main::locale->text('invoice_for_advance_payment')
2955 # $main::locale->text('final_invoice')
2956 # $main::locale->text('proforma')
2957 # $main::locale->text('sales_order')
2958 # $main::locale->text('pick_list')
2959 # $main::locale->text('purchase_order')
2960 # $main::locale->text('bin_list')
2961 # $main::locale->text('sales_quotation')
2962 # $main::locale->text('request_quotation')
2965 $main::lxdebug->enter_sub();
2968 my $dbh = shift || SL::DB->client->dbh;
2969 SL::DB->client->with_transaction(sub {
2971 if(!exists $self->{employee_id}) {
2972 &get_employee($self, $dbh);
2976 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2977 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
2978 my @values = (conv_i($self->{id}), $self->{login},
2979 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
2980 do_query($self, $dbh, $query, @values);
2982 }) or do { die SL::DB->client->error };
2984 $main::lxdebug->leave_sub();
2988 $main::lxdebug->enter_sub();
2990 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
2991 my ($orderBy, $desc) = split(/\-\-/, $order);
2992 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
2995 if ($trans_id ne "") {
2997 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 | .
2998 qq|FROM history_erp h | .
2999 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3000 qq|WHERE (trans_id = | . $dbh->quote($trans_id) . qq|) $restriction | .
3003 my $sth = $dbh->prepare($query) || $self->dberror($query);
3005 $sth->execute() || $self->dberror("$query");
3007 while(my $hash_ref = $sth->fetchrow_hashref()) {
3008 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3009 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3010 my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
3011 $hash_ref->{snumbers} = $number;
3012 $hash_ref->{haslink} = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
3013 $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
3014 $tempArray[$i++] = $hash_ref;
3016 $main::lxdebug->leave_sub() and return \@tempArray
3017 if ($i > 0 && $tempArray[0] ne "");
3019 $main::lxdebug->leave_sub();
3023 sub get_partsgroup {
3024 $main::lxdebug->enter_sub();
3026 my ($self, $myconfig, $p) = @_;
3027 my $target = $p->{target} || 'all_partsgroup';
3029 my $dbh = $self->get_standard_dbh($myconfig);
3031 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3033 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3036 if ($p->{searchitems} eq 'part') {
3037 $query .= qq|WHERE p.part_type = 'part'|;
3039 if ($p->{searchitems} eq 'service') {
3040 $query .= qq|WHERE p.part_type = 'service'|;
3042 if ($p->{searchitems} eq 'assembly') {
3043 $query .= qq|WHERE p.part_type = 'assembly'|;
3046 $query .= qq|ORDER BY partsgroup|;
3049 $query = qq|SELECT id, partsgroup FROM partsgroup
3050 ORDER BY partsgroup|;
3053 if ($p->{language_code}) {
3054 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3055 t.description AS translation
3057 JOIN parts p ON (p.partsgroup_id = pg.id)
3058 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3059 ORDER BY translation|;
3060 @values = ($p->{language_code});
3063 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3065 $main::lxdebug->leave_sub();
3068 sub get_pricegroup {
3069 $main::lxdebug->enter_sub();
3071 my ($self, $myconfig, $p) = @_;
3073 my $dbh = $self->get_standard_dbh($myconfig);
3075 my $query = qq|SELECT p.id, p.pricegroup
3078 $query .= qq| ORDER BY pricegroup|;
3081 $query = qq|SELECT id, pricegroup FROM pricegroup
3082 ORDER BY pricegroup|;
3085 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3087 $main::lxdebug->leave_sub();
3091 # usage $form->all_years($myconfig, [$dbh])
3092 # return list of all years where bookings found
3095 $main::lxdebug->enter_sub();
3097 my ($self, $myconfig, $dbh) = @_;
3099 $dbh ||= $self->get_standard_dbh($myconfig);
3102 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3103 (SELECT MAX(transdate) FROM acc_trans)|;
3104 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3106 if ($myconfig->{dateformat} =~ /^yy/) {
3107 ($startdate) = split /\W/, $startdate;
3108 ($enddate) = split /\W/, $enddate;
3110 (@_) = split /\W/, $startdate;
3112 (@_) = split /\W/, $enddate;
3117 $startdate = substr($startdate,0,4);
3118 $enddate = substr($enddate,0,4);
3120 while ($enddate >= $startdate) {
3121 push @all_years, $enddate--;
3126 $main::lxdebug->leave_sub();
3130 $main::lxdebug->enter_sub();
3134 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3136 $main::lxdebug->leave_sub();
3140 $main::lxdebug->enter_sub();
3145 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3147 $main::lxdebug->leave_sub();
3150 sub prepare_for_printing {
3153 my $defaults = SL::DB::Default->get;
3155 $self->{templates} ||= $defaults->templates;
3156 $self->{formname} ||= $self->{type};
3157 $self->{media} ||= 'email';
3159 die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3161 # Several fields that used to reside in %::myconfig (stored in
3162 # auth.user_config) are now stored in defaults. Copy them over for
3164 $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
3166 $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
3168 if (!$self->{employee_id}) {
3169 $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
3170 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
3173 my $language = $self->{language} ? '_' . $self->{language} : '';
3175 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3176 if ($self->{language_id}) {
3177 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3180 $output_dateformat ||= $::myconfig{dateformat};
3181 $output_numberformat ||= $::myconfig{numberformat};
3182 $output_longdates //= 1;
3184 $self->{myconfig_output_dateformat} = $output_dateformat // $::myconfig{dateformat};
3185 $self->{myconfig_output_longdates} = $output_longdates // 1;
3186 $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
3188 # Retrieve accounts for tax calculation.
3189 IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3191 if ($self->{type} =~ /_delivery_order$/) {
3192 DO->order_details(\%::myconfig, $self);
3193 } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3194 OE->order_details(\%::myconfig, $self);
3196 IS->invoice_details(\%::myconfig, $self, $::locale);
3199 $self->set_addition_billing_address_print_variables;
3201 # Chose extension & set source file name
3202 my $extension = 'html';
3203 if ($self->{format} eq 'postscript') {
3204 $self->{postscript} = 1;
3206 } elsif ($self->{"format"} =~ /pdf/) {
3208 $extension = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3209 } elsif ($self->{"format"} =~ /opendocument/) {
3210 $self->{opendocument} = 1;
3212 } elsif ($self->{"format"} =~ /excel/) {
3217 my $printer_code = $self->{printer_code} ? '_' . $self->{printer_code} : '';
3218 my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
3219 $self->{IN} = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3222 $self->format_dates($output_dateformat, $output_longdates,
3223 qw(invdate orddate quodate pldate duedate reqdate transdate tax_point shippingdate deliverydate validitydate paymentdate datepaid
3224 transdate_oe deliverydate_oe employee_startdate employee_enddate),
3225 grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3227 $self->reformat_numbers($output_numberformat, 2,
3228 qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3229 grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3231 $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3233 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3235 if (scalar @{ $cvar_date_fields }) {
3236 $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3239 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3240 $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3244 if (($self->{language} // '') ne '') {
3245 my $template_arrays = $self->{TEMPLATE_ARRAYS} || $self;
3246 for my $idx (0..scalar(@{ $template_arrays->{unit} }) - 1) {
3247 $template_arrays->{unit}->[$idx] = AM->translate_units($self, $self->{language}, $template_arrays->{unit}->[$idx], $template_arrays->{qty}->[$idx])
3251 $self->{template_meta} = {
3252 formname => $self->{formname},
3253 language => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
3254 format => $self->{format},
3255 media => $self->{media},
3256 extension => $extension,
3257 printer => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
3258 today => DateTime->today,
3261 if ($defaults->print_interpolate_variables_in_positions) {
3262 $self->substitute_placeholders_in_template_arrays({ field => 'description', type => 'text' }, { field => 'longdescription', type => 'html' });
3268 sub set_addition_billing_address_print_variables {
3271 return if !$self->{billing_address_id};
3273 my $address = SL::DB::Manager::AdditionalBillingAddress->find_by(id => $self->{billing_address_id});
3274 return if !$address;
3276 $self->{"billing_address_${_}"} = $address->$_ for map { $_->name } @{ $address->meta->columns };
3279 sub substitute_placeholders_in_template_arrays {
3280 my ($self, @fields) = @_;
3282 foreach my $spec (@fields) {
3283 $spec = { field => $spec, type => 'text' } if !ref($spec);
3284 my $field = $spec->{field};
3286 next unless exists $self->{TEMPLATE_ARRAYS} && exists $self->{TEMPLATE_ARRAYS}->{$field};
3288 my $tag_start = $spec->{type} eq 'html' ? '<%' : '<%';
3289 my $tag_end = $spec->{type} eq 'html' ? '%>' : '%>';
3290 my $formatter = $spec->{type} eq 'html' ? sub { $::locale->quote_special_chars('html', $_[0] // '') } : sub { $_[0] };
3292 $self->{TEMPLATE_ARRAYS}->{$field} = [
3293 apply { s{${tag_start}(.+?)${tag_end}}{ $formatter->($self->{$1}) }eg }
3294 @{ $self->{TEMPLATE_ARRAYS}->{$field} }
3301 sub calculate_arap {
3302 my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
3304 # this function is used to calculate netamount, total_tax and amount for AP and
3305 # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
3307 # Thus it needs a fully prepared $form to work on.
3308 # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
3310 # The calculated total values are all rounded (default is to 2 places) and
3311 # returned as parameters rather than directly modifying form. The aim is to
3312 # make the calculation of AP and AR behave identically. There is a test-case
3313 # for this function in t/form/arap.t
3315 # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
3316 # modified and formatted and receive the correct sign for writing straight to
3317 # acc_trans, depending on whether they are ar or ap.
3320 die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
3321 die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
3322 die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
3323 $roundplaces = 2 unless $roundplaces;
3325 my $sign = 1; # adjust final results for writing amount to acc_trans
3326 $sign = -1 if $buysell eq 'buy';
3328 my ($netamount,$total_tax,$amount);
3332 # parse and round amounts, setting correct sign for writing to acc_trans
3333 for my $i (1 .. $self->{rowcount}) {
3334 $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
3336 $amount += $self->{"amount_$i"} * $sign;
3339 for my $i (1 .. $self->{rowcount}) {
3340 next unless $self->{"amount_$i"};
3341 ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
3342 my $tax_id = $self->{"tax_id_$i"};
3344 my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
3346 if ( $selected_tax ) {
3348 if ( $buysell eq 'sell' ) {
3349 $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3351 $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3354 $self->{"taxkey_$i"} = $selected_tax->taxkey;
3355 $self->{"taxrate_$i"} = $selected_tax->rate;
3358 ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
3360 $netamount += $self->{"amount_$i"};
3361 $total_tax += $self->{"tax_$i"};
3364 $amount = $netamount + $total_tax;
3366 # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
3367 # but reverse sign of totals for writing amounts to ar
3368 if ( $buysell eq 'buy' ) {
3374 return($netamount,$total_tax,$amount);
3378 my ($self, $dateformat, $longformat, @indices) = @_;
3380 $dateformat ||= $::myconfig{dateformat};
3382 foreach my $idx (@indices) {
3383 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3384 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3385 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3389 next unless defined $self->{$idx};
3391 if (!ref($self->{$idx})) {
3392 $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3394 } elsif (ref($self->{$idx}) eq "ARRAY") {
3395 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3396 $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3402 sub reformat_numbers {
3403 my ($self, $numberformat, $places, @indices) = @_;
3405 return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3407 foreach my $idx (@indices) {
3408 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3409 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3410 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3414 next unless defined $self->{$idx};
3416 if (!ref($self->{$idx})) {
3417 $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3419 } elsif (ref($self->{$idx}) eq "ARRAY") {
3420 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3421 $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3426 my $saved_numberformat = $::myconfig{numberformat};
3427 $::myconfig{numberformat} = $numberformat;
3429 foreach my $idx (@indices) {
3430 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3431 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3432 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3436 next unless defined $self->{$idx};
3438 if (!ref($self->{$idx})) {
3439 $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3441 } elsif (ref($self->{$idx}) eq "ARRAY") {
3442 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3443 $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3448 $::myconfig{numberformat} = $saved_numberformat;
3451 sub create_email_signature {
3452 my $client_signature = $::instance_conf->get_signature;
3453 my $user_signature = $::myconfig{signature};
3455 return join '', grep { $_ } ($user_signature, $client_signature);
3459 # this function calculates the net amount and tax for the lines in ar, ap and
3460 # gl and is used for update as well as post. When used with update the return
3461 # value of amount isn't needed
3463 # calculate_tax should always work with positive values, or rather as the user inputs them
3464 # calculate_tax uses db/perl numberformat, i.e. parsed numbers
3465 # convert to negative numbers (when necessary) only when writing to acc_trans
3466 # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
3467 # for post_transaction amount already contains exchangerate and correct sign and is rounded
3468 # calculate_tax doesn't (need to) know anything about exchangerate
3470 my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
3478 # calculate tax (unrounded), subtract from amount, round amount and round tax
3479 $tax = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
3480 $amount = $self->round_amount($amount - $tax, $roundplaces);
3481 $tax = $self->round_amount($tax, $roundplaces);
3483 $tax = $amount * $taxrate;
3484 $tax = $self->round_amount($tax, $roundplaces);
3487 $tax = 0 unless $tax;
3489 return ($amount,$tax);
3498 SL::Form.pm - main data object.
3502 This is the main data object of kivitendo.
3503 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3504 Points of interest for a beginner are:
3506 - $form->error - renders a generic error in html. accepts an error message
3507 - $form->get_standard_dbh - returns a database connection for the
3509 =head1 SPECIAL FUNCTIONS
3511 =head2 C<redirect_header> $url
3513 Generates a HTTP redirection header for the new C<$url>. Constructs an
3514 absolute URL including scheme, host name and port. If C<$url> is a
3515 relative URL then it is considered relative to kivitendo base URL.
3517 This function C<die>s if headers have already been created with
3518 C<$::form-E<gt>header>.
3522 print $::form->redirect_header('oe.pl?action=edit&id=1234');
3523 print $::form->redirect_header('http://www.lx-office.org/');
3527 Generates a general purpose http/html header and includes most of the scripts
3528 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3530 Only one header will be generated. If the method was already called in this
3531 request it will not output anything and return undef. Also if no
3532 HTTP_USER_AGENT is found, no header is generated.
3534 Although header does not accept parameters itself, it will honor special
3535 hashkeys of its Form instance:
3543 If one of these is set, a http-equiv refresh is generated. Missing parameters
3544 default to 3 seconds and the refering url.
3548 Either a scalar or an array ref. Will be inlined into the header. Add
3549 stylesheets with the L<use_stylesheet> function.
3553 If true, a css snippet will be generated that sets the page in landscape mode.
3557 Used to override the default favicon.
3561 A html page title will be generated from this
3563 =item mtime_ischanged
3565 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
3567 Can be used / called with any table, that has itime and mtime attributes.
3568 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
3569 Can be called wit C<option> mail to generate a different error message.
3571 Returns undef if no save operation has been done yet ($self->{id} not present).
3572 Returns undef if no concurrent write process is detected otherwise a error message.