TopQuickSearch für den Benutzer konfigurierbar gemacht.
[kivitendo-erp.git] / SL / Form.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 # Contributors: Thomas Bayen <bayen@gmx.de>
16 #               Antti Kaihola <akaihola@siba.fi>
17 #               Moritz Bunkus (tex code)
18 #
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.
23 #
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,
31 # MA 02110-1335, USA.
32 #======================================================================
33 # Utilities for parsing forms
34 # and supporting routines for linking account numbers
35 # used in AR, AP and IS, IR modules
36 #
37 #======================================================================
38
39 package Form;
40
41 use Carp;
42 use Data::Dumper;
43
44 use Carp;
45 use Config;
46 use CGI;
47 use Cwd;
48 use Encode;
49 use File::Copy;
50 use IO::File;
51 use Math::BigInt;
52 use POSIX qw(strftime);
53 use SL::Auth;
54 use SL::Auth::DB;
55 use SL::Auth::LDAP;
56 use SL::AM;
57 use SL::Common;
58 use SL::CVar;
59 use SL::DB;
60 use SL::DBConnect;
61 use SL::DBUtils;
62 use SL::DB::Customer;
63 use SL::DB::Default;
64 use SL::DB::PaymentTerm;
65 use SL::DB::Vendor;
66 use SL::DO;
67 use SL::Helper::Flash qw();
68 use SL::IC;
69 use SL::IS;
70 use SL::Layout::Dispatcher;
71 use SL::Locale;
72 use SL::Locale::String;
73 use SL::Mailer;
74 use SL::Menu;
75 use SL::MoreCommon qw(uri_encode uri_decode);
76 use SL::OE;
77 use SL::PrefixedNumber;
78 use SL::Request;
79 use SL::Template;
80 use SL::User;
81 use SL::Util;
82 use SL::Version;
83 use SL::X;
84 use Template;
85 use URI;
86 use List::Util qw(first max min sum);
87 use List::MoreUtils qw(all any apply);
88 use SL::DB::Tax;
89 use SL::Helper::File qw(:all);
90 use SL::Helper::CreatePDF qw(merge_pdfs);
91
92 use strict;
93
94 sub read_version {
95   SL::Version->get_version;
96 }
97
98 sub new {
99   $main::lxdebug->enter_sub();
100
101   my $type = shift;
102
103   my $self = {};
104
105   no warnings 'once';
106   if ($LXDebug::watch_form) {
107     require SL::Watchdog;
108     tie %{ $self }, 'SL::Watchdog';
109   }
110
111   bless $self, $type;
112
113   $main::lxdebug->leave_sub();
114
115   return $self;
116 }
117
118 sub read_cgi_input {
119   my ($self) = @_;
120   SL::Request::read_cgi_input($self);
121 }
122
123 sub _flatten_variables_rec {
124   $main::lxdebug->enter_sub(2);
125
126   my $self   = shift;
127   my $curr   = shift;
128   my $prefix = shift;
129   my $key    = shift;
130
131   my @result;
132
133   if ('' eq ref $curr->{$key}) {
134     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
135
136   } elsif ('HASH' eq ref $curr->{$key}) {
137     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
138       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
139     }
140
141   } else {
142     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
143       my $first_array_entry = 1;
144
145       my $element = $curr->{$key}[$idx];
146
147       if ('HASH' eq ref $element) {
148         foreach my $hash_key (sort keys %{ $element }) {
149           push @result, $self->_flatten_variables_rec($element, $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
150           $first_array_entry = 0;
151         }
152       } else {
153         @result = ({ 'key' => $prefix . $key . ($first_array_entry ? '[+]' : '[]'), 'value' => $element });
154       }
155     }
156   }
157
158   $main::lxdebug->leave_sub(2);
159
160   return @result;
161 }
162
163 sub flatten_variables {
164   $main::lxdebug->enter_sub(2);
165
166   my $self = shift;
167   my @keys = @_;
168
169   my @variables;
170
171   foreach (@keys) {
172     push @variables, $self->_flatten_variables_rec($self, '', $_);
173   }
174
175   $main::lxdebug->leave_sub(2);
176
177   return @variables;
178 }
179
180 sub flatten_standard_variables {
181   $main::lxdebug->enter_sub(2);
182
183   my $self      = shift;
184   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar), @_);
185
186   my @variables;
187
188   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
189     push @variables, $self->_flatten_variables_rec($self, '', $_);
190   }
191
192   $main::lxdebug->leave_sub(2);
193
194   return @variables;
195 }
196
197 sub escape {
198   my ($self, $str) = @_;
199
200   return uri_encode($str);
201 }
202
203 sub unescape {
204   my ($self, $str) = @_;
205
206   return uri_decode($str);
207 }
208
209 sub quote {
210   $main::lxdebug->enter_sub();
211   my ($self, $str) = @_;
212
213   if ($str && !ref($str)) {
214     $str =~ s/\"/&quot;/g;
215   }
216
217   $main::lxdebug->leave_sub();
218
219   return $str;
220 }
221
222 sub unquote {
223   $main::lxdebug->enter_sub();
224   my ($self, $str) = @_;
225
226   if ($str && !ref($str)) {
227     $str =~ s/&quot;/\"/g;
228   }
229
230   $main::lxdebug->leave_sub();
231
232   return $str;
233 }
234
235 sub hide_form {
236   $main::lxdebug->enter_sub();
237   my $self = shift;
238
239   if (@_) {
240     map({ print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
241   } else {
242     for (sort keys %$self) {
243       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
244       print($::request->{cgi}->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
245     }
246   }
247   $main::lxdebug->leave_sub();
248 }
249
250 sub throw_on_error {
251   my ($self, $code) = @_;
252   local $self->{__ERROR_HANDLER} = sub { die SL::X::FormError->new($_[0]) };
253   $code->();
254 }
255
256 sub error {
257   $main::lxdebug->enter_sub();
258
259   $main::lxdebug->show_backtrace();
260
261   my ($self, $msg) = @_;
262
263   if ($self->{__ERROR_HANDLER}) {
264     $self->{__ERROR_HANDLER}->($msg);
265
266   } elsif ($ENV{HTTP_USER_AGENT}) {
267     $msg =~ s/\n/<br>/g;
268     $self->show_generic_error($msg);
269
270   } else {
271     confess "Error: $msg\n";
272   }
273
274   $main::lxdebug->leave_sub();
275 }
276
277 sub info {
278   $main::lxdebug->enter_sub();
279
280   my ($self, $msg) = @_;
281
282   if ($ENV{HTTP_USER_AGENT}) {
283     $self->header;
284     print $self->parse_html_template('generic/form_info', { message => $msg });
285
286   } elsif ($self->{info_function}) {
287     &{ $self->{info_function} }($msg);
288   } else {
289     print "$msg\n";
290   }
291
292   $main::lxdebug->leave_sub();
293 }
294
295 # calculates the number of rows in a textarea based on the content and column number
296 # can be capped with maxrows
297 sub numtextrows {
298   $main::lxdebug->enter_sub();
299   my ($self, $str, $cols, $maxrows, $minrows) = @_;
300
301   $minrows ||= 1;
302
303   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
304   $maxrows ||= $rows;
305
306   $main::lxdebug->leave_sub();
307
308   return max(min($rows, $maxrows), $minrows);
309 }
310
311 sub dberror {
312   my ($self, $msg) = @_;
313
314   die SL::X::DBError->new(
315     msg   => $msg,
316     error => $DBI::errstr,
317   );
318 }
319
320 sub isblank {
321   $main::lxdebug->enter_sub();
322
323   my ($self, $name, $msg) = @_;
324
325   my $curr = $self;
326   foreach my $part (split m/\./, $name) {
327     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
328       $self->error($msg);
329     }
330     $curr = $curr->{$part};
331   }
332
333   $main::lxdebug->leave_sub();
334 }
335
336 sub _get_request_uri {
337   my $self = shift;
338
339   return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
340   return URI->new                                  if !$ENV{REQUEST_URI}; # for testing
341
342   my $scheme =  $::request->is_https ? 'https' : 'http';
343   my $port   =  $ENV{SERVER_PORT};
344   $port      =  undef if (($scheme eq 'http' ) && ($port == 80))
345                       || (($scheme eq 'https') && ($port == 443));
346
347   my $uri    =  URI->new("${scheme}://");
348   $uri->scheme($scheme);
349   $uri->port($port);
350   $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
351   $uri->path_query($ENV{REQUEST_URI});
352   $uri->query('');
353
354   return $uri;
355 }
356
357 sub _add_to_request_uri {
358   my $self              = shift;
359
360   my $relative_new_path = shift;
361   my $request_uri       = shift || $self->_get_request_uri;
362   my $relative_new_uri  = URI->new($relative_new_path);
363   my @request_segments  = $request_uri->path_segments;
364
365   my $new_uri           = $request_uri->clone;
366   $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
367
368   return $new_uri;
369 }
370
371 sub create_http_response {
372   $main::lxdebug->enter_sub();
373
374   my $self     = shift;
375   my %params   = @_;
376
377   my $cgi      = $::request->{cgi};
378
379   my $session_cookie;
380   if (defined $main::auth) {
381     my $uri      = $self->_get_request_uri;
382     my @segments = $uri->path_segments;
383     pop @segments;
384     $uri->path_segments(@segments);
385
386     my $session_cookie_value = $main::auth->get_session_id();
387
388     if ($session_cookie_value) {
389       $session_cookie = $cgi->cookie('-name'   => $main::auth->get_session_cookie_name(),
390                                      '-value'  => $session_cookie_value,
391                                      '-path'   => $uri->path,
392                                      '-secure' => $::request->is_https);
393     }
394   }
395
396   my %cgi_params = ('-type' => $params{content_type});
397   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
398   $cgi_params{'-cookie'}  = $session_cookie  if ($session_cookie);
399
400   map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length);
401
402   my $output = $cgi->header(%cgi_params);
403
404   $main::lxdebug->leave_sub();
405
406   return $output;
407 }
408
409 sub header {
410   $::lxdebug->enter_sub;
411
412   my ($self, %params) = @_;
413   my @header;
414
415   $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
416
417   if ($params{no_layout}) {
418     $::request->{layout} = SL::Layout::Dispatcher->new(style => 'none');
419   }
420
421   my $layout = $::request->{layout};
422
423   # standard css for all
424   # this should gradually move to the layouts that need it
425   $layout->use_stylesheet("$_.css") for qw(
426     common main menu list_accounts jquery.autocomplete
427     jquery.multiselect2side
428     ui-lightness/jquery-ui
429     jquery-ui.custom
430     tooltipster themes/tooltipster-light
431   );
432
433   $layout->use_javascript("$_.js") for (qw(
434     jquery jquery-ui jquery.cookie jquery.checkall jquery.download
435     jquery/jquery.form jquery/fixes client_js
436     jquery/jquery.tooltipster.min
437     jquery.multiselect2side
438     common part_selection
439   ), "jquery/ui/i18n/jquery.ui.datepicker-$::myconfig{countrycode}");
440
441   $self->{favicon} ||= "favicon.ico";
442   $self->{titlebar} = join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->read_version if $self->{title} || !$self->{titlebar};
443
444   # build includes
445   if ($self->{refresh_url} || $self->{refresh_time}) {
446     my $refresh_time = $self->{refresh_time} || 3;
447     my $refresh_url  = $self->{refresh_url}  || $ENV{REFERER};
448     push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
449   }
450
451   my $auto_reload_resources_param = $layout->auto_reload_resources_param;
452
453   push @header, map { qq|<link rel="stylesheet" href="${_}${auto_reload_resources_param}" type="text/css" title="Stylesheet">| } $layout->stylesheets;
454   push @header, "<style type='text/css'>\@page { size:landscape; }</style> "                     if $self->{landscape};
455   push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>"         if -f $self->{favicon};
456   push @header, map { qq|<script type="text/javascript" src="${_}${auto_reload_resources_param}"></script>| }                    $layout->javascripts;
457   push @header, $self->{javascript} if $self->{javascript};
458   push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
459
460   my  %doctypes = (
461     strict       => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|,
462     transitional => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|,
463     frameset     => qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|,
464     html5        => qq|<!DOCTYPE html>|,
465   );
466
467   # output
468   print $self->create_http_response(content_type => 'text/html', charset => 'UTF-8');
469   print $doctypes{$params{doctype} || 'transitional'}, $/;
470   print <<EOT;
471 <html>
472  <head>
473   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
474   <title>$self->{titlebar}</title>
475 EOT
476   print "  $_\n" for @header;
477   print <<EOT;
478   <meta name="robots" content="noindex,nofollow">
479  </head>
480  <body>
481
482 EOT
483   print $::request->{layout}->pre_content;
484   print $::request->{layout}->start_content;
485
486   $layout->header_done;
487
488   $::lxdebug->leave_sub;
489 }
490
491 sub footer {
492   return unless $::request->{layout}->need_footer;
493
494   print $::request->{layout}->end_content;
495   print $::request->{layout}->post_content;
496
497   if (my @inline_scripts = $::request->{layout}->javascripts_inline) {
498     print "<script type='text/javascript'>" . join("; ", @inline_scripts) . "</script>\n";
499   }
500
501   print <<EOL
502  </body>
503 </html>
504 EOL
505 }
506
507 sub ajax_response_header {
508   $main::lxdebug->enter_sub();
509
510   my ($self) = @_;
511
512   my $output = $::request->{cgi}->header('-charset' => 'UTF-8');
513
514   $main::lxdebug->leave_sub();
515
516   return $output;
517 }
518
519 sub redirect_header {
520   my $self     = shift;
521   my $new_url  = shift;
522
523   my $base_uri = $self->_get_request_uri;
524   my $new_uri  = URI->new_abs($new_url, $base_uri);
525
526   die "Headers already sent" if $self->{header};
527   $self->{header} = 1;
528
529   return $::request->{cgi}->redirect($new_uri);
530 }
531
532 sub set_standard_title {
533   $::lxdebug->enter_sub;
534   my $self = shift;
535
536   $self->{titlebar}  = "kivitendo " . $::locale->text('Version') . " " . $self->read_version;
537   $self->{titlebar} .= "- $::myconfig{name}"   if $::myconfig{name};
538   $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
539
540   $::lxdebug->leave_sub;
541 }
542
543 sub _prepare_html_template {
544   $main::lxdebug->enter_sub();
545
546   my ($self, $file, $additional_params) = @_;
547   my $language;
548
549   if (!%::myconfig || !$::myconfig{"countrycode"}) {
550     $language = $::lx_office_conf{system}->{language};
551   } else {
552     $language = $main::myconfig{"countrycode"};
553   }
554   $language = "de" unless ($language);
555
556   if (-f "templates/webpages/${file}.html") {
557     $file = "templates/webpages/${file}.html";
558
559   } elsif (ref $file eq 'SCALAR') {
560     # file is a scalarref, use inline mode
561   } else {
562     my $info = "Web page template '${file}' not found.\n";
563     $::form->header;
564     print qq|<pre>$info</pre>|;
565     $::dispatcher->end_request;
566   }
567
568   $additional_params->{AUTH}          = $::auth;
569   $additional_params->{INSTANCE_CONF} = $::instance_conf;
570   $additional_params->{LOCALE}        = $::locale;
571   $additional_params->{LXCONFIG}      = \%::lx_office_conf;
572   $additional_params->{LXDEBUG}       = $::lxdebug;
573   $additional_params->{MYCONFIG}      = \%::myconfig;
574
575   $main::lxdebug->leave_sub();
576
577   return $file;
578 }
579
580 sub parse_html_template {
581   $main::lxdebug->enter_sub();
582
583   my ($self, $file, $additional_params) = @_;
584
585   $additional_params ||= { };
586
587   my $real_file = $self->_prepare_html_template($file, $additional_params);
588   my $template  = $self->template;
589
590   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
591
592   my $output;
593   $template->process($real_file, $additional_params, \$output) || die $template->error;
594
595   $main::lxdebug->leave_sub();
596
597   return $output;
598 }
599
600 sub template { $::request->presenter->get_template }
601
602 sub show_generic_error {
603   $main::lxdebug->enter_sub();
604
605   my ($self, $error, %params) = @_;
606
607   if ($self->{__ERROR_HANDLER}) {
608     $self->{__ERROR_HANDLER}->($error);
609     $main::lxdebug->leave_sub();
610     return;
611   }
612
613   if ($::request->is_ajax) {
614     SL::ClientJS->new
615       ->error($error)
616       ->render(SL::Controller::Base->new);
617     $::dispatcher->end_request;
618   }
619
620   my $add_params = {
621     'title_error' => $params{title},
622     'label_error' => $error,
623   };
624
625   $self->{title} = $params{title} if $params{title};
626
627   for my $bar ($::request->layout->get('actionbar')) {
628     $bar->add(
629       action => [
630         t8('Back'),
631         call      => [ 'kivi.history_back' ],
632         accesskey => 'enter',
633       ],
634     );
635   }
636
637   $self->header();
638   print $self->parse_html_template("generic/error", $add_params);
639
640   print STDERR "Error: $error\n";
641
642   $main::lxdebug->leave_sub();
643
644   $::dispatcher->end_request;
645 }
646
647 sub show_generic_information {
648   $main::lxdebug->enter_sub();
649
650   my ($self, $text, $title) = @_;
651
652   my $add_params = {
653     'title_information' => $title,
654     'label_information' => $text,
655   };
656
657   $self->{title} = $title if ($title);
658
659   $self->header();
660   print $self->parse_html_template("generic/information", $add_params);
661
662   $main::lxdebug->leave_sub();
663
664   $::dispatcher->end_request;
665 }
666
667 sub _store_redirect_info_in_session {
668   my ($self) = @_;
669
670   return unless $self->{callback} =~ m:^ ( [^\?/]+ \.pl ) \? (.+) :x;
671
672   my ($controller, $params) = ($1, $2);
673   my $form                  = { map { map { $self->unescape($_) } split /=/, $_, 2 } split m/\&/, $params };
674   $self->{callback}         = "${controller}?RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session(form => $form);
675 }
676
677 sub redirect {
678   $main::lxdebug->enter_sub();
679
680   my ($self, $msg) = @_;
681
682   if (!$self->{callback}) {
683     $self->info($msg);
684
685   } else {
686     SL::Helper::Flash::flash_later('info', $msg) if $msg;
687     $self->_store_redirect_info_in_session;
688     print $::form->redirect_header($self->{callback});
689   }
690
691   $::dispatcher->end_request;
692
693   $main::lxdebug->leave_sub();
694 }
695
696 # sort of columns removed - empty sub
697 sub sort_columns {
698   $main::lxdebug->enter_sub();
699
700   my ($self, @columns) = @_;
701
702   $main::lxdebug->leave_sub();
703
704   return @columns;
705 }
706 #
707 sub format_amount {
708   $main::lxdebug->enter_sub(2);
709
710   my ($self, $myconfig, $amount, $places, $dash) = @_;
711   $amount ||= 0;
712   $dash   ||= '';
713   my $neg = $amount < 0;
714   my $force_places = defined $places && $places >= 0;
715
716   $amount = $self->round_amount($amount, abs $places) if $force_places;
717   $neg    = 0 if $amount == 0; # don't show negative zero
718   $amount = sprintf "%.*f", ($force_places ? $places : 10), abs $amount; # 6 is default for %fa
719
720   # before the sprintf amount was a number, afterwards it's a string. because of the dynamic nature of perl
721   # this is easy to confuse, so keep in mind: before this comment no s///, m//, concat or other strong ops on
722   # $amount. after this comment no +,-,*,/,abs. it will only introduce subtle bugs.
723
724   $amount =~ s/0*$// unless defined $places && $places == 0;             # cull trailing 0s
725
726   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
727   my @p = split(/\./, $amount);                                          # split amount at decimal point
728
729   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1];                             # add 1,000 delimiters
730   $amount = $p[0];
731   if ($places || $p[1]) {
732     $amount .= $d[0]
733             .  ( $p[1] || '' )
734             .  (0 x max(abs($places || 0) - length ($p[1]||''), 0));     # pad the fraction
735   }
736
737   $amount = do {
738     ($dash =~ /-/)    ? ($neg ? "($amount)"                            : "$amount" )                              :
739     ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
740                         ($neg ? "-$amount"                             : "$amount" )                              ;
741   };
742
743   $main::lxdebug->leave_sub(2);
744   return $amount;
745 }
746
747 sub format_amount_units {
748   $main::lxdebug->enter_sub();
749
750   my $self             = shift;
751   my %params           = @_;
752
753   my $myconfig         = \%main::myconfig;
754   my $amount           = $params{amount} * 1;
755   my $places           = $params{places};
756   my $part_unit_name   = $params{part_unit};
757   my $amount_unit_name = $params{amount_unit};
758   my $conv_units       = $params{conv_units};
759   my $max_places       = $params{max_places};
760
761   if (!$part_unit_name) {
762     $main::lxdebug->leave_sub();
763     return '';
764   }
765
766   my $all_units        = AM->retrieve_all_units;
767
768   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
769     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
770   }
771
772   if (!scalar @{ $conv_units }) {
773     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
774     $main::lxdebug->leave_sub();
775     return $result;
776   }
777
778   my $part_unit  = $all_units->{$part_unit_name};
779   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
780
781   $amount       *= $conv_unit->{factor};
782
783   my @values;
784   my $num;
785
786   foreach my $unit (@$conv_units) {
787     my $last = $unit->{name} eq $part_unit->{name};
788     if (!$last) {
789       $num     = int($amount / $unit->{factor});
790       $amount -= $num * $unit->{factor};
791     }
792
793     if ($last ? $amount : $num) {
794       push @values, { "unit"   => $unit->{name},
795                       "amount" => $last ? $amount / $unit->{factor} : $num,
796                       "places" => $last ? $places : 0 };
797     }
798
799     last if $last;
800   }
801
802   if (!@values) {
803     push @values, { "unit"   => $part_unit_name,
804                     "amount" => 0,
805                     "places" => 0 };
806   }
807
808   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
809
810   $main::lxdebug->leave_sub();
811
812   return $result;
813 }
814
815 sub format_string {
816   $main::lxdebug->enter_sub(2);
817
818   my $self  = shift;
819   my $input = shift;
820
821   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
822   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
823   $input =~ s/\#\#/\#/g;
824
825   $main::lxdebug->leave_sub(2);
826
827   return $input;
828 }
829
830 #
831
832 sub parse_amount {
833   $main::lxdebug->enter_sub(2);
834
835   my ($self, $myconfig, $amount) = @_;
836
837   if (!defined($amount) || ($amount eq '')) {
838     $main::lxdebug->leave_sub(2);
839     return 0;
840   }
841
842   if (   ($myconfig->{numberformat} eq '1.000,00')
843       || ($myconfig->{numberformat} eq '1000,00')) {
844     $amount =~ s/\.//g;
845     $amount =~ s/,/\./g;
846   }
847
848   if ($myconfig->{numberformat} eq "1'000.00") {
849     $amount =~ s/\'//g;
850   }
851
852   $amount =~ s/,//g;
853
854   $main::lxdebug->leave_sub(2);
855
856   # Make sure no code wich is not a math expression ends up in eval().
857   return 0 unless $amount =~ /^ [\s \d \( \) \- \+ \* \/ \. ]* $/x;
858
859   # Prevent numbers from being parsed as octals;
860   $amount =~ s{ (?<! [\d.] ) 0+ (?= [1-9] ) }{}gx;
861
862   return scalar(eval($amount)) * 1 ;
863 }
864
865 sub round_amount {
866   my ($self, $amount, $places, $adjust) = @_;
867
868   return 0 if !defined $amount;
869
870   $places //= 0;
871
872   if ($adjust) {
873     my $precision = $::instance_conf->get_precision || 0.01;
874     return $self->round_amount( $self->round_amount($amount / $precision, 0) * $precision, $places);
875   }
876
877   # We use Perl's knowledge of string representation for
878   # rounding. First, convert the floating point number to a string
879   # with a high number of places. Then split the string on the decimal
880   # sign and use integer calculation for rounding the decimal places
881   # part. If an overflow occurs then apply that overflow to the part
882   # before the decimal sign as well using integer arithmetic again.
883
884   my $int_amount = int(abs $amount);
885   my $str_places = max(min(10, 16 - length("$int_amount") - $places), $places);
886   my $amount_str = sprintf '%.*f', $places + $str_places, abs($amount);
887
888   return $amount unless $amount_str =~ m{^(\d+)\.(\d+)$};
889
890   my ($pre, $post)      = ($1, $2);
891   my $decimals          = '1' . substr($post, 0, $places);
892
893   my $propagation_limit = $Config{i32size} == 4 ? 7 : 18;
894   my $add_for_rounding  = substr($post, $places, 1) >= 5 ? 1 : 0;
895
896   if ($places > $propagation_limit) {
897     $decimals = Math::BigInt->new($decimals)->badd($add_for_rounding);
898     $pre      = Math::BigInt->new($decimals)->badd(1) if substr($decimals, 0, 1) eq '2';
899
900   } else {
901     $decimals += $add_for_rounding;
902     $pre      += 1 if substr($decimals, 0, 1) eq '2';
903   }
904
905   $amount  = ("${pre}." . substr($decimals, 1)) * ($amount <=> 0);
906
907   return $amount;
908 }
909
910 sub parse_template {
911   $main::lxdebug->enter_sub();
912
913   my ($self, $myconfig) = @_;
914   my ($out, $out_mode);
915
916   local (*IN, *OUT);
917
918   my $defaults  = SL::DB::Default->get;
919   my $userspath = $::lx_office_conf{paths}->{userspath};
920
921   $self->{"cwd"} = getcwd();
922   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
923
924   my $ext_for_format;
925
926   my $template_type;
927   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
928     $template_type  = 'OpenDocument';
929     $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
930
931   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
932     $template_type    = 'LaTeX';
933     $ext_for_format   = 'pdf';
934
935   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
936     $template_type  = 'HTML';
937     $ext_for_format = 'html';
938
939   } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
940     $template_type  = 'XML';
941     $ext_for_format = 'xml';
942
943   } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
944     $template_type = 'XML';
945
946   } elsif ( $self->{"format"} =~ /excel/i ) {
947     $template_type  = 'Excel';
948     $ext_for_format = 'xls';
949
950   } elsif ( defined $self->{'format'}) {
951     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
952
953   } elsif ( $self->{'format'} eq '' ) {
954     $self->error("No Outputformat given: $self->{'format'}");
955
956   } else { #Catch the rest
957     $self->error("Outputformat not defined: $self->{'format'}");
958   }
959
960   my $template = SL::Template::create(type      => $template_type,
961                                       file_name => $self->{IN},
962                                       form      => $self,
963                                       myconfig  => $myconfig,
964                                       userspath => $userspath,
965                                       %{ $self->{TEMPLATE_DRIVER_OPTIONS} || {} });
966
967   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
968   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" } if exists $self->{ $self->{"formname"} . "notes" };
969
970   if (!$self->{employee_id}) {
971     $self->{"employee_${_}"} = $myconfig->{$_} for qw(email tel fax name signature);
972     $self->{"employee_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
973   }
974
975   $self->{"myconfig_${_}"} = $myconfig->{$_} for grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
976   $self->{$_}              = $defaults->$_   for qw(co_ustid);
977   $self->{"myconfig_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
978   $self->{AUTH}            = $::auth;
979   $self->{INSTANCE_CONF}   = $::instance_conf;
980   $self->{LOCALE}          = $::locale;
981   $self->{LXCONFIG}        = $::lx_office_conf;
982   $self->{LXDEBUG}         = $::lxdebug;
983   $self->{MYCONFIG}        = \%::myconfig;
984
985   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
986
987   # OUT is used for the media, screen, printer, email
988   # for postscript we store a copy in a temporary file
989   my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
990
991   my ($temp_fh, $suffix);
992   $suffix =  $self->{IN};
993   $suffix =~ s/.*\.//;
994   ($temp_fh, $self->{tmpfile}) = File::Temp::tempfile(
995     strftime('kivitendo-print-%Y%m%d%H%M%S-XXXXXX', localtime()),
996     SUFFIX => '.' . ($suffix || 'tex'),
997     DIR    => $userspath,
998     UNLINK => $keep_temp_files ? 0 : 1,
999   );
1000   close $temp_fh;
1001   chmod 0644, $self->{tmpfile} if $keep_temp_files;
1002   (undef, undef, $self->{template_meta}{tmpfile}) = File::Spec->splitpath( $self->{tmpfile} );
1003
1004   $out              = $self->{OUT};
1005   $out_mode         = $self->{OUT_MODE} || '>';
1006   $self->{OUT}      = "$self->{tmpfile}";
1007   $self->{OUT_MODE} = '>';
1008
1009   my $result;
1010   my $command_formatter = sub {
1011     my ($out_mode, $out) = @_;
1012     return $out_mode eq '|-' ? SL::Template::create(type => 'ShellCommand', form => $self)->parse($out) : $out;
1013   };
1014
1015   if ($self->{OUT}) {
1016     $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1017     open(OUT, $self->{OUT_MODE}, $self->{OUT}) or $self->error("error on opening $self->{OUT} with mode $self->{OUT_MODE} : $!");
1018   } else {
1019     *OUT = ($::dispatcher->get_standard_filehandles)[1];
1020     $self->header;
1021   }
1022
1023   if (!$template->parse(*OUT)) {
1024     $self->cleanup();
1025     $self->error("$self->{IN} : " . $template->get_error());
1026   }
1027
1028   close OUT if $self->{OUT};
1029   # check only one flag (webdav_documents)
1030   # therefore copy to webdav, even if we do not have the webdav feature enabled (just archive)
1031   my $copy_to_webdav =  $::instance_conf->get_webdav_documents && !$self->{preview} && $self->{tmpdir} && $self->{tmpfile} && $self->{type}
1032                         && $self->{type} ne 'statement';
1033   if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
1034     $self->append_general_pdf_attachments(filepath =>  $self->{tmpdir}."/".$self->{tmpfile},
1035                                           type     =>  $self->{type});
1036   }
1037   if ($self->{media} eq 'file') {
1038     copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
1039     Common::copy_file_to_webdav_folder($self)                                                                         if $copy_to_webdav;
1040     if (!$self->{preview} && $self->doc_storage_enabled)
1041     {
1042       $self->{attachment_filename} ||= $self->generate_attachment_filename;
1043       $self->store_pdf($self);
1044     }
1045     $self->cleanup;
1046     chdir("$self->{cwd}");
1047
1048     $::lxdebug->leave_sub();
1049
1050     return;
1051   }
1052
1053   Common::copy_file_to_webdav_folder($self) if $copy_to_webdav;
1054
1055   if ( !$self->{preview} && $ext_for_format eq 'pdf' && $self->doc_storage_enabled) {
1056     $self->{attachment_filename} ||= $self->generate_attachment_filename;
1057     my $file_obj = $self->store_pdf($self);
1058     $self->{print_file_id} = $file_obj->id if $file_obj;
1059   }
1060   if ($self->{media} eq 'email') {
1061     if ( getcwd() eq $self->{"tmpdir"} ) {
1062       # in the case of generating pdf we are in the tmpdir, but WHY ???
1063       $self->{tmpfile} = $userspath."/".$self->{tmpfile};
1064       chdir("$self->{cwd}");
1065     }
1066     $self->send_email(\%::myconfig,$ext_for_format);
1067   }
1068   else {
1069     $self->{OUT}      = $out;
1070     $self->{OUT_MODE} = $out_mode;
1071     $self->output_file($template->get_mime_type,$command_formatter);
1072   }
1073   delete $self->{print_file_id};
1074
1075   $self->cleanup;
1076
1077   chdir("$self->{cwd}");
1078   $main::lxdebug->leave_sub();
1079 }
1080
1081 sub get_bcc_defaults {
1082   my ($self, $myconfig, $mybcc) = @_;
1083   if (SL::DB::Default->get->bcc_to_login) {
1084     $mybcc .= ", " if $mybcc;
1085     $mybcc .= $myconfig->{email};
1086   }
1087   my $otherbcc = SL::DB::Default->get->global_bcc;
1088   if ($otherbcc) {
1089     $mybcc .= ", " if $mybcc;
1090     $mybcc .= $otherbcc;
1091   }
1092   return $mybcc;
1093 }
1094
1095 sub send_email {
1096   $main::lxdebug->enter_sub();
1097   my ($self, $myconfig, $ext_for_format) = @_;
1098   my $mail = Mailer->new;
1099
1100   map { $mail->{$_} = $self->{$_} }
1101     qw(cc subject message format);
1102
1103   $mail->{bcc}    = $self->get_bcc_defaults($myconfig, $self->{bcc});
1104   $mail->{to}     = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1105   $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1106   $mail->{fileid} = time() . '.' . $$ . '.';
1107   my $full_signature     =  $self->create_email_signature();
1108   $full_signature        =~ s/\r//g;
1109
1110   $mail->{attachments} =  [];
1111   my @attfiles;
1112   # if we send html or plain text inline
1113   if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1114     $mail->{content_type}   =  "text/html";
1115     $mail->{message}        =~ s/\r//g;
1116     $mail->{message}        =~ s/\n/<br>\n/g;
1117     $full_signature         =~ s/\n/<br>\n/g;
1118     $mail->{message}       .=  $full_signature;
1119
1120     open(IN, "<", $self->{tmpfile})
1121       or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1122     $mail->{message} .= $_ while <IN>;
1123     close(IN);
1124
1125   } elsif (($self->{attachment_policy} // '') ne 'no_file') {
1126     my $attachment_name  =  $self->{attachment_filename}  || $self->{tmpfile};
1127     $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1128
1129     if (($self->{attachment_policy} // '') eq 'old_file') {
1130       my ( $attfile ) = SL::File->get_all(object_id   => $self->{id},
1131                                           object_type => $self->{formname},
1132                                           file_type   => 'document');
1133
1134       if ($attfile) {
1135         $attfile->{override_file_name} = $attachment_name if $attachment_name;
1136         push @attfiles, $attfile;
1137       }
1138
1139     } else {
1140       push @{ $mail->{attachments} }, { path => $self->{tmpfile},
1141                                         id   => $self->{print_file_id},
1142                                         type => "application/pdf",
1143                                         name => $attachment_name };
1144     }
1145   }
1146
1147   push @attfiles,
1148     grep { $_ }
1149     map  { SL::File->get(id => $_) }
1150     @{ $self->{attach_file_ids} // [] };
1151
1152   foreach my $attfile ( @attfiles ) {
1153     push @{ $mail->{attachments} }, {
1154       path    => $attfile->get_file,
1155       id      => $attfile->id,
1156       type    => $attfile->mime_type,
1157       name    => $attfile->{override_file_name} // $attfile->file_name,
1158       content => $attfile->get_content ? ${ $attfile->get_content } : undef,
1159     };
1160   }
1161
1162   $mail->{message}  =~ s/\r//g;
1163   $mail->{message} .= $full_signature;
1164   $self->{emailerr} = $mail->send();
1165
1166   if ($self->{emailerr}) {
1167     $self->cleanup;
1168     $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
1169   }
1170
1171   $self->{email_journal_id} = $mail->{journalentry};
1172   $self->{snumbers}  = "emailjournal" . "_" . $self->{email_journal_id};
1173   $self->{what_done} = $::form->{type};
1174   $self->{addition}  = "MAILED";
1175   $self->save_history;
1176
1177   #write back for message info and mail journal
1178   $self->{cc}  = $mail->{cc};
1179   $self->{bcc} = $mail->{bcc};
1180   $self->{email} = $mail->{to};
1181
1182   $main::lxdebug->leave_sub();
1183 }
1184
1185 sub output_file {
1186   $main::lxdebug->enter_sub();
1187
1188   my ($self,$mimeType,$command_formatter) = @_;
1189   my $numbytes = (-s $self->{tmpfile});
1190   open(IN, "<", $self->{tmpfile})
1191     or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1192   binmode IN;
1193
1194   $self->{copies} = 1 unless $self->{media} eq 'printer';
1195
1196   chdir("$self->{cwd}");
1197   for my $i (1 .. $self->{copies}) {
1198     if ($self->{OUT}) {
1199       $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1200
1201       open  OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1202       print OUT $_ while <IN>;
1203       close OUT;
1204       seek  IN, 0, 0;
1205
1206     } else {
1207       my %headers = ('-type'       => $mimeType,
1208                      '-connection' => 'close',
1209                      '-charset'    => 'UTF-8');
1210
1211       $self->{attachment_filename} ||= $self->generate_attachment_filename;
1212
1213       if ($self->{attachment_filename}) {
1214         %headers = (
1215           %headers,
1216           '-attachment'     => $self->{attachment_filename},
1217           '-content-length' => $numbytes,
1218           '-charset'        => '',
1219         );
1220       }
1221
1222       print $::request->cgi->header(%headers);
1223
1224       $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1225     }
1226   }
1227   close(IN);
1228   $main::lxdebug->leave_sub();
1229 }
1230
1231 sub get_formname_translation {
1232   $main::lxdebug->enter_sub();
1233   my ($self, $formname) = @_;
1234
1235   $formname ||= $self->{formname};
1236
1237   $self->{recipient_locale} ||=  Locale->lang_to_locale($self->{language});
1238   local $::locale = Locale->new($self->{recipient_locale});
1239
1240   my %formname_translations = (
1241     bin_list                => $main::locale->text('Bin List'),
1242     credit_note             => $main::locale->text('Credit Note'),
1243     invoice                 => $main::locale->text('Invoice'),
1244     pick_list               => $main::locale->text('Pick List'),
1245     proforma                => $main::locale->text('Proforma Invoice'),
1246     purchase_order          => $main::locale->text('Purchase Order'),
1247     request_quotation       => $main::locale->text('RFQ'),
1248     sales_order             => $main::locale->text('Confirmation'),
1249     sales_quotation         => $main::locale->text('Quotation'),
1250     storno_invoice          => $main::locale->text('Storno Invoice'),
1251     sales_delivery_order    => $main::locale->text('Delivery Order'),
1252     purchase_delivery_order => $main::locale->text('Delivery Order'),
1253     dunning                 => $main::locale->text('Dunning'),
1254     dunning1                => $main::locale->text('Payment Reminder'),
1255     dunning2                => $main::locale->text('Dunning'),
1256     dunning3                => $main::locale->text('Last Dunning'),
1257     dunning_invoice         => $main::locale->text('Dunning Invoice'),
1258     letter                  => $main::locale->text('Letter'),
1259     ic_supply               => $main::locale->text('Intra-Community supply'),
1260     statement               => $main::locale->text('Statement'),
1261   );
1262
1263   $main::lxdebug->leave_sub();
1264   return $formname_translations{$formname};
1265 }
1266
1267 sub get_number_prefix_for_type {
1268   $main::lxdebug->enter_sub();
1269   my ($self) = @_;
1270
1271   my $prefix =
1272       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1273     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
1274     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
1275     : ($self->{type} =~ /letter/)                             ? 'letter'
1276     :                                                           'ord';
1277
1278   # better default like this?
1279   # : ($self->{type} =~ /(sales|purcharse)_order/           :  'ord';
1280   # :                                                           'prefix_undefined';
1281
1282   $main::lxdebug->leave_sub();
1283   return $prefix;
1284 }
1285
1286 sub get_extension_for_format {
1287   $main::lxdebug->enter_sub();
1288   my ($self)    = @_;
1289
1290   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
1291                 : $self->{format} =~ /postscript/i   ? ".ps"
1292                 : $self->{format} =~ /opendocument/i ? ".odt"
1293                 : $self->{format} =~ /excel/i        ? ".xls"
1294                 : $self->{format} =~ /html/i         ? ".html"
1295                 :                                      "";
1296
1297   $main::lxdebug->leave_sub();
1298   return $extension;
1299 }
1300
1301 sub generate_attachment_filename {
1302   $main::lxdebug->enter_sub();
1303   my ($self) = @_;
1304
1305   $self->{recipient_locale} ||=  Locale->lang_to_locale($self->{language});
1306   my $recipient_locale = Locale->new($self->{recipient_locale});
1307
1308   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1309   my $prefix              = $self->get_number_prefix_for_type();
1310
1311   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1312     $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
1313
1314   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1315     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1316
1317   } elsif ($attachment_filename) {
1318     $attachment_filename .=  $self->get_extension_for_format();
1319
1320   } else {
1321     $attachment_filename = "";
1322   }
1323
1324   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
1325   $attachment_filename =~ s|[\s/\\]+|_|g;
1326
1327   $main::lxdebug->leave_sub();
1328   return $attachment_filename;
1329 }
1330
1331 sub generate_email_subject {
1332   $main::lxdebug->enter_sub();
1333   my ($self) = @_;
1334
1335   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1336   my $prefix  = $self->get_number_prefix_for_type();
1337
1338   if ($subject && $self->{"${prefix}number"}) {
1339     $subject .= " " . $self->{"${prefix}number"}
1340   }
1341
1342   $main::lxdebug->leave_sub();
1343   return $subject;
1344 }
1345
1346 sub generate_email_body {
1347   $main::lxdebug->enter_sub();
1348   my ($self) = @_;
1349   # simple german and english will work grammatically (most european languages as well)
1350   # Dear Mr Alan Greenspan:
1351   # Sehr geehrte Frau Meyer,
1352   # A l’attention de Mme Villeroy,
1353   # Gentile Signora Ferrari,
1354   my $body = '';
1355
1356   if ($self->{cp_id}) {
1357     my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
1358     my $name      = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
1359     my $gender    = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
1360     my $mf = $gender eq 'f' ? 'female' : 'male';
1361     $body  = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
1362     $body .= ' ' . $givenname . ' ' . $name if $body;
1363   } else {
1364     $body  = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
1365   }
1366
1367   return undef unless $body;
1368
1369   $body   .= GenericTranslations->get(translation_type =>"salutation_punctuation_mark", language_id => $self->{language_id}) . "\n";
1370   $body   .= GenericTranslations->get(translation_type =>"preset_text_$self->{formname}", language_id => $self->{language_id});
1371
1372   $body = $main::locale->unquote_special_chars('HTML', $body);
1373
1374   $main::lxdebug->leave_sub();
1375   return $body;
1376 }
1377
1378 sub cleanup {
1379   $main::lxdebug->enter_sub();
1380
1381   my ($self, $application) = @_;
1382
1383   my $error_code = $?;
1384
1385   chdir("$self->{tmpdir}");
1386
1387   my @err = ();
1388   if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1389     push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1390
1391   } elsif (-f "$self->{tmpfile}.err") {
1392     open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
1393     @err = <FH>;
1394     close(FH);
1395   }
1396
1397   if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1398     $self->{tmpfile} =~ s|.*/||g;
1399     # strip extension
1400     $self->{tmpfile} =~ s/\.\w+$//g;
1401     my $tmpfile = $self->{tmpfile};
1402     unlink(<$tmpfile.*>);
1403   }
1404
1405   chdir("$self->{cwd}");
1406
1407   $main::lxdebug->leave_sub();
1408
1409   return "@err";
1410 }
1411
1412 sub datetonum {
1413   $main::lxdebug->enter_sub();
1414
1415   my ($self, $date, $myconfig) = @_;
1416   my ($yy, $mm, $dd);
1417
1418   if ($date && $date =~ /\D/) {
1419
1420     if ($myconfig->{dateformat} =~ /^yy/) {
1421       ($yy, $mm, $dd) = split /\D/, $date;
1422     }
1423     if ($myconfig->{dateformat} =~ /^mm/) {
1424       ($mm, $dd, $yy) = split /\D/, $date;
1425     }
1426     if ($myconfig->{dateformat} =~ /^dd/) {
1427       ($dd, $mm, $yy) = split /\D/, $date;
1428     }
1429
1430     $dd *= 1;
1431     $mm *= 1;
1432     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1433     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1434
1435     $dd = "0$dd" if ($dd < 10);
1436     $mm = "0$mm" if ($mm < 10);
1437
1438     $date = "$yy$mm$dd";
1439   }
1440
1441   $main::lxdebug->leave_sub();
1442
1443   return $date;
1444 }
1445
1446 # Database routines used throughout
1447 # DB Handling got moved to SL::DB, these are only shims for compatibility
1448
1449 sub dbconnect {
1450   SL::DB->client->dbh;
1451 }
1452
1453 sub get_standard_dbh {
1454   my $dbh = SL::DB->client->dbh;
1455
1456   if ($dbh && !$dbh->{Active}) {
1457     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
1458     SL::DB->client->dbh(undef);
1459   }
1460
1461   SL::DB->client->dbh;
1462 }
1463
1464 sub disconnect_standard_dbh {
1465   SL::DB->client->dbh->rollback;
1466 }
1467
1468 # /database
1469
1470 sub date_closed {
1471   $main::lxdebug->enter_sub();
1472
1473   my ($self, $date, $myconfig) = @_;
1474   my $dbh = $self->get_standard_dbh;
1475
1476   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1477   my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1478
1479   # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1480   # es ist sicher ein conv_date vorher IMMER auszuführen.
1481   # Testfälle ohne definiertes closedto:
1482   #   Leere Datumseingabe i.O.
1483   #     SELECT 1 FROM defaults WHERE '' < closedto
1484   #   normale Zahlungsbuchung über Rechnungsmaske i.O.
1485   #     SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1486   # Testfälle mit definiertem closedto (30.04.2011):
1487   #  Leere Datumseingabe i.O.
1488   #   SELECT 1 FROM defaults WHERE '' < closedto
1489   # normale Buchung im geschloßenem Zeitraum i.O.
1490   #   SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1491   #     Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1492   # normale Buchung in aktiver Buchungsperiode i.O.
1493   #   SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1494
1495   my ($closed) = $sth->fetchrow_array;
1496
1497   $main::lxdebug->leave_sub();
1498
1499   return $closed;
1500 }
1501
1502 # prevents bookings to the to far away future
1503 sub date_max_future {
1504   $main::lxdebug->enter_sub();
1505
1506   my ($self, $date, $myconfig) = @_;
1507   my $dbh = $self->get_standard_dbh;
1508
1509   my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
1510   my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1511
1512   my ($max_future_booking_interval) = $sth->fetchrow_array;
1513
1514   $main::lxdebug->leave_sub();
1515
1516   return $max_future_booking_interval;
1517 }
1518
1519
1520 sub update_balance {
1521   $main::lxdebug->enter_sub();
1522
1523   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1524
1525   # if we have a value, go do it
1526   if ($value != 0) {
1527
1528     # retrieve balance from table
1529     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1530     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1531     my ($balance) = $sth->fetchrow_array;
1532     $sth->finish;
1533
1534     $balance += $value;
1535
1536     # update balance
1537     $query = "UPDATE $table SET $field = $balance WHERE $where";
1538     do_query($self, $dbh, $query, @values);
1539   }
1540   $main::lxdebug->leave_sub();
1541 }
1542
1543 sub update_exchangerate {
1544   $main::lxdebug->enter_sub();
1545
1546   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1547   my ($query);
1548   # some sanity check for currency
1549   if ($curr eq '') {
1550     $main::lxdebug->leave_sub();
1551     return;
1552   }
1553   $query = qq|SELECT name AS curr FROM currencies WHERE id=(SELECT currency_id FROM defaults)|;
1554
1555   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1556
1557   if ($curr eq $defaultcurrency) {
1558     $main::lxdebug->leave_sub();
1559     return;
1560   }
1561
1562   $query = qq|SELECT e.currency_id FROM exchangerate e
1563                  WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
1564                  FOR UPDATE|;
1565   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1566
1567   if ($buy == 0) {
1568     $buy = "";
1569   }
1570   if ($sell == 0) {
1571     $sell = "";
1572   }
1573
1574   $buy = conv_i($buy, "NULL");
1575   $sell = conv_i($sell, "NULL");
1576
1577   my $set;
1578   if ($buy != 0 && $sell != 0) {
1579     $set = "buy = $buy, sell = $sell";
1580   } elsif ($buy != 0) {
1581     $set = "buy = $buy";
1582   } elsif ($sell != 0) {
1583     $set = "sell = $sell";
1584   }
1585
1586   if ($sth->fetchrow_array) {
1587     $query = qq|UPDATE exchangerate
1588                 SET $set
1589                 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
1590                 AND transdate = ?|;
1591
1592   } else {
1593     $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
1594                 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
1595   }
1596   $sth->finish;
1597   do_query($self, $dbh, $query, $curr, $transdate);
1598
1599   $main::lxdebug->leave_sub();
1600 }
1601
1602 sub save_exchangerate {
1603   $main::lxdebug->enter_sub();
1604
1605   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1606
1607   SL::DB->client->with_transaction(sub {
1608     my $dbh = SL::DB->client->dbh;
1609
1610     my ($buy, $sell);
1611
1612     $buy  = $rate if $fld eq 'buy';
1613     $sell = $rate if $fld eq 'sell';
1614
1615
1616     $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1617     1;
1618   }) or do { die SL::DB->client->error };
1619
1620   $main::lxdebug->leave_sub();
1621 }
1622
1623 sub get_exchangerate {
1624   $main::lxdebug->enter_sub();
1625
1626   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1627   my ($query);
1628
1629   unless ($transdate && $curr) {
1630     $main::lxdebug->leave_sub();
1631     return 1;
1632   }
1633
1634   $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1635
1636   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1637
1638   if ($curr eq $defaultcurrency) {
1639     $main::lxdebug->leave_sub();
1640     return 1;
1641   }
1642
1643   $query = qq|SELECT e.$fld FROM exchangerate e
1644                  WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1645   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1646
1647
1648
1649   $main::lxdebug->leave_sub();
1650
1651   return $exchangerate;
1652 }
1653
1654 sub check_exchangerate {
1655   $main::lxdebug->enter_sub();
1656
1657   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1658
1659   if ($fld !~/^buy|sell$/) {
1660     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1661   }
1662
1663   unless ($transdate) {
1664     $main::lxdebug->leave_sub();
1665     return "";
1666   }
1667
1668   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1669
1670   if ($currency eq $defaultcurrency) {
1671     $main::lxdebug->leave_sub();
1672     return 1;
1673   }
1674
1675   my $dbh   = $self->get_standard_dbh($myconfig);
1676   my $query = qq|SELECT e.$fld FROM exchangerate e
1677                  WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1678
1679   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1680
1681   $main::lxdebug->leave_sub();
1682
1683   return $exchangerate;
1684 }
1685
1686 sub get_all_currencies {
1687   $main::lxdebug->enter_sub();
1688
1689   my $self     = shift;
1690   my $myconfig = shift || \%::myconfig;
1691   my $dbh      = $self->get_standard_dbh($myconfig);
1692
1693   my $query = qq|SELECT name FROM currencies|;
1694   my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
1695
1696   $main::lxdebug->leave_sub();
1697
1698   return @currencies;
1699 }
1700
1701 sub get_default_currency {
1702   $main::lxdebug->enter_sub();
1703
1704   my ($self, $myconfig) = @_;
1705   my $dbh      = $self->get_standard_dbh($myconfig);
1706   my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1707
1708   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1709
1710   $main::lxdebug->leave_sub();
1711
1712   return $defaultcurrency;
1713 }
1714
1715 sub set_payment_options {
1716   my ($self, $myconfig, $transdate, $type) = @_;
1717
1718   my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
1719   return if !$terms;
1720
1721   my $is_invoice                = $type =~ m{invoice}i;
1722
1723   $transdate                  ||= $self->{invdate} || $self->{transdate};
1724   my $due_date                  = $self->{duedate} || $self->{reqdate};
1725
1726   $self->{$_}                   = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
1727   $self->{payment_description}  = $terms->description;
1728   $self->{netto_date}           = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
1729   $self->{skonto_date}          = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
1730
1731   my ($invtotal, $total);
1732   my (%amounts, %formatted_amounts);
1733
1734   if ($self->{type} =~ /_order$/) {
1735     $amounts{invtotal} = $self->{ordtotal};
1736     $amounts{total}    = $self->{ordtotal};
1737
1738   } elsif ($self->{type} =~ /_quotation$/) {
1739     $amounts{invtotal} = $self->{quototal};
1740     $amounts{total}    = $self->{quototal};
1741
1742   } else {
1743     $amounts{invtotal} = $self->{invtotal};
1744     $amounts{total}    = $self->{total};
1745   }
1746   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1747
1748   $amounts{skonto_in_percent}  = 100.0 * $self->{percent_skonto};
1749   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1750   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1751   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1752
1753   foreach (keys %amounts) {
1754     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1755     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1756   }
1757
1758   if ($self->{"language_id"}) {
1759     my $language             = SL::DB::Language->new(id => $self->{language_id})->load;
1760
1761     $self->{payment_terms}   = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
1762     $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
1763
1764     if ($language->output_dateformat) {
1765       foreach my $key (qw(netto_date skonto_date)) {
1766         $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
1767       }
1768     }
1769
1770     if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
1771       local $myconfig->{numberformat};
1772       $myconfig->{"numberformat"} = $language->output_numberformat;
1773       $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
1774     }
1775   }
1776
1777   $self->{payment_terms} =  $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
1778
1779   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1780   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1781   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1782   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1783   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1784   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1785   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1786   $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
1787   $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
1788   $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
1789   $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
1790
1791   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1792
1793   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1794
1795 }
1796
1797 sub get_template_language {
1798   $main::lxdebug->enter_sub();
1799
1800   my ($self, $myconfig) = @_;
1801
1802   my $template_code = "";
1803
1804   if ($self->{language_id}) {
1805     my $dbh = $self->get_standard_dbh($myconfig);
1806     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1807     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1808   }
1809
1810   $main::lxdebug->leave_sub();
1811
1812   return $template_code;
1813 }
1814
1815 sub get_printer_code {
1816   $main::lxdebug->enter_sub();
1817
1818   my ($self, $myconfig) = @_;
1819
1820   my $template_code = "";
1821
1822   if ($self->{printer_id}) {
1823     my $dbh = $self->get_standard_dbh($myconfig);
1824     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1825     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1826   }
1827
1828   $main::lxdebug->leave_sub();
1829
1830   return $template_code;
1831 }
1832
1833 sub get_shipto {
1834   $main::lxdebug->enter_sub();
1835
1836   my ($self, $myconfig) = @_;
1837
1838   my $template_code = "";
1839
1840   if ($self->{shipto_id}) {
1841     my $dbh = $self->get_standard_dbh($myconfig);
1842     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1843     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1844     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1845
1846     my $cvars = CVar->get_custom_variables(
1847       dbh      => $dbh,
1848       module   => 'ShipTo',
1849       trans_id => $self->{shipto_id},
1850     );
1851     $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
1852   }
1853
1854   $main::lxdebug->leave_sub();
1855 }
1856
1857 sub add_shipto {
1858   my ($self, $dbh, $id, $module) = @_;
1859
1860   my $shipto;
1861   my @values;
1862
1863   foreach my $item (qw(name department_1 department_2 street zipcode city country gln
1864                        contact cp_gender phone fax email)) {
1865     if ($self->{"shipto$item"}) {
1866       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1867     }
1868     push(@values, $self->{"shipto${item}"});
1869   }
1870
1871   return if !$shipto;
1872
1873   my $shipto_id = $self->{shipto_id};
1874
1875   if ($self->{shipto_id}) {
1876     my $query = qq|UPDATE shipto set
1877                      shiptoname = ?,
1878                      shiptodepartment_1 = ?,
1879                      shiptodepartment_2 = ?,
1880                      shiptostreet = ?,
1881                      shiptozipcode = ?,
1882                      shiptocity = ?,
1883                      shiptocountry = ?,
1884                      shiptogln = ?,
1885                      shiptocontact = ?,
1886                      shiptocp_gender = ?,
1887                      shiptophone = ?,
1888                      shiptofax = ?,
1889                      shiptoemail = ?
1890                    WHERE shipto_id = ?|;
1891     do_query($self, $dbh, $query, @values, $self->{shipto_id});
1892   } else {
1893     my $query = qq|SELECT * FROM shipto
1894                    WHERE shiptoname = ? AND
1895                      shiptodepartment_1 = ? AND
1896                      shiptodepartment_2 = ? AND
1897                      shiptostreet = ? AND
1898                      shiptozipcode = ? AND
1899                      shiptocity = ? AND
1900                      shiptocountry = ? AND
1901                      shiptogln = ? AND
1902                      shiptocontact = ? AND
1903                      shiptocp_gender = ? AND
1904                      shiptophone = ? AND
1905                      shiptofax = ? AND
1906                      shiptoemail = ? AND
1907                      module = ? AND
1908                      trans_id = ?|;
1909     my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1910     if(!$insert_check){
1911       my $insert_query =
1912         qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1913                                shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
1914                                shiptocontact, shiptocp_gender, shiptophone, shiptofax, shiptoemail, module)
1915            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1916       do_query($self, $dbh, $insert_query, $id, @values, $module);
1917
1918       $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1919     }
1920
1921     $shipto_id = $insert_check->{shipto_id};
1922   }
1923
1924   return unless $shipto_id;
1925
1926   CVar->save_custom_variables(
1927     dbh         => $dbh,
1928     module      => 'ShipTo',
1929     trans_id    => $shipto_id,
1930     variables   => $self,
1931     name_prefix => 'shipto',
1932   );
1933 }
1934
1935 sub get_employee {
1936   $main::lxdebug->enter_sub();
1937
1938   my ($self, $dbh) = @_;
1939
1940   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1941
1942   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1943   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1944   $self->{"employee_id"} *= 1;
1945
1946   $main::lxdebug->leave_sub();
1947 }
1948
1949 sub get_employee_data {
1950   $main::lxdebug->enter_sub();
1951
1952   my $self     = shift;
1953   my %params   = @_;
1954   my $defaults = SL::DB::Default->get;
1955
1956   Common::check_params(\%params, qw(prefix));
1957   Common::check_params_x(\%params, qw(id));
1958
1959   if (!$params{id}) {
1960     $main::lxdebug->leave_sub();
1961     return;
1962   }
1963
1964   my $myconfig = \%main::myconfig;
1965   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
1966
1967   my ($login, $deleted)  = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
1968
1969   if ($login) {
1970     # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
1971     $self->{$params{prefix} . '_login'}   = $login;
1972     $self->{$params{prefix} . "_${_}"}    = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
1973
1974     if (!$deleted) {
1975       # get employee data from auth.user_config
1976       my $user = User->new(login => $login);
1977       $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
1978     } else {
1979       # get saved employee data from employee
1980       my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
1981       $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
1982       $self->{$params{prefix} . "_name"} = $employee->name;
1983     }
1984  }
1985   $main::lxdebug->leave_sub();
1986 }
1987
1988 sub _get_contacts {
1989   $main::lxdebug->enter_sub();
1990
1991   my ($self, $dbh, $id, $key) = @_;
1992
1993   $key = "all_contacts" unless ($key);
1994
1995   if (!$id) {
1996     $self->{$key} = [];
1997     $main::lxdebug->leave_sub();
1998     return;
1999   }
2000
2001   my $query =
2002     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2003     qq|FROM contacts | .
2004     qq|WHERE cp_cv_id = ? | .
2005     qq|ORDER BY lower(cp_name)|;
2006
2007   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2008
2009   $main::lxdebug->leave_sub();
2010 }
2011
2012 sub _get_projects {
2013   $main::lxdebug->enter_sub();
2014
2015   my ($self, $dbh, $key) = @_;
2016
2017   my ($all, $old_id, $where, @values);
2018
2019   if (ref($key) eq "HASH") {
2020     my $params = $key;
2021
2022     $key = "ALL_PROJECTS";
2023
2024     foreach my $p (keys(%{$params})) {
2025       if ($p eq "all") {
2026         $all = $params->{$p};
2027       } elsif ($p eq "old_id") {
2028         $old_id = $params->{$p};
2029       } elsif ($p eq "key") {
2030         $key = $params->{$p};
2031       }
2032     }
2033   }
2034
2035   if (!$all) {
2036     $where = "WHERE active ";
2037     if ($old_id) {
2038       if (ref($old_id) eq "ARRAY") {
2039         my @ids = grep({ $_ } @{$old_id});
2040         if (@ids) {
2041           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2042           push(@values, @ids);
2043         }
2044       } else {
2045         $where .= " OR (id = ?) ";
2046         push(@values, $old_id);
2047       }
2048     }
2049   }
2050
2051   my $query =
2052     qq|SELECT id, projectnumber, description, active | .
2053     qq|FROM project | .
2054     $where .
2055     qq|ORDER BY lower(projectnumber)|;
2056
2057   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2058
2059   $main::lxdebug->leave_sub();
2060 }
2061
2062 sub _get_shipto {
2063   $main::lxdebug->enter_sub();
2064
2065   my ($self, $dbh, $vc_id, $key) = @_;
2066
2067   $key = "all_shipto" unless ($key);
2068
2069   if ($vc_id) {
2070     # get shipping addresses
2071     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2072
2073     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2074
2075   } else {
2076     $self->{$key} = [];
2077   }
2078
2079   $main::lxdebug->leave_sub();
2080 }
2081
2082 sub _get_printers {
2083   $main::lxdebug->enter_sub();
2084
2085   my ($self, $dbh, $key) = @_;
2086
2087   $key = "all_printers" unless ($key);
2088
2089   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2090
2091   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2092
2093   $main::lxdebug->leave_sub();
2094 }
2095
2096 sub _get_charts {
2097   $main::lxdebug->enter_sub();
2098
2099   my ($self, $dbh, $params) = @_;
2100   my ($key);
2101
2102   $key = $params->{key};
2103   $key = "all_charts" unless ($key);
2104
2105   my $transdate = quote_db_date($params->{transdate});
2106
2107   my $query =
2108     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2109     qq|FROM chart c | .
2110     qq|LEFT JOIN taxkeys tk ON | .
2111     qq|(tk.id = (SELECT id FROM taxkeys | .
2112     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2113     qq|          ORDER BY startdate DESC LIMIT 1)) | .
2114     qq|ORDER BY c.accno|;
2115
2116   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2117
2118   $main::lxdebug->leave_sub();
2119 }
2120
2121 sub _get_taxcharts {
2122   $main::lxdebug->enter_sub();
2123
2124   my ($self, $dbh, $params) = @_;
2125
2126   my $key = "all_taxcharts";
2127   my @where;
2128
2129   if (ref $params eq 'HASH') {
2130     $key = $params->{key} if ($params->{key});
2131     if ($params->{module} eq 'AR') {
2132       push @where, 'chart_categories ~ \'[ACILQ]\'';
2133
2134     } elsif ($params->{module} eq 'AP') {
2135       push @where, 'chart_categories ~ \'[ACELQ]\'';
2136     }
2137
2138   } elsif ($params) {
2139     $key = $params;
2140   }
2141
2142   my $where = @where ? ' WHERE ' . join(' AND ', map { "($_)" } @where) : '';
2143
2144   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey, rate|;
2145
2146   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2147
2148   $main::lxdebug->leave_sub();
2149 }
2150
2151 sub _get_taxzones {
2152   $main::lxdebug->enter_sub();
2153
2154   my ($self, $dbh, $key) = @_;
2155
2156   $key = "all_taxzones" unless ($key);
2157   my $tzfilter = "";
2158   $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
2159
2160   my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
2161
2162   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2163
2164   $main::lxdebug->leave_sub();
2165 }
2166
2167 sub _get_employees {
2168   $main::lxdebug->enter_sub();
2169
2170   my ($self, $dbh, $params) = @_;
2171
2172   my $deleted = 0;
2173
2174   my $key;
2175   if (ref $params eq 'HASH') {
2176     $key     = $params->{key};
2177     $deleted = $params->{deleted};
2178
2179   } else {
2180     $key = $params;
2181   }
2182
2183   $key     ||= "all_employees";
2184   my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
2185   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
2186
2187   $main::lxdebug->leave_sub();
2188 }
2189
2190 sub _get_business_types {
2191   $main::lxdebug->enter_sub();
2192
2193   my ($self, $dbh, $key) = @_;
2194
2195   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
2196   $options->{key} ||= "all_business_types";
2197   my $where         = '';
2198
2199   if (exists $options->{salesman}) {
2200     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2201   }
2202
2203   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2204
2205   $main::lxdebug->leave_sub();
2206 }
2207
2208 sub _get_languages {
2209   $main::lxdebug->enter_sub();
2210
2211   my ($self, $dbh, $key) = @_;
2212
2213   $key = "all_languages" unless ($key);
2214
2215   my $query = qq|SELECT * FROM language ORDER BY id|;
2216
2217   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2218
2219   $main::lxdebug->leave_sub();
2220 }
2221
2222 sub _get_dunning_configs {
2223   $main::lxdebug->enter_sub();
2224
2225   my ($self, $dbh, $key) = @_;
2226
2227   $key = "all_dunning_configs" unless ($key);
2228
2229   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2230
2231   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2232
2233   $main::lxdebug->leave_sub();
2234 }
2235
2236 sub _get_currencies {
2237 $main::lxdebug->enter_sub();
2238
2239   my ($self, $dbh, $key) = @_;
2240
2241   $key = "all_currencies" unless ($key);
2242
2243   $self->{$key} = [$self->get_all_currencies()];
2244
2245   $main::lxdebug->leave_sub();
2246 }
2247
2248 sub _get_payments {
2249 $main::lxdebug->enter_sub();
2250
2251   my ($self, $dbh, $key) = @_;
2252
2253   $key = "all_payments" unless ($key);
2254
2255   my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2256
2257   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2258
2259   $main::lxdebug->leave_sub();
2260 }
2261
2262 sub _get_customers {
2263   $main::lxdebug->enter_sub();
2264
2265   my ($self, $dbh, $key) = @_;
2266
2267   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
2268   $options->{key}  ||= "all_customers";
2269   my $limit_clause   = $options->{limit} ? "LIMIT $options->{limit}" : '';
2270
2271   my @where;
2272   push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if  $options->{business_is_salesman};
2273   push @where, qq|NOT obsolete|                                            if !$options->{with_obsolete};
2274   my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2275
2276   my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2277   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2278
2279   $main::lxdebug->leave_sub();
2280 }
2281
2282 sub _get_vendors {
2283   $main::lxdebug->enter_sub();
2284
2285   my ($self, $dbh, $key) = @_;
2286
2287   $key = "all_vendors" unless ($key);
2288
2289   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2290
2291   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2292
2293   $main::lxdebug->leave_sub();
2294 }
2295
2296 sub _get_departments {
2297   $main::lxdebug->enter_sub();
2298
2299   my ($self, $dbh, $key) = @_;
2300
2301   $key = "all_departments" unless ($key);
2302
2303   my $query = qq|SELECT * FROM department ORDER BY description|;
2304
2305   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2306
2307   $main::lxdebug->leave_sub();
2308 }
2309
2310 sub _get_warehouses {
2311   $main::lxdebug->enter_sub();
2312
2313   my ($self, $dbh, $param) = @_;
2314
2315   my ($key, $bins_key);
2316
2317   if ('' eq ref $param) {
2318     $key = $param;
2319
2320   } else {
2321     $key      = $param->{key};
2322     $bins_key = $param->{bins};
2323   }
2324
2325   my $query = qq|SELECT w.* FROM warehouse w
2326                  WHERE (NOT w.invalid) AND
2327                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2328                  ORDER BY w.sortkey|;
2329
2330   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2331
2332   if ($bins_key) {
2333     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2334                 ORDER BY description|;
2335     my $sth = prepare_query($self, $dbh, $query);
2336
2337     foreach my $warehouse (@{ $self->{$key} }) {
2338       do_statement($self, $sth, $query, $warehouse->{id});
2339       $warehouse->{$bins_key} = [];
2340
2341       while (my $ref = $sth->fetchrow_hashref()) {
2342         push @{ $warehouse->{$bins_key} }, $ref;
2343       }
2344     }
2345     $sth->finish();
2346   }
2347
2348   $main::lxdebug->leave_sub();
2349 }
2350
2351 sub _get_simple {
2352   $main::lxdebug->enter_sub();
2353
2354   my ($self, $dbh, $table, $key, $sortkey) = @_;
2355
2356   my $query  = qq|SELECT * FROM $table|;
2357   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
2358
2359   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2360
2361   $main::lxdebug->leave_sub();
2362 }
2363
2364 #sub _get_groups {
2365 #  $main::lxdebug->enter_sub();
2366 #
2367 #  my ($self, $dbh, $key) = @_;
2368 #
2369 #  $key ||= "all_groups";
2370 #
2371 #  my $groups = $main::auth->read_groups();
2372 #
2373 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2374 #
2375 #  $main::lxdebug->leave_sub();
2376 #}
2377
2378 sub get_lists {
2379   $main::lxdebug->enter_sub();
2380
2381   my $self = shift;
2382   my %params = @_;
2383
2384   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2385   my ($sth, $query, $ref);
2386
2387   my ($vc, $vc_id);
2388   if ($params{contacts} || $params{shipto}) {
2389     $vc = 'customer' if $self->{"vc"} eq "customer";
2390     $vc = 'vendor'   if $self->{"vc"} eq "vendor";
2391     die "invalid use of get_lists, need 'vc'" unless $vc;
2392     $vc_id = $self->{"${vc}_id"};
2393   }
2394
2395   if ($params{"contacts"}) {
2396     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2397   }
2398
2399   if ($params{"shipto"}) {
2400     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2401   }
2402
2403   if ($params{"projects"} || $params{"all_projects"}) {
2404     $self->_get_projects($dbh, $params{"all_projects"} ?
2405                          $params{"all_projects"} : $params{"projects"},
2406                          $params{"all_projects"} ? 1 : 0);
2407   }
2408
2409   if ($params{"printers"}) {
2410     $self->_get_printers($dbh, $params{"printers"});
2411   }
2412
2413   if ($params{"languages"}) {
2414     $self->_get_languages($dbh, $params{"languages"});
2415   }
2416
2417   if ($params{"charts"}) {
2418     $self->_get_charts($dbh, $params{"charts"});
2419   }
2420
2421   if ($params{"taxcharts"}) {
2422     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2423   }
2424
2425   if ($params{"taxzones"}) {
2426     $self->_get_taxzones($dbh, $params{"taxzones"});
2427   }
2428
2429   if ($params{"employees"}) {
2430     $self->_get_employees($dbh, $params{"employees"});
2431   }
2432
2433   if ($params{"salesmen"}) {
2434     $self->_get_employees($dbh, $params{"salesmen"});
2435   }
2436
2437   if ($params{"business_types"}) {
2438     $self->_get_business_types($dbh, $params{"business_types"});
2439   }
2440
2441   if ($params{"dunning_configs"}) {
2442     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2443   }
2444
2445   if($params{"currencies"}) {
2446     $self->_get_currencies($dbh, $params{"currencies"});
2447   }
2448
2449   if($params{"customers"}) {
2450     $self->_get_customers($dbh, $params{"customers"});
2451   }
2452
2453   if($params{"vendors"}) {
2454     if (ref $params{"vendors"} eq 'HASH') {
2455       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2456     } else {
2457       $self->_get_vendors($dbh, $params{"vendors"});
2458     }
2459   }
2460
2461   if($params{"payments"}) {
2462     $self->_get_payments($dbh, $params{"payments"});
2463   }
2464
2465   if($params{"departments"}) {
2466     $self->_get_departments($dbh, $params{"departments"});
2467   }
2468
2469   if ($params{price_factors}) {
2470     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2471   }
2472
2473   if ($params{warehouses}) {
2474     $self->_get_warehouses($dbh, $params{warehouses});
2475   }
2476
2477 #  if ($params{groups}) {
2478 #    $self->_get_groups($dbh, $params{groups});
2479 #  }
2480
2481   if ($params{partsgroup}) {
2482     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2483   }
2484
2485   $main::lxdebug->leave_sub();
2486 }
2487
2488 # this sub gets the id and name from $table
2489 sub get_name {
2490   $main::lxdebug->enter_sub();
2491
2492   my ($self, $myconfig, $table) = @_;
2493
2494   # connect to database
2495   my $dbh = $self->get_standard_dbh($myconfig);
2496
2497   $table = $table eq "customer" ? "customer" : "vendor";
2498   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2499
2500   my ($query, @values);
2501
2502   if (!$self->{openinvoices}) {
2503     my $where;
2504     if ($self->{customernumber} ne "") {
2505       $where = qq|(vc.customernumber ILIKE ?)|;
2506       push(@values, like($self->{customernumber}));
2507     } else {
2508       $where = qq|(vc.name ILIKE ?)|;
2509       push(@values, like($self->{$table}));
2510     }
2511
2512     $query =
2513       qq~SELECT vc.id, vc.name,
2514            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2515          FROM $table vc
2516          WHERE $where AND (NOT vc.obsolete)
2517          ORDER BY vc.name~;
2518   } else {
2519     $query =
2520       qq~SELECT DISTINCT vc.id, vc.name,
2521            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2522          FROM $arap a
2523          JOIN $table vc ON (a.${table}_id = vc.id)
2524          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2525          ORDER BY vc.name~;
2526     push(@values, like($self->{$table}));
2527   }
2528
2529   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2530
2531   $main::lxdebug->leave_sub();
2532
2533   return scalar(@{ $self->{name_list} });
2534 }
2535
2536 sub new_lastmtime {
2537
2538   my ($self, $table, $provided_dbh) = @_;
2539
2540   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
2541   return                                       unless $self->{id};
2542   croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2543
2544   my $query       = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2545   my $ref         = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2546   $ref->{mtime} ||= $ref->{itime};
2547   $self->{lastmtime} = $ref->{mtime};
2548
2549 }
2550
2551 sub mtime_ischanged {
2552   my ($self, $table, $option) = @_;
2553
2554   return                                       unless $self->{id};
2555   croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2556
2557   my $query       = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2558   my $ref         = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
2559   $ref->{mtime} ||= $ref->{itime};
2560
2561   if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
2562       $self->error(($option eq 'mail') ?
2563         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") :
2564         t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
2565       );
2566     $::dispatcher->end_request;
2567   }
2568 }
2569
2570 # language_payment duplicates some of the functionality of all_vc (language,
2571 # printer, payment_terms), and at least in the case of sales invoices both
2572 # all_vc and language_payment are called when adding new invoices
2573 sub language_payment {
2574   $main::lxdebug->enter_sub();
2575
2576   my ($self, $myconfig) = @_;
2577
2578   my $dbh = $self->get_standard_dbh($myconfig);
2579   # get languages
2580   my $query = qq|SELECT id, description
2581                  FROM language
2582                  ORDER BY id|;
2583
2584   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2585
2586   # get printer
2587   $query = qq|SELECT printer_description, id
2588               FROM printers
2589               ORDER BY printer_description|;
2590
2591   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2592
2593   # get payment terms
2594   $query = qq|SELECT id, description
2595               FROM payment_terms
2596               WHERE ( obsolete IS FALSE OR id = ? )
2597               ORDER BY sortkey |;
2598   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
2599
2600   # get buchungsgruppen
2601   $query = qq|SELECT id, description
2602               FROM buchungsgruppen|;
2603
2604   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2605
2606   $main::lxdebug->leave_sub();
2607 }
2608
2609 # this is only used for reports
2610 sub all_departments {
2611   $main::lxdebug->enter_sub();
2612
2613   my ($self, $myconfig, $table) = @_;
2614
2615   my $dbh = $self->get_standard_dbh($myconfig);
2616
2617   my $query = qq|SELECT id, description
2618                  FROM department
2619                  ORDER BY description|;
2620   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2621
2622   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2623
2624   $main::lxdebug->leave_sub();
2625 }
2626
2627 sub create_links {
2628   $main::lxdebug->enter_sub();
2629
2630   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2631
2632   my ($fld, $arap);
2633   if ($table eq "customer") {
2634     $fld = "buy";
2635     $arap = "ar";
2636   } else {
2637     $table = "vendor";
2638     $fld = "sell";
2639     $arap = "ap";
2640   }
2641
2642   # get last customers or vendors
2643   my ($query, $sth, $ref);
2644
2645   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2646   my %xkeyref = ();
2647
2648   if (!$self->{id}) {
2649
2650     my $transdate = "current_date";
2651     if ($self->{transdate}) {
2652       $transdate = $dbh->quote($self->{transdate});
2653     }
2654
2655     # now get the account numbers
2656     $query = qq|
2657       SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
2658         FROM chart c
2659         -- find newest entries in taxkeys
2660         INNER JOIN (
2661           SELECT chart_id, MAX(startdate) AS startdate
2662           FROM taxkeys
2663           WHERE (startdate <= $transdate)
2664           GROUP BY chart_id
2665         ) tk ON (c.id = tk.chart_id)
2666         -- and load all of those entries
2667         INNER JOIN taxkeys tk2
2668            ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
2669        WHERE (c.link LIKE ?)
2670       ORDER BY c.accno|;
2671
2672     $sth = $dbh->prepare($query);
2673
2674     do_statement($self, $sth, $query, like($module));
2675
2676     $self->{accounts} = "";
2677     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2678
2679       foreach my $key (split(/:/, $ref->{link})) {
2680         if ($key =~ /\Q$module\E/) {
2681
2682           # cross reference for keys
2683           $xkeyref{ $ref->{accno} } = $key;
2684
2685           push @{ $self->{"${module}_links"}{$key} },
2686             { accno       => $ref->{accno},
2687               chart_id    => $ref->{chart_id},
2688               description => $ref->{description},
2689               taxkey      => $ref->{taxkey_id},
2690               tax_id      => $ref->{tax_id} };
2691
2692           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2693         }
2694       }
2695     }
2696   }
2697
2698   # get taxkeys and description
2699   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2700   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2701
2702   if (($module eq "AP") || ($module eq "AR")) {
2703     # get tax rates and description
2704     $query = qq|SELECT * FROM tax|;
2705     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2706   }
2707
2708   my $extra_columns = '';
2709   $extra_columns   .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
2710
2711   if ($self->{id}) {
2712     $query =
2713       qq|SELECT
2714            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2715            a.duedate, a.ordnumber, a.taxincluded, (SELECT cu.name FROM currencies cu WHERE cu.id=a.currency_id) AS currency, a.notes,
2716            a.mtime, a.itime,
2717            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2718            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2719            a.globalproject_id, ${extra_columns}
2720            c.name AS $table,
2721            d.description AS department,
2722            e.name AS employee
2723          FROM $arap a
2724          JOIN $table c ON (a.${table}_id = c.id)
2725          LEFT JOIN employee e ON (e.id = a.employee_id)
2726          LEFT JOIN department d ON (d.id = a.department_id)
2727          WHERE a.id = ?|;
2728     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2729
2730     foreach my $key (keys %$ref) {
2731       $self->{$key} = $ref->{$key};
2732     }
2733     $self->{mtime}   ||= $self->{itime};
2734     $self->{lastmtime} = $self->{mtime};
2735     my $transdate = "current_date";
2736     if ($self->{transdate}) {
2737       $transdate = $dbh->quote($self->{transdate});
2738     }
2739
2740     # now get the account numbers
2741     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
2742                 FROM chart c
2743                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2744                 WHERE c.link LIKE ?
2745                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2746                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2747                 ORDER BY c.accno|;
2748
2749     $sth = $dbh->prepare($query);
2750     do_statement($self, $sth, $query, like($module));
2751
2752     $self->{accounts} = "";
2753     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2754
2755       foreach my $key (split(/:/, $ref->{link})) {
2756         if ($key =~ /\Q$module\E/) {
2757
2758           # cross reference for keys
2759           $xkeyref{ $ref->{accno} } = $key;
2760
2761           push @{ $self->{"${module}_links"}{$key} },
2762             { accno       => $ref->{accno},
2763               chart_id    => $ref->{chart_id},
2764               description => $ref->{description},
2765               taxkey      => $ref->{taxkey_id},
2766               tax_id      => $ref->{tax_id} };
2767
2768           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2769         }
2770       }
2771     }
2772
2773
2774     # get amounts from individual entries
2775     $query =
2776       qq|SELECT
2777            c.accno, c.description,
2778            a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
2779            p.projectnumber,
2780            t.rate, t.id
2781          FROM acc_trans a
2782          LEFT JOIN chart c ON (c.id = a.chart_id)
2783          LEFT JOIN project p ON (p.id = a.project_id)
2784          LEFT JOIN tax t ON (t.id= a.tax_id)
2785          WHERE a.trans_id = ?
2786          AND a.fx_transaction = '0'
2787          ORDER BY a.acc_trans_id, a.transdate|;
2788     $sth = $dbh->prepare($query);
2789     do_statement($self, $sth, $query, $self->{id});
2790
2791     # get exchangerate for currency
2792     $self->{exchangerate} =
2793       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2794     my $index = 0;
2795
2796     # store amounts in {acc_trans}{$key} for multiple accounts
2797     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2798       $ref->{exchangerate} =
2799         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2800       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2801         $index++;
2802       }
2803       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2804         $ref->{amount} *= -1;
2805       }
2806       $ref->{index} = $index;
2807
2808       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2809     }
2810
2811     $sth->finish;
2812     #check das:
2813     $query =
2814       qq|SELECT
2815            d.closedto, d.revtrans,
2816            (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2817            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2818            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2819            (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2820            (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2821          FROM defaults d|;
2822     $ref = selectfirst_hashref_query($self, $dbh, $query);
2823     map { $self->{$_} = $ref->{$_} } keys %$ref;
2824
2825   } else {
2826
2827     # get date
2828     $query =
2829        qq|SELECT
2830             current_date AS transdate, d.closedto, d.revtrans,
2831             (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2832             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2833             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2834             (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2835             (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2836           FROM defaults d|;
2837     $ref = selectfirst_hashref_query($self, $dbh, $query);
2838     map { $self->{$_} = $ref->{$_} } keys %$ref;
2839
2840     if ($self->{"$self->{vc}_id"}) {
2841
2842       # only setup currency
2843       ($self->{currency}) = $self->{defaultcurrency} if !$self->{currency};
2844
2845     } else {
2846
2847       $self->lastname_used($dbh, $myconfig, $table, $module);
2848
2849       # get exchangerate for currency
2850       $self->{exchangerate} =
2851         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2852
2853     }
2854
2855   }
2856
2857   $main::lxdebug->leave_sub();
2858 }
2859
2860 sub lastname_used {
2861   $main::lxdebug->enter_sub();
2862
2863   my ($self, $dbh, $myconfig, $table, $module) = @_;
2864
2865   my ($arap, $where);
2866
2867   $table         = $table eq "customer" ? "customer" : "vendor";
2868   my %column_map = ("a.${table}_id"           => "${table}_id",
2869                     "a.department_id"         => "department_id",
2870                     "d.description"           => "department",
2871                     "ct.name"                 => $table,
2872                     "cu.name"                 => "currency",
2873     );
2874
2875   if ($self->{type} =~ /delivery_order/) {
2876     $arap  = 'delivery_orders';
2877     delete $column_map{"cu.currency"};
2878
2879   } elsif ($self->{type} =~ /_order/) {
2880     $arap  = 'oe';
2881     $where = "quotation = '0'";
2882
2883   } elsif ($self->{type} =~ /_quotation/) {
2884     $arap  = 'oe';
2885     $where = "quotation = '1'";
2886
2887   } elsif ($table eq 'customer') {
2888     $arap  = 'ar';
2889
2890   } else {
2891     $arap  = 'ap';
2892
2893   }
2894
2895   $where           = "($where) AND" if ($where);
2896   my $query        = qq|SELECT MAX(id) FROM $arap
2897                         WHERE $where ${table}_id > 0|;
2898   my ($trans_id)   = selectrow_query($self, $dbh, $query);
2899   $trans_id       *= 1;
2900
2901   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2902   $query           = qq|SELECT $column_spec
2903                         FROM $arap a
2904                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
2905                         LEFT JOIN department d  ON (a.department_id = d.id)
2906                         LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
2907                         WHERE a.id = ?|;
2908   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2909
2910   map { $self->{$_} = $ref->{$_} } values %column_map;
2911
2912   $main::lxdebug->leave_sub();
2913 }
2914
2915 sub get_variable_content_types {
2916   my %html_variables  = (
2917       longdescription => 'html',
2918       partnotes       => 'html',
2919       notes           => 'html',
2920       orignotes       => 'html',
2921       notes1          => 'html',
2922       notes2          => 'html',
2923       notes3          => 'html',
2924       notes4          => 'html',
2925       header_text     => 'html',
2926       footer_text     => 'html',
2927   );
2928   return \%html_variables;
2929 }
2930
2931 sub current_date {
2932   $main::lxdebug->enter_sub();
2933
2934   my $self     = shift;
2935   my $myconfig = shift || \%::myconfig;
2936   my ($thisdate, $days) = @_;
2937
2938   my $dbh = $self->get_standard_dbh($myconfig);
2939   my $query;
2940
2941   $days *= 1;
2942   if ($thisdate) {
2943     my $dateformat = $myconfig->{dateformat};
2944     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2945     $thisdate = $dbh->quote($thisdate);
2946     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2947   } else {
2948     $query = qq|SELECT current_date AS thisdate|;
2949   }
2950
2951   ($thisdate) = selectrow_query($self, $dbh, $query);
2952
2953   $main::lxdebug->leave_sub();
2954
2955   return $thisdate;
2956 }
2957
2958 sub redo_rows {
2959   $main::lxdebug->enter_sub();
2960
2961   my ($self, $flds, $new, $count, $numrows) = @_;
2962
2963   my @ndx = ();
2964
2965   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2966
2967   my $i = 0;
2968
2969   # fill rows
2970   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2971     $i++;
2972     my $j = $item->{ndx} - 1;
2973     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2974   }
2975
2976   # delete empty rows
2977   for $i ($count + 1 .. $numrows) {
2978     map { delete $self->{"${_}_$i"} } @{$flds};
2979   }
2980
2981   $main::lxdebug->leave_sub();
2982 }
2983
2984 sub update_status {
2985   $main::lxdebug->enter_sub();
2986
2987   my ($self, $myconfig) = @_;
2988
2989   my ($i, $id);
2990
2991   SL::DB->client->with_transaction(sub {
2992     my $dbh = SL::DB->client->dbh;
2993
2994     my $query = qq|DELETE FROM status
2995                    WHERE (formname = ?) AND (trans_id = ?)|;
2996     my $sth = prepare_query($self, $dbh, $query);
2997
2998     if ($self->{formname} =~ /(check|receipt)/) {
2999       for $i (1 .. $self->{rowcount}) {
3000         do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3001       }
3002     } else {
3003       do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3004     }
3005     $sth->finish();
3006
3007     my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3008     my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3009
3010     my %queued = split / /, $self->{queued};
3011     my @values;
3012
3013     if ($self->{formname} =~ /(check|receipt)/) {
3014
3015       # this is a check or receipt, add one entry for each lineitem
3016       my ($accno) = split /--/, $self->{account};
3017       $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3018                   VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3019       @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3020       $sth = prepare_query($self, $dbh, $query);
3021
3022       for $i (1 .. $self->{rowcount}) {
3023         if ($self->{"checked_$i"}) {
3024           do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3025         }
3026       }
3027       $sth->finish();
3028
3029     } else {
3030       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3031                   VALUES (?, ?, ?, ?, ?)|;
3032       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3033                $queued{$self->{formname}}, $self->{formname});
3034     }
3035     1;
3036   }) or do { die SL::DB->client->error };
3037
3038   $main::lxdebug->leave_sub();
3039 }
3040
3041 sub save_status {
3042   $main::lxdebug->enter_sub();
3043
3044   my ($self, $dbh) = @_;
3045
3046   my ($query, $printed, $emailed);
3047
3048   my $formnames  = $self->{printed};
3049   my $emailforms = $self->{emailed};
3050
3051   $query = qq|DELETE FROM status
3052                  WHERE (formname = ?) AND (trans_id = ?)|;
3053   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3054
3055   # this only applies to the forms
3056   # checks and receipts are posted when printed or queued
3057
3058   if ($self->{queued}) {
3059     my %queued = split / /, $self->{queued};
3060
3061     foreach my $formname (keys %queued) {
3062       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3063       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3064
3065       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3066                   VALUES (?, ?, ?, ?, ?)|;
3067       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3068
3069       $formnames  =~ s/\Q$self->{formname}\E//;
3070       $emailforms =~ s/\Q$self->{formname}\E//;
3071
3072     }
3073   }
3074
3075   # save printed, emailed info
3076   $formnames  =~ s/^ +//g;
3077   $emailforms =~ s/^ +//g;
3078
3079   my %status = ();
3080   map { $status{$_}{printed} = 1 } split / +/, $formnames;
3081   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3082
3083   foreach my $formname (keys %status) {
3084     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
3085     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3086
3087     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3088                 VALUES (?, ?, ?, ?)|;
3089     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3090   }
3091
3092   $main::lxdebug->leave_sub();
3093 }
3094
3095 #--- 4 locale ---#
3096 # $main::locale->text('SAVED')
3097 # $main::locale->text('SCREENED')
3098 # $main::locale->text('DELETED')
3099 # $main::locale->text('ADDED')
3100 # $main::locale->text('PAYMENT POSTED')
3101 # $main::locale->text('POSTED')
3102 # $main::locale->text('POSTED AS NEW')
3103 # $main::locale->text('ELSE')
3104 # $main::locale->text('SAVED FOR DUNNING')
3105 # $main::locale->text('DUNNING STARTED')
3106 # $main::locale->text('PRINTED')
3107 # $main::locale->text('MAILED')
3108 # $main::locale->text('SCREENED')
3109 # $main::locale->text('CANCELED')
3110 # $main::locale->text('IMPORT')
3111 # $main::locale->text('UNIMPORT')
3112 # $main::locale->text('invoice')
3113 # $main::locale->text('proforma')
3114 # $main::locale->text('sales_order')
3115 # $main::locale->text('pick_list')
3116 # $main::locale->text('purchase_order')
3117 # $main::locale->text('bin_list')
3118 # $main::locale->text('sales_quotation')
3119 # $main::locale->text('request_quotation')
3120
3121 sub save_history {
3122   $main::lxdebug->enter_sub();
3123
3124   my $self = shift;
3125   my $dbh  = shift || SL::DB->client->dbh;
3126   SL::DB->client->with_transaction(sub {
3127
3128     if(!exists $self->{employee_id}) {
3129       &get_employee($self, $dbh);
3130     }
3131
3132     my $query =
3133      qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3134      qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3135     my @values = (conv_i($self->{id}), $self->{login},
3136                   $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3137     do_query($self, $dbh, $query, @values);
3138     1;
3139   }) or do { die SL::DB->client->error };
3140
3141   $main::lxdebug->leave_sub();
3142 }
3143
3144 sub get_history {
3145   $main::lxdebug->enter_sub();
3146
3147   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3148   my ($orderBy, $desc) = split(/\-\-/, $order);
3149   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3150   my @tempArray;
3151   my $i = 0;
3152   if ($trans_id ne "") {
3153     my $query =
3154       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 | .
3155       qq|FROM history_erp h | .
3156       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3157       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3158       $order;
3159
3160     my $sth = $dbh->prepare($query) || $self->dberror($query);
3161
3162     $sth->execute() || $self->dberror("$query");
3163
3164     while(my $hash_ref = $sth->fetchrow_hashref()) {
3165       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3166       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3167       my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
3168       $hash_ref->{snumbers} = $number;
3169       $hash_ref->{haslink}  = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
3170       $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
3171       $tempArray[$i++] = $hash_ref;
3172     }
3173     $main::lxdebug->leave_sub() and return \@tempArray
3174       if ($i > 0 && $tempArray[0] ne "");
3175   }
3176   $main::lxdebug->leave_sub();
3177   return 0;
3178 }
3179
3180 sub get_partsgroup {
3181   $main::lxdebug->enter_sub();
3182
3183   my ($self, $myconfig, $p) = @_;
3184   my $target = $p->{target} || 'all_partsgroup';
3185
3186   my $dbh = $self->get_standard_dbh($myconfig);
3187
3188   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3189                  FROM partsgroup pg
3190                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
3191   my @values;
3192
3193   if ($p->{searchitems} eq 'part') {
3194     $query .= qq|WHERE p.part_type = 'part'|;
3195   }
3196   if ($p->{searchitems} eq 'service') {
3197     $query .= qq|WHERE p.part_type = 'service'|;
3198   }
3199   if ($p->{searchitems} eq 'assembly') {
3200     $query .= qq|WHERE p.part_type = 'assembly'|;
3201   }
3202
3203   $query .= qq|ORDER BY partsgroup|;
3204
3205   if ($p->{all}) {
3206     $query = qq|SELECT id, partsgroup FROM partsgroup
3207                 ORDER BY partsgroup|;
3208   }
3209
3210   if ($p->{language_code}) {
3211     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3212                   t.description AS translation
3213                 FROM partsgroup pg
3214                 JOIN parts p ON (p.partsgroup_id = pg.id)
3215                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3216                 ORDER BY translation|;
3217     @values = ($p->{language_code});
3218   }
3219
3220   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3221
3222   $main::lxdebug->leave_sub();
3223 }
3224
3225 sub get_pricegroup {
3226   $main::lxdebug->enter_sub();
3227
3228   my ($self, $myconfig, $p) = @_;
3229
3230   my $dbh = $self->get_standard_dbh($myconfig);
3231
3232   my $query = qq|SELECT p.id, p.pricegroup
3233                  FROM pricegroup p|;
3234
3235   $query .= qq| ORDER BY pricegroup|;
3236
3237   if ($p->{all}) {
3238     $query = qq|SELECT id, pricegroup FROM pricegroup
3239                 ORDER BY pricegroup|;
3240   }
3241
3242   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3243
3244   $main::lxdebug->leave_sub();
3245 }
3246
3247 sub all_years {
3248 # usage $form->all_years($myconfig, [$dbh])
3249 # return list of all years where bookings found
3250 # (@all_years)
3251
3252   $main::lxdebug->enter_sub();
3253
3254   my ($self, $myconfig, $dbh) = @_;
3255
3256   $dbh ||= $self->get_standard_dbh($myconfig);
3257
3258   # get years
3259   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3260                    (SELECT MAX(transdate) FROM acc_trans)|;
3261   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3262
3263   if ($myconfig->{dateformat} =~ /^yy/) {
3264     ($startdate) = split /\W/, $startdate;
3265     ($enddate) = split /\W/, $enddate;
3266   } else {
3267     (@_) = split /\W/, $startdate;
3268     $startdate = $_[2];
3269     (@_) = split /\W/, $enddate;
3270     $enddate = $_[2];
3271   }
3272
3273   my @all_years;
3274   $startdate = substr($startdate,0,4);
3275   $enddate = substr($enddate,0,4);
3276
3277   while ($enddate >= $startdate) {
3278     push @all_years, $enddate--;
3279   }
3280
3281   return @all_years;
3282
3283   $main::lxdebug->leave_sub();
3284 }
3285
3286 sub backup_vars {
3287   $main::lxdebug->enter_sub();
3288   my $self = shift;
3289   my @vars = @_;
3290
3291   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3292
3293   $main::lxdebug->leave_sub();
3294 }
3295
3296 sub restore_vars {
3297   $main::lxdebug->enter_sub();
3298
3299   my $self = shift;
3300   my @vars = @_;
3301
3302   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3303
3304   $main::lxdebug->leave_sub();
3305 }
3306
3307 sub prepare_for_printing {
3308   my ($self) = @_;
3309
3310   my $defaults         = SL::DB::Default->get;
3311
3312   $self->{templates} ||= $defaults->templates;
3313   $self->{formname}  ||= $self->{type};
3314   $self->{media}     ||= 'email';
3315
3316   die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3317
3318   # Several fields that used to reside in %::myconfig (stored in
3319   # auth.user_config) are now stored in defaults. Copy them over for
3320   # compatibility.
3321   $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
3322
3323   $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
3324
3325   if (!$self->{employee_id}) {
3326     $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
3327     $self->{"employee_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
3328   }
3329
3330   # Load shipping address from database. If shipto_id is set then it's
3331   # one from the customer's/vendor's master data. Otherwise look an a
3332   # customized address linking back to the current record.
3333   my $shipto_module = $self->{type} =~ /_delivery_order$/                                             ? 'DO'
3334                     : $self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/ ? 'OE'
3335                     :                                                                                   'AR';
3336   my $shipto        = $self->{shipto_id} ? SL::DB::Shipto->new(shipto_id => $self->{shipto_id})->load
3337                     :                      SL::DB::Manager::Shipto->get_first(where => [ module => $shipto_module, trans_id => $self->{id} ]);
3338   if ($shipto) {
3339     $self->{$_} = $shipto->$_ for grep { m{^shipto} } map { $_->name } @{ $shipto->meta->columns };
3340     $self->{"shiptocvar_" . $_->config->name} = $_->value_as_text for @{ $shipto->cvars_by_config };
3341   }
3342
3343   my $language = $self->{language} ? '_' . $self->{language} : '';
3344
3345   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3346   if ($self->{language_id}) {
3347     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3348   }
3349
3350   $output_dateformat   ||= $::myconfig{dateformat};
3351   $output_numberformat ||= $::myconfig{numberformat};
3352   $output_longdates    //= 1;
3353
3354   $self->{myconfig_output_dateformat}   = $output_dateformat   // $::myconfig{dateformat};
3355   $self->{myconfig_output_longdates}    = $output_longdates    // 1;
3356   $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
3357
3358   # Retrieve accounts for tax calculation.
3359   IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3360
3361   if ($self->{type} =~ /_delivery_order$/) {
3362     DO->order_details(\%::myconfig, $self);
3363   } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3364     OE->order_details(\%::myconfig, $self);
3365   } else {
3366     IS->invoice_details(\%::myconfig, $self, $::locale);
3367   }
3368
3369   # Chose extension & set source file name
3370   my $extension = 'html';
3371   if ($self->{format} eq 'postscript') {
3372     $self->{postscript}   = 1;
3373     $extension            = 'tex';
3374   } elsif ($self->{"format"} =~ /pdf/) {
3375     $self->{pdf}          = 1;
3376     $extension            = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3377   } elsif ($self->{"format"} =~ /opendocument/) {
3378     $self->{opendocument} = 1;
3379     $extension            = 'odt';
3380   } elsif ($self->{"format"} =~ /excel/) {
3381     $self->{excel}        = 1;
3382     $extension            = 'xls';
3383   }
3384
3385   my $printer_code    = $self->{printer_code} ? '_' . $self->{printer_code} : '';
3386   my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
3387   $self->{IN}         = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3388
3389   # Format dates.
3390   $self->format_dates($output_dateformat, $output_longdates,
3391                       qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate datepaid
3392                          transdate_oe deliverydate_oe employee_startdate employee_enddate),
3393                       grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3394
3395   $self->reformat_numbers($output_numberformat, 2,
3396                           qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3397                           grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3398
3399   $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3400
3401   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3402
3403   if (scalar @{ $cvar_date_fields }) {
3404     $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3405   }
3406
3407   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3408     $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3409   }
3410
3411   $self->{template_meta} = {
3412     formname  => $self->{formname},
3413     language  => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
3414     format    => $self->{format},
3415     media     => $self->{media},
3416     extension => $extension,
3417     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
3418     today     => DateTime->today,
3419   };
3420
3421   return $self;
3422 }
3423
3424 sub calculate_arap {
3425   my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
3426
3427   # this function is used to calculate netamount, total_tax and amount for AP and
3428   # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
3429   # (1..$rowcount)
3430   # Thus it needs a fully prepared $form to work on.
3431   # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
3432
3433   # The calculated total values are all rounded (default is to 2 places) and
3434   # returned as parameters rather than directly modifying form.  The aim is to
3435   # make the calculation of AP and AR behave identically.  There is a test-case
3436   # for this function in t/form/arap.t
3437
3438   # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
3439   # modified and formatted and receive the correct sign for writing straight to
3440   # acc_trans, depending on whether they are ar or ap.
3441
3442   # check parameters
3443   die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
3444   die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
3445   die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
3446   $roundplaces = 2 unless $roundplaces;
3447
3448   my $sign = 1;  # adjust final results for writing amount to acc_trans
3449   $sign = -1 if $buysell eq 'buy';
3450
3451   my ($netamount,$total_tax,$amount);
3452
3453   my $tax;
3454
3455   # parse and round amounts, setting correct sign for writing to acc_trans
3456   for my $i (1 .. $self->{rowcount}) {
3457     $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
3458
3459     $amount += $self->{"amount_$i"} * $sign;
3460   }
3461
3462   for my $i (1 .. $self->{rowcount}) {
3463     next unless $self->{"amount_$i"};
3464     ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
3465     my $tax_id = $self->{"tax_id_$i"};
3466
3467     my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
3468
3469     if ( $selected_tax ) {
3470
3471       if ( $buysell eq 'sell' ) {
3472         $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3473       } else {
3474         $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3475       };
3476
3477       $self->{"taxkey_$i"} = $selected_tax->taxkey;
3478       $self->{"taxrate_$i"} = $selected_tax->rate;
3479     };
3480
3481     ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
3482
3483     $netamount  += $self->{"amount_$i"};
3484     $total_tax  += $self->{"tax_$i"};
3485
3486   }
3487   $amount = $netamount + $total_tax;
3488
3489   # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
3490   # but reverse sign of totals for writing amounts to ar
3491   if ( $buysell eq 'buy' ) {
3492     $netamount *= -1;
3493     $amount    *= -1;
3494     $total_tax *= -1;
3495   };
3496
3497   return($netamount,$total_tax,$amount);
3498 }
3499
3500 sub format_dates {
3501   my ($self, $dateformat, $longformat, @indices) = @_;
3502
3503   $dateformat ||= $::myconfig{dateformat};
3504
3505   foreach my $idx (@indices) {
3506     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3507       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3508         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3509       }
3510     }
3511
3512     next unless defined $self->{$idx};
3513
3514     if (!ref($self->{$idx})) {
3515       $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3516
3517     } elsif (ref($self->{$idx}) eq "ARRAY") {
3518       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3519         $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3520       }
3521     }
3522   }
3523 }
3524
3525 sub reformat_numbers {
3526   my ($self, $numberformat, $places, @indices) = @_;
3527
3528   return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3529
3530   foreach my $idx (@indices) {
3531     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3532       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3533         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3534       }
3535     }
3536
3537     next unless defined $self->{$idx};
3538
3539     if (!ref($self->{$idx})) {
3540       $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3541
3542     } elsif (ref($self->{$idx}) eq "ARRAY") {
3543       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3544         $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3545       }
3546     }
3547   }
3548
3549   my $saved_numberformat    = $::myconfig{numberformat};
3550   $::myconfig{numberformat} = $numberformat;
3551
3552   foreach my $idx (@indices) {
3553     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3554       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3555         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3556       }
3557     }
3558
3559     next unless defined $self->{$idx};
3560
3561     if (!ref($self->{$idx})) {
3562       $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3563
3564     } elsif (ref($self->{$idx}) eq "ARRAY") {
3565       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3566         $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3567       }
3568     }
3569   }
3570
3571   $::myconfig{numberformat} = $saved_numberformat;
3572 }
3573
3574 sub create_email_signature {
3575
3576   my $client_signature = $::instance_conf->get_signature;
3577   my $user_signature   = $::myconfig{signature};
3578
3579   my $signature = '';
3580   if ( $client_signature or $user_signature ) {
3581     $signature  = "\n\n-- \n";
3582     $signature .= $user_signature   . "\n" if $user_signature;
3583     $signature .= $client_signature . "\n" if $client_signature;
3584   };
3585   return $signature;
3586
3587 };
3588
3589 sub calculate_tax {
3590   # this function calculates the net amount and tax for the lines in ar, ap and
3591   # gl and is used for update as well as post. When used with update the return
3592   # value of amount isn't needed
3593
3594   # calculate_tax should always work with positive values, or rather as the user inputs them
3595   # calculate_tax uses db/perl numberformat, i.e. parsed numbers
3596   # convert to negative numbers (when necessary) only when writing to acc_trans
3597   # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
3598   # for post_transaction amount already contains exchangerate and correct sign and is rounded
3599   # calculate_tax doesn't (need to) know anything about exchangerate
3600
3601   my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
3602
3603   $roundplaces //= 2;
3604   $taxincluded //= 0;
3605
3606   my $tax;
3607
3608   if ($taxincluded) {
3609     # calculate tax (unrounded), subtract from amount, round amount and round tax
3610     $tax       = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
3611     $amount    = $self->round_amount($amount - $tax, $roundplaces);
3612     $tax       = $self->round_amount($tax, $roundplaces);
3613   } else {
3614     $tax       = $amount * $taxrate;
3615     $tax       = $self->round_amount($tax, $roundplaces);
3616   }
3617
3618   $tax = 0 unless $tax;
3619
3620   return ($amount,$tax);
3621 };
3622
3623 1;
3624
3625 __END__
3626
3627 =head1 NAME
3628
3629 SL::Form.pm - main data object.
3630
3631 =head1 SYNOPSIS
3632
3633 This is the main data object of kivitendo.
3634 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3635 Points of interest for a beginner are:
3636
3637  - $form->error            - renders a generic error in html. accepts an error message
3638  - $form->get_standard_dbh - returns a database connection for the
3639
3640 =head1 SPECIAL FUNCTIONS
3641
3642 =head2 C<redirect_header> $url
3643
3644 Generates a HTTP redirection header for the new C<$url>. Constructs an
3645 absolute URL including scheme, host name and port. If C<$url> is a
3646 relative URL then it is considered relative to kivitendo base URL.
3647
3648 This function C<die>s if headers have already been created with
3649 C<$::form-E<gt>header>.
3650
3651 Examples:
3652
3653   print $::form->redirect_header('oe.pl?action=edit&id=1234');
3654   print $::form->redirect_header('http://www.lx-office.org/');
3655
3656 =head2 C<header>
3657
3658 Generates a general purpose http/html header and includes most of the scripts
3659 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3660
3661 Only one header will be generated. If the method was already called in this
3662 request it will not output anything and return undef. Also if no
3663 HTTP_USER_AGENT is found, no header is generated.
3664
3665 Although header does not accept parameters itself, it will honor special
3666 hashkeys of its Form instance:
3667
3668 =over 4
3669
3670 =item refresh_time
3671
3672 =item refresh_url
3673
3674 If one of these is set, a http-equiv refresh is generated. Missing parameters
3675 default to 3 seconds and the refering url.
3676
3677 =item stylesheet
3678
3679 Either a scalar or an array ref. Will be inlined into the header. Add
3680 stylesheets with the L<use_stylesheet> function.
3681
3682 =item landscape
3683
3684 If true, a css snippet will be generated that sets the page in landscape mode.
3685
3686 =item favicon
3687
3688 Used to override the default favicon.
3689
3690 =item title
3691
3692 A html page title will be generated from this
3693
3694 =item mtime_ischanged
3695
3696 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
3697
3698 Can be used / called with any table, that has itime and mtime attributes.
3699 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
3700 Can be called wit C<option> mail to generate a different error message.
3701
3702 Returns undef if no save operation has been done yet ($self->{id} not present).
3703 Returns undef if no concurrent write process is detected otherwise a error message.
3704
3705 =back
3706
3707 =cut