1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
15 # Contributors: Thomas Bayen <bayen@gmx.de>
16 # Antti Kaihola <akaihola@siba.fi>
17 # Moritz Bunkus (tex code)
19 # This program is free software; you can redistribute it and/or modify
20 # it under the terms of the GNU General Public License as published by
21 # the Free Software Foundation; either version 2 of the License, or
22 # (at your option) any later version.
24 # This program is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 # GNU General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, write to the Free Software
30 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
32 #======================================================================
33 # Utilities for parsing forms
34 # and supporting routines for linking account numbers
35 # used in AR, AP and IS, IR modules
37 #======================================================================
52 use POSIX qw(strftime);
64 use SL::DB::PaymentTerm;
67 use SL::Helper::Flash qw();
70 use SL::Layout::Dispatcher;
72 use SL::Locale::String;
75 use SL::MoreCommon qw(uri_encode uri_decode);
77 use SL::PrefixedNumber;
86 use List::Util qw(first max min sum);
87 use List::MoreUtils qw(all any apply);
89 use SL::Helper::File qw(:all);
90 use SL::Helper::Number;
91 use SL::Helper::CreatePDF qw(merge_pdfs);
96 SL::Version->get_version;
100 $main::lxdebug->enter_sub();
107 if ($LXDebug::watch_form) {
108 require SL::Watchdog;
109 tie %{ $self }, 'SL::Watchdog';
114 $main::lxdebug->leave_sub();
119 sub _flatten_variables_rec {
120 $main::lxdebug->enter_sub(2);
129 if ('' eq ref $curr->{$key}) {
130 @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
132 } elsif ('HASH' eq ref $curr->{$key}) {
133 foreach my $hash_key (sort keys %{ $curr->{$key} }) {
134 push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
138 foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
139 my $first_array_entry = 1;
141 my $element = $curr->{$key}[$idx];
143 if ('HASH' eq ref $element) {
144 foreach my $hash_key (sort keys %{ $element }) {
145 push @result, $self->_flatten_variables_rec($element, $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
146 $first_array_entry = 0;
149 push @result, { 'key' => $prefix . $key . '[]', 'value' => $element };
154 $main::lxdebug->leave_sub(2);
159 sub flatten_variables {
160 $main::lxdebug->enter_sub(2);
168 push @variables, $self->_flatten_variables_rec($self, '', $_);
171 $main::lxdebug->leave_sub(2);
176 sub flatten_standard_variables {
177 $main::lxdebug->enter_sub(2);
180 my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar), @_);
184 foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
185 push @variables, $self->_flatten_variables_rec($self, '', $_);
188 $main::lxdebug->leave_sub(2);
194 my ($self, $str) = @_;
196 return uri_encode($str);
200 my ($self, $str) = @_;
202 return uri_decode($str);
206 $main::lxdebug->enter_sub();
207 my ($self, $str) = @_;
209 if ($str && !ref($str)) {
210 $str =~ s/\"/"/g;
213 $main::lxdebug->leave_sub();
219 $main::lxdebug->enter_sub();
220 my ($self, $str) = @_;
222 if ($str && !ref($str)) {
223 $str =~ s/"/\"/g;
226 $main::lxdebug->leave_sub();
232 $main::lxdebug->enter_sub();
236 map({ print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
238 for (sort keys %$self) {
239 next if (($_ eq "header") || (ref($self->{$_}) ne ""));
240 print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
243 $main::lxdebug->leave_sub();
247 my ($self, $code) = @_;
248 local $self->{__ERROR_HANDLER} = sub { SL::X::FormError->throw(error => $_[0]) };
253 $main::lxdebug->enter_sub();
255 $main::lxdebug->show_backtrace();
257 my ($self, $msg) = @_;
259 if ($self->{__ERROR_HANDLER}) {
260 $self->{__ERROR_HANDLER}->($msg);
262 } elsif ($ENV{HTTP_USER_AGENT}) {
264 $self->show_generic_error($msg);
267 confess "Error: $msg\n";
270 $main::lxdebug->leave_sub();
274 $main::lxdebug->enter_sub();
276 my ($self, $msg) = @_;
278 if ($ENV{HTTP_USER_AGENT}) {
280 print $self->parse_html_template('generic/form_info', { message => $msg });
282 } elsif ($self->{info_function}) {
283 &{ $self->{info_function} }($msg);
288 $main::lxdebug->leave_sub();
291 # calculates the number of rows in a textarea based on the content and column number
292 # can be capped with maxrows
294 $main::lxdebug->enter_sub();
295 my ($self, $str, $cols, $maxrows, $minrows) = @_;
299 my $rows = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
302 $main::lxdebug->leave_sub();
304 return max(min($rows, $maxrows), $minrows);
308 my ($self, $msg) = @_;
310 SL::X::DBError->throw(
312 db_error => $DBI::errstr,
317 $main::lxdebug->enter_sub();
319 my ($self, $name, $msg) = @_;
322 foreach my $part (split m/\./, $name) {
323 if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
326 $curr = $curr->{$part};
329 $main::lxdebug->leave_sub();
332 sub _get_request_uri {
335 return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
336 return URI->new if !$ENV{REQUEST_URI}; # for testing
338 my $scheme = $::request->is_https ? 'https' : 'http';
339 my $port = $ENV{SERVER_PORT};
340 $port = undef if (($scheme eq 'http' ) && ($port == 80))
341 || (($scheme eq 'https') && ($port == 443));
343 my $uri = URI->new("${scheme}://");
344 $uri->scheme($scheme);
346 $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
347 $uri->path_query($ENV{REQUEST_URI});
353 sub _add_to_request_uri {
356 my $relative_new_path = shift;
357 my $request_uri = shift || $self->_get_request_uri;
358 my $relative_new_uri = URI->new($relative_new_path);
359 my @request_segments = $request_uri->path_segments;
361 my $new_uri = $request_uri->clone;
362 $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
367 sub create_http_response {
368 $main::lxdebug->enter_sub();
373 my $cgi = $::request->{cgi};
376 if (defined $main::auth) {
377 my $uri = $self->_get_request_uri;
378 my @segments = $uri->path_segments;
380 $uri->path_segments(@segments);
382 my $session_cookie_value = $main::auth->get_session_id();
384 if ($session_cookie_value) {
385 $session_cookie = $cgi->cookie('-name' => $main::auth->get_session_cookie_name(),
386 '-value' => $session_cookie_value,
387 '-path' => $uri->path,
388 '-expires' => '+' . $::auth->{session_timeout} . 'm',
389 '-secure' => $::request->is_https);
393 my %cgi_params = ('-type' => $params{content_type});
394 $cgi_params{'-charset'} = $params{charset} if ($params{charset});
395 $cgi_params{'-cookie'} = $session_cookie if ($session_cookie);
397 map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length status);
399 my $output = $cgi->header(%cgi_params);
401 $main::lxdebug->leave_sub();
407 $::lxdebug->enter_sub;
409 my ($self, %params) = @_;
412 $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
414 if ($params{no_layout}) {
415 $::request->{layout} = SL::Layout::Dispatcher->new(style => 'none');
418 my $layout = $::request->{layout};
420 # standard css for all
421 # this should gradually move to the layouts that need it
422 $layout->use_stylesheet("$_.css") for qw(
423 common main menu list_accounts jquery.autocomplete
424 jquery.multiselect2side
425 ui-lightness/jquery-ui
427 tooltipster themes/tooltipster-light
430 $layout->use_javascript("$_.js") for (qw(
431 jquery jquery-ui jquery.cookie jquery.checkall jquery.download
432 jquery/jquery.form jquery/fixes client_js
433 jquery/jquery.tooltipster.min
434 common part_selection
435 ), "jquery/ui/i18n/jquery.ui.datepicker-$::myconfig{countrycode}");
437 $self->{favicon} ||= "favicon.ico";
438 $self->{titlebar} = join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->read_version if $self->{title} || !$self->{titlebar};
441 if ($self->{refresh_url} || $self->{refresh_time}) {
442 my $refresh_time = $self->{refresh_time} || 3;
443 my $refresh_url = $self->{refresh_url} || $ENV{REFERER};
444 push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
447 my $auto_reload_resources_param = $layout->auto_reload_resources_param;
449 push @header, map { qq|<link rel="stylesheet" href="${_}${auto_reload_resources_param}" type="text/css" title="Stylesheet">| } $layout->stylesheets;
450 push @header, "<style type='text/css'>\@page { size:landscape; }</style> " if $self->{landscape};
451 push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
452 push @header, map { qq|<script type="text/javascript" src="${_}${auto_reload_resources_param}"></script>| } $layout->javascripts;
453 push @header, '<meta name="viewport" content="width=device-width, initial-scale=1">';
454 push @header, $self->{javascript} if $self->{javascript};
455 push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
458 strict => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
459 transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
460 frameset => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
461 html5 => qq|<!DOCTYPE html>|,
465 print $self->create_http_response(content_type => 'text/html', charset => 'UTF-8');
466 print $doctypes{$params{doctype} || 'transitional'}, $/;
470 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
471 <title>$self->{titlebar}</title>
473 print " $_\n" for @header;
475 <meta name="robots" content="noindex,nofollow">
480 print $::request->{layout}->pre_content;
481 print $::request->{layout}->start_content;
483 $layout->header_done;
485 $::lxdebug->leave_sub;
489 return unless $::request->{layout}->need_footer;
491 print $::request->{layout}->end_content;
492 print $::request->{layout}->post_content;
494 if (my @inline_scripts = $::request->{layout}->javascripts_inline) {
495 print "<script type='text/javascript'>" . join("; ", @inline_scripts) . "</script>\n";
504 sub ajax_response_header {
505 $main::lxdebug->enter_sub();
509 my $output = $::request->{cgi}->header('-charset' => 'UTF-8');
511 $main::lxdebug->leave_sub();
516 sub redirect_header {
520 my $base_uri = $self->_get_request_uri;
521 my $new_uri = URI->new_abs($new_url, $base_uri);
523 die "Headers already sent" if $self->{header};
526 return $::request->{cgi}->redirect($new_uri);
529 sub set_standard_title {
530 $::lxdebug->enter_sub;
533 $self->{titlebar} = "kivitendo " . $::locale->text('Version') . " " . $self->read_version;
534 $self->{titlebar} .= "- $::myconfig{name}" if $::myconfig{name};
535 $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
537 $::lxdebug->leave_sub;
540 sub _prepare_html_template {
541 $main::lxdebug->enter_sub();
543 my ($self, $file, $additional_params) = @_;
546 if (!%::myconfig || !$::myconfig{"countrycode"}) {
547 $language = $::lx_office_conf{system}->{language};
549 $language = $main::myconfig{"countrycode"};
551 $language = "de" unless ($language);
553 my $webpages_path = $::request->layout->webpages_path;
555 if (-f "${webpages_path}/${file}.html") {
556 $file = "${webpages_path}/${file}.html";
558 } elsif (ref $file eq 'SCALAR') {
559 # file is a scalarref, use inline mode
561 my $info = "Web page template '${file}' not found.\n";
563 print qq|<pre>$info</pre>|;
564 $::dispatcher->end_request;
567 $additional_params->{AUTH} = $::auth;
568 $additional_params->{INSTANCE_CONF} = $::instance_conf;
569 $additional_params->{LOCALE} = $::locale;
570 $additional_params->{LXCONFIG} = \%::lx_office_conf;
571 $additional_params->{LXDEBUG} = $::lxdebug;
572 $additional_params->{MYCONFIG} = \%::myconfig;
574 $main::lxdebug->leave_sub();
579 sub parse_html_template {
580 $main::lxdebug->enter_sub();
582 my ($self, $file, $additional_params) = @_;
584 $additional_params ||= { };
586 my $real_file = $self->_prepare_html_template($file, $additional_params);
587 my $template = $self->template;
589 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
592 $template->process($real_file, $additional_params, \$output) || die $template->error;
594 $main::lxdebug->leave_sub();
599 sub template { $::request->presenter->get_template }
601 sub show_generic_error {
602 $main::lxdebug->enter_sub();
604 my ($self, $error, %params) = @_;
606 if ($self->{__ERROR_HANDLER}) {
607 $self->{__ERROR_HANDLER}->($error);
608 $main::lxdebug->leave_sub();
612 if ($::request->is_ajax) {
615 ->render(SL::Controller::Base->new);
616 $::dispatcher->end_request;
620 'title_error' => $params{title},
621 'label_error' => $error,
624 $self->{title} = $params{title} if $params{title};
626 for my $bar ($::request->layout->get('actionbar')) {
630 call => [ 'kivi.history_back' ],
631 accesskey => 'enter',
637 print $self->parse_html_template("generic/error", $add_params);
639 print STDERR "Error: $error\n";
641 $main::lxdebug->leave_sub();
643 $::dispatcher->end_request;
646 sub show_generic_information {
647 $main::lxdebug->enter_sub();
649 my ($self, $text, $title) = @_;
652 'title_information' => $title,
653 'label_information' => $text,
656 $self->{title} = $title if ($title);
659 print $self->parse_html_template("generic/information", $add_params);
661 $main::lxdebug->leave_sub();
663 $::dispatcher->end_request;
666 sub _store_redirect_info_in_session {
669 return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
671 my ($controller, $params) = ($1, $2);
672 my $form = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
673 $self->{callback} = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
677 $main::lxdebug->enter_sub();
679 my ($self, $msg) = @_;
681 if (!$self->{callback}) {
685 SL::Helper::Flash::flash_later('info', $msg) if $msg;
686 $self->_store_redirect_info_in_session;
687 print $::form->redirect_header($self->{callback});
690 $::dispatcher->end_request;
692 $main::lxdebug->leave_sub();
695 # sort of columns removed - empty sub
697 $main::lxdebug->enter_sub();
699 my ($self, @columns) = @_;
701 $main::lxdebug->leave_sub();
708 my ($self, $myconfig, $amount, $places, $dash) = @_;
709 SL::Helper::Number::_format_number($amount, $places, %$myconfig, dash => $dash);
712 sub format_amount_units {
713 $main::lxdebug->enter_sub();
718 my $myconfig = \%main::myconfig;
719 my $amount = $params{amount} * 1;
720 my $places = $params{places};
721 my $part_unit_name = $params{part_unit};
722 my $amount_unit_name = $params{amount_unit};
723 my $conv_units = $params{conv_units};
724 my $max_places = $params{max_places};
726 if (!$part_unit_name) {
727 $main::lxdebug->leave_sub();
731 my $all_units = AM->retrieve_all_units;
733 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
734 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
737 if (!scalar @{ $conv_units }) {
738 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
739 $main::lxdebug->leave_sub();
743 my $part_unit = $all_units->{$part_unit_name};
744 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
746 $amount *= $conv_unit->{factor};
751 foreach my $unit (@$conv_units) {
752 my $last = $unit->{name} eq $part_unit->{name};
754 $num = int($amount / $unit->{factor});
755 $amount -= $num * $unit->{factor};
758 if ($last ? $amount : $num) {
759 push @values, { "unit" => $unit->{name},
760 "amount" => $last ? $amount / $unit->{factor} : $num,
761 "places" => $last ? $places : 0 };
768 push @values, { "unit" => $part_unit_name,
773 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
775 $main::lxdebug->leave_sub();
781 $main::lxdebug->enter_sub(2);
786 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
787 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
788 $input =~ s/\#\#/\#/g;
790 $main::lxdebug->leave_sub(2);
798 my ($self, $myconfig, $amount) = @_;
799 SL::Helper::Number::_parse_number($amount, %$myconfig);
802 sub round_amount { shift; goto &SL::Helper::Number::_round_number; }
805 $main::lxdebug->enter_sub();
807 my ($self, $myconfig) = @_;
808 my ($out, $out_mode);
812 my $defaults = SL::DB::Default->get;
814 my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
815 $self->{cwd} = getcwd();
816 my $temp_dir = File::Temp->newdir(
817 "kivitendo-print-XXXXXX",
818 DIR => $self->{cwd} . "/" . $::lx_office_conf{paths}->{userspath},
819 CLEANUP => !$keep_temp_files,
822 my $userspath = File::Spec->abs2rel($temp_dir->dirname);
823 $self->{tmpdir} = $temp_dir->dirname;
828 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
829 $template_type = 'OpenDocument';
830 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
832 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
833 $template_type = 'LaTeX';
834 $ext_for_format = 'pdf';
836 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
837 $template_type = 'HTML';
838 $ext_for_format = 'html';
840 } elsif ( $self->{"format"} =~ /excel/i ) {
841 $template_type = 'Excel';
842 $ext_for_format = 'xls';
844 } elsif ( defined $self->{'format'}) {
845 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
847 } elsif ( $self->{'format'} eq '' ) {
848 $self->error("No Outputformat given: $self->{'format'}");
850 } else { #Catch the rest
851 $self->error("Outputformat not defined: $self->{'format'}");
854 my $template = SL::Template::create(type => $template_type,
855 file_name => $self->{IN},
857 myconfig => $myconfig,
858 userspath => $userspath,
859 %{ $self->{TEMPLATE_DRIVER_OPTIONS} || {} });
861 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
862 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" } if exists $self->{ $self->{"formname"} . "notes" };
864 if (!$self->{employee_id}) {
865 $self->{"employee_${_}"} = $myconfig->{$_} for qw(email tel fax name signature);
866 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
869 $self->{"myconfig_${_}"} = $myconfig->{$_} for grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
870 $self->{$_} = $defaults->$_ for qw(co_ustid);
871 $self->{"myconfig_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
872 $self->{AUTH} = $::auth;
873 $self->{INSTANCE_CONF} = $::instance_conf;
874 $self->{LOCALE} = $::locale;
875 $self->{LXCONFIG} = $::lx_office_conf;
876 $self->{LXDEBUG} = $::lxdebug;
877 $self->{MYCONFIG} = \%::myconfig;
879 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
881 # OUT is used for the media, screen, printer, email
882 # for postscript we store a copy in a temporary file
884 my ($temp_fh, $suffix);
885 $suffix = $self->{IN};
887 ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
888 strftime('kivitendo-print-%Y%m%d%H%M%S-XXXXXX', localtime()),
889 SUFFIX => '.' . ($suffix || 'tex'),
891 UNLINK => $keep_temp_files ? 0 : 1,
894 chmod 0644, $self->{tmpfile} if $keep_temp_files;
895 (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
898 $out_mode = $self->{OUT_MODE} || '>';
899 $self->{OUT} = "$self->{tmpfile}";
900 $self->{OUT_MODE} = '>';
903 my $command_formatter = sub {
904 my ($out_mode, $out) = @_;
905 return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
909 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
910 open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
912 *OUT = ($::dispatcher->get_standard_filehandles)[1];
916 if (!$template->parse(*OUT)) {
918 $self->error("$self->{IN} : " . $template->get_error());
921 close OUT if $self->{OUT};
922 # check only one flag (webdav_documents)
923 # therefore copy to webdav, even if we do not have the webdav feature enabled (just archive)
924 my $copy_to_webdav = $::instance_conf->get_webdav_documents && !$self->{preview} && $self->{tmpdir} && $self->{tmpfile} && $self->{type}
925 && $self->{type} ne 'statement';
926 if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
927 $self->append_general_pdf_attachments(filepath => $self->{tmpdir}."/".$self->{tmpfile},
928 type => $self->{type});
930 if ($self->{media} eq 'file') {
931 copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
933 if ($copy_to_webdav) {
934 if (my $error = Common::copy_file_to_webdav_folder($self)) {
935 chdir("$self->{cwd}");
936 $self->error($error);
940 if (!$self->{preview} && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled)
942 $self->{attachment_filename} ||= $self->generate_attachment_filename;
943 $self->store_pdf($self);
946 chdir("$self->{cwd}");
948 $::lxdebug->leave_sub();
953 if ($copy_to_webdav) {
954 if (my $error = Common::copy_file_to_webdav_folder($self)) {
955 chdir("$self->{cwd}");
956 $self->error($error);
960 if ( !$self->{preview} && $ext_for_format eq 'pdf' && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled) {
961 $self->{attachment_filename} ||= $self->generate_attachment_filename;
962 my $file_obj = $self->store_pdf($self);
963 $self->{print_file_id} = $file_obj->id if $file_obj;
965 if ($self->{media} eq 'email') {
966 if ( getcwd() eq $self->{"tmpdir"} ) {
967 # in the case of generating pdf we are in the tmpdir, but WHY ???
968 $self->{tmpfile} = $userspath."/".$self->{tmpfile};
969 chdir("$self->{cwd}");
971 $self->send_email(\%::myconfig,$ext_for_format);
975 $self->{OUT_MODE} = $out_mode;
976 $self->output_file($template->get_mime_type,$command_formatter);
978 delete $self->{print_file_id};
982 chdir("$self->{cwd}");
983 $main::lxdebug->leave_sub();
986 sub get_bcc_defaults {
987 my ($self, $myconfig, $mybcc) = @_;
988 if (SL::DB::Default->get->bcc_to_login) {
989 $mybcc .= ", " if $mybcc;
990 $mybcc .= $myconfig->{email};
992 my $otherbcc = SL::DB::Default->get->global_bcc;
994 $mybcc .= ", " if $mybcc;
1001 $main::lxdebug->enter_sub();
1002 my ($self, $myconfig, $ext_for_format) = @_;
1003 my $mail = Mailer->new;
1005 map { $mail->{$_} = $self->{$_} }
1006 qw(cc subject message format);
1008 if ($self->{cc_employee}) {
1009 my ($user, $my_emp_cc);
1010 $user = SL::DB::Manager::AuthUser->find_by(login => $self->{cc_employee});
1011 $my_emp_cc = $user->get_config_value('email') if ref $user eq 'SL::DB::AuthUser';
1012 $mail->{cc} .= ", " if $mail->{cc};
1013 $mail->{cc} .= $my_emp_cc if $my_emp_cc;
1016 $mail->{bcc} = $self->get_bcc_defaults($myconfig, $self->{bcc});
1017 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1018 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1019 $mail->{fileid} = time() . '.' . $$ . '.';
1020 my $full_signature = $self->create_email_signature();
1021 $full_signature =~ s/\r//g;
1023 $mail->{attachments} = [];
1025 # if we send html or plain text inline
1026 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1027 $mail->{content_type} = "text/html";
1028 $mail->{message} =~ s/\r//g;
1029 $mail->{message} =~ s{\n}{<br>\n}g;
1030 $full_signature =~ s{\n}{<br>\n}g;
1031 $mail->{message} .= $full_signature;
1033 open(IN, "<", $self->{tmpfile})
1034 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1035 $mail->{message} .= $_ while <IN>;
1038 } elsif (($self->{attachment_policy} // '') ne 'no_file') {
1039 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1040 $attachment_name =~ s{\.(.+?)$}{.${ext_for_format}} if ($ext_for_format);
1042 if (($self->{attachment_policy} // '') eq 'old_file') {
1043 my ( $attfile ) = SL::File->get_all(object_id => $self->{id},
1044 object_type => $self->{formname},
1045 file_type => 'document');
1048 $attfile->{override_file_name} = $attachment_name if $attachment_name;
1049 push @attfiles, $attfile;
1053 push @{ $mail->{attachments} }, { path => $self->{tmpfile},
1054 id => $self->{print_file_id},
1055 type => "application/pdf",
1056 name => $attachment_name };
1062 map { SL::File->get(id => $_) }
1063 @{ $self->{attach_file_ids} // [] };
1065 foreach my $attfile ( @attfiles ) {
1066 push @{ $mail->{attachments} }, {
1067 path => $attfile->get_file,
1069 type => $attfile->mime_type,
1070 name => $attfile->{override_file_name} // $attfile->file_name,
1071 content => $attfile->get_content ? ${ $attfile->get_content } : undef,
1075 $mail->{message} =~ s/\r//g;
1076 $mail->{message} .= $full_signature;
1077 $self->{emailerr} = $mail->send();
1079 if ($self->{emailerr}) {
1081 $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
1084 $self->{email_journal_id} = $mail->{journalentry};
1085 $self->{snumbers} = "emailjournal" . "_" . $self->{email_journal_id};
1086 $self->{what_done} = $::form->{type};
1087 $self->{addition} = "MAILED";
1088 $self->save_history;
1090 #write back for message info and mail journal
1091 $self->{cc} = $mail->{cc};
1092 $self->{bcc} = $mail->{bcc};
1093 $self->{email} = $mail->{to};
1095 $main::lxdebug->leave_sub();
1099 $main::lxdebug->enter_sub();
1101 my ($self,$mimeType,$command_formatter) = @_;
1102 my $numbytes = (-s $self->{tmpfile});
1103 open(IN, "<", $self->{tmpfile})
1104 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1107 $self->{copies} = 1 unless $self->{media} eq 'printer';
1109 chdir("$self->{cwd}");
1110 for my $i (1 .. $self->{copies}) {
1112 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1114 open OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1115 print OUT $_ while <IN>;
1120 my %headers = ('-type' => $mimeType,
1121 '-connection' => 'close',
1122 '-charset' => 'UTF-8');
1124 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1126 if ($self->{attachment_filename}) {
1129 '-attachment' => $self->{attachment_filename},
1130 '-content-length' => $numbytes,
1135 print $::request->cgi->header(%headers);
1137 $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1141 $main::lxdebug->leave_sub();
1144 sub get_formname_translation {
1145 $main::lxdebug->enter_sub();
1146 my ($self, $formname) = @_;
1148 $formname ||= $self->{formname};
1150 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1151 local $::locale = Locale->new($self->{recipient_locale});
1153 my %formname_translations = (
1154 bin_list => $main::locale->text('Bin List'),
1155 credit_note => $main::locale->text('Credit Note'),
1156 invoice => $main::locale->text('Invoice'),
1157 invoice_copy => $main::locale->text('Invoice Copy'),
1158 pick_list => $main::locale->text('Pick List'),
1159 proforma => $main::locale->text('Proforma Invoice'),
1160 purchase_order => $main::locale->text('Purchase Order'),
1161 request_quotation => $main::locale->text('RFQ'),
1162 sales_order => $main::locale->text('Confirmation'),
1163 sales_quotation => $main::locale->text('Quotation'),
1164 storno_invoice => $main::locale->text('Storno Invoice'),
1165 sales_delivery_order => $main::locale->text('Delivery Order'),
1166 purchase_delivery_order => $main::locale->text('Delivery Order'),
1167 dunning => $main::locale->text('Dunning'),
1168 dunning1 => $main::locale->text('Payment Reminder'),
1169 dunning2 => $main::locale->text('Dunning'),
1170 dunning3 => $main::locale->text('Last Dunning'),
1171 dunning_invoice => $main::locale->text('Dunning Invoice'),
1172 letter => $main::locale->text('Letter'),
1173 ic_supply => $main::locale->text('Intra-Community supply'),
1174 statement => $main::locale->text('Statement'),
1177 $main::lxdebug->leave_sub();
1178 return $formname_translations{$formname};
1181 sub get_cusordnumber_translation {
1182 $main::lxdebug->enter_sub();
1183 my ($self, $formname) = @_;
1185 $formname ||= $self->{formname};
1187 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1188 local $::locale = Locale->new($self->{recipient_locale});
1191 $main::lxdebug->leave_sub();
1192 return $main::locale->text('Your Order');
1195 sub get_number_prefix_for_type {
1196 $main::lxdebug->enter_sub();
1200 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1201 : ($self->{type} =~ /_quotation$/) ? 'quo'
1202 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1203 : ($self->{type} =~ /letter/) ? 'letter'
1206 # better default like this?
1207 # : ($self->{type} =~ /(sales|purcharse)_order/ : 'ord';
1208 # : 'prefix_undefined';
1210 $main::lxdebug->leave_sub();
1214 sub get_extension_for_format {
1215 $main::lxdebug->enter_sub();
1218 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1219 : $self->{format} =~ /postscript/i ? ".ps"
1220 : $self->{format} =~ /opendocument/i ? ".odt"
1221 : $self->{format} =~ /excel/i ? ".xls"
1222 : $self->{format} =~ /html/i ? ".html"
1225 $main::lxdebug->leave_sub();
1229 sub generate_attachment_filename {
1230 $main::lxdebug->enter_sub();
1233 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1234 my $recipient_locale = Locale->new($self->{recipient_locale});
1236 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1237 my $prefix = $self->get_number_prefix_for_type();
1239 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1240 $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
1242 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1243 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1245 } elsif ($attachment_filename) {
1246 $attachment_filename .= $self->get_extension_for_format();
1249 $attachment_filename = "";
1252 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1253 $attachment_filename =~ s|[\s/\\]+|_|g;
1255 $main::lxdebug->leave_sub();
1256 return $attachment_filename;
1259 sub generate_email_subject {
1260 $main::lxdebug->enter_sub();
1263 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1264 my $prefix = $self->get_number_prefix_for_type();
1266 if ($subject && $self->{"${prefix}number"}) {
1267 $subject .= " " . $self->{"${prefix}number"}
1270 if ($self->{cusordnumber}) {
1271 $subject = $self->get_cusordnumber_translation() . ' ' . $self->{cusordnumber} . ' / ' . $subject;
1274 $main::lxdebug->leave_sub();
1278 sub generate_email_body {
1279 $main::lxdebug->enter_sub();
1280 my ($self, %params) = @_;
1281 # simple german and english will work grammatically (most european languages as well)
1282 # Dear Mr Alan Greenspan:
1283 # Sehr geehrte Frau Meyer,
1284 # A l’attention de Mme Villeroy,
1285 # Gentile Signora Ferrari,
1288 if ($self->{cp_id} && !$params{record_email}) {
1289 my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
1290 my $name = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
1291 my $gender = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
1292 my $mf = $gender eq 'f' ? 'female' : 'male';
1293 $body = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
1294 $body .= ' ' . $givenname . ' ' . $name if $body;
1296 $body = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
1299 return undef unless $body;
1301 my $translation_type = $params{translation_type} // "preset_text_$self->{formname}";
1302 my $main_body = GenericTranslations->get(translation_type => $translation_type, language_id => $self->{language_id});
1303 $main_body = GenericTranslations->get(translation_type => $params{fallback_translation_type}, language_id => $self->{language_id}) if !$main_body && $params{fallback_translation_type};
1304 $body .= GenericTranslations->get(translation_type => "salutation_punctuation_mark", language_id => $self->{language_id}) . "\n\n";
1305 $body .= $main_body;
1307 $body = $main::locale->unquote_special_chars('HTML', $body);
1309 $main::lxdebug->leave_sub();
1314 $main::lxdebug->enter_sub();
1316 my ($self, $application) = @_;
1318 my $error_code = $?;
1320 chdir("$self->{tmpdir}");
1323 if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1324 push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1326 } elsif (-f "$self->{tmpfile}.err") {
1327 open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
1332 if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1333 $self->{tmpfile} =~ s|.*/||g;
1335 $self->{tmpfile} =~ s/\.\w+$//g;
1336 my $tmpfile = $self->{tmpfile};
1337 unlink(<$tmpfile.*>);
1340 chdir("$self->{cwd}");
1342 $main::lxdebug->leave_sub();
1348 $main::lxdebug->enter_sub();
1350 my ($self, $date, $myconfig) = @_;
1353 if ($date && $date =~ /\D/) {
1355 if ($myconfig->{dateformat} =~ /^yy/) {
1356 ($yy, $mm, $dd) = split /\D/, $date;
1358 if ($myconfig->{dateformat} =~ /^mm/) {
1359 ($mm, $dd, $yy) = split /\D/, $date;
1361 if ($myconfig->{dateformat} =~ /^dd/) {
1362 ($dd, $mm, $yy) = split /\D/, $date;
1367 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1368 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1370 $dd = "0$dd" if ($dd < 10);
1371 $mm = "0$mm" if ($mm < 10);
1373 $date = "$yy$mm$dd";
1376 $main::lxdebug->leave_sub();
1381 # Database routines used throughout
1382 # DB Handling got moved to SL::DB, these are only shims for compatibility
1385 SL::DB->client->dbh;
1388 sub get_standard_dbh {
1389 my $dbh = SL::DB->client->dbh;
1391 if ($dbh && !$dbh->{Active}) {
1392 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
1393 SL::DB->client->dbh(undef);
1396 SL::DB->client->dbh;
1399 sub disconnect_standard_dbh {
1400 SL::DB->client->dbh->rollback;
1406 $main::lxdebug->enter_sub();
1408 my ($self, $date, $myconfig) = @_;
1409 my $dbh = $self->get_standard_dbh;
1411 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1412 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1414 # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1415 # es ist sicher ein conv_date vorher IMMER auszuführen.
1416 # Testfälle ohne definiertes closedto:
1417 # Leere Datumseingabe i.O.
1418 # SELECT 1 FROM defaults WHERE '' < closedto
1419 # normale Zahlungsbuchung über Rechnungsmaske i.O.
1420 # SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1421 # Testfälle mit definiertem closedto (30.04.2011):
1422 # Leere Datumseingabe i.O.
1423 # SELECT 1 FROM defaults WHERE '' < closedto
1424 # normale Buchung im geschloßenem Zeitraum i.O.
1425 # SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1426 # Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1427 # normale Buchung in aktiver Buchungsperiode i.O.
1428 # SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1430 my ($closed) = $sth->fetchrow_array;
1432 $main::lxdebug->leave_sub();
1437 # prevents bookings to the to far away future
1438 sub date_max_future {
1439 $main::lxdebug->enter_sub();
1441 my ($self, $date, $myconfig) = @_;
1442 my $dbh = $self->get_standard_dbh;
1444 my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
1445 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1447 my ($max_future_booking_interval) = $sth->fetchrow_array;
1449 $main::lxdebug->leave_sub();
1451 return $max_future_booking_interval;
1455 sub update_balance {
1456 $main::lxdebug->enter_sub();
1458 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1460 # if we have a value, go do it
1463 # retrieve balance from table
1464 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1465 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1466 my ($balance) = $sth->fetchrow_array;
1472 $query = "UPDATE $table SET $field = $balance WHERE $where";
1473 do_query($self, $dbh, $query, @values);
1475 $main::lxdebug->leave_sub();
1478 sub update_exchangerate {
1479 $main::lxdebug->enter_sub();
1481 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1483 # some sanity check for currency
1485 $main::lxdebug->leave_sub();
1488 $query = qq|SELECT name AS curr FROM currencies WHERE id=(SELECT currency_id FROM defaults)|;
1490 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1492 if ($curr eq $defaultcurrency) {
1493 $main::lxdebug->leave_sub();
1497 $query = qq|SELECT e.currency_id FROM exchangerate e
1498 WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
1500 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1509 $buy = conv_i($buy, "NULL");
1510 $sell = conv_i($sell, "NULL");
1513 if ($buy != 0 && $sell != 0) {
1514 $set = "buy = $buy, sell = $sell";
1515 } elsif ($buy != 0) {
1516 $set = "buy = $buy";
1517 } elsif ($sell != 0) {
1518 $set = "sell = $sell";
1521 if ($sth->fetchrow_array) {
1522 $query = qq|UPDATE exchangerate
1524 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
1528 $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
1529 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
1532 do_query($self, $dbh, $query, $curr, $transdate);
1534 $main::lxdebug->leave_sub();
1537 sub save_exchangerate {
1538 $main::lxdebug->enter_sub();
1540 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1542 SL::DB->client->with_transaction(sub {
1543 my $dbh = SL::DB->client->dbh;
1547 $buy = $rate if $fld eq 'buy';
1548 $sell = $rate if $fld eq 'sell';
1551 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1553 }) or do { die SL::DB->client->error };
1555 $main::lxdebug->leave_sub();
1558 sub get_exchangerate {
1559 $main::lxdebug->enter_sub();
1561 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1564 unless ($transdate && $curr) {
1565 $main::lxdebug->leave_sub();
1569 $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1571 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1573 if ($curr eq $defaultcurrency) {
1574 $main::lxdebug->leave_sub();
1578 $query = qq|SELECT e.$fld FROM exchangerate e
1579 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1580 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1584 $main::lxdebug->leave_sub();
1586 return $exchangerate;
1589 sub check_exchangerate {
1590 $main::lxdebug->enter_sub();
1592 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1594 if ($fld !~/^buy|sell$/) {
1595 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1598 unless ($transdate) {
1599 $main::lxdebug->leave_sub();
1603 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1605 if ($currency eq $defaultcurrency) {
1606 $main::lxdebug->leave_sub();
1610 my $dbh = $self->get_standard_dbh($myconfig);
1611 my $query = qq|SELECT e.$fld FROM exchangerate e
1612 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1614 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1616 $main::lxdebug->leave_sub();
1618 return $exchangerate;
1621 sub get_all_currencies {
1622 $main::lxdebug->enter_sub();
1625 my $myconfig = shift || \%::myconfig;
1626 my $dbh = $self->get_standard_dbh($myconfig);
1628 my $query = qq|SELECT name FROM currencies|;
1629 my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
1631 $main::lxdebug->leave_sub();
1636 sub get_default_currency {
1637 $main::lxdebug->enter_sub();
1639 my ($self, $myconfig) = @_;
1640 my $dbh = $self->get_standard_dbh($myconfig);
1641 my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1643 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1645 $main::lxdebug->leave_sub();
1647 return $defaultcurrency;
1650 sub set_payment_options {
1651 my ($self, $myconfig, $transdate, $type) = @_;
1653 my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
1656 my $is_invoice = $type =~ m{invoice}i;
1658 $transdate ||= $self->{invdate} || $self->{transdate};
1659 my $due_date = $self->{duedate} || $self->{reqdate};
1661 $self->{$_} = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
1662 $self->{payment_description} = $terms->description;
1663 $self->{netto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
1664 $self->{skonto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
1666 my ($invtotal, $total);
1667 my (%amounts, %formatted_amounts);
1669 if ($self->{type} =~ /_order$/) {
1670 $amounts{invtotal} = $self->{ordtotal};
1671 $amounts{total} = $self->{ordtotal};
1673 } elsif ($self->{type} =~ /_quotation$/) {
1674 $amounts{invtotal} = $self->{quototal};
1675 $amounts{total} = $self->{quototal};
1678 $amounts{invtotal} = $self->{invtotal};
1679 $amounts{total} = $self->{total};
1681 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1683 $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1684 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1685 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1686 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1688 foreach (keys %amounts) {
1689 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1690 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1693 if ($self->{"language_id"}) {
1694 my $language = SL::DB::Language->new(id => $self->{language_id})->load;
1696 $self->{payment_terms} = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
1697 $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
1699 if ($language->output_dateformat) {
1700 foreach my $key (qw(netto_date skonto_date)) {
1701 $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
1705 if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
1706 local $myconfig->{numberformat};
1707 $myconfig->{"numberformat"} = $language->output_numberformat;
1708 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
1712 $self->{payment_terms} = $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
1714 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1715 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1716 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1717 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1718 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1719 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1720 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1721 $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
1722 $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
1723 $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
1724 $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
1726 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1728 $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1732 sub get_template_language {
1733 $main::lxdebug->enter_sub();
1735 my ($self, $myconfig) = @_;
1737 my $template_code = "";
1739 if ($self->{language_id}) {
1740 my $dbh = $self->get_standard_dbh($myconfig);
1741 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1742 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1745 $main::lxdebug->leave_sub();
1747 return $template_code;
1750 sub get_printer_code {
1751 $main::lxdebug->enter_sub();
1753 my ($self, $myconfig) = @_;
1755 my $template_code = "";
1757 if ($self->{printer_id}) {
1758 my $dbh = $self->get_standard_dbh($myconfig);
1759 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1760 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1763 $main::lxdebug->leave_sub();
1765 return $template_code;
1769 $main::lxdebug->enter_sub();
1771 my ($self, $myconfig) = @_;
1773 my $template_code = "";
1775 if ($self->{shipto_id}) {
1776 my $dbh = $self->get_standard_dbh($myconfig);
1777 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1778 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1779 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1781 my $cvars = CVar->get_custom_variables(
1784 trans_id => $self->{shipto_id},
1786 $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
1789 $main::lxdebug->leave_sub();
1793 my ($self, $dbh, $id, $module) = @_;
1798 foreach my $item (qw(name department_1 department_2 street zipcode city country gln
1799 contact phone fax email)) {
1800 if ($self->{"shipto$item"}) {
1801 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1803 push(@values, $self->{"shipto${item}"});
1808 # shiptocp_gender only makes sense, if any other shipto attribute is set.
1809 # Because shiptocp_gender is set to 'm' by default in forms
1810 # it must not be considered above to decide if shiptos has to be added or
1811 # updated, but must be inserted or updated as well in case.
1812 push(@values, $self->{shiptocp_gender});
1814 my $shipto_id = $self->{shipto_id};
1816 if ($self->{shipto_id}) {
1817 my $query = qq|UPDATE shipto set
1819 shiptodepartment_1 = ?,
1820 shiptodepartment_2 = ?,
1830 shiptocp_gender = ?,
1831 WHERE shipto_id = ?|;
1832 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1834 my $query = qq|SELECT * FROM shipto
1835 WHERE shiptoname = ? AND
1836 shiptodepartment_1 = ? AND
1837 shiptodepartment_2 = ? AND
1838 shiptostreet = ? AND
1839 shiptozipcode = ? AND
1841 shiptocountry = ? AND
1843 shiptocontact = ? AND
1847 shiptocp_gender = ? AND
1850 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1853 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1854 shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
1855 shiptocontact, shiptophone, shiptofax, shiptoemail, shiptocp_gender, module)
1856 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1857 do_query($self, $dbh, $insert_query, $id, @values, $module);
1859 $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1862 $shipto_id = $insert_check->{shipto_id};
1865 return unless $shipto_id;
1867 CVar->save_custom_variables(
1870 trans_id => $shipto_id,
1872 name_prefix => 'shipto',
1877 $main::lxdebug->enter_sub();
1879 my ($self, $dbh) = @_;
1881 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1883 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1884 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1885 $self->{"employee_id"} *= 1;
1887 $main::lxdebug->leave_sub();
1890 sub get_employee_data {
1891 $main::lxdebug->enter_sub();
1895 my $defaults = SL::DB::Default->get;
1897 Common::check_params(\%params, qw(prefix));
1898 Common::check_params_x(\%params, qw(id));
1901 $main::lxdebug->leave_sub();
1905 my $myconfig = \%main::myconfig;
1906 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
1908 my ($login, $deleted) = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
1911 # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
1912 $self->{$params{prefix} . '_login'} = $login;
1913 $self->{$params{prefix} . "_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
1916 # get employee data from auth.user_config
1917 my $user = User->new(login => $login);
1918 $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
1920 # get saved employee data from employee
1921 my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
1922 $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
1923 $self->{$params{prefix} . "_name"} = $employee->name;
1926 $main::lxdebug->leave_sub();
1930 $main::lxdebug->enter_sub();
1932 my ($self, $dbh, $id, $key) = @_;
1934 $key = "all_contacts" unless ($key);
1938 $main::lxdebug->leave_sub();
1943 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1944 qq|FROM contacts | .
1945 qq|WHERE cp_cv_id = ? | .
1946 qq|ORDER BY lower(cp_name)|;
1948 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1950 $main::lxdebug->leave_sub();
1954 $main::lxdebug->enter_sub();
1956 my ($self, $dbh, $key) = @_;
1958 my ($all, $old_id, $where, @values);
1960 if (ref($key) eq "HASH") {
1963 $key = "ALL_PROJECTS";
1965 foreach my $p (keys(%{$params})) {
1967 $all = $params->{$p};
1968 } elsif ($p eq "old_id") {
1969 $old_id = $params->{$p};
1970 } elsif ($p eq "key") {
1971 $key = $params->{$p};
1977 $where = "WHERE active ";
1979 if (ref($old_id) eq "ARRAY") {
1980 my @ids = grep({ $_ } @{$old_id});
1982 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1983 push(@values, @ids);
1986 $where .= " OR (id = ?) ";
1987 push(@values, $old_id);
1993 qq|SELECT id, projectnumber, description, active | .
1996 qq|ORDER BY lower(projectnumber)|;
1998 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2000 $main::lxdebug->leave_sub();
2004 $main::lxdebug->enter_sub();
2006 my ($self, $dbh, $key) = @_;
2008 $key = "all_printers" unless ($key);
2010 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2012 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2014 $main::lxdebug->leave_sub();
2018 $main::lxdebug->enter_sub();
2020 my ($self, $dbh, $params) = @_;
2023 $key = $params->{key};
2024 $key = "all_charts" unless ($key);
2026 my $transdate = quote_db_date($params->{transdate});
2029 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2031 qq|LEFT JOIN taxkeys tk ON | .
2032 qq|(tk.id = (SELECT id FROM taxkeys | .
2033 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2034 qq| ORDER BY startdate DESC LIMIT 1)) | .
2035 qq|ORDER BY c.accno|;
2037 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2039 $main::lxdebug->leave_sub();
2043 $main::lxdebug->enter_sub();
2045 my ($self, $dbh, $key) = @_;
2047 $key = "all_taxzones" unless ($key);
2049 $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
2051 my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
2053 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2055 $main::lxdebug->leave_sub();
2058 sub _get_employees {
2059 $main::lxdebug->enter_sub();
2061 my ($self, $dbh, $params) = @_;
2066 if (ref $params eq 'HASH') {
2067 $key = $params->{key};
2068 $deleted = $params->{deleted};
2074 $key ||= "all_employees";
2075 my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
2076 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
2078 $main::lxdebug->leave_sub();
2081 sub _get_business_types {
2082 $main::lxdebug->enter_sub();
2084 my ($self, $dbh, $key) = @_;
2086 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2087 $options->{key} ||= "all_business_types";
2090 if (exists $options->{salesman}) {
2091 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2094 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2096 $main::lxdebug->leave_sub();
2099 sub _get_languages {
2100 $main::lxdebug->enter_sub();
2102 my ($self, $dbh, $key) = @_;
2104 $key = "all_languages" unless ($key);
2106 my $query = qq|SELECT * FROM language ORDER BY id|;
2108 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2110 $main::lxdebug->leave_sub();
2113 sub _get_dunning_configs {
2114 $main::lxdebug->enter_sub();
2116 my ($self, $dbh, $key) = @_;
2118 $key = "all_dunning_configs" unless ($key);
2120 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2122 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2124 $main::lxdebug->leave_sub();
2127 sub _get_currencies {
2128 $main::lxdebug->enter_sub();
2130 my ($self, $dbh, $key) = @_;
2132 $key = "all_currencies" unless ($key);
2134 $self->{$key} = [$self->get_all_currencies()];
2136 $main::lxdebug->leave_sub();
2140 $main::lxdebug->enter_sub();
2142 my ($self, $dbh, $key) = @_;
2144 $key = "all_payments" unless ($key);
2146 my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2148 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2150 $main::lxdebug->leave_sub();
2153 sub _get_customers {
2154 $main::lxdebug->enter_sub();
2156 my ($self, $dbh, $key) = @_;
2158 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2159 $options->{key} ||= "all_customers";
2160 my $limit_clause = $options->{limit} ? "LIMIT $options->{limit}" : '';
2163 push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman};
2164 push @where, qq|NOT obsolete| if !$options->{with_obsolete};
2165 my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2167 my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2168 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2170 $main::lxdebug->leave_sub();
2174 $main::lxdebug->enter_sub();
2176 my ($self, $dbh, $key) = @_;
2178 $key = "all_vendors" unless ($key);
2180 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2182 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2184 $main::lxdebug->leave_sub();
2187 sub _get_departments {
2188 $main::lxdebug->enter_sub();
2190 my ($self, $dbh, $key) = @_;
2192 $key = "all_departments" unless ($key);
2194 my $query = qq|SELECT * FROM department ORDER BY description|;
2196 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2198 $main::lxdebug->leave_sub();
2201 sub _get_warehouses {
2202 $main::lxdebug->enter_sub();
2204 my ($self, $dbh, $param) = @_;
2206 my ($key, $bins_key);
2208 if ('' eq ref $param) {
2212 $key = $param->{key};
2213 $bins_key = $param->{bins};
2216 my $query = qq|SELECT w.* FROM warehouse w
2217 WHERE (NOT w.invalid) AND
2218 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2219 ORDER BY w.sortkey|;
2221 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2224 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2225 ORDER BY description|;
2226 my $sth = prepare_query($self, $dbh, $query);
2228 foreach my $warehouse (@{ $self->{$key} }) {
2229 do_statement($self, $sth, $query, $warehouse->{id});
2230 $warehouse->{$bins_key} = [];
2232 while (my $ref = $sth->fetchrow_hashref()) {
2233 push @{ $warehouse->{$bins_key} }, $ref;
2239 $main::lxdebug->leave_sub();
2243 $main::lxdebug->enter_sub();
2245 my ($self, $dbh, $table, $key, $sortkey) = @_;
2247 my $query = qq|SELECT * FROM $table|;
2248 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2250 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2252 $main::lxdebug->leave_sub();
2256 $main::lxdebug->enter_sub();
2261 croak "get_lists: shipto is no longer supported" if $params{shipto};
2263 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2264 my ($sth, $query, $ref);
2267 if ($params{contacts}) {
2268 $vc = 'customer' if $self->{"vc"} eq "customer";
2269 $vc = 'vendor' if $self->{"vc"} eq "vendor";
2270 die "invalid use of get_lists, need 'vc'" unless $vc;
2271 $vc_id = $self->{"${vc}_id"};
2274 if ($params{"contacts"}) {
2275 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2278 if ($params{"projects"} || $params{"all_projects"}) {
2279 $self->_get_projects($dbh, $params{"all_projects"} ?
2280 $params{"all_projects"} : $params{"projects"},
2281 $params{"all_projects"} ? 1 : 0);
2284 if ($params{"printers"}) {
2285 $self->_get_printers($dbh, $params{"printers"});
2288 if ($params{"languages"}) {
2289 $self->_get_languages($dbh, $params{"languages"});
2292 if ($params{"charts"}) {
2293 $self->_get_charts($dbh, $params{"charts"});
2296 if ($params{"taxzones"}) {
2297 $self->_get_taxzones($dbh, $params{"taxzones"});
2300 if ($params{"employees"}) {
2301 $self->_get_employees($dbh, $params{"employees"});
2304 if ($params{"salesmen"}) {
2305 $self->_get_employees($dbh, $params{"salesmen"});
2308 if ($params{"business_types"}) {
2309 $self->_get_business_types($dbh, $params{"business_types"});
2312 if ($params{"dunning_configs"}) {
2313 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2316 if($params{"currencies"}) {
2317 $self->_get_currencies($dbh, $params{"currencies"});
2320 if($params{"customers"}) {
2321 $self->_get_customers($dbh, $params{"customers"});
2324 if($params{"vendors"}) {
2325 if (ref $params{"vendors"} eq 'HASH') {
2326 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2328 $self->_get_vendors($dbh, $params{"vendors"});
2332 if($params{"payments"}) {
2333 $self->_get_payments($dbh, $params{"payments"});
2336 if($params{"departments"}) {
2337 $self->_get_departments($dbh, $params{"departments"});
2340 if ($params{price_factors}) {
2341 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2344 if ($params{warehouses}) {
2345 $self->_get_warehouses($dbh, $params{warehouses});
2348 if ($params{partsgroup}) {
2349 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2352 $main::lxdebug->leave_sub();
2355 # this sub gets the id and name from $table
2357 $main::lxdebug->enter_sub();
2359 my ($self, $myconfig, $table) = @_;
2361 # connect to database
2362 my $dbh = $self->get_standard_dbh($myconfig);
2364 $table = $table eq "customer" ? "customer" : "vendor";
2365 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2367 my ($query, @values);
2369 if (!$self->{openinvoices}) {
2371 if ($self->{customernumber} ne "") {
2372 $where = qq|(vc.customernumber ILIKE ?)|;
2373 push(@values, like($self->{customernumber}));
2375 $where = qq|(vc.name ILIKE ?)|;
2376 push(@values, like($self->{$table}));
2380 qq~SELECT vc.id, vc.name,
2381 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2383 WHERE $where AND (NOT vc.obsolete)
2387 qq~SELECT DISTINCT vc.id, vc.name,
2388 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2390 JOIN $table vc ON (a.${table}_id = vc.id)
2391 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2393 push(@values, like($self->{$table}));
2396 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2398 $main::lxdebug->leave_sub();
2400 return scalar(@{ $self->{name_list} });
2405 my ($self, $table, $provided_dbh) = @_;
2407 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
2408 return unless $self->{id};
2409 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2411 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2412 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2413 $ref->{mtime} ||= $ref->{itime};
2414 $self->{lastmtime} = $ref->{mtime};
2418 sub mtime_ischanged {
2419 my ($self, $table, $option) = @_;
2421 return unless $self->{id};
2422 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2424 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2425 my $ref = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
2426 $ref->{mtime} ||= $ref->{itime};
2428 if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
2429 $self->error(($option eq 'mail') ?
2430 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") :
2431 t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
2433 $::dispatcher->end_request;
2437 # language_payment duplicates some of the functionality of all_vc (language,
2438 # printer, payment_terms), and at least in the case of sales invoices both
2439 # all_vc and language_payment are called when adding new invoices
2440 sub language_payment {
2441 $main::lxdebug->enter_sub();
2443 my ($self, $myconfig) = @_;
2445 my $dbh = $self->get_standard_dbh($myconfig);
2447 my $query = qq|SELECT id, description
2451 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2454 $query = qq|SELECT printer_description, id
2456 ORDER BY printer_description|;
2458 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2461 $query = qq|SELECT id, description
2463 WHERE ( obsolete IS FALSE OR id = ? )
2465 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
2467 # get buchungsgruppen
2468 $query = qq|SELECT id, description
2469 FROM buchungsgruppen|;
2471 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2473 $main::lxdebug->leave_sub();
2476 # this is only used for reports
2477 sub all_departments {
2478 $main::lxdebug->enter_sub();
2480 my ($self, $myconfig, $table) = @_;
2482 my $dbh = $self->get_standard_dbh($myconfig);
2484 my $query = qq|SELECT id, description
2486 ORDER BY description|;
2487 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2489 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2491 $main::lxdebug->leave_sub();
2495 $main::lxdebug->enter_sub();
2497 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2500 if ($table eq "customer") {
2509 # get last customers or vendors
2510 my ($query, $sth, $ref);
2512 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2517 my $transdate = "current_date";
2518 if ($self->{transdate}) {
2519 $transdate = $dbh->quote($self->{transdate});
2522 # now get the account numbers
2524 SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
2526 -- find newest entries in taxkeys
2528 SELECT chart_id, MAX(startdate) AS startdate
2530 WHERE (startdate <= $transdate)
2532 ) tk ON (c.id = tk.chart_id)
2533 -- and load all of those entries
2534 INNER JOIN taxkeys tk2
2535 ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
2536 WHERE (c.link LIKE ?)
2539 $sth = $dbh->prepare($query);
2541 do_statement($self, $sth, $query, like($module));
2543 $self->{accounts} = "";
2544 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2546 foreach my $key (split(/:/, $ref->{link})) {
2547 if ($key =~ /\Q$module\E/) {
2549 # cross reference for keys
2550 $xkeyref{ $ref->{accno} } = $key;
2552 push @{ $self->{"${module}_links"}{$key} },
2553 { accno => $ref->{accno},
2554 chart_id => $ref->{chart_id},
2555 description => $ref->{description},
2556 taxkey => $ref->{taxkey_id},
2557 tax_id => $ref->{tax_id} };
2559 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2565 # get taxkeys and description
2566 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2567 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2569 if (($module eq "AP") || ($module eq "AR")) {
2570 # get tax rates and description
2571 $query = qq|SELECT * FROM tax|;
2572 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2575 my $extra_columns = '';
2576 $extra_columns .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
2581 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid, a.deliverydate,
2582 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,
2584 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2585 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2586 a.globalproject_id, ${extra_columns}
2588 d.description AS department,
2591 JOIN $table c ON (a.${table}_id = c.id)
2592 LEFT JOIN employee e ON (e.id = a.employee_id)
2593 LEFT JOIN department d ON (d.id = a.department_id)
2595 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2597 foreach my $key (keys %$ref) {
2598 $self->{$key} = $ref->{$key};
2600 $self->{mtime} ||= $self->{itime};
2601 $self->{lastmtime} = $self->{mtime};
2602 my $transdate = "current_date";
2603 if ($self->{transdate}) {
2604 $transdate = $dbh->quote($self->{transdate});
2607 # now get the account numbers
2608 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
2610 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2612 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2613 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2616 $sth = $dbh->prepare($query);
2617 do_statement($self, $sth, $query, like($module));
2619 $self->{accounts} = "";
2620 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2622 foreach my $key (split(/:/, $ref->{link})) {
2623 if ($key =~ /\Q$module\E/) {
2625 # cross reference for keys
2626 $xkeyref{ $ref->{accno} } = $key;
2628 push @{ $self->{"${module}_links"}{$key} },
2629 { accno => $ref->{accno},
2630 chart_id => $ref->{chart_id},
2631 description => $ref->{description},
2632 taxkey => $ref->{taxkey_id},
2633 tax_id => $ref->{tax_id} };
2635 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2641 # get amounts from individual entries
2644 c.accno, c.description,
2645 a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
2649 LEFT JOIN chart c ON (c.id = a.chart_id)
2650 LEFT JOIN project p ON (p.id = a.project_id)
2651 LEFT JOIN tax t ON (t.id= a.tax_id)
2652 WHERE a.trans_id = ?
2653 AND a.fx_transaction = '0'
2654 ORDER BY a.acc_trans_id, a.transdate|;
2655 $sth = $dbh->prepare($query);
2656 do_statement($self, $sth, $query, $self->{id});
2658 # get exchangerate for currency
2659 $self->{exchangerate} =
2660 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2663 # store amounts in {acc_trans}{$key} for multiple accounts
2664 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2665 $ref->{exchangerate} =
2666 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2667 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2670 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2671 $ref->{amount} *= -1;
2673 $ref->{index} = $index;
2675 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2682 d.closedto, d.revtrans,
2683 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2684 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2685 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2686 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2687 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2689 $ref = selectfirst_hashref_query($self, $dbh, $query);
2690 map { $self->{$_} = $ref->{$_} } keys %$ref;
2697 current_date AS transdate, d.closedto, d.revtrans,
2698 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2699 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2700 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2701 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2702 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2704 $ref = selectfirst_hashref_query($self, $dbh, $query);
2705 map { $self->{$_} = $ref->{$_} } keys %$ref;
2707 if ($self->{"$self->{vc}_id"}) {
2709 # only setup currency
2710 ($self->{currency}) = $self->{defaultcurrency} if !$self->{currency};
2714 $self->lastname_used($dbh, $myconfig, $table, $module);
2716 # get exchangerate for currency
2717 $self->{exchangerate} =
2718 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2724 $main::lxdebug->leave_sub();
2728 $main::lxdebug->enter_sub();
2730 my ($self, $dbh, $myconfig, $table, $module) = @_;
2734 $table = $table eq "customer" ? "customer" : "vendor";
2735 my %column_map = ("a.${table}_id" => "${table}_id",
2736 "a.department_id" => "department_id",
2737 "d.description" => "department",
2738 "ct.name" => $table,
2739 "cu.name" => "currency",
2742 if ($self->{type} =~ /delivery_order/) {
2743 $arap = 'delivery_orders';
2744 delete $column_map{"cu.currency"};
2746 } elsif ($self->{type} =~ /_order/) {
2748 $where = "quotation = '0'";
2750 } elsif ($self->{type} =~ /_quotation/) {
2752 $where = "quotation = '1'";
2754 } elsif ($table eq 'customer') {
2762 $where = "($where) AND" if ($where);
2763 my $query = qq|SELECT MAX(id) FROM $arap
2764 WHERE $where ${table}_id > 0|;
2765 my ($trans_id) = selectrow_query($self, $dbh, $query);
2768 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2769 $query = qq|SELECT $column_spec
2771 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2772 LEFT JOIN department d ON (a.department_id = d.id)
2773 LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
2775 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2777 map { $self->{$_} = $ref->{$_} } values %column_map;
2779 $main::lxdebug->leave_sub();
2782 sub get_variable_content_types {
2783 my %html_variables = (
2784 longdescription => 'html',
2785 partnotes => 'html',
2787 orignotes => 'html',
2792 header_text => 'html',
2793 footer_text => 'html',
2795 return \%html_variables;
2799 $main::lxdebug->enter_sub();
2802 my $myconfig = shift || \%::myconfig;
2803 my ($thisdate, $days) = @_;
2805 my $dbh = $self->get_standard_dbh($myconfig);
2810 my $dateformat = $myconfig->{dateformat};
2811 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2812 $thisdate = $dbh->quote($thisdate);
2813 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2815 $query = qq|SELECT current_date AS thisdate|;
2818 ($thisdate) = selectrow_query($self, $dbh, $query);
2820 $main::lxdebug->leave_sub();
2826 $main::lxdebug->enter_sub();
2828 my ($self, $flds, $new, $count, $numrows) = @_;
2832 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2837 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2839 my $j = $item->{ndx} - 1;
2840 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2844 for $i ($count + 1 .. $numrows) {
2845 map { delete $self->{"${_}_$i"} } @{$flds};
2848 $main::lxdebug->leave_sub();
2852 $main::lxdebug->enter_sub();
2854 my ($self, $myconfig) = @_;
2858 SL::DB->client->with_transaction(sub {
2859 my $dbh = SL::DB->client->dbh;
2861 my $query = qq|DELETE FROM status
2862 WHERE (formname = ?) AND (trans_id = ?)|;
2863 my $sth = prepare_query($self, $dbh, $query);
2865 if ($self->{formname} =~ /(check|receipt)/) {
2866 for $i (1 .. $self->{rowcount}) {
2867 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2870 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2874 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2875 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2877 my %queued = split / /, $self->{queued};
2880 if ($self->{formname} =~ /(check|receipt)/) {
2882 # this is a check or receipt, add one entry for each lineitem
2883 my ($accno) = split /--/, $self->{account};
2884 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2885 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2886 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2887 $sth = prepare_query($self, $dbh, $query);
2889 for $i (1 .. $self->{rowcount}) {
2890 if ($self->{"checked_$i"}) {
2891 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2897 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2898 VALUES (?, ?, ?, ?, ?)|;
2899 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2900 $queued{$self->{formname}}, $self->{formname});
2903 }) or do { die SL::DB->client->error };
2905 $main::lxdebug->leave_sub();
2909 $main::lxdebug->enter_sub();
2911 my ($self, $dbh) = @_;
2913 my ($query, $printed, $emailed);
2915 my $formnames = $self->{printed};
2916 my $emailforms = $self->{emailed};
2918 $query = qq|DELETE FROM status
2919 WHERE (formname = ?) AND (trans_id = ?)|;
2920 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2922 # this only applies to the forms
2923 # checks and receipts are posted when printed or queued
2925 if ($self->{queued}) {
2926 my %queued = split / /, $self->{queued};
2928 foreach my $formname (keys %queued) {
2929 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2930 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2932 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2933 VALUES (?, ?, ?, ?, ?)|;
2934 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2936 $formnames =~ s/\Q$self->{formname}\E//;
2937 $emailforms =~ s/\Q$self->{formname}\E//;
2942 # save printed, emailed info
2943 $formnames =~ s/^ +//g;
2944 $emailforms =~ s/^ +//g;
2947 map { $status{$_}{printed} = 1 } split / +/, $formnames;
2948 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2950 foreach my $formname (keys %status) {
2951 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
2952 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
2954 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2955 VALUES (?, ?, ?, ?)|;
2956 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2959 $main::lxdebug->leave_sub();
2963 # $main::locale->text('SAVED')
2964 # $main::locale->text('SCREENED')
2965 # $main::locale->text('DELETED')
2966 # $main::locale->text('ADDED')
2967 # $main::locale->text('PAYMENT POSTED')
2968 # $main::locale->text('POSTED')
2969 # $main::locale->text('POSTED AS NEW')
2970 # $main::locale->text('ELSE')
2971 # $main::locale->text('SAVED FOR DUNNING')
2972 # $main::locale->text('DUNNING STARTED')
2973 # $main::locale->text('PREVIEWED')
2974 # $main::locale->text('PRINTED')
2975 # $main::locale->text('MAILED')
2976 # $main::locale->text('SCREENED')
2977 # $main::locale->text('CANCELED')
2978 # $main::locale->text('IMPORT')
2979 # $main::locale->text('UNDO TRANSFER')
2980 # $main::locale->text('UNIMPORT')
2981 # $main::locale->text('invoice')
2982 # $main::locale->text('proforma')
2983 # $main::locale->text('sales_order')
2984 # $main::locale->text('pick_list')
2985 # $main::locale->text('purchase_order')
2986 # $main::locale->text('bin_list')
2987 # $main::locale->text('sales_quotation')
2988 # $main::locale->text('request_quotation')
2991 $main::lxdebug->enter_sub();
2994 my $dbh = shift || SL::DB->client->dbh;
2995 SL::DB->client->with_transaction(sub {
2997 if(!exists $self->{employee_id}) {
2998 &get_employee($self, $dbh);
3002 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3003 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3004 my @values = (conv_i($self->{id}), $self->{login},
3005 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3006 do_query($self, $dbh, $query, @values);
3008 }) or do { die SL::DB->client->error };
3010 $main::lxdebug->leave_sub();
3014 $main::lxdebug->enter_sub();
3016 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3017 my ($orderBy, $desc) = split(/\-\-/, $order);
3018 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3021 if ($trans_id ne "") {
3023 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 | .
3024 qq|FROM history_erp h | .
3025 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3026 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3029 my $sth = $dbh->prepare($query) || $self->dberror($query);
3031 $sth->execute() || $self->dberror("$query");
3033 while(my $hash_ref = $sth->fetchrow_hashref()) {
3034 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3035 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3036 my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
3037 $hash_ref->{snumbers} = $number;
3038 $hash_ref->{haslink} = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
3039 $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
3040 $tempArray[$i++] = $hash_ref;
3042 $main::lxdebug->leave_sub() and return \@tempArray
3043 if ($i > 0 && $tempArray[0] ne "");
3045 $main::lxdebug->leave_sub();
3049 sub get_partsgroup {
3050 $main::lxdebug->enter_sub();
3052 my ($self, $myconfig, $p) = @_;
3053 my $target = $p->{target} || 'all_partsgroup';
3055 my $dbh = $self->get_standard_dbh($myconfig);
3057 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3059 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3062 if ($p->{searchitems} eq 'part') {
3063 $query .= qq|WHERE p.part_type = 'part'|;
3065 if ($p->{searchitems} eq 'service') {
3066 $query .= qq|WHERE p.part_type = 'service'|;
3068 if ($p->{searchitems} eq 'assembly') {
3069 $query .= qq|WHERE p.part_type = 'assembly'|;
3072 $query .= qq|ORDER BY partsgroup|;
3075 $query = qq|SELECT id, partsgroup FROM partsgroup
3076 ORDER BY partsgroup|;
3079 if ($p->{language_code}) {
3080 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3081 t.description AS translation
3083 JOIN parts p ON (p.partsgroup_id = pg.id)
3084 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3085 ORDER BY translation|;
3086 @values = ($p->{language_code});
3089 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3091 $main::lxdebug->leave_sub();
3094 sub get_pricegroup {
3095 $main::lxdebug->enter_sub();
3097 my ($self, $myconfig, $p) = @_;
3099 my $dbh = $self->get_standard_dbh($myconfig);
3101 my $query = qq|SELECT p.id, p.pricegroup
3104 $query .= qq| ORDER BY pricegroup|;
3107 $query = qq|SELECT id, pricegroup FROM pricegroup
3108 ORDER BY pricegroup|;
3111 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3113 $main::lxdebug->leave_sub();
3117 # usage $form->all_years($myconfig, [$dbh])
3118 # return list of all years where bookings found
3121 $main::lxdebug->enter_sub();
3123 my ($self, $myconfig, $dbh) = @_;
3125 $dbh ||= $self->get_standard_dbh($myconfig);
3128 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3129 (SELECT MAX(transdate) FROM acc_trans)|;
3130 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3132 if ($myconfig->{dateformat} =~ /^yy/) {
3133 ($startdate) = split /\W/, $startdate;
3134 ($enddate) = split /\W/, $enddate;
3136 (@_) = split /\W/, $startdate;
3138 (@_) = split /\W/, $enddate;
3143 $startdate = substr($startdate,0,4);
3144 $enddate = substr($enddate,0,4);
3146 while ($enddate >= $startdate) {
3147 push @all_years, $enddate--;
3152 $main::lxdebug->leave_sub();
3156 $main::lxdebug->enter_sub();
3160 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3162 $main::lxdebug->leave_sub();
3166 $main::lxdebug->enter_sub();
3171 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3173 $main::lxdebug->leave_sub();
3176 sub prepare_for_printing {
3179 my $defaults = SL::DB::Default->get;
3181 $self->{templates} ||= $defaults->templates;
3182 $self->{formname} ||= $self->{type};
3183 $self->{media} ||= 'email';
3185 die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3187 # Several fields that used to reside in %::myconfig (stored in
3188 # auth.user_config) are now stored in defaults. Copy them over for
3190 $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
3192 $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
3194 if (!$self->{employee_id}) {
3195 $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
3196 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
3199 my $language = $self->{language} ? '_' . $self->{language} : '';
3201 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3202 if ($self->{language_id}) {
3203 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3206 $output_dateformat ||= $::myconfig{dateformat};
3207 $output_numberformat ||= $::myconfig{numberformat};
3208 $output_longdates //= 1;
3210 $self->{myconfig_output_dateformat} = $output_dateformat // $::myconfig{dateformat};
3211 $self->{myconfig_output_longdates} = $output_longdates // 1;
3212 $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
3214 # Retrieve accounts for tax calculation.
3215 IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3217 if ($self->{type} =~ /_delivery_order$/) {
3218 DO->order_details(\%::myconfig, $self);
3219 } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3220 OE->order_details(\%::myconfig, $self);
3222 IS->invoice_details(\%::myconfig, $self, $::locale);
3225 # Chose extension & set source file name
3226 my $extension = 'html';
3227 if ($self->{format} eq 'postscript') {
3228 $self->{postscript} = 1;
3230 } elsif ($self->{"format"} =~ /pdf/) {
3232 $extension = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3233 } elsif ($self->{"format"} =~ /opendocument/) {
3234 $self->{opendocument} = 1;
3236 } elsif ($self->{"format"} =~ /excel/) {
3241 my $printer_code = $self->{printer_code} ? '_' . $self->{printer_code} : '';
3242 my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
3243 $self->{IN} = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3246 $self->format_dates($output_dateformat, $output_longdates,
3247 qw(invdate orddate quodate pldate duedate reqdate transdate tax_point shippingdate deliverydate validitydate paymentdate datepaid
3248 transdate_oe deliverydate_oe employee_startdate employee_enddate),
3249 grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3251 $self->reformat_numbers($output_numberformat, 2,
3252 qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3253 grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3255 $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3257 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3259 if (scalar @{ $cvar_date_fields }) {
3260 $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3263 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3264 $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3268 if (($self->{language} // '') ne '') {
3269 my $template_arrays = $self->{TEMPLATE_ARRAYS} || $self;
3270 for my $idx (0..scalar(@{ $template_arrays->{unit} }) - 1) {
3271 $template_arrays->{unit}->[$idx] = AM->translate_units($self, $self->{language}, $template_arrays->{unit}->[$idx], $template_arrays->{qty}->[$idx])
3275 $self->{template_meta} = {
3276 formname => $self->{formname},
3277 language => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
3278 format => $self->{format},
3279 media => $self->{media},
3280 extension => $extension,
3281 printer => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
3282 today => DateTime->today,
3288 sub calculate_arap {
3289 my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
3291 # this function is used to calculate netamount, total_tax and amount for AP and
3292 # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
3294 # Thus it needs a fully prepared $form to work on.
3295 # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
3297 # The calculated total values are all rounded (default is to 2 places) and
3298 # returned as parameters rather than directly modifying form. The aim is to
3299 # make the calculation of AP and AR behave identically. There is a test-case
3300 # for this function in t/form/arap.t
3302 # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
3303 # modified and formatted and receive the correct sign for writing straight to
3304 # acc_trans, depending on whether they are ar or ap.
3307 die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
3308 die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
3309 die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
3310 $roundplaces = 2 unless $roundplaces;
3312 my $sign = 1; # adjust final results for writing amount to acc_trans
3313 $sign = -1 if $buysell eq 'buy';
3315 my ($netamount,$total_tax,$amount);
3319 # parse and round amounts, setting correct sign for writing to acc_trans
3320 for my $i (1 .. $self->{rowcount}) {
3321 $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
3323 $amount += $self->{"amount_$i"} * $sign;
3326 for my $i (1 .. $self->{rowcount}) {
3327 next unless $self->{"amount_$i"};
3328 ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
3329 my $tax_id = $self->{"tax_id_$i"};
3331 my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
3333 if ( $selected_tax ) {
3335 if ( $buysell eq 'sell' ) {
3336 $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3338 $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3341 $self->{"taxkey_$i"} = $selected_tax->taxkey;
3342 $self->{"taxrate_$i"} = $selected_tax->rate;
3345 ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
3347 $netamount += $self->{"amount_$i"};
3348 $total_tax += $self->{"tax_$i"};
3351 $amount = $netamount + $total_tax;
3353 # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
3354 # but reverse sign of totals for writing amounts to ar
3355 if ( $buysell eq 'buy' ) {
3361 return($netamount,$total_tax,$amount);
3365 my ($self, $dateformat, $longformat, @indices) = @_;
3367 $dateformat ||= $::myconfig{dateformat};
3369 foreach my $idx (@indices) {
3370 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3371 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3372 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3376 next unless defined $self->{$idx};
3378 if (!ref($self->{$idx})) {
3379 $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3381 } elsif (ref($self->{$idx}) eq "ARRAY") {
3382 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3383 $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3389 sub reformat_numbers {
3390 my ($self, $numberformat, $places, @indices) = @_;
3392 return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3394 foreach my $idx (@indices) {
3395 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3396 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3397 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3401 next unless defined $self->{$idx};
3403 if (!ref($self->{$idx})) {
3404 $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3406 } elsif (ref($self->{$idx}) eq "ARRAY") {
3407 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3408 $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3413 my $saved_numberformat = $::myconfig{numberformat};
3414 $::myconfig{numberformat} = $numberformat;
3416 foreach my $idx (@indices) {
3417 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3418 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3419 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3423 next unless defined $self->{$idx};
3425 if (!ref($self->{$idx})) {
3426 $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3428 } elsif (ref($self->{$idx}) eq "ARRAY") {
3429 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3430 $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3435 $::myconfig{numberformat} = $saved_numberformat;
3438 sub create_email_signature {
3440 my $client_signature = $::instance_conf->get_signature;
3441 my $user_signature = $::myconfig{signature};
3444 if ( $client_signature or $user_signature ) {
3445 $signature = "\n\n-- \n";
3446 $signature .= $user_signature . "\n" if $user_signature;
3447 $signature .= $client_signature . "\n" if $client_signature;
3454 # this function calculates the net amount and tax for the lines in ar, ap and
3455 # gl and is used for update as well as post. When used with update the return
3456 # value of amount isn't needed
3458 # calculate_tax should always work with positive values, or rather as the user inputs them
3459 # calculate_tax uses db/perl numberformat, i.e. parsed numbers
3460 # convert to negative numbers (when necessary) only when writing to acc_trans
3461 # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
3462 # for post_transaction amount already contains exchangerate and correct sign and is rounded
3463 # calculate_tax doesn't (need to) know anything about exchangerate
3465 my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
3473 # calculate tax (unrounded), subtract from amount, round amount and round tax
3474 $tax = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
3475 $amount = $self->round_amount($amount - $tax, $roundplaces);
3476 $tax = $self->round_amount($tax, $roundplaces);
3478 $tax = $amount * $taxrate;
3479 $tax = $self->round_amount($tax, $roundplaces);
3482 $tax = 0 unless $tax;
3484 return ($amount,$tax);
3493 SL::Form.pm - main data object.
3497 This is the main data object of kivitendo.
3498 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3499 Points of interest for a beginner are:
3501 - $form->error - renders a generic error in html. accepts an error message
3502 - $form->get_standard_dbh - returns a database connection for the
3504 =head1 SPECIAL FUNCTIONS
3506 =head2 C<redirect_header> $url
3508 Generates a HTTP redirection header for the new C<$url>. Constructs an
3509 absolute URL including scheme, host name and port. If C<$url> is a
3510 relative URL then it is considered relative to kivitendo base URL.
3512 This function C<die>s if headers have already been created with
3513 C<$::form-E<gt>header>.
3517 print $::form->redirect_header('oe.pl?action=edit&id=1234');
3518 print $::form->redirect_header('http://www.lx-office.org/');
3522 Generates a general purpose http/html header and includes most of the scripts
3523 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3525 Only one header will be generated. If the method was already called in this
3526 request it will not output anything and return undef. Also if no
3527 HTTP_USER_AGENT is found, no header is generated.
3529 Although header does not accept parameters itself, it will honor special
3530 hashkeys of its Form instance:
3538 If one of these is set, a http-equiv refresh is generated. Missing parameters
3539 default to 3 seconds and the refering url.
3543 Either a scalar or an array ref. Will be inlined into the header. Add
3544 stylesheets with the L<use_stylesheet> function.
3548 If true, a css snippet will be generated that sets the page in landscape mode.
3552 Used to override the default favicon.
3556 A html page title will be generated from this
3558 =item mtime_ischanged
3560 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
3562 Can be used / called with any table, that has itime and mtime attributes.
3563 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
3564 Can be called wit C<option> mail to generate a different error message.
3566 Returns undef if no save operation has been done yet ($self->{id} not present).
3567 Returns undef if no concurrent write process is detected otherwise a error message.