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 if (-f "templates/webpages/${file}.html") {
554 $file = "templates/webpages/${file}.html";
556 } elsif (ref $file eq 'SCALAR') {
557 # file is a scalarref, use inline mode
559 my $info = "Web page template '${file}' not found.\n";
561 print qq|<pre>$info</pre>|;
562 $::dispatcher->end_request;
565 $additional_params->{AUTH} = $::auth;
566 $additional_params->{INSTANCE_CONF} = $::instance_conf;
567 $additional_params->{LOCALE} = $::locale;
568 $additional_params->{LXCONFIG} = \%::lx_office_conf;
569 $additional_params->{LXDEBUG} = $::lxdebug;
570 $additional_params->{MYCONFIG} = \%::myconfig;
572 $main::lxdebug->leave_sub();
577 sub parse_html_template {
578 $main::lxdebug->enter_sub();
580 my ($self, $file, $additional_params) = @_;
582 $additional_params ||= { };
584 my $real_file = $self->_prepare_html_template($file, $additional_params);
585 my $template = $self->template;
587 map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
590 $template->process($real_file, $additional_params, \$output) || die $template->error;
592 $main::lxdebug->leave_sub();
597 sub template { $::request->presenter->get_template }
599 sub show_generic_error {
600 $main::lxdebug->enter_sub();
602 my ($self, $error, %params) = @_;
604 if ($self->{__ERROR_HANDLER}) {
605 $self->{__ERROR_HANDLER}->($error);
606 $main::lxdebug->leave_sub();
610 if ($::request->is_ajax) {
613 ->render(SL::Controller::Base->new);
614 $::dispatcher->end_request;
618 'title_error' => $params{title},
619 'label_error' => $error,
622 $self->{title} = $params{title} if $params{title};
624 for my $bar ($::request->layout->get('actionbar')) {
628 call => [ 'kivi.history_back' ],
629 accesskey => 'enter',
635 print $self->parse_html_template("generic/error", $add_params);
637 print STDERR "Error: $error\n";
639 $main::lxdebug->leave_sub();
641 $::dispatcher->end_request;
644 sub show_generic_information {
645 $main::lxdebug->enter_sub();
647 my ($self, $text, $title) = @_;
650 'title_information' => $title,
651 'label_information' => $text,
654 $self->{title} = $title if ($title);
657 print $self->parse_html_template("generic/information", $add_params);
659 $main::lxdebug->leave_sub();
661 $::dispatcher->end_request;
664 sub _store_redirect_info_in_session {
667 return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
669 my ($controller, $params) = ($1, $2);
670 my $form = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
671 $self->{callback} = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
675 $main::lxdebug->enter_sub();
677 my ($self, $msg) = @_;
679 if (!$self->{callback}) {
683 SL::Helper::Flash::flash_later('info', $msg) if $msg;
684 $self->_store_redirect_info_in_session;
685 print $::form->redirect_header($self->{callback});
688 $::dispatcher->end_request;
690 $main::lxdebug->leave_sub();
693 # sort of columns removed - empty sub
695 $main::lxdebug->enter_sub();
697 my ($self, @columns) = @_;
699 $main::lxdebug->leave_sub();
706 my ($self, $myconfig, $amount, $places, $dash) = @_;
707 SL::Helper::Number::_format_number($amount, $places, %$myconfig, dash => $dash);
710 sub format_amount_units {
711 $main::lxdebug->enter_sub();
716 my $myconfig = \%main::myconfig;
717 my $amount = $params{amount} * 1;
718 my $places = $params{places};
719 my $part_unit_name = $params{part_unit};
720 my $amount_unit_name = $params{amount_unit};
721 my $conv_units = $params{conv_units};
722 my $max_places = $params{max_places};
724 if (!$part_unit_name) {
725 $main::lxdebug->leave_sub();
729 my $all_units = AM->retrieve_all_units;
731 if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
732 $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
735 if (!scalar @{ $conv_units }) {
736 my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
737 $main::lxdebug->leave_sub();
741 my $part_unit = $all_units->{$part_unit_name};
742 my $conv_unit = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
744 $amount *= $conv_unit->{factor};
749 foreach my $unit (@$conv_units) {
750 my $last = $unit->{name} eq $part_unit->{name};
752 $num = int($amount / $unit->{factor});
753 $amount -= $num * $unit->{factor};
756 if ($last ? $amount : $num) {
757 push @values, { "unit" => $unit->{name},
758 "amount" => $last ? $amount / $unit->{factor} : $num,
759 "places" => $last ? $places : 0 };
766 push @values, { "unit" => $part_unit_name,
771 my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
773 $main::lxdebug->leave_sub();
779 $main::lxdebug->enter_sub(2);
784 $input =~ s/(^|[^\#]) \# (\d+) /$1$_[$2 - 1]/gx;
785 $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
786 $input =~ s/\#\#/\#/g;
788 $main::lxdebug->leave_sub(2);
796 my ($self, $myconfig, $amount) = @_;
797 SL::Helper::Number::_parse_number($amount, %$myconfig);
800 sub round_amount { shift; goto &SL::Helper::Number::_round_number; }
803 $main::lxdebug->enter_sub();
805 my ($self, $myconfig) = @_;
806 my ($out, $out_mode);
810 my $defaults = SL::DB::Default->get;
812 my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
813 $self->{cwd} = getcwd();
814 my $temp_dir = File::Temp->newdir(
815 "kivitendo-print-XXXXXX",
816 DIR => $self->{cwd} . "/" . $::lx_office_conf{paths}->{userspath},
817 CLEANUP => !$keep_temp_files,
820 my $userspath = File::Spec->abs2rel($temp_dir->dirname);
821 $self->{tmpdir} = $temp_dir->dirname;
826 if ($self->{"format"} =~ /(opendocument|oasis)/i) {
827 $template_type = 'OpenDocument';
828 $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
830 } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
831 $template_type = 'LaTeX';
832 $ext_for_format = 'pdf';
834 } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
835 $template_type = 'HTML';
836 $ext_for_format = 'html';
838 } elsif ( $self->{"format"} =~ /excel/i ) {
839 $template_type = 'Excel';
840 $ext_for_format = 'xls';
842 } elsif ( defined $self->{'format'}) {
843 $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
845 } elsif ( $self->{'format'} eq '' ) {
846 $self->error("No Outputformat given: $self->{'format'}");
848 } else { #Catch the rest
849 $self->error("Outputformat not defined: $self->{'format'}");
852 my $template = SL::Template::create(type => $template_type,
853 file_name => $self->{IN},
855 myconfig => $myconfig,
856 userspath => $userspath,
857 %{ $self->{TEMPLATE_DRIVER_OPTIONS} || {} });
859 # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
860 $self->{"notes"} = $self->{ $self->{"formname"} . "notes" } if exists $self->{ $self->{"formname"} . "notes" };
862 if (!$self->{employee_id}) {
863 $self->{"employee_${_}"} = $myconfig->{$_} for qw(email tel fax name signature);
864 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
867 $self->{"myconfig_${_}"} = $myconfig->{$_} for grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
868 $self->{$_} = $defaults->$_ for qw(co_ustid);
869 $self->{"myconfig_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
870 $self->{AUTH} = $::auth;
871 $self->{INSTANCE_CONF} = $::instance_conf;
872 $self->{LOCALE} = $::locale;
873 $self->{LXCONFIG} = $::lx_office_conf;
874 $self->{LXDEBUG} = $::lxdebug;
875 $self->{MYCONFIG} = \%::myconfig;
877 $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
879 # OUT is used for the media, screen, printer, email
880 # for postscript we store a copy in a temporary file
882 my ($temp_fh, $suffix);
883 $suffix = $self->{IN};
885 ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
886 strftime('kivitendo-print-%Y%m%d%H%M%S-XXXXXX', localtime()),
887 SUFFIX => '.' . ($suffix || 'tex'),
889 UNLINK => $keep_temp_files ? 0 : 1,
892 chmod 0644, $self->{tmpfile} if $keep_temp_files;
893 (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
896 $out_mode = $self->{OUT_MODE} || '>';
897 $self->{OUT} = "$self->{tmpfile}";
898 $self->{OUT_MODE} = '>';
901 my $command_formatter = sub {
902 my ($out_mode, $out) = @_;
903 return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
907 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
908 open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
910 *OUT = ($::dispatcher->get_standard_filehandles)[1];
914 if (!$template->parse(*OUT)) {
916 $self->error("$self->{IN} : " . $template->get_error());
919 close OUT if $self->{OUT};
920 # check only one flag (webdav_documents)
921 # therefore copy to webdav, even if we do not have the webdav feature enabled (just archive)
922 my $copy_to_webdav = $::instance_conf->get_webdav_documents && !$self->{preview} && $self->{tmpdir} && $self->{tmpfile} && $self->{type}
923 && $self->{type} ne 'statement';
924 if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
925 $self->append_general_pdf_attachments(filepath => $self->{tmpdir}."/".$self->{tmpfile},
926 type => $self->{type});
928 if ($self->{media} eq 'file') {
929 copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
931 if ($copy_to_webdav) {
932 if (my $error = Common::copy_file_to_webdav_folder($self)) {
933 chdir("$self->{cwd}");
934 $self->error($error);
938 if (!$self->{preview} && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled)
940 $self->{attachment_filename} ||= $self->generate_attachment_filename;
941 $self->store_pdf($self);
944 chdir("$self->{cwd}");
946 $::lxdebug->leave_sub();
951 if ($copy_to_webdav) {
952 if (my $error = Common::copy_file_to_webdav_folder($self)) {
953 chdir("$self->{cwd}");
954 $self->error($error);
958 if ( !$self->{preview} && $ext_for_format eq 'pdf' && $self->{attachment_type} !~ m{^dunning} && $self->doc_storage_enabled) {
959 $self->{attachment_filename} ||= $self->generate_attachment_filename;
960 my $file_obj = $self->store_pdf($self);
961 $self->{print_file_id} = $file_obj->id if $file_obj;
963 if ($self->{media} eq 'email') {
964 if ( getcwd() eq $self->{"tmpdir"} ) {
965 # in the case of generating pdf we are in the tmpdir, but WHY ???
966 $self->{tmpfile} = $userspath."/".$self->{tmpfile};
967 chdir("$self->{cwd}");
969 $self->send_email(\%::myconfig,$ext_for_format);
973 $self->{OUT_MODE} = $out_mode;
974 $self->output_file($template->get_mime_type,$command_formatter);
976 delete $self->{print_file_id};
980 chdir("$self->{cwd}");
981 $main::lxdebug->leave_sub();
984 sub get_bcc_defaults {
985 my ($self, $myconfig, $mybcc) = @_;
986 if (SL::DB::Default->get->bcc_to_login) {
987 $mybcc .= ", " if $mybcc;
988 $mybcc .= $myconfig->{email};
990 my $otherbcc = SL::DB::Default->get->global_bcc;
992 $mybcc .= ", " if $mybcc;
999 $main::lxdebug->enter_sub();
1000 my ($self, $myconfig, $ext_for_format) = @_;
1001 my $mail = Mailer->new;
1003 map { $mail->{$_} = $self->{$_} }
1004 qw(cc subject message format);
1006 if ($self->{cc_employee}) {
1007 my ($user, $my_emp_cc);
1008 $user = SL::DB::Manager::AuthUser->find_by(login => $self->{cc_employee});
1009 $my_emp_cc = $user->get_config_value('email') if ref $user eq 'SL::DB::AuthUser';
1010 $mail->{cc} .= ", " if $mail->{cc};
1011 $mail->{cc} .= $my_emp_cc if $my_emp_cc;
1014 $mail->{bcc} = $self->get_bcc_defaults($myconfig, $self->{bcc});
1015 $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1016 $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1017 $mail->{fileid} = time() . '.' . $$ . '.';
1018 my $full_signature = $self->create_email_signature();
1019 $full_signature =~ s/\r//g;
1021 $mail->{attachments} = [];
1023 # if we send html or plain text inline
1024 if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1025 $mail->{content_type} = "text/html";
1026 $mail->{message} =~ s/\r//g;
1027 $mail->{message} =~ s{\n}{<br>\n}g;
1028 $full_signature =~ s{\n}{<br>\n}g;
1029 $mail->{message} .= $full_signature;
1031 open(IN, "<", $self->{tmpfile})
1032 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1033 $mail->{message} .= $_ while <IN>;
1036 } elsif (($self->{attachment_policy} // '') ne 'no_file') {
1037 my $attachment_name = $self->{attachment_filename} || $self->{tmpfile};
1038 $attachment_name =~ s{\.(.+?)$}{.${ext_for_format}} if ($ext_for_format);
1040 if (($self->{attachment_policy} // '') eq 'old_file') {
1041 my ( $attfile ) = SL::File->get_all(object_id => $self->{id},
1042 object_type => $self->{formname},
1043 file_type => 'document');
1046 $attfile->{override_file_name} = $attachment_name if $attachment_name;
1047 push @attfiles, $attfile;
1051 push @{ $mail->{attachments} }, { path => $self->{tmpfile},
1052 id => $self->{print_file_id},
1053 type => "application/pdf",
1054 name => $attachment_name };
1060 map { SL::File->get(id => $_) }
1061 @{ $self->{attach_file_ids} // [] };
1063 foreach my $attfile ( @attfiles ) {
1064 push @{ $mail->{attachments} }, {
1065 path => $attfile->get_file,
1067 type => $attfile->mime_type,
1068 name => $attfile->{override_file_name} // $attfile->file_name,
1069 content => $attfile->get_content ? ${ $attfile->get_content } : undef,
1073 $mail->{message} =~ s/\r//g;
1074 $mail->{message} .= $full_signature;
1075 $self->{emailerr} = $mail->send();
1077 if ($self->{emailerr}) {
1079 $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
1082 $self->{email_journal_id} = $mail->{journalentry};
1083 $self->{snumbers} = "emailjournal" . "_" . $self->{email_journal_id};
1084 $self->{what_done} = $::form->{type};
1085 $self->{addition} = "MAILED";
1086 $self->save_history;
1088 #write back for message info and mail journal
1089 $self->{cc} = $mail->{cc};
1090 $self->{bcc} = $mail->{bcc};
1091 $self->{email} = $mail->{to};
1093 $main::lxdebug->leave_sub();
1097 $main::lxdebug->enter_sub();
1099 my ($self,$mimeType,$command_formatter) = @_;
1100 my $numbytes = (-s $self->{tmpfile});
1101 open(IN, "<", $self->{tmpfile})
1102 or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1105 $self->{copies} = 1 unless $self->{media} eq 'printer';
1107 chdir("$self->{cwd}");
1108 for my $i (1 .. $self->{copies}) {
1110 $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1112 open OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1113 print OUT $_ while <IN>;
1118 my %headers = ('-type' => $mimeType,
1119 '-connection' => 'close',
1120 '-charset' => 'UTF-8');
1122 $self->{attachment_filename} ||= $self->generate_attachment_filename;
1124 if ($self->{attachment_filename}) {
1127 '-attachment' => $self->{attachment_filename},
1128 '-content-length' => $numbytes,
1133 print $::request->cgi->header(%headers);
1135 $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1139 $main::lxdebug->leave_sub();
1142 sub get_formname_translation {
1143 $main::lxdebug->enter_sub();
1144 my ($self, $formname) = @_;
1146 $formname ||= $self->{formname};
1148 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1149 local $::locale = Locale->new($self->{recipient_locale});
1151 my %formname_translations = (
1152 bin_list => $main::locale->text('Bin List'),
1153 credit_note => $main::locale->text('Credit Note'),
1154 invoice => $main::locale->text('Invoice'),
1155 pick_list => $main::locale->text('Pick List'),
1156 proforma => $main::locale->text('Proforma Invoice'),
1157 purchase_order => $main::locale->text('Purchase Order'),
1158 request_quotation => $main::locale->text('RFQ'),
1159 sales_order => $main::locale->text('Confirmation'),
1160 sales_quotation => $main::locale->text('Quotation'),
1161 storno_invoice => $main::locale->text('Storno Invoice'),
1162 sales_delivery_order => $main::locale->text('Delivery Order'),
1163 purchase_delivery_order => $main::locale->text('Delivery Order'),
1164 dunning => $main::locale->text('Dunning'),
1165 dunning1 => $main::locale->text('Payment Reminder'),
1166 dunning2 => $main::locale->text('Dunning'),
1167 dunning3 => $main::locale->text('Last Dunning'),
1168 dunning_invoice => $main::locale->text('Dunning Invoice'),
1169 letter => $main::locale->text('Letter'),
1170 ic_supply => $main::locale->text('Intra-Community supply'),
1171 statement => $main::locale->text('Statement'),
1174 $main::lxdebug->leave_sub();
1175 return $formname_translations{$formname};
1178 sub get_cusordnumber_translation {
1179 $main::lxdebug->enter_sub();
1180 my ($self, $formname) = @_;
1182 $formname ||= $self->{formname};
1184 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1185 local $::locale = Locale->new($self->{recipient_locale});
1188 $main::lxdebug->leave_sub();
1189 return $main::locale->text('Your Order');
1192 sub get_number_prefix_for_type {
1193 $main::lxdebug->enter_sub();
1197 (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1198 : ($self->{type} =~ /_quotation$/) ? 'quo'
1199 : ($self->{type} =~ /_delivery_order$/) ? 'do'
1200 : ($self->{type} =~ /letter/) ? 'letter'
1203 # better default like this?
1204 # : ($self->{type} =~ /(sales|purcharse)_order/ : 'ord';
1205 # : 'prefix_undefined';
1207 $main::lxdebug->leave_sub();
1211 sub get_extension_for_format {
1212 $main::lxdebug->enter_sub();
1215 my $extension = $self->{format} =~ /pdf/i ? ".pdf"
1216 : $self->{format} =~ /postscript/i ? ".ps"
1217 : $self->{format} =~ /opendocument/i ? ".odt"
1218 : $self->{format} =~ /excel/i ? ".xls"
1219 : $self->{format} =~ /html/i ? ".html"
1222 $main::lxdebug->leave_sub();
1226 sub generate_attachment_filename {
1227 $main::lxdebug->enter_sub();
1230 $self->{recipient_locale} ||= Locale->lang_to_locale($self->{language});
1231 my $recipient_locale = Locale->new($self->{recipient_locale});
1233 my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1234 my $prefix = $self->get_number_prefix_for_type();
1236 if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1237 $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
1239 } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1240 $attachment_filename .= "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1242 } elsif ($attachment_filename) {
1243 $attachment_filename .= $self->get_extension_for_format();
1246 $attachment_filename = "";
1249 $attachment_filename = $main::locale->quote_special_chars('filenames', $attachment_filename);
1250 $attachment_filename =~ s|[\s/\\]+|_|g;
1252 $main::lxdebug->leave_sub();
1253 return $attachment_filename;
1256 sub generate_email_subject {
1257 $main::lxdebug->enter_sub();
1260 my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1261 my $prefix = $self->get_number_prefix_for_type();
1263 if ($subject && $self->{"${prefix}number"}) {
1264 $subject .= " " . $self->{"${prefix}number"}
1267 if ($self->{cusordnumber}) {
1268 $subject = $self->get_cusordnumber_translation() . ' ' . $self->{cusordnumber} . ' / ' . $subject;
1271 $main::lxdebug->leave_sub();
1275 sub generate_email_body {
1276 $main::lxdebug->enter_sub();
1277 my ($self, %params) = @_;
1278 # simple german and english will work grammatically (most european languages as well)
1279 # Dear Mr Alan Greenspan:
1280 # Sehr geehrte Frau Meyer,
1281 # A l’attention de Mme Villeroy,
1282 # Gentile Signora Ferrari,
1285 if ($self->{cp_id} && !$params{record_email}) {
1286 my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
1287 my $name = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
1288 my $gender = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
1289 my $mf = $gender eq 'f' ? 'female' : 'male';
1290 $body = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
1291 $body .= ' ' . $givenname . ' ' . $name if $body;
1293 $body = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
1296 return undef unless $body;
1298 my $translation_type = $params{translation_type} // "preset_text_$self->{formname}";
1299 my $main_body = GenericTranslations->get(translation_type => $translation_type, language_id => $self->{language_id});
1300 $main_body = GenericTranslations->get(translation_type => $params{fallback_translation_type}, language_id => $self->{language_id}) if !$main_body && $params{fallback_translation_type};
1301 $body .= GenericTranslations->get(translation_type => "salutation_punctuation_mark", language_id => $self->{language_id}) . "\n\n";
1302 $body .= $main_body;
1304 $body = $main::locale->unquote_special_chars('HTML', $body);
1306 $main::lxdebug->leave_sub();
1311 $main::lxdebug->enter_sub();
1313 my ($self, $application) = @_;
1315 my $error_code = $?;
1317 chdir("$self->{tmpdir}");
1320 if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1321 push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1323 } elsif (-f "$self->{tmpfile}.err") {
1324 open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
1329 if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1330 $self->{tmpfile} =~ s|.*/||g;
1332 $self->{tmpfile} =~ s/\.\w+$//g;
1333 my $tmpfile = $self->{tmpfile};
1334 unlink(<$tmpfile.*>);
1337 chdir("$self->{cwd}");
1339 $main::lxdebug->leave_sub();
1345 $main::lxdebug->enter_sub();
1347 my ($self, $date, $myconfig) = @_;
1350 if ($date && $date =~ /\D/) {
1352 if ($myconfig->{dateformat} =~ /^yy/) {
1353 ($yy, $mm, $dd) = split /\D/, $date;
1355 if ($myconfig->{dateformat} =~ /^mm/) {
1356 ($mm, $dd, $yy) = split /\D/, $date;
1358 if ($myconfig->{dateformat} =~ /^dd/) {
1359 ($dd, $mm, $yy) = split /\D/, $date;
1364 $yy = ($yy < 70) ? $yy + 2000 : $yy;
1365 $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1367 $dd = "0$dd" if ($dd < 10);
1368 $mm = "0$mm" if ($mm < 10);
1370 $date = "$yy$mm$dd";
1373 $main::lxdebug->leave_sub();
1378 # Database routines used throughout
1379 # DB Handling got moved to SL::DB, these are only shims for compatibility
1382 SL::DB->client->dbh;
1385 sub get_standard_dbh {
1386 my $dbh = SL::DB->client->dbh;
1388 if ($dbh && !$dbh->{Active}) {
1389 $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
1390 SL::DB->client->dbh(undef);
1393 SL::DB->client->dbh;
1396 sub disconnect_standard_dbh {
1397 SL::DB->client->dbh->rollback;
1403 $main::lxdebug->enter_sub();
1405 my ($self, $date, $myconfig) = @_;
1406 my $dbh = $self->get_standard_dbh;
1408 my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1409 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1411 # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1412 # es ist sicher ein conv_date vorher IMMER auszuführen.
1413 # Testfälle ohne definiertes closedto:
1414 # Leere Datumseingabe i.O.
1415 # SELECT 1 FROM defaults WHERE '' < closedto
1416 # normale Zahlungsbuchung über Rechnungsmaske i.O.
1417 # SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1418 # Testfälle mit definiertem closedto (30.04.2011):
1419 # Leere Datumseingabe i.O.
1420 # SELECT 1 FROM defaults WHERE '' < closedto
1421 # normale Buchung im geschloßenem Zeitraum i.O.
1422 # SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1423 # Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1424 # normale Buchung in aktiver Buchungsperiode i.O.
1425 # SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1427 my ($closed) = $sth->fetchrow_array;
1429 $main::lxdebug->leave_sub();
1434 # prevents bookings to the to far away future
1435 sub date_max_future {
1436 $main::lxdebug->enter_sub();
1438 my ($self, $date, $myconfig) = @_;
1439 my $dbh = $self->get_standard_dbh;
1441 my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
1442 my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1444 my ($max_future_booking_interval) = $sth->fetchrow_array;
1446 $main::lxdebug->leave_sub();
1448 return $max_future_booking_interval;
1452 sub update_balance {
1453 $main::lxdebug->enter_sub();
1455 my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1457 # if we have a value, go do it
1460 # retrieve balance from table
1461 my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1462 my $sth = prepare_execute_query($self, $dbh, $query, @values);
1463 my ($balance) = $sth->fetchrow_array;
1469 $query = "UPDATE $table SET $field = $balance WHERE $where";
1470 do_query($self, $dbh, $query, @values);
1472 $main::lxdebug->leave_sub();
1475 sub update_exchangerate {
1476 $main::lxdebug->enter_sub();
1478 my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1480 # some sanity check for currency
1482 $main::lxdebug->leave_sub();
1485 $query = qq|SELECT name AS curr FROM currencies WHERE id=(SELECT currency_id FROM defaults)|;
1487 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1489 if ($curr eq $defaultcurrency) {
1490 $main::lxdebug->leave_sub();
1494 $query = qq|SELECT e.currency_id FROM exchangerate e
1495 WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
1497 my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1506 $buy = conv_i($buy, "NULL");
1507 $sell = conv_i($sell, "NULL");
1510 if ($buy != 0 && $sell != 0) {
1511 $set = "buy = $buy, sell = $sell";
1512 } elsif ($buy != 0) {
1513 $set = "buy = $buy";
1514 } elsif ($sell != 0) {
1515 $set = "sell = $sell";
1518 if ($sth->fetchrow_array) {
1519 $query = qq|UPDATE exchangerate
1521 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
1525 $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
1526 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
1529 do_query($self, $dbh, $query, $curr, $transdate);
1531 $main::lxdebug->leave_sub();
1534 sub save_exchangerate {
1535 $main::lxdebug->enter_sub();
1537 my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1539 SL::DB->client->with_transaction(sub {
1540 my $dbh = SL::DB->client->dbh;
1544 $buy = $rate if $fld eq 'buy';
1545 $sell = $rate if $fld eq 'sell';
1548 $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1550 }) or do { die SL::DB->client->error };
1552 $main::lxdebug->leave_sub();
1555 sub get_exchangerate {
1556 $main::lxdebug->enter_sub();
1558 my ($self, $dbh, $curr, $transdate, $fld) = @_;
1561 unless ($transdate && $curr) {
1562 $main::lxdebug->leave_sub();
1566 $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1568 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1570 if ($curr eq $defaultcurrency) {
1571 $main::lxdebug->leave_sub();
1575 $query = qq|SELECT e.$fld FROM exchangerate e
1576 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1577 my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1581 $main::lxdebug->leave_sub();
1583 return $exchangerate;
1586 sub check_exchangerate {
1587 $main::lxdebug->enter_sub();
1589 my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1591 if ($fld !~/^buy|sell$/) {
1592 $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1595 unless ($transdate) {
1596 $main::lxdebug->leave_sub();
1600 my ($defaultcurrency) = $self->get_default_currency($myconfig);
1602 if ($currency eq $defaultcurrency) {
1603 $main::lxdebug->leave_sub();
1607 my $dbh = $self->get_standard_dbh($myconfig);
1608 my $query = qq|SELECT e.$fld FROM exchangerate e
1609 WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1611 my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1613 $main::lxdebug->leave_sub();
1615 return $exchangerate;
1618 sub get_all_currencies {
1619 $main::lxdebug->enter_sub();
1622 my $myconfig = shift || \%::myconfig;
1623 my $dbh = $self->get_standard_dbh($myconfig);
1625 my $query = qq|SELECT name FROM currencies|;
1626 my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
1628 $main::lxdebug->leave_sub();
1633 sub get_default_currency {
1634 $main::lxdebug->enter_sub();
1636 my ($self, $myconfig) = @_;
1637 my $dbh = $self->get_standard_dbh($myconfig);
1638 my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1640 my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1642 $main::lxdebug->leave_sub();
1644 return $defaultcurrency;
1647 sub set_payment_options {
1648 my ($self, $myconfig, $transdate, $type) = @_;
1650 my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
1653 my $is_invoice = $type =~ m{invoice}i;
1655 $transdate ||= $self->{invdate} || $self->{transdate};
1656 my $due_date = $self->{duedate} || $self->{reqdate};
1658 $self->{$_} = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
1659 $self->{payment_description} = $terms->description;
1660 $self->{netto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
1661 $self->{skonto_date} = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
1663 my ($invtotal, $total);
1664 my (%amounts, %formatted_amounts);
1666 if ($self->{type} =~ /_order$/) {
1667 $amounts{invtotal} = $self->{ordtotal};
1668 $amounts{total} = $self->{ordtotal};
1670 } elsif ($self->{type} =~ /_quotation$/) {
1671 $amounts{invtotal} = $self->{quototal};
1672 $amounts{total} = $self->{quototal};
1675 $amounts{invtotal} = $self->{invtotal};
1676 $amounts{total} = $self->{total};
1678 map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1680 $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1681 $amounts{skonto_amount} = $amounts{invtotal} * $self->{percent_skonto};
1682 $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1683 $amounts{total_wo_skonto} = $amounts{total} * (1 - $self->{percent_skonto});
1685 foreach (keys %amounts) {
1686 $amounts{$_} = $self->round_amount($amounts{$_}, 2);
1687 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1690 if ($self->{"language_id"}) {
1691 my $language = SL::DB::Language->new(id => $self->{language_id})->load;
1693 $self->{payment_terms} = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
1694 $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
1696 if ($language->output_dateformat) {
1697 foreach my $key (qw(netto_date skonto_date)) {
1698 $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
1702 if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
1703 local $myconfig->{numberformat};
1704 $myconfig->{"numberformat"} = $language->output_numberformat;
1705 $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
1709 $self->{payment_terms} = $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
1711 $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1712 $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1713 $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1714 $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1715 $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1716 $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1717 $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1718 $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
1719 $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
1720 $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
1721 $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
1723 map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1725 $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1729 sub get_template_language {
1730 $main::lxdebug->enter_sub();
1732 my ($self, $myconfig) = @_;
1734 my $template_code = "";
1736 if ($self->{language_id}) {
1737 my $dbh = $self->get_standard_dbh($myconfig);
1738 my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1739 ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1742 $main::lxdebug->leave_sub();
1744 return $template_code;
1747 sub get_printer_code {
1748 $main::lxdebug->enter_sub();
1750 my ($self, $myconfig) = @_;
1752 my $template_code = "";
1754 if ($self->{printer_id}) {
1755 my $dbh = $self->get_standard_dbh($myconfig);
1756 my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1757 ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1760 $main::lxdebug->leave_sub();
1762 return $template_code;
1766 $main::lxdebug->enter_sub();
1768 my ($self, $myconfig) = @_;
1770 my $template_code = "";
1772 if ($self->{shipto_id}) {
1773 my $dbh = $self->get_standard_dbh($myconfig);
1774 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1775 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1776 map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1778 my $cvars = CVar->get_custom_variables(
1781 trans_id => $self->{shipto_id},
1783 $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
1786 $main::lxdebug->leave_sub();
1790 my ($self, $dbh, $id, $module) = @_;
1795 foreach my $item (qw(name department_1 department_2 street zipcode city country gln
1796 contact phone fax email)) {
1797 if ($self->{"shipto$item"}) {
1798 $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1800 push(@values, $self->{"shipto${item}"});
1805 # shiptocp_gender only makes sense, if any other shipto attribute is set.
1806 # Because shiptocp_gender is set to 'm' by default in forms
1807 # it must not be considered above to decide if shiptos has to be added or
1808 # updated, but must be inserted or updated as well in case.
1809 push(@values, $self->{shiptocp_gender});
1811 my $shipto_id = $self->{shipto_id};
1813 if ($self->{shipto_id}) {
1814 my $query = qq|UPDATE shipto set
1816 shiptodepartment_1 = ?,
1817 shiptodepartment_2 = ?,
1827 shiptocp_gender = ?,
1828 WHERE shipto_id = ?|;
1829 do_query($self, $dbh, $query, @values, $self->{shipto_id});
1831 my $query = qq|SELECT * FROM shipto
1832 WHERE shiptoname = ? AND
1833 shiptodepartment_1 = ? AND
1834 shiptodepartment_2 = ? AND
1835 shiptostreet = ? AND
1836 shiptozipcode = ? AND
1838 shiptocountry = ? AND
1840 shiptocontact = ? AND
1844 shiptocp_gender = ? AND
1847 my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1850 qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1851 shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
1852 shiptocontact, shiptophone, shiptofax, shiptoemail, shiptocp_gender, module)
1853 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1854 do_query($self, $dbh, $insert_query, $id, @values, $module);
1856 $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1859 $shipto_id = $insert_check->{shipto_id};
1862 return unless $shipto_id;
1864 CVar->save_custom_variables(
1867 trans_id => $shipto_id,
1869 name_prefix => 'shipto',
1874 $main::lxdebug->enter_sub();
1876 my ($self, $dbh) = @_;
1878 $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1880 my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1881 ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1882 $self->{"employee_id"} *= 1;
1884 $main::lxdebug->leave_sub();
1887 sub get_employee_data {
1888 $main::lxdebug->enter_sub();
1892 my $defaults = SL::DB::Default->get;
1894 Common::check_params(\%params, qw(prefix));
1895 Common::check_params_x(\%params, qw(id));
1898 $main::lxdebug->leave_sub();
1902 my $myconfig = \%main::myconfig;
1903 my $dbh = $params{dbh} || $self->get_standard_dbh($myconfig);
1905 my ($login, $deleted) = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
1908 # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
1909 $self->{$params{prefix} . '_login'} = $login;
1910 $self->{$params{prefix} . "_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
1913 # get employee data from auth.user_config
1914 my $user = User->new(login => $login);
1915 $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
1917 # get saved employee data from employee
1918 my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
1919 $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
1920 $self->{$params{prefix} . "_name"} = $employee->name;
1923 $main::lxdebug->leave_sub();
1927 $main::lxdebug->enter_sub();
1929 my ($self, $dbh, $id, $key) = @_;
1931 $key = "all_contacts" unless ($key);
1935 $main::lxdebug->leave_sub();
1940 qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1941 qq|FROM contacts | .
1942 qq|WHERE cp_cv_id = ? | .
1943 qq|ORDER BY lower(cp_name)|;
1945 $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1947 $main::lxdebug->leave_sub();
1951 $main::lxdebug->enter_sub();
1953 my ($self, $dbh, $key) = @_;
1955 my ($all, $old_id, $where, @values);
1957 if (ref($key) eq "HASH") {
1960 $key = "ALL_PROJECTS";
1962 foreach my $p (keys(%{$params})) {
1964 $all = $params->{$p};
1965 } elsif ($p eq "old_id") {
1966 $old_id = $params->{$p};
1967 } elsif ($p eq "key") {
1968 $key = $params->{$p};
1974 $where = "WHERE active ";
1976 if (ref($old_id) eq "ARRAY") {
1977 my @ids = grep({ $_ } @{$old_id});
1979 $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1980 push(@values, @ids);
1983 $where .= " OR (id = ?) ";
1984 push(@values, $old_id);
1990 qq|SELECT id, projectnumber, description, active | .
1993 qq|ORDER BY lower(projectnumber)|;
1995 $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1997 $main::lxdebug->leave_sub();
2001 $main::lxdebug->enter_sub();
2003 my ($self, $dbh, $key) = @_;
2005 $key = "all_printers" unless ($key);
2007 my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2009 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2011 $main::lxdebug->leave_sub();
2015 $main::lxdebug->enter_sub();
2017 my ($self, $dbh, $params) = @_;
2020 $key = $params->{key};
2021 $key = "all_charts" unless ($key);
2023 my $transdate = quote_db_date($params->{transdate});
2026 qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2028 qq|LEFT JOIN taxkeys tk ON | .
2029 qq|(tk.id = (SELECT id FROM taxkeys | .
2030 qq| WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2031 qq| ORDER BY startdate DESC LIMIT 1)) | .
2032 qq|ORDER BY c.accno|;
2034 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2036 $main::lxdebug->leave_sub();
2040 $main::lxdebug->enter_sub();
2042 my ($self, $dbh, $key) = @_;
2044 $key = "all_taxzones" unless ($key);
2046 $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
2048 my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
2050 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2052 $main::lxdebug->leave_sub();
2055 sub _get_employees {
2056 $main::lxdebug->enter_sub();
2058 my ($self, $dbh, $params) = @_;
2063 if (ref $params eq 'HASH') {
2064 $key = $params->{key};
2065 $deleted = $params->{deleted};
2071 $key ||= "all_employees";
2072 my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
2073 $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
2075 $main::lxdebug->leave_sub();
2078 sub _get_business_types {
2079 $main::lxdebug->enter_sub();
2081 my ($self, $dbh, $key) = @_;
2083 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2084 $options->{key} ||= "all_business_types";
2087 if (exists $options->{salesman}) {
2088 $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2091 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2093 $main::lxdebug->leave_sub();
2096 sub _get_languages {
2097 $main::lxdebug->enter_sub();
2099 my ($self, $dbh, $key) = @_;
2101 $key = "all_languages" unless ($key);
2103 my $query = qq|SELECT * FROM language ORDER BY id|;
2105 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2107 $main::lxdebug->leave_sub();
2110 sub _get_dunning_configs {
2111 $main::lxdebug->enter_sub();
2113 my ($self, $dbh, $key) = @_;
2115 $key = "all_dunning_configs" unless ($key);
2117 my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2119 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2121 $main::lxdebug->leave_sub();
2124 sub _get_currencies {
2125 $main::lxdebug->enter_sub();
2127 my ($self, $dbh, $key) = @_;
2129 $key = "all_currencies" unless ($key);
2131 $self->{$key} = [$self->get_all_currencies()];
2133 $main::lxdebug->leave_sub();
2137 $main::lxdebug->enter_sub();
2139 my ($self, $dbh, $key) = @_;
2141 $key = "all_payments" unless ($key);
2143 my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2145 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2147 $main::lxdebug->leave_sub();
2150 sub _get_customers {
2151 $main::lxdebug->enter_sub();
2153 my ($self, $dbh, $key) = @_;
2155 my $options = ref $key eq 'HASH' ? $key : { key => $key };
2156 $options->{key} ||= "all_customers";
2157 my $limit_clause = $options->{limit} ? "LIMIT $options->{limit}" : '';
2160 push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if $options->{business_is_salesman};
2161 push @where, qq|NOT obsolete| if !$options->{with_obsolete};
2162 my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2164 my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2165 $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2167 $main::lxdebug->leave_sub();
2171 $main::lxdebug->enter_sub();
2173 my ($self, $dbh, $key) = @_;
2175 $key = "all_vendors" unless ($key);
2177 my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2179 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2181 $main::lxdebug->leave_sub();
2184 sub _get_departments {
2185 $main::lxdebug->enter_sub();
2187 my ($self, $dbh, $key) = @_;
2189 $key = "all_departments" unless ($key);
2191 my $query = qq|SELECT * FROM department ORDER BY description|;
2193 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2195 $main::lxdebug->leave_sub();
2198 sub _get_warehouses {
2199 $main::lxdebug->enter_sub();
2201 my ($self, $dbh, $param) = @_;
2203 my ($key, $bins_key);
2205 if ('' eq ref $param) {
2209 $key = $param->{key};
2210 $bins_key = $param->{bins};
2213 my $query = qq|SELECT w.* FROM warehouse w
2214 WHERE (NOT w.invalid) AND
2215 ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2216 ORDER BY w.sortkey|;
2218 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2221 $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2222 ORDER BY description|;
2223 my $sth = prepare_query($self, $dbh, $query);
2225 foreach my $warehouse (@{ $self->{$key} }) {
2226 do_statement($self, $sth, $query, $warehouse->{id});
2227 $warehouse->{$bins_key} = [];
2229 while (my $ref = $sth->fetchrow_hashref()) {
2230 push @{ $warehouse->{$bins_key} }, $ref;
2236 $main::lxdebug->leave_sub();
2240 $main::lxdebug->enter_sub();
2242 my ($self, $dbh, $table, $key, $sortkey) = @_;
2244 my $query = qq|SELECT * FROM $table|;
2245 $query .= qq| ORDER BY $sortkey| if ($sortkey);
2247 $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2249 $main::lxdebug->leave_sub();
2253 $main::lxdebug->enter_sub();
2258 croak "get_lists: shipto is no longer supported" if $params{shipto};
2260 my $dbh = $self->get_standard_dbh(\%main::myconfig);
2261 my ($sth, $query, $ref);
2264 if ($params{contacts}) {
2265 $vc = 'customer' if $self->{"vc"} eq "customer";
2266 $vc = 'vendor' if $self->{"vc"} eq "vendor";
2267 die "invalid use of get_lists, need 'vc'" unless $vc;
2268 $vc_id = $self->{"${vc}_id"};
2271 if ($params{"contacts"}) {
2272 $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2275 if ($params{"projects"} || $params{"all_projects"}) {
2276 $self->_get_projects($dbh, $params{"all_projects"} ?
2277 $params{"all_projects"} : $params{"projects"},
2278 $params{"all_projects"} ? 1 : 0);
2281 if ($params{"printers"}) {
2282 $self->_get_printers($dbh, $params{"printers"});
2285 if ($params{"languages"}) {
2286 $self->_get_languages($dbh, $params{"languages"});
2289 if ($params{"charts"}) {
2290 $self->_get_charts($dbh, $params{"charts"});
2293 if ($params{"taxzones"}) {
2294 $self->_get_taxzones($dbh, $params{"taxzones"});
2297 if ($params{"employees"}) {
2298 $self->_get_employees($dbh, $params{"employees"});
2301 if ($params{"salesmen"}) {
2302 $self->_get_employees($dbh, $params{"salesmen"});
2305 if ($params{"business_types"}) {
2306 $self->_get_business_types($dbh, $params{"business_types"});
2309 if ($params{"dunning_configs"}) {
2310 $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2313 if($params{"currencies"}) {
2314 $self->_get_currencies($dbh, $params{"currencies"});
2317 if($params{"customers"}) {
2318 $self->_get_customers($dbh, $params{"customers"});
2321 if($params{"vendors"}) {
2322 if (ref $params{"vendors"} eq 'HASH') {
2323 $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2325 $self->_get_vendors($dbh, $params{"vendors"});
2329 if($params{"payments"}) {
2330 $self->_get_payments($dbh, $params{"payments"});
2333 if($params{"departments"}) {
2334 $self->_get_departments($dbh, $params{"departments"});
2337 if ($params{price_factors}) {
2338 $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2341 if ($params{warehouses}) {
2342 $self->_get_warehouses($dbh, $params{warehouses});
2345 if ($params{partsgroup}) {
2346 $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2349 $main::lxdebug->leave_sub();
2352 # this sub gets the id and name from $table
2354 $main::lxdebug->enter_sub();
2356 my ($self, $myconfig, $table) = @_;
2358 # connect to database
2359 my $dbh = $self->get_standard_dbh($myconfig);
2361 $table = $table eq "customer" ? "customer" : "vendor";
2362 my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2364 my ($query, @values);
2366 if (!$self->{openinvoices}) {
2368 if ($self->{customernumber} ne "") {
2369 $where = qq|(vc.customernumber ILIKE ?)|;
2370 push(@values, like($self->{customernumber}));
2372 $where = qq|(vc.name ILIKE ?)|;
2373 push(@values, like($self->{$table}));
2377 qq~SELECT vc.id, vc.name,
2378 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2380 WHERE $where AND (NOT vc.obsolete)
2384 qq~SELECT DISTINCT vc.id, vc.name,
2385 vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2387 JOIN $table vc ON (a.${table}_id = vc.id)
2388 WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2390 push(@values, like($self->{$table}));
2393 $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2395 $main::lxdebug->leave_sub();
2397 return scalar(@{ $self->{name_list} });
2402 my ($self, $table, $provided_dbh) = @_;
2404 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
2405 return unless $self->{id};
2406 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2408 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2409 my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2410 $ref->{mtime} ||= $ref->{itime};
2411 $self->{lastmtime} = $ref->{mtime};
2415 sub mtime_ischanged {
2416 my ($self, $table, $option) = @_;
2418 return unless $self->{id};
2419 croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2421 my $query = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2422 my $ref = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
2423 $ref->{mtime} ||= $ref->{itime};
2425 if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
2426 $self->error(($option eq 'mail') ?
2427 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") :
2428 t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
2430 $::dispatcher->end_request;
2434 # language_payment duplicates some of the functionality of all_vc (language,
2435 # printer, payment_terms), and at least in the case of sales invoices both
2436 # all_vc and language_payment are called when adding new invoices
2437 sub language_payment {
2438 $main::lxdebug->enter_sub();
2440 my ($self, $myconfig) = @_;
2442 my $dbh = $self->get_standard_dbh($myconfig);
2444 my $query = qq|SELECT id, description
2448 $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2451 $query = qq|SELECT printer_description, id
2453 ORDER BY printer_description|;
2455 $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2458 $query = qq|SELECT id, description
2460 WHERE ( obsolete IS FALSE OR id = ? )
2462 $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
2464 # get buchungsgruppen
2465 $query = qq|SELECT id, description
2466 FROM buchungsgruppen|;
2468 $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2470 $main::lxdebug->leave_sub();
2473 # this is only used for reports
2474 sub all_departments {
2475 $main::lxdebug->enter_sub();
2477 my ($self, $myconfig, $table) = @_;
2479 my $dbh = $self->get_standard_dbh($myconfig);
2481 my $query = qq|SELECT id, description
2483 ORDER BY description|;
2484 $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2486 delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2488 $main::lxdebug->leave_sub();
2492 $main::lxdebug->enter_sub();
2494 my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2497 if ($table eq "customer") {
2506 # get last customers or vendors
2507 my ($query, $sth, $ref);
2509 my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2514 my $transdate = "current_date";
2515 if ($self->{transdate}) {
2516 $transdate = $dbh->quote($self->{transdate});
2519 # now get the account numbers
2521 SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
2523 -- find newest entries in taxkeys
2525 SELECT chart_id, MAX(startdate) AS startdate
2527 WHERE (startdate <= $transdate)
2529 ) tk ON (c.id = tk.chart_id)
2530 -- and load all of those entries
2531 INNER JOIN taxkeys tk2
2532 ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
2533 WHERE (c.link LIKE ?)
2536 $sth = $dbh->prepare($query);
2538 do_statement($self, $sth, $query, like($module));
2540 $self->{accounts} = "";
2541 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2543 foreach my $key (split(/:/, $ref->{link})) {
2544 if ($key =~ /\Q$module\E/) {
2546 # cross reference for keys
2547 $xkeyref{ $ref->{accno} } = $key;
2549 push @{ $self->{"${module}_links"}{$key} },
2550 { accno => $ref->{accno},
2551 chart_id => $ref->{chart_id},
2552 description => $ref->{description},
2553 taxkey => $ref->{taxkey_id},
2554 tax_id => $ref->{tax_id} };
2556 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2562 # get taxkeys and description
2563 $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2564 $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2566 if (($module eq "AP") || ($module eq "AR")) {
2567 # get tax rates and description
2568 $query = qq|SELECT * FROM tax|;
2569 $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2572 my $extra_columns = '';
2573 $extra_columns .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
2578 a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid, a.deliverydate,
2579 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,
2581 a.intnotes, a.department_id, a.amount AS oldinvtotal,
2582 a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2583 a.globalproject_id, ${extra_columns}
2585 d.description AS department,
2588 JOIN $table c ON (a.${table}_id = c.id)
2589 LEFT JOIN employee e ON (e.id = a.employee_id)
2590 LEFT JOIN department d ON (d.id = a.department_id)
2592 $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2594 foreach my $key (keys %$ref) {
2595 $self->{$key} = $ref->{$key};
2597 $self->{mtime} ||= $self->{itime};
2598 $self->{lastmtime} = $self->{mtime};
2599 my $transdate = "current_date";
2600 if ($self->{transdate}) {
2601 $transdate = $dbh->quote($self->{transdate});
2604 # now get the account numbers
2605 $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
2607 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2609 AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2610 OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2613 $sth = $dbh->prepare($query);
2614 do_statement($self, $sth, $query, like($module));
2616 $self->{accounts} = "";
2617 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2619 foreach my $key (split(/:/, $ref->{link})) {
2620 if ($key =~ /\Q$module\E/) {
2622 # cross reference for keys
2623 $xkeyref{ $ref->{accno} } = $key;
2625 push @{ $self->{"${module}_links"}{$key} },
2626 { accno => $ref->{accno},
2627 chart_id => $ref->{chart_id},
2628 description => $ref->{description},
2629 taxkey => $ref->{taxkey_id},
2630 tax_id => $ref->{tax_id} };
2632 $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2638 # get amounts from individual entries
2641 c.accno, c.description,
2642 a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
2646 LEFT JOIN chart c ON (c.id = a.chart_id)
2647 LEFT JOIN project p ON (p.id = a.project_id)
2648 LEFT JOIN tax t ON (t.id= a.tax_id)
2649 WHERE a.trans_id = ?
2650 AND a.fx_transaction = '0'
2651 ORDER BY a.acc_trans_id, a.transdate|;
2652 $sth = $dbh->prepare($query);
2653 do_statement($self, $sth, $query, $self->{id});
2655 # get exchangerate for currency
2656 $self->{exchangerate} =
2657 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2660 # store amounts in {acc_trans}{$key} for multiple accounts
2661 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2662 $ref->{exchangerate} =
2663 $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2664 if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2667 if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2668 $ref->{amount} *= -1;
2670 $ref->{index} = $index;
2672 push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2679 d.closedto, d.revtrans,
2680 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2681 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2682 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2683 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2684 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2686 $ref = selectfirst_hashref_query($self, $dbh, $query);
2687 map { $self->{$_} = $ref->{$_} } keys %$ref;
2694 current_date AS transdate, d.closedto, d.revtrans,
2695 (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2696 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2697 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2698 (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2699 (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2701 $ref = selectfirst_hashref_query($self, $dbh, $query);
2702 map { $self->{$_} = $ref->{$_} } keys %$ref;
2704 if ($self->{"$self->{vc}_id"}) {
2706 # only setup currency
2707 ($self->{currency}) = $self->{defaultcurrency} if !$self->{currency};
2711 $self->lastname_used($dbh, $myconfig, $table, $module);
2713 # get exchangerate for currency
2714 $self->{exchangerate} =
2715 $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2721 $main::lxdebug->leave_sub();
2725 $main::lxdebug->enter_sub();
2727 my ($self, $dbh, $myconfig, $table, $module) = @_;
2731 $table = $table eq "customer" ? "customer" : "vendor";
2732 my %column_map = ("a.${table}_id" => "${table}_id",
2733 "a.department_id" => "department_id",
2734 "d.description" => "department",
2735 "ct.name" => $table,
2736 "cu.name" => "currency",
2739 if ($self->{type} =~ /delivery_order/) {
2740 $arap = 'delivery_orders';
2741 delete $column_map{"cu.currency"};
2743 } elsif ($self->{type} =~ /_order/) {
2745 $where = "quotation = '0'";
2747 } elsif ($self->{type} =~ /_quotation/) {
2749 $where = "quotation = '1'";
2751 } elsif ($table eq 'customer') {
2759 $where = "($where) AND" if ($where);
2760 my $query = qq|SELECT MAX(id) FROM $arap
2761 WHERE $where ${table}_id > 0|;
2762 my ($trans_id) = selectrow_query($self, $dbh, $query);
2765 my $column_spec = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2766 $query = qq|SELECT $column_spec
2768 LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2769 LEFT JOIN department d ON (a.department_id = d.id)
2770 LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
2772 my $ref = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2774 map { $self->{$_} = $ref->{$_} } values %column_map;
2776 $main::lxdebug->leave_sub();
2779 sub get_variable_content_types {
2780 my %html_variables = (
2781 longdescription => 'html',
2782 partnotes => 'html',
2784 orignotes => 'html',
2789 header_text => 'html',
2790 footer_text => 'html',
2792 return \%html_variables;
2796 $main::lxdebug->enter_sub();
2799 my $myconfig = shift || \%::myconfig;
2800 my ($thisdate, $days) = @_;
2802 my $dbh = $self->get_standard_dbh($myconfig);
2807 my $dateformat = $myconfig->{dateformat};
2808 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2809 $thisdate = $dbh->quote($thisdate);
2810 $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2812 $query = qq|SELECT current_date AS thisdate|;
2815 ($thisdate) = selectrow_query($self, $dbh, $query);
2817 $main::lxdebug->leave_sub();
2823 $main::lxdebug->enter_sub();
2825 my ($self, $flds, $new, $count, $numrows) = @_;
2829 map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2834 foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2836 my $j = $item->{ndx} - 1;
2837 map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2841 for $i ($count + 1 .. $numrows) {
2842 map { delete $self->{"${_}_$i"} } @{$flds};
2845 $main::lxdebug->leave_sub();
2849 $main::lxdebug->enter_sub();
2851 my ($self, $myconfig) = @_;
2855 SL::DB->client->with_transaction(sub {
2856 my $dbh = SL::DB->client->dbh;
2858 my $query = qq|DELETE FROM status
2859 WHERE (formname = ?) AND (trans_id = ?)|;
2860 my $sth = prepare_query($self, $dbh, $query);
2862 if ($self->{formname} =~ /(check|receipt)/) {
2863 for $i (1 .. $self->{rowcount}) {
2864 do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2867 do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2871 my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2872 my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2874 my %queued = split / /, $self->{queued};
2877 if ($self->{formname} =~ /(check|receipt)/) {
2879 # this is a check or receipt, add one entry for each lineitem
2880 my ($accno) = split /--/, $self->{account};
2881 $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2882 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2883 @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2884 $sth = prepare_query($self, $dbh, $query);
2886 for $i (1 .. $self->{rowcount}) {
2887 if ($self->{"checked_$i"}) {
2888 do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2894 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2895 VALUES (?, ?, ?, ?, ?)|;
2896 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2897 $queued{$self->{formname}}, $self->{formname});
2900 }) or do { die SL::DB->client->error };
2902 $main::lxdebug->leave_sub();
2906 $main::lxdebug->enter_sub();
2908 my ($self, $dbh) = @_;
2910 my ($query, $printed, $emailed);
2912 my $formnames = $self->{printed};
2913 my $emailforms = $self->{emailed};
2915 $query = qq|DELETE FROM status
2916 WHERE (formname = ?) AND (trans_id = ?)|;
2917 do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2919 # this only applies to the forms
2920 # checks and receipts are posted when printed or queued
2922 if ($self->{queued}) {
2923 my %queued = split / /, $self->{queued};
2925 foreach my $formname (keys %queued) {
2926 $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2927 $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2929 $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2930 VALUES (?, ?, ?, ?, ?)|;
2931 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2933 $formnames =~ s/\Q$self->{formname}\E//;
2934 $emailforms =~ s/\Q$self->{formname}\E//;
2939 # save printed, emailed info
2940 $formnames =~ s/^ +//g;
2941 $emailforms =~ s/^ +//g;
2944 map { $status{$_}{printed} = 1 } split / +/, $formnames;
2945 map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2947 foreach my $formname (keys %status) {
2948 $printed = ($formnames =~ /\Q$self->{formname}\E/) ? "1" : "0";
2949 $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
2951 $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2952 VALUES (?, ?, ?, ?)|;
2953 do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2956 $main::lxdebug->leave_sub();
2960 # $main::locale->text('SAVED')
2961 # $main::locale->text('SCREENED')
2962 # $main::locale->text('DELETED')
2963 # $main::locale->text('ADDED')
2964 # $main::locale->text('PAYMENT POSTED')
2965 # $main::locale->text('POSTED')
2966 # $main::locale->text('POSTED AS NEW')
2967 # $main::locale->text('ELSE')
2968 # $main::locale->text('SAVED FOR DUNNING')
2969 # $main::locale->text('DUNNING STARTED')
2970 # $main::locale->text('PREVIEWED')
2971 # $main::locale->text('PRINTED')
2972 # $main::locale->text('MAILED')
2973 # $main::locale->text('SCREENED')
2974 # $main::locale->text('CANCELED')
2975 # $main::locale->text('IMPORT')
2976 # $main::locale->text('UNDO TRANSFER')
2977 # $main::locale->text('UNIMPORT')
2978 # $main::locale->text('invoice')
2979 # $main::locale->text('proforma')
2980 # $main::locale->text('sales_order')
2981 # $main::locale->text('pick_list')
2982 # $main::locale->text('purchase_order')
2983 # $main::locale->text('bin_list')
2984 # $main::locale->text('sales_quotation')
2985 # $main::locale->text('request_quotation')
2988 $main::lxdebug->enter_sub();
2991 my $dbh = shift || SL::DB->client->dbh;
2992 SL::DB->client->with_transaction(sub {
2994 if(!exists $self->{employee_id}) {
2995 &get_employee($self, $dbh);
2999 qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3000 qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3001 my @values = (conv_i($self->{id}), $self->{login},
3002 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3003 do_query($self, $dbh, $query, @values);
3005 }) or do { die SL::DB->client->error };
3007 $main::lxdebug->leave_sub();
3011 $main::lxdebug->enter_sub();
3013 my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3014 my ($orderBy, $desc) = split(/\-\-/, $order);
3015 $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3018 if ($trans_id ne "") {
3020 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 | .
3021 qq|FROM history_erp h | .
3022 qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3023 qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3026 my $sth = $dbh->prepare($query) || $self->dberror($query);
3028 $sth->execute() || $self->dberror("$query");
3030 while(my $hash_ref = $sth->fetchrow_hashref()) {
3031 $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3032 $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3033 my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
3034 $hash_ref->{snumbers} = $number;
3035 $hash_ref->{haslink} = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
3036 $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
3037 $tempArray[$i++] = $hash_ref;
3039 $main::lxdebug->leave_sub() and return \@tempArray
3040 if ($i > 0 && $tempArray[0] ne "");
3042 $main::lxdebug->leave_sub();
3046 sub get_partsgroup {
3047 $main::lxdebug->enter_sub();
3049 my ($self, $myconfig, $p) = @_;
3050 my $target = $p->{target} || 'all_partsgroup';
3052 my $dbh = $self->get_standard_dbh($myconfig);
3054 my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3056 JOIN parts p ON (p.partsgroup_id = pg.id) |;
3059 if ($p->{searchitems} eq 'part') {
3060 $query .= qq|WHERE p.part_type = 'part'|;
3062 if ($p->{searchitems} eq 'service') {
3063 $query .= qq|WHERE p.part_type = 'service'|;
3065 if ($p->{searchitems} eq 'assembly') {
3066 $query .= qq|WHERE p.part_type = 'assembly'|;
3069 $query .= qq|ORDER BY partsgroup|;
3072 $query = qq|SELECT id, partsgroup FROM partsgroup
3073 ORDER BY partsgroup|;
3076 if ($p->{language_code}) {
3077 $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3078 t.description AS translation
3080 JOIN parts p ON (p.partsgroup_id = pg.id)
3081 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3082 ORDER BY translation|;
3083 @values = ($p->{language_code});
3086 $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3088 $main::lxdebug->leave_sub();
3091 sub get_pricegroup {
3092 $main::lxdebug->enter_sub();
3094 my ($self, $myconfig, $p) = @_;
3096 my $dbh = $self->get_standard_dbh($myconfig);
3098 my $query = qq|SELECT p.id, p.pricegroup
3101 $query .= qq| ORDER BY pricegroup|;
3104 $query = qq|SELECT id, pricegroup FROM pricegroup
3105 ORDER BY pricegroup|;
3108 $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3110 $main::lxdebug->leave_sub();
3114 # usage $form->all_years($myconfig, [$dbh])
3115 # return list of all years where bookings found
3118 $main::lxdebug->enter_sub();
3120 my ($self, $myconfig, $dbh) = @_;
3122 $dbh ||= $self->get_standard_dbh($myconfig);
3125 my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3126 (SELECT MAX(transdate) FROM acc_trans)|;
3127 my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3129 if ($myconfig->{dateformat} =~ /^yy/) {
3130 ($startdate) = split /\W/, $startdate;
3131 ($enddate) = split /\W/, $enddate;
3133 (@_) = split /\W/, $startdate;
3135 (@_) = split /\W/, $enddate;
3140 $startdate = substr($startdate,0,4);
3141 $enddate = substr($enddate,0,4);
3143 while ($enddate >= $startdate) {
3144 push @all_years, $enddate--;
3149 $main::lxdebug->leave_sub();
3153 $main::lxdebug->enter_sub();
3157 map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3159 $main::lxdebug->leave_sub();
3163 $main::lxdebug->enter_sub();
3168 map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3170 $main::lxdebug->leave_sub();
3173 sub prepare_for_printing {
3176 my $defaults = SL::DB::Default->get;
3178 $self->{templates} ||= $defaults->templates;
3179 $self->{formname} ||= $self->{type};
3180 $self->{media} ||= 'email';
3182 die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3184 # Several fields that used to reside in %::myconfig (stored in
3185 # auth.user_config) are now stored in defaults. Copy them over for
3187 $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
3189 $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
3191 if (!$self->{employee_id}) {
3192 $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
3193 $self->{"employee_${_}"} = $defaults->$_ for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
3196 my $language = $self->{language} ? '_' . $self->{language} : '';
3198 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3199 if ($self->{language_id}) {
3200 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3203 $output_dateformat ||= $::myconfig{dateformat};
3204 $output_numberformat ||= $::myconfig{numberformat};
3205 $output_longdates //= 1;
3207 $self->{myconfig_output_dateformat} = $output_dateformat // $::myconfig{dateformat};
3208 $self->{myconfig_output_longdates} = $output_longdates // 1;
3209 $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
3211 # Retrieve accounts for tax calculation.
3212 IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3214 if ($self->{type} =~ /_delivery_order$/) {
3215 DO->order_details(\%::myconfig, $self);
3216 } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3217 OE->order_details(\%::myconfig, $self);
3219 IS->invoice_details(\%::myconfig, $self, $::locale);
3222 # Chose extension & set source file name
3223 my $extension = 'html';
3224 if ($self->{format} eq 'postscript') {
3225 $self->{postscript} = 1;
3227 } elsif ($self->{"format"} =~ /pdf/) {
3229 $extension = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3230 } elsif ($self->{"format"} =~ /opendocument/) {
3231 $self->{opendocument} = 1;
3233 } elsif ($self->{"format"} =~ /excel/) {
3238 my $printer_code = $self->{printer_code} ? '_' . $self->{printer_code} : '';
3239 my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
3240 $self->{IN} = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3243 $self->format_dates($output_dateformat, $output_longdates,
3244 qw(invdate orddate quodate pldate duedate reqdate transdate tax_point shippingdate deliverydate validitydate paymentdate datepaid
3245 transdate_oe deliverydate_oe employee_startdate employee_enddate),
3246 grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3248 $self->reformat_numbers($output_numberformat, 2,
3249 qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3250 grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3252 $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3254 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3256 if (scalar @{ $cvar_date_fields }) {
3257 $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3260 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3261 $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3265 if (($self->{language} // '') ne '') {
3266 my $template_arrays = $self->{TEMPLATE_ARRAYS} || $self;
3267 for my $idx (0..scalar(@{ $template_arrays->{unit} }) - 1) {
3268 $template_arrays->{unit}->[$idx] = AM->translate_units($self, $self->{language}, $template_arrays->{unit}->[$idx], $template_arrays->{qty}->[$idx])
3272 $self->{template_meta} = {
3273 formname => $self->{formname},
3274 language => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
3275 format => $self->{format},
3276 media => $self->{media},
3277 extension => $extension,
3278 printer => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
3279 today => DateTime->today,
3285 sub calculate_arap {
3286 my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
3288 # this function is used to calculate netamount, total_tax and amount for AP and
3289 # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
3291 # Thus it needs a fully prepared $form to work on.
3292 # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
3294 # The calculated total values are all rounded (default is to 2 places) and
3295 # returned as parameters rather than directly modifying form. The aim is to
3296 # make the calculation of AP and AR behave identically. There is a test-case
3297 # for this function in t/form/arap.t
3299 # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
3300 # modified and formatted and receive the correct sign for writing straight to
3301 # acc_trans, depending on whether they are ar or ap.
3304 die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
3305 die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
3306 die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
3307 $roundplaces = 2 unless $roundplaces;
3309 my $sign = 1; # adjust final results for writing amount to acc_trans
3310 $sign = -1 if $buysell eq 'buy';
3312 my ($netamount,$total_tax,$amount);
3316 # parse and round amounts, setting correct sign for writing to acc_trans
3317 for my $i (1 .. $self->{rowcount}) {
3318 $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
3320 $amount += $self->{"amount_$i"} * $sign;
3323 for my $i (1 .. $self->{rowcount}) {
3324 next unless $self->{"amount_$i"};
3325 ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
3326 my $tax_id = $self->{"tax_id_$i"};
3328 my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
3330 if ( $selected_tax ) {
3332 if ( $buysell eq 'sell' ) {
3333 $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3335 $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3338 $self->{"taxkey_$i"} = $selected_tax->taxkey;
3339 $self->{"taxrate_$i"} = $selected_tax->rate;
3342 ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
3344 $netamount += $self->{"amount_$i"};
3345 $total_tax += $self->{"tax_$i"};
3348 $amount = $netamount + $total_tax;
3350 # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
3351 # but reverse sign of totals for writing amounts to ar
3352 if ( $buysell eq 'buy' ) {
3358 return($netamount,$total_tax,$amount);
3362 my ($self, $dateformat, $longformat, @indices) = @_;
3364 $dateformat ||= $::myconfig{dateformat};
3366 foreach my $idx (@indices) {
3367 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3368 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3369 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3373 next unless defined $self->{$idx};
3375 if (!ref($self->{$idx})) {
3376 $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3378 } elsif (ref($self->{$idx}) eq "ARRAY") {
3379 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3380 $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3386 sub reformat_numbers {
3387 my ($self, $numberformat, $places, @indices) = @_;
3389 return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3391 foreach my $idx (@indices) {
3392 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3393 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3394 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3398 next unless defined $self->{$idx};
3400 if (!ref($self->{$idx})) {
3401 $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3403 } elsif (ref($self->{$idx}) eq "ARRAY") {
3404 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3405 $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3410 my $saved_numberformat = $::myconfig{numberformat};
3411 $::myconfig{numberformat} = $numberformat;
3413 foreach my $idx (@indices) {
3414 if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3415 for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3416 $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3420 next unless defined $self->{$idx};
3422 if (!ref($self->{$idx})) {
3423 $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3425 } elsif (ref($self->{$idx}) eq "ARRAY") {
3426 for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3427 $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3432 $::myconfig{numberformat} = $saved_numberformat;
3435 sub create_email_signature {
3437 my $client_signature = $::instance_conf->get_signature;
3438 my $user_signature = $::myconfig{signature};
3441 if ( $client_signature or $user_signature ) {
3442 $signature = "\n\n-- \n";
3443 $signature .= $user_signature . "\n" if $user_signature;
3444 $signature .= $client_signature . "\n" if $client_signature;
3451 # this function calculates the net amount and tax for the lines in ar, ap and
3452 # gl and is used for update as well as post. When used with update the return
3453 # value of amount isn't needed
3455 # calculate_tax should always work with positive values, or rather as the user inputs them
3456 # calculate_tax uses db/perl numberformat, i.e. parsed numbers
3457 # convert to negative numbers (when necessary) only when writing to acc_trans
3458 # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
3459 # for post_transaction amount already contains exchangerate and correct sign and is rounded
3460 # calculate_tax doesn't (need to) know anything about exchangerate
3462 my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
3470 # calculate tax (unrounded), subtract from amount, round amount and round tax
3471 $tax = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
3472 $amount = $self->round_amount($amount - $tax, $roundplaces);
3473 $tax = $self->round_amount($tax, $roundplaces);
3475 $tax = $amount * $taxrate;
3476 $tax = $self->round_amount($tax, $roundplaces);
3479 $tax = 0 unless $tax;
3481 return ($amount,$tax);
3490 SL::Form.pm - main data object.
3494 This is the main data object of kivitendo.
3495 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3496 Points of interest for a beginner are:
3498 - $form->error - renders a generic error in html. accepts an error message
3499 - $form->get_standard_dbh - returns a database connection for the
3501 =head1 SPECIAL FUNCTIONS
3503 =head2 C<redirect_header> $url
3505 Generates a HTTP redirection header for the new C<$url>. Constructs an
3506 absolute URL including scheme, host name and port. If C<$url> is a
3507 relative URL then it is considered relative to kivitendo base URL.
3509 This function C<die>s if headers have already been created with
3510 C<$::form-E<gt>header>.
3514 print $::form->redirect_header('oe.pl?action=edit&id=1234');
3515 print $::form->redirect_header('http://www.lx-office.org/');
3519 Generates a general purpose http/html header and includes most of the scripts
3520 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3522 Only one header will be generated. If the method was already called in this
3523 request it will not output anything and return undef. Also if no
3524 HTTP_USER_AGENT is found, no header is generated.
3526 Although header does not accept parameters itself, it will honor special
3527 hashkeys of its Form instance:
3535 If one of these is set, a http-equiv refresh is generated. Missing parameters
3536 default to 3 seconds and the refering url.
3540 Either a scalar or an array ref. Will be inlined into the header. Add
3541 stylesheets with the L<use_stylesheet> function.
3545 If true, a css snippet will be generated that sets the page in landscape mode.
3549 Used to override the default favicon.
3553 A html page title will be generated from this
3555 =item mtime_ischanged
3557 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
3559 Can be used / called with any table, that has itime and mtime attributes.
3560 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
3561 Can be called wit C<option> mail to generate a different error message.
3563 Returns undef if no save operation has been done yet ($self->{id} not present).
3564 Returns undef if no concurrent write process is detected otherwise a error message.