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