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 Params::Validate qw(:all);
53 use POSIX qw(strftime);
63 use SL::DB::AdditionalBillingAddress;
65 use SL::DB::CustomVariableConfig;
67 use SL::DB::PaymentTerm;
70 use SL::Helper::Flash qw();
73 use SL::Layout::Dispatcher;
75 use SL::Locale::String;
78 use SL::MoreCommon qw(uri_encode uri_decode);
80 use SL::PrefixedNumber;
89 use List::Util qw(first max min sum);
90 use List::MoreUtils qw(all any apply);
92 use SL::Helper::File qw(:all);
93 use SL::Helper::Number;
94 use SL::Helper::CreatePDF qw(merge_pdfs);
99 SL::Version->get_version;
103 $main::lxdebug->enter_sub();
110 if ($LXDebug::watch_form) {
111 require SL::Watchdog;
112 tie %{ $self }, 'SL::Watchdog';
117 $main::lxdebug->leave_sub();
122 sub _flatten_variables_rec {
123 $main::lxdebug->enter_sub(2);
132 if ('' eq ref $curr->{$key}) {
133 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
135 } elsif ('HASH' eq ref $curr->{$key}) {
136 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
137 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
141 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
142 my $first_array_entry = 1;
144 my $element = $curr->{$key}[$idx];
146 if ('HASH' eq ref $element) {
147 foreach my $hash_key (sort keys %{ $element }) {
148 push @result, $self->_flatten_variables_rec($element, $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
149 $first_array_entry = 0;
152 push @result, { 'key' => $prefix . $key . '[]', 'value' => $element };
157 $main::lxdebug->leave_sub(2);
162 sub flatten_variables {
163 $main::lxdebug->enter_sub(2);
171 push @variables, $self->_flatten_variables_rec($self, '', $_);
174 $main::lxdebug->leave_sub(2);
179 sub flatten_standard_variables {
180 $main::lxdebug->enter_sub(2);
183 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar), @_);
187 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
188 push @variables, $self->_flatten_variables_rec($self, '', $_);
191 $main::lxdebug->leave_sub(2);
197 my ($self, $str) = @_;
199 return uri_encode($str);
203 my ($self, $str) = @_;
205 return uri_decode($str);
209 $main::lxdebug->enter_sub();
210 my ($self, $str) = @_;
212 if ($str && !ref($str)) {
213 $str =~ s/\"/"/g;
216 $main::lxdebug->leave_sub();
222 $main::lxdebug->enter_sub();
223 my ($self, $str) = @_;
225 if ($str && !ref($str)) {
226 $str =~ s/"/\"/g;
229 $main::lxdebug->leave_sub();
235 $main::lxdebug->enter_sub();
239 map({ print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
241 for (sort keys %$self) {
242 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
243 print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
246 $main::lxdebug->leave_sub();
250 my ($self, $code) = @_;
251 local $self->{__ERROR_HANDLER} = sub { SL::X::FormError->throw(error => $_[0]) };
256 $main::lxdebug->enter_sub();
258 $main::lxdebug->show_backtrace();
260 my ($self, $msg) = @_;
262 if ($self->{__ERROR_HANDLER}) {
263 $self->{__ERROR_HANDLER}->($msg);
265 } elsif ($ENV{HTTP_USER_AGENT}) {
267 $self->show_generic_error($msg);
270 confess "Error: $msg\n";
273 $main::lxdebug->leave_sub();
277 $main::lxdebug->enter_sub();
279 my ($self, $msg) = @_;
281 if ($ENV{HTTP_USER_AGENT}) {
283 print $self->parse_html_template('generic/form_info', { message => $msg });
285 } elsif ($self->{info_function}) {
286 &{ $self->{info_function} }($msg);
291 $main::lxdebug->leave_sub();
294 # calculates the number of rows in a textarea based on the content and column number
295 # can be capped with maxrows
297 $main::lxdebug->enter_sub();
298 my ($self, $str, $cols, $maxrows, $minrows) = @_;
302 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
305 $main::lxdebug->leave_sub();
307 return max(min($rows, $maxrows), $minrows);
311 my ($self, $msg) = @_;
313 SL::X::DBError->throw(
315 db_error => $DBI::errstr,
320 $main::lxdebug->enter_sub();
322 my ($self, $name, $msg) = @_;
325 foreach my $part (split m/\./, $name) {
326 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
329 $curr = $curr->{$part};
332 $main::lxdebug->leave_sub();
335 sub _get_request_uri {
338 return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
339 return URI->new if !$ENV{REQUEST_URI}; # for testing
341 my $scheme = $::request->is_https ? 'https' : 'http';
342 my $port = $ENV{SERVER_PORT};
343 $port = undef if (($scheme eq 'http' ) && ($port == 80))
344 || (($scheme eq 'https') && ($port == 443));
346 my $uri = URI->new("${scheme}://");
347 $uri->scheme($scheme);
349 $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
350 $uri->path_query($ENV{REQUEST_URI});
356 sub _add_to_request_uri {
359 my $relative_new_path = shift;
360 my $request_uri = shift || $self->_get_request_uri;
361 my $relative_new_uri = URI->new($relative_new_path);
362 my @request_segments = $request_uri->path_segments;
364 my $new_uri = $request_uri->clone;
365 $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
370 sub create_http_response {
371 $main::lxdebug->enter_sub();
376 my $cgi = $::request->{cgi};
379 if (defined $main::auth) {
380 my $uri = $self->_get_request_uri;
381 my @segments = $uri->path_segments;
383 $uri->path_segments(@segments);
385 my $session_cookie_value = $main::auth->get_session_id();
387 if ($session_cookie_value) {
388 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
389 '-value' => $session_cookie_value,
390 '-path' => $uri->path,
391 '-expires' => '+' . $::auth->{session_timeout} . 'm',
392 '-secure' => $::request->is_https);
393 $session_cookie = "$session_cookie; SameSite=strict";
397 my %cgi_params = ('-type' => $params{content_type});
398 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
399 $cgi_params{'-cookie'} = $session_cookie if ($session_cookie);
401 map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length status);
403 my $output = $cgi->header(%cgi_params);
405 $main::lxdebug->leave_sub();
411 $::lxdebug->enter_sub;
413 my ($self, %params) = @_;
416 $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
418 if ($params{no_layout}) {
419 $::request->{layout} = SL::Layout::Dispatcher->new(style => 'none');
422 my $layout = $::request->{layout};
424 # standard css for all
425 # this should gradually move to the layouts that need it
426 $layout->use_stylesheet("$_.css") for qw(
427 common main menu list_accounts jquery.autocomplete
428 jquery.multiselect2side
429 ui-lightness/jquery-ui
431 tooltipster themes/tooltipster-light
434 $layout->use_javascript("$_.js") for (qw(
435 jquery jquery-ui jquery.cookie jquery.checkall jquery.download
436 jquery/jquery.form jquery/fixes namespace client_js
437 jquery/jquery.tooltipster.min
438 common part_selection
439 ), "jquery/ui/i18n/jquery.ui.datepicker-$::myconfig{countrycode}");
441 $layout->use_javascript("$_.js") for @{ $params{use_javascripts} // [] };
443 $self->{favicon} ||= "favicon.ico";
444 $self->{titlebar} = join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->read_version if $self->{title} || !$self->{titlebar};
447 if ($self->{refresh_url} || $self->{refresh_time}) {
448 my $refresh_time = $self->{refresh_time} || 3;
449 my $refresh_url = $self->{refresh_url} || $ENV{REFERER};
450 push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
453 my $auto_reload_resources_param = $layout->auto_reload_resources_param;
455 push @header, map { qq|<link rel="stylesheet" href="${_}${auto_reload_resources_param}" type="text/css" title="Stylesheet">| } $layout->stylesheets;
456 push @header, "<style type='text/css'>\@page { size:landscape; }</style> " if $self->{landscape};
457 push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
458 push @header, map { qq|<script type="text/javascript" src="${_}${auto_reload_resources_param}"></script>| } $layout->javascripts;
459 push @header, '<meta name="viewport" content="width=device-width, initial-scale=1">';
460 push @header, $self->{javascript} if $self->{javascript};
461 push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
464 strict => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
465 transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
466 frameset => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
467 html5 => qq|<!DOCTYPE html>|,
471 print $self->create_http_response(content_type => 'text/html', charset => 'UTF-8');
472 print $doctypes{$params{doctype} || $::request->layout->html_dialect}, $/;
476 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
477 <title>$self->{titlebar}</title>
479 print " $_\n" for @header;
481 <meta name="robots" content="noindex,nofollow">
486 print $::request->{layout}->pre_content;
487 print $::request->{layout}->start_content;
489 $layout->header_done;
491 $::lxdebug->leave_sub;
495 return unless $::request->{layout}->need_footer;
497 print $::request->{layout}->end_content;
498 print $::request->{layout}->post_content;
500 if (my @inline_scripts = $::request->{layout}->javascripts_inline) {
501 print "<script type='text/javascript'>" . join("; ", @inline_scripts) . "</script>\n";
510 sub ajax_response_header {
511 $main::lxdebug->enter_sub();
515 my $output = $::request->{cgi}->header('-charset' => 'UTF-8');
517 $main::lxdebug->leave_sub();
522 sub redirect_header {
526 my $base_uri = $self->_get_request_uri;
527 my $new_uri = URI->new_abs($new_url, $base_uri);
529 die "Headers already sent" if $self->{header};
532 return $::request->{cgi}->redirect($new_uri);
535 sub set_standard_title {
536 $::lxdebug->enter_sub;
539 $self->{titlebar} = "kivitendo " . $::locale->text('Version') . " " . $self->read_version;
540 $self->{titlebar} .= "- $::myconfig{name}" if $::myconfig{name};
541 $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
543 $::lxdebug->leave_sub;
546 sub _prepare_html_template {
547 $main::lxdebug->enter_sub();
549 my ($self, $file, $additional_params) = @_;
552 if (!%::myconfig || !$::myconfig{"countrycode"}) {
553 $language = $::lx_office_conf{system}->{language};
555 $language = $main::myconfig{"countrycode"};
557 $language = "de" unless ($language);
559 my $webpages_path = $::request->layout->webpages_path;
560 my $webpages_fallback = $::request->layout->webpages_fallback_path;
562 my @templates = first { -f } map { "${_}/${file}.html" } grep { defined } $webpages_path, $webpages_fallback;
565 $file = $templates[0];
566 } elsif (ref $file eq 'SCALAR') {
567 # file is a scalarref, use inline mode
569 my $info = "Web page template '${file}' not found.\n";
571 print qq|<pre>$info</pre>|;
572 $::dispatcher->end_request;
575 $additional_params->{AUTH} = $::auth;
576 $additional_params->{INSTANCE_CONF} = $::instance_conf;
577 $additional_params->{LOCALE} = $::locale;
578 $additional_params->{LXCONFIG} = \%::lx_office_conf;
579 $additional_params->{LXDEBUG} = $::lxdebug;
580 $additional_params->{MYCONFIG} = \%::myconfig;
582 $main::lxdebug->leave_sub();
587 sub parse_html_template {
588 $main::lxdebug->enter_sub();
590 my ($self, $file, $additional_params) = @_;
592 $additional_params ||= { };
594 my $real_file = $self->_prepare_html_template($file, $additional_params);
595 my $template = $self->template;
597 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
600 $template->process($real_file, $additional_params, \$output) || die $template->error;
602 $main::lxdebug->leave_sub();
607 sub template { $::request->presenter->get_template }
609 sub show_generic_error {
610 $main::lxdebug->enter_sub();
612 my ($self, $error, %params) = @_;
614 if ($self->{__ERROR_HANDLER}) {
615 $self->{__ERROR_HANDLER}->($error);
616 $main::lxdebug->leave_sub();
620 if ($::request->is_ajax) {
623 ->render(SL::Controller::Base->new);
624 $::dispatcher->end_request;
628 'title_error' => $params{title},
629 'label_error' => $error,
632 $self->{title} = $params{title} if $params{title};
634 for my $bar ($::request->layout->get('actionbar')) {
638 call => [ 'kivi.history_back' ],
639 accesskey => 'enter',
645 print $self->parse_html_template("generic/error", $add_params);
647 print STDERR "Error: $error\n";
649 $main::lxdebug->leave_sub();
651 $::dispatcher->end_request;
654 sub show_generic_information {
655 $main::lxdebug->enter_sub();
657 my ($self, $text, $title) = @_;
660 'title_information' => $title,
661 'label_information' => $text,
664 $self->{title} = $title if ($title);
667 print $self->parse_html_template("generic/information", $add_params);
669 $main::lxdebug->leave_sub();
671 $::dispatcher->end_request;
674 sub _store_redirect_info_in_session {
677 return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
679 my ($controller, $params) = ($1, $2);
680 my $form = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
681 $self->{callback} = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
685 $main::lxdebug->enter_sub();
687 my ($self, $msg) = @_;
689 if (!$self->{callback}) {
693 SL::Helper::Flash::flash_later('info', $msg) if $msg;
694 $self->_store_redirect_info_in_session;
695 print $::form->redirect_header($self->{callback});
698 $::dispatcher->end_request;
700 $main::lxdebug->leave_sub();
703 # sort of columns removed - empty sub
705 $main::lxdebug->enter_sub();
707 my ($self, @columns) = @_;
709 $main::lxdebug->leave_sub();
716 my ($self, $myconfig, $amount, $places, $dash) = @_;
717 SL::Helper::Number::_format_number($amount, $places, %$myconfig, dash => $dash);
721 $main::lxdebug->enter_sub(2);
726 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
727 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
728 $input =~ s/\#\#/\#/g;
730 $main::lxdebug->leave_sub(2);
738 my ($self, $myconfig, $amount) = @_;
739 SL::Helper::Number::_parse_number($amount, %$myconfig);
742 sub round_amount { shift; goto &SL::Helper::Number::_round_number; }
745 $main::lxdebug->enter_sub();
747 my ($self, $myconfig) = @_;
748 my ($out, $out_mode);
752 my $defaults = SL::DB::Default->get;
754 my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
755 $self->{cwd} = getcwd();
756 my $temp_dir = File::Temp->newdir(
757 "kivitendo-print-XXXXXX",
758 DIR => $self->{cwd} . "/" . $::lx_office_conf{paths}->{userspath},
759 CLEANUP => !$keep_temp_files,
762 my $userspath = File::Spec->abs2rel($temp_dir->dirname);
763 $self->{tmpdir} = $temp_dir->dirname;
768 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
769 $template_type = 'OpenDocument';
770 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
772 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
773 $template_type = 'LaTeX';
774 $ext_for_format = 'pdf';
776 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
777 $template_type = 'HTML';
778 $ext_for_format = 'html';
780 } elsif ( $self->{"format"} =~ /excel/i ) {
781 $template_type = 'Excel';
782 $ext_for_format = 'xls';
784 } elsif ( defined $self->{'format'}) {
785 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
787 } elsif ( $self->{'format'} eq '' ) {
788 $self->error("No Outputformat given: $self->{'format'}");
790 } else { #Catch the rest
791 $self->error("Outputformat not defined: $self->{'format'}");
794 my $template = SL::Template::create(type => $template_type,
795 file_name => $self->{IN},
797 myconfig => $myconfig,
798 userspath => $userspath,
799 %{ $self->{TEMPLATE_DRIVER_OPTIONS} || {} });
801 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
802 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" } if exists $self->{ $self->{"formname"} . "notes" };
804 if (!$self->{employee_id}) {
805 $self->{"employee_${_}"} = $myconfig->{$_} for qw(email tel fax name signature);
806 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
809 $self->{"myconfig_${_}"} = $myconfig->{$_} for grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
810 $self->{$_} = $defaults->$_ for qw(co_ustid);
811 $self->{"myconfig_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
812 $self->{AUTH} = $::auth;
813 $self->{INSTANCE_CONF} = $::instance_conf;
814 $self->{LOCALE} = $::locale;
815 $self->{LXCONFIG} = $::lx_office_conf;
816 $self->{LXDEBUG} = $::lxdebug;
817 $self->{MYCONFIG} = \%::myconfig;
819 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
821 # OUT is used for the media, screen, printer, email
822 # for postscript we store a copy in a temporary file
824 my ($temp_fh, $suffix);
825 $suffix = $self->{IN};
827 ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
828 strftime('kivitendo-print-%Y%m%d%H%M%S-XXXXXX', localtime()),
829 SUFFIX => '.' . ($suffix || 'tex'),
831 UNLINK => $keep_temp_files ? 0 : 1,
834 chmod 0644, $self->{tmpfile} if $keep_temp_files;
835 (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
838 $out_mode = $self->{OUT_MODE} || '>';
839 $self->{OUT} = "$self->{tmpfile}";
840 $self->{OUT_MODE} = '>';
843 my $command_formatter = sub {
844 my ($out_mode, $out) = @_;
845 return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
849 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
850 open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
852 *OUT = ($::dispatcher->get_standard_filehandles)[1];
856 if (!$template->parse(*OUT)) {
858 $self->error("$self->{IN} : " . $template->get_error());
861 close OUT if $self->{OUT};
862 # check only one flag (webdav_documents)
863 # therefore copy to webdav, even if we do not have the webdav feature enabled (just archive)
864 my $copy_to_webdav = $::instance_conf->get_webdav_documents && !$self->{preview} && $self->{tmpdir} && $self->{tmpfile} && $self->{type}
865 && $self->{type} ne 'statement';
867 $self->{attachment_filename} ||= $self->generate_attachment_filename;
869 if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
870 $self->append_general_pdf_attachments(filepath => $self->{tmpdir}."/".$self->{tmpfile},
871 type => $self->{type});
873 if ($self->{media} eq 'file') {
874 copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
876 if ($copy_to_webdav) {
877 if (my $error = Common::copy_file_to_webdav_folder($self)) {
878 chdir("$self->{cwd}");
879 $self->error($error);
883 if (!$self->{preview} && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled)
885 $self->store_pdf($self);
888 chdir("$self->{cwd}");
890 $::lxdebug->leave_sub();
895 if ($copy_to_webdav) {
896 if (my $error = Common::copy_file_to_webdav_folder($self)) {
897 chdir("$self->{cwd}");
898 $self->error($error);
902 if ( !$self->{preview} && $ext_for_format eq 'pdf' && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled) {
903 my $file_obj = $self->store_pdf($self);
904 $self->{print_file_id} = $file_obj->id if $file_obj;
906 # dn has its own send email method, but sets media for print templates
907 if ($self->{media} eq 'email' && !$self->{dunning_id}) {
908 if ( getcwd() eq $self->{"tmpdir"} ) {
909 # in the case of generating pdf we are in the tmpdir, but WHY ???
910 $self->{tmpfile} = $userspath."/".$self->{tmpfile};
911 chdir("$self->{cwd}");
913 $self->send_email(\%::myconfig,$ext_for_format);
917 $self->{OUT_MODE} = $out_mode;
918 $self->output_file($template->get_mime_type,$command_formatter);
920 delete $self->{print_file_id};
924 chdir("$self->{cwd}");
925 $main::lxdebug->leave_sub();
928 sub get_bcc_defaults {
929 my ($self, $myconfig, $mybcc) = @_;
930 if (SL::DB::Default->get->bcc_to_login) {
931 $mybcc .= ", " if $mybcc;
932 $mybcc .= $myconfig->{email};
934 my $otherbcc = SL::DB::Default->get->global_bcc;
936 $mybcc .= ", " if $mybcc;
943 $main::lxdebug->enter_sub();
944 my ($self, $myconfig, $ext_for_format) = @_;
945 my $mail = Mailer->new;
947 map { $mail->{$_} = $self->{$_} }
948 qw(cc subject message format);
950 if ($self->{cc_employee}) {
951 my ($user, $my_emp_cc);
952 $user = SL::DB::Manager::AuthUser->find_by(login => $self->{cc_employee});
953 $my_emp_cc = $user->get_config_value('email') if ref $user eq 'SL::DB::AuthUser';
954 $mail->{cc} .= ", " if $mail->{cc};
955 $mail->{cc} .= $my_emp_cc if $my_emp_cc;
958 $mail->{bcc} = $self->get_bcc_defaults($myconfig, $self->{bcc});
959 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
960 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
961 $mail->{fileid} = time() . '.' . $$ . '.';
962 $mail->{content_type} = "text/html";
963 my $full_signature = $self->create_email_signature();
965 $mail->{attachments} = [];
967 # if we send html or plain text inline
968 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
969 $mail->{message} =~ s/\r//g;
970 $mail->{message} =~ s{\n}{<br>\n}g;
971 $mail->{message} .= $full_signature;
973 open(IN, "<", $self->{tmpfile})
974 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
975 $mail->{message} .= $_ while <IN>;
978 } elsif (($self->{attachment_policy} // '') ne 'no_file') {
979 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
980 $attachment_name =~ s{\.(.+?)$}{.${ext_for_format}} if ($ext_for_format);
982 if (($self->{attachment_policy} // '') eq 'old_file') {
983 my ( $attfile ) = SL::File->get_all(object_id => $self->{id},
984 object_type => $self->{type},
985 file_type => 'document',
986 print_variant => $self->{formname},);
989 $attfile->{override_file_name} = $attachment_name if $attachment_name;
990 push @attfiles, $attfile;
991 $self->{file_id} = $attfile->id;
995 push @{ $mail->{attachments} }, { path => $self->{tmpfile},
996 id => $self->{print_file_id},
997 type => "application/pdf",
998 name => $attachment_name };
1004 map { SL::File->get(id => $_) }
1005 @{ $self->{attach_file_ids} // [] };
1007 foreach my $attfile ( @attfiles ) {
1008 push @{ $mail->{attachments} }, {
1009 path => $attfile->get_file,
1011 type => $attfile->mime_type,
1012 name => $attfile->{override_file_name} // $attfile->file_name,
1013 content => $attfile->get_content ? ${ $attfile->get_content } : undef,
1017 $mail->{message} =~ s/\r//g;
1018 $mail->{message} .= $full_signature;
1019 $self->{emailerr} = $mail->send();
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 if ($self->{emailerr}) {
1029 $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
1032 #write back for message info and mail journal
1033 $self->{cc} = $mail->{cc};
1034 $self->{bcc} = $mail->{bcc};
1035 $self->{email} = $mail->{to};
1037 $main::lxdebug->leave_sub();
1041 $main::lxdebug->enter_sub();
1043 my ($self,$mimeType,$command_formatter) = @_;
1044 my $numbytes = (-s $self->{tmpfile});
1045 open(IN, "<", $self->{tmpfile})
1046 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1049 $self->{copies} = 1 unless $self->{media} eq 'printer';
1051 chdir("$self->{cwd}");
1052 for my $i (1 .. $self->{copies}) {
1054 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1056 open OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1057 print OUT $_ while <IN>;
1062 my %headers = ('-type' => $mimeType,
1063 '-connection' => 'close',
1064 '-charset' => 'UTF-8');
1066 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1068 if ($self->{attachment_filename}) {
1071 '-attachment' => $self->{attachment_filename},
1072 '-content-length' => $numbytes,
1077 print $::request->cgi->header(%headers);
1079 $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1083 $main::lxdebug->leave_sub();
1086 sub get_formname_translation {
1087 $main::lxdebug->enter_sub();
1088 my ($self, $formname) = @_;
1090 $formname ||= $self->{formname};
1092 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1093 local $::locale = Locale->new($self->{recipient_locale});
1095 my %formname_translations = (
1096 bin_list => $main::locale->text('Bin List'),
1097 credit_note => $main::locale->text('Credit Note'),
1098 invoice => $main::locale->text('Invoice'),
1099 invoice_copy => $main::locale->text('Invoice Copy'),
1100 invoice_for_advance_payment => $main::locale->text('Invoice for Advance Payment'),
1101 final_invoice => $main::locale->text('Final Invoice'),
1102 pick_list => $main::locale->text('Pick List'),
1103 proforma => $main::locale->text('Proforma Invoice'),
1104 purchase_order => $main::locale->text('Purchase Order'),
1105 purchase_order_confirmation => $main::locale->text('Purchase Order Confirmation'),
1106 request_quotation => $main::locale->text('RFQ'),
1107 purchase_quotation_intake => $main::locale->text('Purchase Quotation Intake'),
1108 sales_order_intake => $main::locale->text('Sales Order Intake'),
1109 sales_order => $main::locale->text('Confirmation'),
1110 sales_quotation => $main::locale->text('Quotation'),
1111 storno_invoice => $main::locale->text('Storno Invoice'),
1112 sales_delivery_order => $main::locale->text('Delivery Order'),
1113 purchase_delivery_order => $main::locale->text('Delivery Order'),
1114 supplier_delivery_order => $main::locale->text('Supplier Delivery Order'),
1115 rma_delivery_order => $main::locale->text('RMA Delivery Order'),
1116 sales_reclamation => $main::locale->text('Sales Reclamation'),
1117 purchase_reclamation => $main::locale->text('Purchase Reclamation'),
1118 dunning => $main::locale->text('Dunning'),
1119 dunning1 => $main::locale->text('Payment Reminder'),
1120 dunning2 => $main::locale->text('Dunning'),
1121 dunning3 => $main::locale->text('Last Dunning'),
1122 dunning_invoice => $main::locale->text('Dunning Invoice'),
1123 letter => $main::locale->text('Letter'),
1124 ic_supply => $main::locale->text('Intra-Community supply'),
1125 statement => $main::locale->text('Statement'),
1128 $main::lxdebug->leave_sub();
1129 return $formname_translations{$formname};
1132 sub get_cusordnumber_translation {
1133 $main::lxdebug->enter_sub();
1134 my ($self, $formname) = @_;
1136 $formname ||= $self->{formname};
1138 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1139 local $::locale = Locale->new($self->{recipient_locale});
1142 $main::lxdebug->leave_sub();
1143 return $main::locale->text('Your Order');
1146 sub get_number_prefix_for_type {
1147 $main::lxdebug->enter_sub();
1151 (first { $self->{type} eq $_ } qw(invoice invoice_for_advance_payment final_invoice credit_note)) ? 'inv'
1152 : ($self->{type} =~ /_quotation/) ? 'quo'
1153 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1154 : ($self->{type} =~ /letter/) ? 'letter'
1157 # better default like this?
1158 # : ($self->{type} =~ /(sales|purchase)_order/ : 'ord';
1159 # : 'prefix_undefined';
1161 $main::lxdebug->leave_sub();
1165 sub get_extension_for_format {
1166 $main::lxdebug->enter_sub();
1169 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1170 : $self->{format} =~ /postscript/i ? ".ps"
1171 : $self->{format} =~ /opendocument/i ? ".odt"
1172 : $self->{format} =~ /excel/i ? ".xls"
1173 : $self->{format} =~ /html/i ? ".html"
1176 $main::lxdebug->leave_sub();
1180 sub generate_attachment_filename {
1181 $main::lxdebug->enter_sub();
1184 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1185 my $recipient_locale = Locale->new($self->{recipient_locale});
1187 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1188 my $prefix = $self->get_number_prefix_for_type();
1190 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice invoice_for_advance_payment final_invoice credit_note))) {
1191 $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
1193 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1194 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1196 } elsif ($attachment_filename) {
1197 $attachment_filename .= $self->get_extension_for_format();
1200 $attachment_filename = "";
1203 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1204 $attachment_filename =~ s|[\s/\\]+|_|g;
1206 $main::lxdebug->leave_sub();
1207 return $attachment_filename;
1210 sub generate_email_subject {
1211 $main::lxdebug->enter_sub();
1214 my $defaults = SL::DB::Default->get;
1217 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1218 my $prefix = $self->get_number_prefix_for_type();
1220 if ($subject && $self->{"${prefix}number"}) {
1221 $subject .= " " . $self->{"${prefix}number"}
1224 if ($self->{cusordnumber}) {
1225 $subject = $self->get_cusordnumber_translation() . ' ' . $self->{cusordnumber} . $sep . $subject;
1228 if ($defaults->email_subject_transaction_description) {
1229 $subject .= $sep . $self->{transaction_description} if $self->{transaction_description};
1232 $main::lxdebug->leave_sub();
1236 sub generate_email_body {
1237 $main::lxdebug->enter_sub();
1238 my ($self, %params) = @_;
1239 # simple german and english will work grammatically (most european languages as well)
1240 # Dear Mr Alan Greenspan:
1241 # Sehr geehrte Frau Meyer,
1242 # A l’attention de Mme Villeroy,
1243 # Gentile Signora Ferrari,
1246 if ($self->{cp_id} && !$params{record_email}) {
1247 my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
1248 my $name = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
1249 my $gender = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
1250 my $mf = $gender eq 'f' ? 'female' : 'male';
1251 $body = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
1252 $body .= ' ' . $givenname . ' ' . $name if $body;
1254 $body = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
1257 return undef unless $body;
1259 $body .= GenericTranslations->get(translation_type => "salutation_punctuation_mark", language_id => $self->{language_id});
1260 $body = '<p>' . $::locale->quote_special_chars('HTML', $body) . '</p>';
1262 my $translation_type = $params{translation_type} // "preset_text_$self->{formname}";
1263 my $main_body = GenericTranslations->get(translation_type => $translation_type, language_id => $self->{language_id});
1264 $main_body = GenericTranslations->get(translation_type => $params{fallback_translation_type}, language_id => $self->{language_id}) if !$main_body && $params{fallback_translation_type};
1265 $body .= $main_body;
1267 $body = $main::locale->unquote_special_chars('HTML', $body);
1269 $main::lxdebug->leave_sub();
1274 $main::lxdebug->enter_sub();
1276 my ($self, $application) = @_;
1278 my $error_code = $?;
1280 chdir("$self->{tmpdir}");
1283 if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1284 push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1286 } elsif (-f "$self->{tmpfile}.err") {
1287 open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
1292 if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1293 $self->{tmpfile} =~ s|.*/||g;
1295 $self->{tmpfile} =~ s/\.\w+$//g;
1296 my $tmpfile = $self->{tmpfile};
1297 unlink(<$tmpfile.*>);
1300 chdir("$self->{cwd}");
1302 $main::lxdebug->leave_sub();
1308 $main::lxdebug->enter_sub();
1310 my ($self, $date, $myconfig) = @_;
1313 if ($date && $date =~ /\D/) {
1315 if ($myconfig->{dateformat} =~ /^yy/) {
1316 ($yy, $mm, $dd) = split /\D/, $date;
1318 if ($myconfig->{dateformat} =~ /^mm/) {
1319 ($mm, $dd, $yy) = split /\D/, $date;
1321 if ($myconfig->{dateformat} =~ /^dd/) {
1322 ($dd, $mm, $yy) = split /\D/, $date;
1327 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1328 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1330 $dd = "0$dd" if ($dd < 10);
1331 $mm = "0$mm" if ($mm < 10);
1333 $date = "$yy$mm$dd";
1336 $main::lxdebug->leave_sub();
1341 # Database routines used throughout
1342 # DB Handling got moved to SL::DB, these are only shims for compatibility
1345 SL::DB->client->dbh;
1348 sub get_standard_dbh {
1349 my $dbh = SL::DB->client->dbh;
1351 if ($dbh && !$dbh->{Active}) {
1352 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
1353 SL::DB->client->dbh(undef);
1356 SL::DB->client->dbh;
1359 sub disconnect_standard_dbh {
1360 SL::DB->client->dbh->rollback;
1366 $main::lxdebug->enter_sub();
1368 my ($self, $date, $myconfig) = @_;
1369 my $dbh = $self->get_standard_dbh;
1371 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1372 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1374 # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1375 # es ist sicher ein conv_date vorher IMMER auszuführen.
1376 # Testfälle ohne definiertes closedto:
1377 # Leere Datumseingabe i.O.
1378 # SELECT 1 FROM defaults WHERE '' < closedto
1379 # normale Zahlungsbuchung über Rechnungsmaske i.O.
1380 # SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1381 # Testfälle mit definiertem closedto (30.04.2011):
1382 # Leere Datumseingabe i.O.
1383 # SELECT 1 FROM defaults WHERE '' < closedto
1384 # normale Buchung im geschloßenem Zeitraum i.O.
1385 # SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1386 # Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1387 # normale Buchung in aktiver Buchungsperiode i.O.
1388 # SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1390 my ($closed) = $sth->fetchrow_array;
1392 $main::lxdebug->leave_sub();
1397 # prevents bookings to the to far away future
1398 sub date_max_future {
1399 $main::lxdebug->enter_sub();
1401 my ($self, $date, $myconfig) = @_;
1402 my $dbh = $self->get_standard_dbh;
1404 my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
1405 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1407 my ($max_future_booking_interval) = $sth->fetchrow_array;
1409 $main::lxdebug->leave_sub();
1411 return $max_future_booking_interval;
1415 sub update_balance {
1416 $main::lxdebug->enter_sub();
1418 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1420 # if we have a value, go do it
1423 # retrieve balance from table
1424 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1425 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1426 my ($balance) = $sth->fetchrow_array;
1432 $query = "UPDATE $table SET $field = $balance WHERE $where";
1433 do_query($self, $dbh, $query, @values);
1435 $main::lxdebug->leave_sub();
1438 sub update_exchangerate {
1439 $main::lxdebug->enter_sub();
1443 { isa => 'DBI::db'},
1444 { type => SCALAR, callbacks => { is_fx_currency => sub { shift ne $_[1]->[0]->{defaultcurrency} } } }, # should be ISO three letter codes for currency identification (ISO 4217)
1445 { type => SCALAR, callbacks => { is_valid_kivi_date => sub { shift =~ m/\d+\d+\d+/ } } }, # we have three numers
1446 { type => SCALAR, callbacks => { is_null_or_ar_int => sub { $_[0] == 0
1448 && $_[1]->[0]->{script} =~ m/cp\.pl|ar\.pl|is\.pl/ } } }, # value buy fxrate
1449 { type => SCALAR, callbacks => { is_null_or_ap_int => sub { $_[0] == 0
1451 && $_[1]->[0]->{script} =~ m/cp\.pl|ap\.pl|ir\.pl/ } } }, # value sell fxrate
1452 { type => SCALAR, callbacks => { is_current_form_id => sub { $_[0] == $_[1]->[0]->{id} } }, optional => 1 },
1453 { type => SCALAR, callbacks => { is_valid_fx_table => sub { shift =~ m/(ar|ap|bank_transactions)/ } }, optional => 1 }
1456 my ($self, $dbh, $curr, $transdate, $buy, $sell, $id, $record_table) = @_;
1458 # record has a exchange rate and should be updated
1459 if ($record_table && $id) {
1460 do_query($self, $dbh, qq|UPDATE $record_table SET exchangerate = ? WHERE id = ?|, $buy || $sell, $id);
1461 $main::lxdebug->leave_sub();
1466 $query = qq|SELECT e.currency_id FROM exchangerate e
1467 WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
1469 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1478 $buy = conv_i($buy, "NULL");
1479 $sell = conv_i($sell, "NULL");
1482 if ($buy != 0 && $sell != 0) {
1483 $set = "buy = $buy, sell = $sell";
1484 } elsif ($buy != 0) {
1485 $set = "buy = $buy";
1486 } elsif ($sell != 0) {
1487 $set = "sell = $sell";
1490 if ($sth->fetchrow_array) {
1491 # die "this never happens never"; # except for credit or debit bookings
1492 $query = qq|UPDATE exchangerate
1494 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
1498 $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
1499 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
1502 do_query($self, $dbh, $query, $curr, $transdate);
1504 $main::lxdebug->leave_sub();
1507 sub check_exchangerate {
1508 $main::lxdebug->enter_sub();
1512 { type => HASHREF, callbacks => { has_yy_in_dateformat => sub { $_[0]->{dateformat} =~ m/yy/ } } },
1513 { type => SCALAR, callbacks => { is_fx_currency => sub { shift ne $_[1]->[0]->{defaultcurrency} } } }, # should be ISO three letter codes for currency identification (ISO 4217)
1514 { type => SCALAR | HASHREF, callbacks => { is_valid_kivi_date => sub { shift =~ m/\d+.\d+.\d+/ } } }, # we have three numbers. Either DateTime or form scalar
1515 { type => SCALAR, callbacks => { is_buy_or_sell_rate => sub { shift =~ m/^(buy|sell)$/ } } },
1516 { type => SCALAR | UNDEF, callbacks => { is_current_form_id => sub { $_[0] == $_[1]->[0]->{id} } }, optional => 1 },
1517 { type => SCALAR, callbacks => { is_valid_fx_table => sub { shift =~ m/^(ar|ap)$/ } }, optional => 1 }
1519 my ($self, $myconfig, $currency, $transdate, $fld, $id, $record_table) = @_;
1521 my $dbh = $self->get_standard_dbh($myconfig);
1523 # callers wants a check if record has a exchange rate and should be fetched instead
1524 if ($record_table && $id) {
1525 my ($record_exchange_rate) = selectrow_query($self, $dbh, qq|SELECT exchangerate FROM $record_table WHERE id = ?|, $id);
1526 if ($record_exchange_rate && $record_exchange_rate > 0) {
1528 $main::lxdebug->leave_sub();
1529 # second param indicates record exchange rate
1530 return ($record_exchange_rate, 1);
1534 # fetch default from exchangerate table
1535 my $query = qq|SELECT e.$fld FROM exchangerate e
1536 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1538 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1540 $main::lxdebug->leave_sub();
1542 return $exchangerate;
1545 sub get_all_currencies {
1546 $main::lxdebug->enter_sub();
1549 my $myconfig = shift || \%::myconfig;
1550 my $dbh = $self->get_standard_dbh($myconfig);
1552 my $query = qq|SELECT name FROM currencies|;
1553 my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
1555 $main::lxdebug->leave_sub();
1560 sub get_default_currency {
1561 $main::lxdebug->enter_sub();
1563 my ($self, $myconfig) = @_;
1564 my $dbh = $self->get_standard_dbh($myconfig);
1565 my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1567 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1569 $main::lxdebug->leave_sub();
1571 return $defaultcurrency;
1574 sub set_payment_options {
1575 my ($self, $myconfig, $transdate, $type) = @_;
1577 my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
1580 my $is_invoice = $type =~ m{invoice}i;
1582 $transdate ||= $self->{invdate} || $self->{transdate};
1583 my $due_date = $self->{duedate} || $self->{reqdate};
1585 $self->{$_} = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
1586 $self->{payment_description} = $terms->description;
1587 $self->{netto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
1588 $self->{skonto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
1590 my ($invtotal, $total);
1591 my (%amounts, %formatted_amounts);
1593 if ($self->{type} =~ /_order$/) {
1594 $amounts{invtotal} = $self->{ordtotal};
1595 $amounts{total} = $self->{ordtotal};
1597 } elsif ($self->{type} =~ /_quotation$/) {
1598 $amounts{invtotal} = $self->{quototal};
1599 $amounts{total} = $self->{quototal};
1602 $amounts{invtotal} = $self->{invtotal};
1603 $amounts{total} = $self->{total};
1605 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1607 $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1608 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1609 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1610 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1612 foreach (keys %amounts) {
1613 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1614 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1617 if ($self->{"language_id"}) {
1618 my $language = SL::DB::Language->new(id => $self->{language_id})->load;
1620 $self->{payment_terms} = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
1621 $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
1623 if ($language->output_dateformat) {
1624 foreach my $key (qw(netto_date skonto_date)) {
1625 $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
1629 if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
1630 local $myconfig->{numberformat};
1631 $myconfig->{"numberformat"} = $language->output_numberformat;
1632 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
1636 $self->{payment_terms} = $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
1638 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1639 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1640 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1641 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1642 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1643 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1644 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1645 $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
1646 $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
1647 $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
1648 $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
1650 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1651 # put amounts in form for print template
1652 foreach (keys %formatted_amounts) {
1653 next if $_ =~ m/(^total$|^invtotal$)/;
1654 $self->{$_} = $formatted_amounts{$_};
1658 sub get_template_language {
1659 $main::lxdebug->enter_sub();
1661 my ($self, $myconfig) = @_;
1663 my $template_code = "";
1665 if ($self->{language_id}) {
1666 my $dbh = $self->get_standard_dbh($myconfig);
1667 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1668 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1671 $main::lxdebug->leave_sub();
1673 return $template_code;
1676 sub get_printer_code {
1677 $main::lxdebug->enter_sub();
1679 my ($self, $myconfig) = @_;
1681 my $template_code = "";
1683 if ($self->{printer_id}) {
1684 my $dbh = $self->get_standard_dbh($myconfig);
1685 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1686 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1689 $main::lxdebug->leave_sub();
1691 return $template_code;
1695 $main::lxdebug->enter_sub();
1697 my ($self, $myconfig) = @_;
1699 my $template_code = "";
1701 if ($self->{shipto_id}) {
1702 my $dbh = $self->get_standard_dbh($myconfig);
1703 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1704 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1705 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1707 my $cvars = CVar->get_custom_variables(
1710 trans_id => $self->{shipto_id},
1712 $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
1715 $main::lxdebug->leave_sub();
1719 my ($self, $dbh, $id, $module) = @_;
1724 foreach my $item (qw(name department_1 department_2 street zipcode city country gln
1725 contact phone fax email)) {
1726 if ($self->{"shipto$item"}) {
1727 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1729 push(@values, $self->{"shipto${item}"});
1734 # shiptocp_gender only makes sense, if any other shipto attribute is set.
1735 # Because shiptocp_gender is set to 'm' by default in forms
1736 # it must not be considered above to decide if shiptos has to be added or
1737 # updated, but must be inserted or updated as well in case.
1738 push(@values, $self->{shiptocp_gender});
1740 my $shipto_id = $self->{shipto_id};
1742 if ($self->{shipto_id}) {
1743 my $query = qq|UPDATE shipto set
1745 shiptodepartment_1 = ?,
1746 shiptodepartment_2 = ?,
1757 WHERE shipto_id = ?|;
1758 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1760 my $query = qq|SELECT * FROM shipto
1761 WHERE shiptoname = ? AND
1762 shiptodepartment_1 = ? AND
1763 shiptodepartment_2 = ? AND
1764 shiptostreet = ? AND
1765 shiptozipcode = ? AND
1767 shiptocountry = ? AND
1769 shiptocontact = ? AND
1773 shiptocp_gender = ? AND
1776 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1779 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1780 shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
1781 shiptocontact, shiptophone, shiptofax, shiptoemail, shiptocp_gender, module)
1782 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1783 do_query($self, $dbh, $insert_query, $id, @values, $module);
1785 $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1788 $shipto_id = $insert_check->{shipto_id};
1791 return unless $shipto_id;
1793 CVar->save_custom_variables(
1796 trans_id => $shipto_id,
1798 name_prefix => 'shipto',
1803 $main::lxdebug->enter_sub();
1805 my ($self, $dbh) = @_;
1807 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1809 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1810 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1811 $self->{"employee_id"} *= 1;
1813 $main::lxdebug->leave_sub();
1816 sub get_employee_data {
1817 $main::lxdebug->enter_sub();
1821 my $defaults = SL::DB::Default->get;
1823 Common::check_params(\%params, qw(prefix));
1824 Common::check_params_x(\%params, qw(id));
1827 $main::lxdebug->leave_sub();
1831 my $myconfig = \%main::myconfig;
1832 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
1834 my ($login, $deleted) = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
1837 # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
1838 $self->{$params{prefix} . '_login'} = $login;
1839 $self->{$params{prefix} . "_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
1842 # get employee data from auth.user_config
1843 my $user = User->new(login => $login);
1844 $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
1846 # get saved employee data from employee
1847 my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
1848 $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
1849 $self->{$params{prefix} . "_name"} = $employee->name;
1852 $main::lxdebug->leave_sub();
1856 $main::lxdebug->enter_sub();
1858 my ($self, $dbh, $id, $key) = @_;
1860 $key = "all_contacts" unless ($key);
1864 $main::lxdebug->leave_sub();
1869 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1870 qq|FROM contacts | .
1871 qq|WHERE cp_cv_id = ? | .
1872 qq|ORDER BY lower(cp_name)|;
1874 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1876 $main::lxdebug->leave_sub();
1880 $main::lxdebug->enter_sub();
1882 my ($self, $dbh, $key) = @_;
1884 my ($all, $old_id, $where, @values);
1886 if (ref($key) eq "HASH") {
1889 $key = "ALL_PROJECTS";
1891 foreach my $p (keys(%{$params})) {
1893 $all = $params->{$p};
1894 } elsif ($p eq "old_id") {
1895 $old_id = $params->{$p};
1896 } elsif ($p eq "key") {
1897 $key = $params->{$p};
1903 $where = "WHERE active ";
1905 if (ref($old_id) eq "ARRAY") {
1906 my @ids = grep({ $_ } @{$old_id});
1908 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1909 push(@values, @ids);
1912 $where .= " OR (id = ?) ";
1913 push(@values, $old_id);
1919 qq|SELECT id, projectnumber, description, active | .
1922 qq|ORDER BY lower(projectnumber)|;
1924 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1926 $main::lxdebug->leave_sub();
1930 $main::lxdebug->enter_sub();
1932 my ($self, $dbh, $key) = @_;
1934 $key = "all_printers" unless ($key);
1936 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1938 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1940 $main::lxdebug->leave_sub();
1944 $main::lxdebug->enter_sub();
1946 my ($self, $dbh, $params) = @_;
1949 $key = $params->{key};
1950 $key = "all_charts" unless ($key);
1952 my $transdate = quote_db_date($params->{transdate});
1955 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
1957 qq|LEFT JOIN taxkeys tk ON | .
1958 qq|(tk.id = (SELECT id FROM taxkeys | .
1959 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1960 qq| ORDER BY startdate DESC LIMIT 1)) | .
1961 qq|ORDER BY c.accno|;
1963 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1965 $main::lxdebug->leave_sub();
1969 $main::lxdebug->enter_sub();
1971 my ($self, $dbh, $key) = @_;
1973 $key = "all_taxzones" unless ($key);
1975 $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
1977 my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
1979 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1981 $main::lxdebug->leave_sub();
1984 sub _get_employees {
1985 $main::lxdebug->enter_sub();
1987 my ($self, $dbh, $params) = @_;
1992 if (ref $params eq 'HASH') {
1993 $key = $params->{key};
1994 $deleted = $params->{deleted};
2000 $key ||= "all_employees";
2001 my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
2002 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
2004 $main::lxdebug->leave_sub();
2007 sub _get_business_types {
2008 $main::lxdebug->enter_sub();
2010 my ($self, $dbh, $key) = @_;
2012 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2013 $options->{key} ||= "all_business_types";
2016 if (exists $options->{salesman}) {
2017 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2020 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2022 $main::lxdebug->leave_sub();
2025 sub _get_languages {
2026 $main::lxdebug->enter_sub();
2028 my ($self, $dbh, $key) = @_;
2030 $key = "all_languages" unless ($key);
2032 my $query = qq|SELECT * FROM language ORDER BY id|;
2034 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2036 $main::lxdebug->leave_sub();
2039 sub _get_dunning_configs {
2040 $main::lxdebug->enter_sub();
2042 my ($self, $dbh, $key) = @_;
2044 $key = "all_dunning_configs" unless ($key);
2046 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2048 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2050 $main::lxdebug->leave_sub();
2053 sub _get_currencies {
2054 $main::lxdebug->enter_sub();
2056 my ($self, $dbh, $key) = @_;
2058 $key = "all_currencies" unless ($key);
2060 $self->{$key} = [$self->get_all_currencies()];
2062 $main::lxdebug->leave_sub();
2066 $main::lxdebug->enter_sub();
2068 my ($self, $dbh, $key) = @_;
2070 $key = "all_payments" unless ($key);
2072 my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2074 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2076 $main::lxdebug->leave_sub();
2079 sub _get_customers {
2080 $main::lxdebug->enter_sub();
2082 my ($self, $dbh, $key) = @_;
2084 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2085 $options->{key} ||= "all_customers";
2086 my $limit_clause = $options->{limit} ? "LIMIT $options->{limit}" : '';
2089 push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman};
2090 push @where, qq|NOT obsolete| if !$options->{with_obsolete};
2091 my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2093 my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2094 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2096 $main::lxdebug->leave_sub();
2100 $main::lxdebug->enter_sub();
2102 my ($self, $dbh, $key) = @_;
2104 $key = "all_vendors" unless ($key);
2106 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2108 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2110 $main::lxdebug->leave_sub();
2113 sub _get_departments {
2114 $main::lxdebug->enter_sub();
2116 my ($self, $dbh, $key) = @_;
2118 $key = "all_departments" unless ($key);
2120 my $query = qq|SELECT * FROM department ORDER BY description|;
2122 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2124 $main::lxdebug->leave_sub();
2127 sub _get_warehouses {
2128 $main::lxdebug->enter_sub();
2130 my ($self, $dbh, $param) = @_;
2132 my ($key, $bins_key);
2134 if ('' eq ref $param) {
2138 $key = $param->{key};
2139 $bins_key = $param->{bins};
2142 my $query = qq|SELECT w.* FROM warehouse w
2143 WHERE (NOT w.invalid) AND
2144 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2145 ORDER BY w.sortkey|;
2147 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2150 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2151 ORDER BY description|;
2152 my $sth = prepare_query($self, $dbh, $query);
2154 foreach my $warehouse (@{ $self->{$key} }) {
2155 do_statement($self, $sth, $query, $warehouse->{id});
2156 $warehouse->{$bins_key} = [];
2158 while (my $ref = $sth->fetchrow_hashref()) {
2159 push @{ $warehouse->{$bins_key} }, $ref;
2165 $main::lxdebug->leave_sub();
2169 $main::lxdebug->enter_sub();
2171 my ($self, $dbh, $table, $key, $sortkey) = @_;
2173 my $query = qq|SELECT * FROM $table|;
2174 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2176 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2178 $main::lxdebug->leave_sub();
2182 $main::lxdebug->enter_sub();
2187 croak "get_lists: shipto is no longer supported" if $params{shipto};
2189 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2190 my ($sth, $query, $ref);
2193 if ($params{contacts}) {
2194 $vc = 'customer' if $self->{"vc"} eq "customer";
2195 $vc = 'vendor' if $self->{"vc"} eq "vendor";
2196 die "invalid use of get_lists, need 'vc'" unless $vc;
2197 $vc_id = $self->{"${vc}_id"};
2200 if ($params{"contacts"}) {
2201 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2204 if ($params{"projects"} || $params{"all_projects"}) {
2205 $self->_get_projects($dbh, $params{"all_projects"} ?
2206 $params{"all_projects"} : $params{"projects"},
2207 $params{"all_projects"} ? 1 : 0);
2210 if ($params{"printers"}) {
2211 $self->_get_printers($dbh, $params{"printers"});
2214 if ($params{"languages"}) {
2215 $self->_get_languages($dbh, $params{"languages"});
2218 if ($params{"charts"}) {
2219 $self->_get_charts($dbh, $params{"charts"});
2222 if ($params{"taxzones"}) {
2223 $self->_get_taxzones($dbh, $params{"taxzones"});
2226 if ($params{"employees"}) {
2227 $self->_get_employees($dbh, $params{"employees"});
2230 if ($params{"salesmen"}) {
2231 $self->_get_employees($dbh, $params{"salesmen"});
2234 if ($params{"business_types"}) {
2235 $self->_get_business_types($dbh, $params{"business_types"});
2238 if ($params{"dunning_configs"}) {
2239 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2242 if($params{"currencies"}) {
2243 $self->_get_currencies($dbh, $params{"currencies"});
2246 if($params{"customers"}) {
2247 $self->_get_customers($dbh, $params{"customers"});
2250 if($params{"vendors"}) {
2251 if (ref $params{"vendors"} eq 'HASH') {
2252 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2254 $self->_get_vendors($dbh, $params{"vendors"});
2258 if($params{"payments"}) {
2259 $self->_get_payments($dbh, $params{"payments"});
2262 if($params{"departments"}) {
2263 $self->_get_departments($dbh, $params{"departments"});
2266 if ($params{price_factors}) {
2267 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2270 if ($params{warehouses}) {
2271 $self->_get_warehouses($dbh, $params{warehouses});
2274 if ($params{partsgroup}) {
2275 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2278 $main::lxdebug->leave_sub();
2281 # this sub gets the id and name from $table
2283 $main::lxdebug->enter_sub();
2285 my ($self, $myconfig, $table) = @_;
2287 # connect to database
2288 my $dbh = $self->get_standard_dbh($myconfig);
2290 $table = $table eq "customer" ? "customer" : "vendor";
2291 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2293 my ($query, @values);
2295 if (!$self->{openinvoices}) {
2297 if ($self->{customernumber} ne "") {
2298 $where = qq|(vc.customernumber ILIKE ?)|;
2299 push(@values, like($self->{customernumber}));
2301 $where = qq|(vc.name ILIKE ?)|;
2302 push(@values, like($self->{$table}));
2306 qq~SELECT vc.id, vc.name,
2307 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2309 WHERE $where AND (NOT vc.obsolete)
2313 qq~SELECT DISTINCT vc.id, vc.name,
2314 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2316 JOIN $table vc ON (a.${table}_id = vc.id)
2317 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2319 push(@values, like($self->{$table}));
2322 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2324 $main::lxdebug->leave_sub();
2326 return scalar(@{ $self->{name_list} });
2331 my ($self, $table, $provided_dbh) = @_;
2333 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
2334 return unless $self->{id};
2335 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2337 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2338 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2339 $ref->{mtime} ||= $ref->{itime};
2340 $self->{lastmtime} = $ref->{mtime};
2344 sub mtime_ischanged {
2345 my ($self, $table, $option) = @_;
2347 return unless $self->{id};
2348 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2350 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2351 my $ref = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
2352 $ref->{mtime} ||= $ref->{itime};
2354 if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
2355 $self->error(($option eq 'mail') ?
2356 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") :
2357 t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
2359 $::dispatcher->end_request;
2363 # language_payment duplicates some of the functionality of all_vc (language,
2364 # printer, payment_terms), and at least in the case of sales invoices both
2365 # all_vc and language_payment are called when adding new invoices
2366 sub language_payment {
2367 $main::lxdebug->enter_sub();
2369 my ($self, $myconfig) = @_;
2371 my $dbh = $self->get_standard_dbh($myconfig);
2373 my $query = qq|SELECT id, description
2377 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2380 $query = qq|SELECT printer_description, id
2382 ORDER BY printer_description|;
2384 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2387 $query = qq|SELECT id, description
2389 WHERE ( obsolete IS FALSE OR id = ? )
2391 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
2393 # get buchungsgruppen
2394 $query = qq|SELECT id, description
2395 FROM buchungsgruppen|;
2397 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2399 $main::lxdebug->leave_sub();
2402 # this is only used for reports
2403 sub all_departments {
2404 $main::lxdebug->enter_sub();
2406 my ($self, $myconfig, $table) = @_;
2408 my $dbh = $self->get_standard_dbh($myconfig);
2410 my $query = qq|SELECT id, description
2412 ORDER BY description|;
2413 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2415 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2417 $main::lxdebug->leave_sub();
2421 $main::lxdebug->enter_sub();
2423 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2426 if ($table eq "customer") {
2435 # get last customers or vendors
2436 my ($query, $sth, $ref);
2438 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2443 my $transdate = "current_date";
2444 if ($self->{transdate}) {
2445 $transdate = $dbh->quote($self->{transdate});
2448 # now get the account numbers
2450 SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
2452 -- find newest entries in taxkeys
2454 SELECT chart_id, MAX(startdate) AS startdate
2456 WHERE (startdate <= $transdate)
2458 ) tk ON (c.id = tk.chart_id)
2459 -- and load all of those entries
2460 INNER JOIN taxkeys tk2
2461 ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
2462 WHERE (c.link LIKE ?)
2465 $sth = $dbh->prepare($query);
2467 do_statement($self, $sth, $query, like($module));
2469 $self->{accounts} = "";
2470 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2472 foreach my $key (split(/:/, $ref->{link})) {
2473 if ($key =~ /\Q$module\E/) {
2475 # cross reference for keys
2476 $xkeyref{ $ref->{accno} } = $key;
2478 push @{ $self->{"${module}_links"}{$key} },
2479 { accno => $ref->{accno},
2480 chart_id => $ref->{chart_id},
2481 description => $ref->{description},
2482 taxkey => $ref->{taxkey_id},
2483 tax_id => $ref->{tax_id} };
2485 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2491 # get taxkeys and description
2492 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2493 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2495 if (($module eq "AP") || ($module eq "AR")) {
2496 # get tax rates and description
2497 $query = qq|SELECT * FROM tax|;
2498 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2501 my $extra_columns = '';
2502 $extra_columns .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
2507 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid, a.deliverydate,
2508 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,
2510 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2511 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2512 a.globalproject_id, a.transaction_description, ${extra_columns}
2514 d.description AS department,
2517 JOIN $table c ON (a.${table}_id = c.id)
2518 LEFT JOIN employee e ON (e.id = a.employee_id)
2519 LEFT JOIN department d ON (d.id = a.department_id)
2521 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2523 foreach my $key (keys %$ref) {
2524 $self->{$key} = $ref->{$key};
2526 $self->{mtime} ||= $self->{itime};
2527 $self->{lastmtime} = $self->{mtime};
2528 my $transdate = "current_date";
2529 if ($self->{transdate}) {
2530 $transdate = $dbh->quote($self->{transdate});
2533 # now get the account numbers
2534 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
2536 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2538 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2539 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2542 $sth = $dbh->prepare($query);
2543 do_statement($self, $sth, $query, like($module));
2545 $self->{accounts} = "";
2546 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2548 foreach my $key (split(/:/, $ref->{link})) {
2549 if ($key =~ /\Q$module\E/) {
2551 # cross reference for keys
2552 $xkeyref{ $ref->{accno} } = $key;
2554 push @{ $self->{"${module}_links"}{$key} },
2555 { accno => $ref->{accno},
2556 chart_id => $ref->{chart_id},
2557 description => $ref->{description},
2558 taxkey => $ref->{taxkey_id},
2559 tax_id => $ref->{tax_id} };
2561 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2567 # get amounts from individual entries
2570 c.accno, c.description,
2571 a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
2576 LEFT JOIN chart c ON (c.id = a.chart_id)
2577 LEFT JOIN project p ON (p.id = a.project_id)
2578 LEFT JOIN tax t ON (t.id= a.tax_id)
2579 WHERE a.trans_id = ?
2580 ORDER BY a.acc_trans_id, a.transdate|;
2581 $sth = $dbh->prepare($query);
2582 do_statement($self, $sth, $query, $self->{id});
2584 # get exchangerate for currency
2585 ($self->{exchangerate}, $self->{record_forex}) = $self->check_exchangerate($myconfig, $self->{currency}, $self->{transdate}, $fld,
2586 $self->{id}, $arap);
2589 my @fx_transaction_entries;
2591 # store amounts in {acc_trans}{$key} for multiple accounts
2592 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2593 # skip fx_transaction entries and add them for post processing
2594 if ($ref->{fx_transaction}) {
2595 die "first entry in a record transaction should not be fx_transaction" unless @fx_transaction_entries;
2596 push @{ $fx_transaction_entries[-1] }, $ref;
2599 push @fx_transaction_entries, [ $ref ];
2603 # credit and debit bookings calc fx rate for positions
2604 # also used as exchangerate_$i for payments - exchangerate here can come from frontend or from bank transactions
2605 $ref->{exchangerate} =
2606 $self->check_exchangerate($myconfig, $self->{currency}, $ref->{transdate}, $fld);
2607 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2610 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2611 $ref->{amount} *= -1;
2613 $ref->{index} = $index;
2615 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2618 # post process fx_transactions.
2619 # old bin/mozilla code first posts the intended foreign currency amount and then the correction for exchange flagged as fx_transaction
2620 # for example: when posting 20 USD on a system in EUR with an exchangerate of 1.1, the resulting acc_trans will say:
2621 # +20 no fx (intended: 20 USD)
2622 # +2 fx (but it's actually 22 EUR)
2624 # for payments this is followed by the fxgain/loss. when paying the above invoice with 20 USD at 1.3 exchange:
2625 # -20 no fx (intended: 20 USD)
2626 # -6 fx (but it's actually 26 EUR)
2627 # +4 fx (but 4 of them go to fxgain)
2629 # bin/mozilla/ controllers will display the intended amount as is, but would have to guess at the actual book value
2630 # without the extra fields
2632 # bank transactions however will convert directly into internal currency, so a foreign currency invoice might end up
2633 # having non-fxtransactions. to make sure that these are roundtrip safe, flag the fx-transaction payments as fx and give the
2634 # intendended internal amount
2636 # this still operates on the cached entries of form->{acc_trans}
2637 for my $fx_block (@fx_transaction_entries) {
2638 my ($ref, @fx_entries) = @$fx_block;
2639 for my $fx_ref (@fx_entries) {
2640 if ($fx_ref->{chart_id} == $ref->{chart_id}) {
2641 $ref->{defaultcurrency_paid} //= $ref->{amount};
2642 $ref->{defaultcurrency_paid} += $fx_ref->{amount};
2643 $ref->{fx_transaction} = 1;
2652 d.closedto, d.revtrans,
2653 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2654 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2655 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2656 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2657 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2659 $ref = selectfirst_hashref_query($self, $dbh, $query);
2660 map { $self->{$_} = $ref->{$_} } keys %$ref;
2667 current_date AS transdate, d.closedto, d.revtrans,
2668 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2669 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2670 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2671 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2672 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2674 $ref = selectfirst_hashref_query($self, $dbh, $query);
2675 map { $self->{$_} = $ref->{$_} } keys %$ref;
2677 # failsafe, set currency if caller has not yet assigned one
2678 $self->lastname_used($dbh, $myconfig, $table, $module) unless ($self->{"$self->{vc}_id"});
2679 $self->{currency} = $self->{defaultcurrency} unless $self->{currency};
2680 $self->{exchangerate} =
2681 $self->check_exchangerate($myconfig, $self->{currency}, $self->{transdate}, $fld);
2684 $main::lxdebug->leave_sub();
2688 $main::lxdebug->enter_sub();
2690 my ($self, $dbh, $myconfig, $table, $module) = @_;
2694 $table = $table eq "customer" ? "customer" : "vendor";
2695 my %column_map = ("a.${table}_id" => "${table}_id",
2696 "a.department_id" => "department_id",
2697 "d.description" => "department",
2698 "ct.name" => $table,
2699 "cu.name" => "currency",
2702 if ($self->{type} =~ /delivery_order/) {
2703 $arap = 'delivery_orders';
2704 delete $column_map{"cu.currency"};
2706 } elsif ($self->{type} =~ /_order/) {
2708 $where = "quotation = '0'";
2710 } elsif ($self->{type} =~ /_quotation/) {
2712 $where = "quotation = '1'";
2714 } elsif ($table eq 'customer') {
2722 $where = "($where) AND" if ($where);
2723 my $query = qq|SELECT MAX(id) FROM $arap
2724 WHERE $where ${table}_id > 0|;
2725 my ($trans_id) = selectrow_query($self, $dbh, $query);
2728 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2729 $query = qq|SELECT $column_spec
2731 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2732 LEFT JOIN department d ON (a.department_id = d.id)
2733 LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
2735 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2737 map { $self->{$_} = $ref->{$_} } values %column_map;
2739 $main::lxdebug->leave_sub();
2742 sub get_variable_content_types {
2745 my %html_variables = (
2746 longdescription => 'html',
2747 partnotes => 'html',
2749 orignotes => 'html',
2754 header_text => 'html',
2755 footer_text => 'html',
2760 $self->get_variable_content_types_for_cvars,
2764 sub get_variable_content_types_for_cvars {
2766 my $html_configs = SL::DB::Manager::CustomVariableConfig->get_all(where => [ type => 'htmlfield' ]);
2769 if (@{ $html_configs }) {
2770 my %prefix_by_module = (
2771 Contacts => 'cp_cvar_',
2774 Projects => 'project_cvar_',
2775 ShipTo => 'shiptocvar_',
2778 foreach my $cfg (@{ $html_configs }) {
2779 my $prefix = $prefix_by_module{$cfg->module};
2780 $types{$prefix . $cfg->name} = 'html' if $prefix;
2788 $main::lxdebug->enter_sub();
2791 my $myconfig = shift || \%::myconfig;
2792 my ($thisdate, $days) = @_;
2794 my $dbh = $self->get_standard_dbh($myconfig);
2799 my $dateformat = $myconfig->{dateformat};
2800 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2801 $thisdate = $dbh->quote($thisdate);
2802 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2804 $query = qq|SELECT current_date AS thisdate|;
2807 ($thisdate) = selectrow_query($self, $dbh, $query);
2809 $main::lxdebug->leave_sub();
2815 $main::lxdebug->enter_sub();
2817 my ($self, $flds, $new, $count, $numrows) = @_;
2821 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2826 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2828 my $j = $item->{ndx} - 1;
2829 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2833 for $i ($count + 1 .. $numrows) {
2834 map { delete $self->{"${_}_$i"} } @{$flds};
2837 $main::lxdebug->leave_sub();
2841 $main::lxdebug->enter_sub();
2843 my ($self, $myconfig) = @_;
2847 SL::DB->client->with_transaction(sub {
2848 my $dbh = SL::DB->client->dbh;
2850 my $query = qq|DELETE FROM status
2851 WHERE (formname = ?) AND (trans_id = ?)|;
2852 my $sth = prepare_query($self, $dbh, $query);
2854 if ($self->{formname} =~ /(check|receipt)/) {
2855 for $i (1 .. $self->{rowcount}) {
2856 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2859 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2863 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2864 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2866 my %queued = split / /, $self->{queued};
2869 if ($self->{formname} =~ /(check|receipt)/) {
2871 # this is a check or receipt, add one entry for each lineitem
2872 my ($accno) = split /--/, $self->{account};
2873 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2874 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2875 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2876 $sth = prepare_query($self, $dbh, $query);
2878 for $i (1 .. $self->{rowcount}) {
2879 if ($self->{"checked_$i"}) {
2880 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2886 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2887 VALUES (?, ?, ?, ?, ?)|;
2888 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2889 $queued{$self->{formname}}, $self->{formname});
2892 }) or do { die SL::DB->client->error };
2894 $main::lxdebug->leave_sub();
2898 $main::lxdebug->enter_sub();
2900 my ($self, $dbh) = @_;
2902 my ($query, $printed, $emailed);
2904 my $formnames = $self->{printed};
2905 my $emailforms = $self->{emailed};
2907 $query = qq|DELETE FROM status
2908 WHERE (formname = ?) AND (trans_id = ?)|;
2909 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2911 # this only applies to the forms
2912 # checks and receipts are posted when printed or queued
2914 if ($self->{queued}) {
2915 my %queued = split / /, $self->{queued};
2917 foreach my $formname (keys %queued) {
2918 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2919 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2921 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2922 VALUES (?, ?, ?, ?, ?)|;
2923 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2925 $formnames =~ s/\Q$self->{formname}\E//;
2926 $emailforms =~ s/\Q$self->{formname}\E//;
2931 # save printed, emailed info
2932 $formnames =~ s/^ +//g;
2933 $emailforms =~ s/^ +//g;
2936 map { $status{$_}{printed} = 1 } split / +/, $formnames;
2937 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2939 foreach my $formname (keys %status) {
2940 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
2941 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
2943 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2944 VALUES (?, ?, ?, ?)|;
2945 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2948 $main::lxdebug->leave_sub();
2952 # $main::locale->text('SAVED')
2953 # $main::locale->text('SCREENED')
2954 # $main::locale->text('DELETED')
2955 # $main::locale->text('ADDED')
2956 # $main::locale->text('PAYMENT POSTED')
2957 # $main::locale->text('POSTED')
2958 # $main::locale->text('POSTED AS NEW')
2959 # $main::locale->text('ELSE')
2960 # $main::locale->text('SAVED FOR DUNNING')
2961 # $main::locale->text('DUNNING STARTED')
2962 # $main::locale->text('PREVIEWED')
2963 # $main::locale->text('PRINTED')
2964 # $main::locale->text('MAILED')
2965 # $main::locale->text('SCREENED')
2966 # $main::locale->text('CANCELED')
2967 # $main::locale->text('IMPORT')
2968 # $main::locale->text('UNDO TRANSFER')
2969 # $main::locale->text('UNIMPORT')
2970 # $main::locale->text('invoice')
2971 # $main::locale->text('invoice_for_advance_payment')
2972 # $main::locale->text('final_invoice')
2973 # $main::locale->text('proforma')
2974 # $main::locale->text('storno_invoice')
2975 # $main::locale->text('sales_order_intake')
2976 # $main::locale->text('sales_order')
2977 # $main::locale->text('pick_list')
2978 # $main::locale->text('purchase_order')
2979 # $main::locale->text('purchase_order_confirmation')
2980 # $main::locale->text('bin_list')
2981 # $main::locale->text('sales_quotation')
2982 # $main::locale->text('request_quotation')
2983 # $main::locale->text('purchase_quotation_intake')
2986 $main::lxdebug->enter_sub();
2989 my $dbh = shift || SL::DB->client->dbh;
2990 SL::DB->client->with_transaction(sub {
2992 if(!exists $self->{employee_id}) {
2993 &get_employee($self, $dbh);
2997 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2998 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
2999 my @values = (conv_i($self->{id}), $self->{login},
3000 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3001 do_query($self, $dbh, $query, @values);
3003 }) or do { die SL::DB->client->error };
3005 $main::lxdebug->leave_sub();
3009 $main::lxdebug->enter_sub();
3011 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3012 my ($orderBy, $desc) = split(/\-\-/, $order);
3013 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3016 if ($trans_id ne "") {
3018 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 | .
3019 qq|FROM history_erp h | .
3020 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3021 qq|WHERE (trans_id = | . $dbh->quote($trans_id) . qq|) $restriction | .
3024 my $sth = $dbh->prepare($query) || $self->dberror($query);
3026 $sth->execute() || $self->dberror("$query");
3028 while(my $hash_ref = $sth->fetchrow_hashref()) {
3029 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3030 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3031 my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
3032 $hash_ref->{snumbers} = $number;
3033 $hash_ref->{haslink} = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
3034 $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
3035 $tempArray[$i++] = $hash_ref;
3037 $main::lxdebug->leave_sub() and return \@tempArray
3038 if ($i > 0 && $tempArray[0] ne "");
3040 $main::lxdebug->leave_sub();
3044 sub get_partsgroup {
3045 $main::lxdebug->enter_sub();
3047 my ($self, $myconfig, $p) = @_;
3048 my $target = $p->{target} || 'all_partsgroup';
3050 my $dbh = $self->get_standard_dbh($myconfig);
3052 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3054 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3057 if ($p->{searchitems} eq 'part') {
3058 $query .= qq|WHERE p.part_type = 'part'|;
3060 if ($p->{searchitems} eq 'service') {
3061 $query .= qq|WHERE p.part_type = 'service'|;
3063 if ($p->{searchitems} eq 'assembly') {
3064 $query .= qq|WHERE p.part_type = 'assembly'|;
3067 $query .= qq|ORDER BY partsgroup|;
3070 $query = qq|SELECT id, partsgroup FROM partsgroup
3071 ORDER BY partsgroup|;
3074 if ($p->{language_code}) {
3075 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3076 t.description AS translation
3078 JOIN parts p ON (p.partsgroup_id = pg.id)
3079 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3080 ORDER BY translation|;
3081 @values = ($p->{language_code});
3084 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3086 $main::lxdebug->leave_sub();
3089 sub get_pricegroup {
3090 $main::lxdebug->enter_sub();
3092 my ($self, $myconfig, $p) = @_;
3094 my $dbh = $self->get_standard_dbh($myconfig);
3096 my $query = qq|SELECT p.id, p.pricegroup
3099 $query .= qq| ORDER BY pricegroup|;
3102 $query = qq|SELECT id, pricegroup FROM pricegroup
3103 ORDER BY pricegroup|;
3106 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3108 $main::lxdebug->leave_sub();
3112 # usage $form->all_years($myconfig, [$dbh])
3113 # return list of all years where bookings found
3116 $main::lxdebug->enter_sub();
3118 my ($self, $myconfig, $dbh) = @_;
3120 $dbh ||= $self->get_standard_dbh($myconfig);
3123 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3124 (SELECT MAX(transdate) FROM acc_trans)|;
3125 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3127 if ($myconfig->{dateformat} =~ /^yy/) {
3128 ($startdate) = split /\W/, $startdate;
3129 ($enddate) = split /\W/, $enddate;
3131 (@_) = split /\W/, $startdate;
3133 (@_) = split /\W/, $enddate;
3138 $startdate = substr($startdate,0,4);
3139 $enddate = substr($enddate,0,4);
3141 while ($enddate >= $startdate) {
3142 push @all_years, $enddate--;
3147 $main::lxdebug->leave_sub();
3151 $main::lxdebug->enter_sub();
3155 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3157 $main::lxdebug->leave_sub();
3161 $main::lxdebug->enter_sub();
3166 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3168 $main::lxdebug->leave_sub();
3171 sub prepare_for_printing {
3174 my $defaults = SL::DB::Default->get;
3176 $self->{templates} ||= $defaults->templates;
3177 $self->{formname} ||= $self->{type};
3178 $self->{media} ||= 'email';
3180 die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3182 # Several fields that used to reside in %::myconfig (stored in
3183 # auth.user_config) are now stored in defaults. Copy them over for
3185 $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
3187 $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
3189 if (!$self->{employee_id}) {
3190 $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
3191 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
3194 my $language = $self->{language} ? '_' . $self->{language} : '';
3196 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3197 if ($self->{language_id}) {
3198 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3201 $output_dateformat ||= $::myconfig{dateformat};
3202 $output_numberformat ||= $::myconfig{numberformat};
3203 $output_longdates //= 1;
3205 $self->{myconfig_output_dateformat} = $output_dateformat // $::myconfig{dateformat};
3206 $self->{myconfig_output_longdates} = $output_longdates // 1;
3207 $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
3209 # Retrieve accounts for tax calculation.
3210 IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3212 if ($self->{type} =~ /_delivery_order$/) {
3213 DO->order_details(\%::myconfig, $self);
3214 } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order|purchase_quotation_intake/) {
3215 OE->order_details(\%::myconfig, $self);
3216 } elsif ($self->{type} =~ /reclamation/) {
3217 # skip reclamation here, legacy template arrays are added in the reclamation controller
3219 IS->invoice_details(\%::myconfig, $self, $::locale);
3222 $self->set_addition_billing_address_print_variables;
3224 # Chose extension & set source file name
3225 my $extension = 'html';
3226 if ($self->{format} eq 'postscript') {
3227 $self->{postscript} = 1;
3229 } elsif ($self->{"format"} =~ /pdf/) {
3231 $extension = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3232 } elsif ($self->{"format"} =~ /opendocument/) {
3233 $self->{opendocument} = 1;
3235 } elsif ($self->{"format"} =~ /excel/) {
3240 my $printer_code = $self->{printer_code} ? '_' . $self->{printer_code} : '';
3241 my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
3242 $self->{IN} = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3245 $self->format_dates($output_dateformat, $output_longdates,
3246 qw(invdate orddate quodate pldate duedate reqdate transdate tax_point shippingdate deliverydate validitydate paymentdate datepaid
3247 transdate_oe deliverydate_oe employee_startdate employee_enddate),
3248 grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3250 $self->reformat_numbers($output_numberformat, 2,
3251 qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3252 grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3254 $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3256 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3258 if (scalar @{ $cvar_date_fields }) {
3259 $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3262 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3263 $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3267 if (($self->{language} // '') ne '') {
3268 my $template_arrays = $self->{TEMPLATE_ARRAYS} || $self;
3269 for my $idx (0..scalar(@{ $template_arrays->{unit} }) - 1) {
3270 $template_arrays->{unit}->[$idx] = AM->translate_units($self, $self->{language}, $template_arrays->{unit}->[$idx], $template_arrays->{qty}->[$idx])
3274 $self->{template_meta} = {
3275 formname => $self->{formname},
3276 language => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
3277 format => $self->{format},
3278 media => $self->{media},
3279 extension => $extension,
3280 printer => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
3281 today => DateTime->today,
3284 if ($defaults->print_interpolate_variables_in_positions) {
3285 $self->substitute_placeholders_in_template_arrays({ field => 'description', type => 'text' }, { field => 'longdescription', type => 'html' });
3291 sub set_addition_billing_address_print_variables {
3294 return if !$self->{billing_address_id};
3296 my $address = SL::DB::Manager::AdditionalBillingAddress->find_by(id => $self->{billing_address_id});
3297 return if !$address;
3299 $self->{"billing_address_${_}"} = $address->$_ for map { $_->name } @{ $address->meta->columns };
3302 sub substitute_placeholders_in_template_arrays {
3303 my ($self, @fields) = @_;
3305 foreach my $spec (@fields) {
3306 $spec = { field => $spec, type => 'text' } if !ref($spec);
3307 my $field = $spec->{field};
3309 next unless exists $self->{TEMPLATE_ARRAYS} && exists $self->{TEMPLATE_ARRAYS}->{$field};
3311 my $tag_start = $spec->{type} eq 'html' ? '<%' : '<%';
3312 my $tag_end = $spec->{type} eq 'html' ? '%>' : '%>';
3313 my $formatter = $spec->{type} eq 'html' ? sub { $::locale->quote_special_chars('html', $_[0] // '') } : sub { $_[0] };
3315 $self->{TEMPLATE_ARRAYS}->{$field} = [
3316 apply { s{${tag_start}(.+?)${tag_end}}{ $formatter->($self->{$1}) }eg }
3317 @{ $self->{TEMPLATE_ARRAYS}->{$field} }
3324 sub calculate_arap {
3325 my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
3327 # this function is used to calculate netamount, total_tax and amount for AP and
3328 # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
3330 # Thus it needs a fully prepared $form to work on.
3331 # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
3333 # The calculated total values are all rounded (default is to 2 places) and
3334 # returned as parameters rather than directly modifying form. The aim is to
3335 # make the calculation of AP and AR behave identically. There is a test-case
3336 # for this function in t/form/arap.t
3338 # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
3339 # modified and formatted and receive the correct sign for writing straight to
3340 # acc_trans, depending on whether they are ar or ap.
3343 die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
3344 die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
3345 die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
3346 $roundplaces = 2 unless $roundplaces;
3348 my $sign = 1; # adjust final results for writing amount to acc_trans
3349 $sign = -1 if $buysell eq 'buy';
3351 my ($netamount,$total_tax,$amount);
3355 # parse and round amounts, setting correct sign for writing to acc_trans
3356 for my $i (1 .. $self->{rowcount}) {
3357 $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
3359 $amount += $self->{"amount_$i"} * $sign;
3362 for my $i (1 .. $self->{rowcount}) {
3363 next unless $self->{"amount_$i"};
3364 ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
3365 my $tax_id = $self->{"tax_id_$i"};
3367 my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
3368 if ( $selected_tax && !$selected_tax->reverse_charge_chart_id) {
3369 if ( $buysell eq 'sell' ) {
3370 $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3372 $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3375 $self->{"taxkey_$i"} = $selected_tax->taxkey;
3376 $self->{"taxrate_$i"} = $selected_tax->rate;
3379 $self->{"taxkey_$i"} = $selected_tax->taxkey if ($selected_tax && $selected_tax->reverse_charge_chart_id);
3381 ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
3383 $netamount += $self->{"amount_$i"};
3384 $total_tax += $self->{"tax_$i"};
3387 $amount = $netamount + $total_tax;
3389 # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
3390 # but reverse sign of totals for writing amounts to ar
3391 if ( $buysell eq 'buy' ) {
3397 return($netamount,$total_tax,$amount);
3401 my ($self, $dateformat, $longformat, @indices) = @_;
3403 $dateformat ||= $::myconfig{dateformat};
3405 foreach my $idx (@indices) {
3406 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3407 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3408 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3412 next unless defined $self->{$idx};
3414 if (!ref($self->{$idx})) {
3415 $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3417 } elsif (ref($self->{$idx}) eq "ARRAY") {
3418 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3419 $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3425 sub reformat_numbers {
3426 my ($self, $numberformat, $places, @indices) = @_;
3428 return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3430 foreach my $idx (@indices) {
3431 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3432 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3433 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3437 next unless defined $self->{$idx};
3439 if (!ref($self->{$idx})) {
3440 $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3442 } elsif (ref($self->{$idx}) eq "ARRAY") {
3443 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3444 $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3449 my $saved_numberformat = $::myconfig{numberformat};
3450 $::myconfig{numberformat} = $numberformat;
3452 foreach my $idx (@indices) {
3453 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3454 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3455 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3459 next unless defined $self->{$idx};
3461 if (!ref($self->{$idx})) {
3462 $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3464 } elsif (ref($self->{$idx}) eq "ARRAY") {
3465 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3466 $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3471 $::myconfig{numberformat} = $saved_numberformat;
3474 sub create_email_signature {
3475 my $client_signature = $::instance_conf->get_signature;
3476 my $user_signature = $::myconfig{signature};
3478 return join '', grep { $_ } ($user_signature, $client_signature);
3482 # this function calculates the net amount and tax for the lines in ar, ap and
3483 # gl and is used for update as well as post. When used with update the return
3484 # value of amount isn't needed
3486 # calculate_tax should always work with positive values, or rather as the user inputs them
3487 # calculate_tax uses db/perl numberformat, i.e. parsed numbers
3488 # convert to negative numbers (when necessary) only when writing to acc_trans
3489 # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
3490 # for post_transaction amount already contains exchangerate and correct sign and is rounded
3491 # calculate_tax doesn't (need to) know anything about exchangerate
3493 my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
3501 # calculate tax (unrounded), subtract from amount, round amount and round tax
3502 $tax = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
3503 $amount = $self->round_amount($amount - $tax, $roundplaces);
3504 $tax = $self->round_amount($tax, $roundplaces);
3506 $tax = $amount * $taxrate;
3507 $tax = $self->round_amount($tax, $roundplaces);
3510 $tax = 0 unless $tax;
3512 return ($amount,$tax);
3521 SL::Form.pm - main data object.
3525 This is the main data object of kivitendo.
3526 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3527 Points of interest for a beginner are:
3529 - $form->error - renders a generic error in html. accepts an error message
3530 - $form->get_standard_dbh - returns a database connection for the
3532 =head1 SPECIAL FUNCTIONS
3534 =head2 C<redirect_header> $url
3536 Generates a HTTP redirection header for the new C<$url>. Constructs an
3537 absolute URL including scheme, host name and port. If C<$url> is a
3538 relative URL then it is considered relative to kivitendo base URL.
3540 This function C<die>s if headers have already been created with
3541 C<$::form-E<gt>header>.
3545 print $::form->redirect_header('oe.pl?action=edit&id=1234');
3546 print $::form->redirect_header('http://www.lx-office.org/');
3550 Generates a general purpose http/html header and includes most of the scripts
3551 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3553 Only one header will be generated. If the method was already called in this
3554 request it will not output anything and return undef. Also if no
3555 HTTP_USER_AGENT is found, no header is generated.
3557 Although header does not accept parameters itself, it will honor special
3558 hashkeys of its Form instance:
3566 If one of these is set, a http-equiv refresh is generated. Missing parameters
3567 default to 3 seconds and the refering url.
3571 Either a scalar or an array ref. Will be inlined into the header. Add
3572 stylesheets with the L<use_stylesheet> function.
3576 If true, a css snippet will be generated that sets the page in landscape mode.
3580 Used to override the default favicon.
3584 A html page title will be generated from this
3586 =item mtime_ischanged
3588 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
3590 Can be used / called with any table, that has itime and mtime attributes.
3591 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
3592 Can be called wit C<option> mail to generate a different error message.
3594 Returns undef if no save operation has been done yet ($self->{id} not present).
3595 Returns undef if no concurrent write process is detected otherwise a error message.
3601 =item C<check_exchangerate> $myconfig, $currency, $transdate, $fld, $id, $record_table
3603 Needs a local myconfig, a currency string, a date of the transaction, a field (fld) which
3604 has to be either the buy or sell exchangerate and checks if there is already a buy or
3605 sell exchangerate for this date.
3606 Returns 0 or (NULL) if no entry is found or the already stored exchangerate.
3607 If the optional parameter id and record_table is passed, the method tries to look up
3608 a custom exchangerate for a record with id. record_table can either be ar, ap or bank_transactions.
3609 If none is found the default (daily) entry will be checked.
3610 The method is very strict about the parameters and tries to fail if anything does
3611 not look like the expected type.
3613 =item C<update_exchangerate> $dbh, $curr, $transdate, $buy, $sell, $id, $record_table
3615 Needs a dbh connection, a currency string, a date of the transaction, buy (0|1), sell (0|1) which
3616 determines if either the buy or sell or both exchangerates should be updated and updates
3617 the exchangerate for this currency for this date.
3618 If the optional parameter id and record_table is passed, the method saves
3619 a custom exchangerate for a record with id. record_table can either be ar, ap or bank_transactions.
3621 The method is very strict about the parameters and tries to fail if anything does not look
3622 like the expected type.