comment fix
[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                         && $self->{type} ne 'statement';
1070   if ( $ext_for_format eq 'pdf' && $self->doc_storage_enabled ) {
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} && $self->doc_storage_enabled)
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' && $self->doc_storage_enabled) {
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
1203   if ($self->{emailerr}) {
1204     $self->cleanup;
1205     $self->error($::locale->text('The email was not sent due to the following error: #1.', $self->{emailerr}));
1206   }
1207
1208   $self->{email_journal_id} = $mail->{journalentry};
1209   $self->{snumbers}  = "emailjournal" . "_" . $self->{email_journal_id};
1210   $self->{what_done} = $::form->{type};
1211   $self->{addition}  = "MAILED";
1212   $self->save_history;
1213
1214   #write back for message info and mail journal
1215   $self->{cc}  = $mail->{cc};
1216   $self->{bcc} = $mail->{bcc};
1217   $self->{email} = $mail->{to};
1218
1219   $main::lxdebug->leave_sub();
1220 }
1221
1222 sub output_file {
1223   $main::lxdebug->enter_sub();
1224
1225   my ($self,$mimeType,$command_formatter) = @_;
1226   my $numbytes = (-s $self->{tmpfile});
1227   open(IN, "<", $self->{tmpfile})
1228     or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1229   binmode IN;
1230
1231   $self->{copies} = 1 unless $self->{media} eq 'printer';
1232
1233   chdir("$self->{cwd}");
1234   for my $i (1 .. $self->{copies}) {
1235     if ($self->{OUT}) {
1236       $self->{OUT} = $command_formatter->($self->{OUT_MODE}, $self->{OUT});
1237
1238       open  OUT, $self->{OUT_MODE}, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1239       print OUT $_ while <IN>;
1240       close OUT;
1241       seek  IN, 0, 0;
1242
1243     } else {
1244       my %headers = ('-type'       => $mimeType,
1245                      '-connection' => 'close',
1246                      '-charset'    => 'UTF-8');
1247
1248       $self->{attachment_filename} ||= $self->generate_attachment_filename;
1249
1250       if ($self->{attachment_filename}) {
1251         %headers = (
1252           %headers,
1253           '-attachment'     => $self->{attachment_filename},
1254           '-content-length' => $numbytes,
1255           '-charset'        => '',
1256         );
1257       }
1258
1259       print $::request->cgi->header(%headers);
1260
1261       $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1262     }
1263   }
1264   close(IN);
1265   $main::lxdebug->leave_sub();
1266 }
1267
1268 sub get_formname_translation {
1269   $main::lxdebug->enter_sub();
1270   my ($self, $formname) = @_;
1271
1272   $formname ||= $self->{formname};
1273
1274   $self->{recipient_locale} ||=  Locale->lang_to_locale($self->{language});
1275   local $::locale = Locale->new($self->{recipient_locale});
1276
1277   my %formname_translations = (
1278     bin_list                => $main::locale->text('Bin List'),
1279     credit_note             => $main::locale->text('Credit Note'),
1280     invoice                 => $main::locale->text('Invoice'),
1281     pick_list               => $main::locale->text('Pick List'),
1282     proforma                => $main::locale->text('Proforma Invoice'),
1283     purchase_order          => $main::locale->text('Purchase Order'),
1284     request_quotation       => $main::locale->text('RFQ'),
1285     sales_order             => $main::locale->text('Confirmation'),
1286     sales_quotation         => $main::locale->text('Quotation'),
1287     storno_invoice          => $main::locale->text('Storno Invoice'),
1288     sales_delivery_order    => $main::locale->text('Delivery Order'),
1289     purchase_delivery_order => $main::locale->text('Delivery Order'),
1290     dunning                 => $main::locale->text('Dunning'),
1291     dunning1                => $main::locale->text('Payment Reminder'),
1292     dunning2                => $main::locale->text('Dunning'),
1293     dunning3                => $main::locale->text('Last Dunning'),
1294     dunning_invoice         => $main::locale->text('Dunning Invoice'),
1295     letter                  => $main::locale->text('Letter'),
1296     ic_supply               => $main::locale->text('Intra-Community supply'),
1297     statement               => $main::locale->text('Statement'),
1298   );
1299
1300   $main::lxdebug->leave_sub();
1301   return $formname_translations{$formname};
1302 }
1303
1304 sub get_number_prefix_for_type {
1305   $main::lxdebug->enter_sub();
1306   my ($self) = @_;
1307
1308   my $prefix =
1309       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1310     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
1311     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
1312     : ($self->{type} =~ /letter/)                             ? 'letter'
1313     :                                                           'ord';
1314
1315   # better default like this?
1316   # : ($self->{type} =~ /(sales|purcharse)_order/           :  'ord';
1317   # :                                                           'prefix_undefined';
1318
1319   $main::lxdebug->leave_sub();
1320   return $prefix;
1321 }
1322
1323 sub get_extension_for_format {
1324   $main::lxdebug->enter_sub();
1325   my ($self)    = @_;
1326
1327   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
1328                 : $self->{format} =~ /postscript/i   ? ".ps"
1329                 : $self->{format} =~ /opendocument/i ? ".odt"
1330                 : $self->{format} =~ /excel/i        ? ".xls"
1331                 : $self->{format} =~ /html/i         ? ".html"
1332                 :                                      "";
1333
1334   $main::lxdebug->leave_sub();
1335   return $extension;
1336 }
1337
1338 sub generate_attachment_filename {
1339   $main::lxdebug->enter_sub();
1340   my ($self) = @_;
1341
1342   $self->{recipient_locale} ||=  Locale->lang_to_locale($self->{language});
1343   my $recipient_locale = Locale->new($self->{recipient_locale});
1344
1345   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1346   my $prefix              = $self->get_number_prefix_for_type();
1347
1348   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1349     $attachment_filename .= ' (' . $recipient_locale->text('Preview') . ')' . $self->get_extension_for_format();
1350
1351   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1352     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1353
1354   } elsif ($attachment_filename) {
1355     $attachment_filename .=  $self->get_extension_for_format();
1356
1357   } else {
1358     $attachment_filename = "";
1359   }
1360
1361   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
1362   $attachment_filename =~ s|[\s/\\]+|_|g;
1363
1364   $main::lxdebug->leave_sub();
1365   return $attachment_filename;
1366 }
1367
1368 sub generate_email_subject {
1369   $main::lxdebug->enter_sub();
1370   my ($self) = @_;
1371
1372   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1373   my $prefix  = $self->get_number_prefix_for_type();
1374
1375   if ($subject && $self->{"${prefix}number"}) {
1376     $subject .= " " . $self->{"${prefix}number"}
1377   }
1378
1379   $main::lxdebug->leave_sub();
1380   return $subject;
1381 }
1382
1383 sub generate_email_body {
1384   $main::lxdebug->enter_sub();
1385   my ($self) = @_;
1386   # simple german and english will work grammatically (most european languages as well)
1387   # Dear Mr Alan Greenspan:
1388   # Sehr geehrte Frau Meyer,
1389   # A l’attention de Mme Villeroy,
1390   # Gentile Signora Ferrari,
1391   my $body = '';
1392
1393   if ($self->{cp_id}) {
1394     my $givenname = SL::DB::Contact->load_cached($self->{cp_id})->cp_givenname; # for qw(gender givename name);
1395     my $name      = SL::DB::Contact->load_cached($self->{cp_id})->cp_name; # for qw(gender givename name);
1396     my $gender    = SL::DB::Contact->load_cached($self->{cp_id})->cp_gender; # for qw(gender givename name);
1397     my $mf = $gender eq 'f' ? 'female' : 'male';
1398     $body  = GenericTranslations->get(translation_type => "salutation_$mf", language_id => $self->{language_id});
1399     $body .= ' ' . $givenname . ' ' . $name if $body;
1400   } else {
1401     $body  = GenericTranslations->get(translation_type => "salutation_general", language_id => $self->{language_id});
1402   }
1403
1404   return undef unless $body;
1405
1406   $body   .= GenericTranslations->get(translation_type =>"salutation_punctuation_mark", language_id => $self->{language_id}) . "\n";
1407   $body   .= GenericTranslations->get(translation_type =>"preset_text_$self->{formname}", language_id => $self->{language_id});
1408
1409   $body = $main::locale->unquote_special_chars('HTML', $body);
1410
1411   $main::lxdebug->leave_sub();
1412   return $body;
1413 }
1414
1415 sub cleanup {
1416   $main::lxdebug->enter_sub();
1417
1418   my ($self, $application) = @_;
1419
1420   my $error_code = $?;
1421
1422   chdir("$self->{tmpdir}");
1423
1424   my @err = ();
1425   if ((-1 == $error_code) || (127 == (($error_code) >> 8))) {
1426     push @err, $::locale->text('The application "#1" was not found on the system.', $application || 'pdflatex') . ' ' . $::locale->text('Please contact your administrator.');
1427
1428   } elsif (-f "$self->{tmpfile}.err") {
1429     open(FH, "<:encoding(UTF-8)", "$self->{tmpfile}.err");
1430     @err = <FH>;
1431     close(FH);
1432   }
1433
1434   if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
1435     $self->{tmpfile} =~ s|.*/||g;
1436     # strip extension
1437     $self->{tmpfile} =~ s/\.\w+$//g;
1438     my $tmpfile = $self->{tmpfile};
1439     unlink(<$tmpfile.*>);
1440   }
1441
1442   chdir("$self->{cwd}");
1443
1444   $main::lxdebug->leave_sub();
1445
1446   return "@err";
1447 }
1448
1449 sub datetonum {
1450   $main::lxdebug->enter_sub();
1451
1452   my ($self, $date, $myconfig) = @_;
1453   my ($yy, $mm, $dd);
1454
1455   if ($date && $date =~ /\D/) {
1456
1457     if ($myconfig->{dateformat} =~ /^yy/) {
1458       ($yy, $mm, $dd) = split /\D/, $date;
1459     }
1460     if ($myconfig->{dateformat} =~ /^mm/) {
1461       ($mm, $dd, $yy) = split /\D/, $date;
1462     }
1463     if ($myconfig->{dateformat} =~ /^dd/) {
1464       ($dd, $mm, $yy) = split /\D/, $date;
1465     }
1466
1467     $dd *= 1;
1468     $mm *= 1;
1469     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1470     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1471
1472     $dd = "0$dd" if ($dd < 10);
1473     $mm = "0$mm" if ($mm < 10);
1474
1475     $date = "$yy$mm$dd";
1476   }
1477
1478   $main::lxdebug->leave_sub();
1479
1480   return $date;
1481 }
1482
1483 # Database routines used throughout
1484 # DB Handling got moved to SL::DB, these are only shims for compatibility
1485
1486 sub dbconnect {
1487   SL::DB->client->dbh;
1488 }
1489
1490 sub get_standard_dbh {
1491   my $dbh = SL::DB->client->dbh;
1492
1493   if ($dbh && !$dbh->{Active}) {
1494     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$dbh is defined but not Active anymore");
1495     SL::DB->client->dbh(undef);
1496   }
1497
1498   SL::DB->client->dbh;
1499 }
1500
1501 sub disconnect_standard_dbh {
1502   SL::DB->client->dbh->rollback;
1503 }
1504
1505 # /database
1506
1507 sub date_closed {
1508   $main::lxdebug->enter_sub();
1509
1510   my ($self, $date, $myconfig) = @_;
1511   my $dbh = $self->get_standard_dbh;
1512
1513   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1514   my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1515
1516   # Falls $date = '' - Fehlermeldung aus der Datenbank. Ich denke,
1517   # es ist sicher ein conv_date vorher IMMER auszuführen.
1518   # Testfälle ohne definiertes closedto:
1519   #   Leere Datumseingabe i.O.
1520   #     SELECT 1 FROM defaults WHERE '' < closedto
1521   #   normale Zahlungsbuchung Ã¼ber Rechnungsmaske i.O.
1522   #     SELECT 1 FROM defaults WHERE '10.05.2011' < closedto
1523   # Testfälle mit definiertem closedto (30.04.2011):
1524   #  Leere Datumseingabe i.O.
1525   #   SELECT 1 FROM defaults WHERE '' < closedto
1526   # normale Buchung im geschloßenem Zeitraum i.O.
1527   #   SELECT 1 FROM defaults WHERE '21.04.2011' < closedto
1528   #     Fehlermeldung: Es können keine Zahlungen für abgeschlossene Bücher gebucht werden!
1529   # normale Buchung in aktiver Buchungsperiode i.O.
1530   #   SELECT 1 FROM defaults WHERE '01.05.2011' < closedto
1531
1532   my ($closed) = $sth->fetchrow_array;
1533
1534   $main::lxdebug->leave_sub();
1535
1536   return $closed;
1537 }
1538
1539 # prevents bookings to the to far away future
1540 sub date_max_future {
1541   $main::lxdebug->enter_sub();
1542
1543   my ($self, $date, $myconfig) = @_;
1544   my $dbh = $self->get_standard_dbh;
1545
1546   my $query = "SELECT 1 FROM defaults WHERE ? - current_date > max_future_booking_interval";
1547   my $sth = prepare_execute_query($self, $dbh, $query, conv_date($date));
1548
1549   my ($max_future_booking_interval) = $sth->fetchrow_array;
1550
1551   $main::lxdebug->leave_sub();
1552
1553   return $max_future_booking_interval;
1554 }
1555
1556
1557 sub update_balance {
1558   $main::lxdebug->enter_sub();
1559
1560   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1561
1562   # if we have a value, go do it
1563   if ($value != 0) {
1564
1565     # retrieve balance from table
1566     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1567     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1568     my ($balance) = $sth->fetchrow_array;
1569     $sth->finish;
1570
1571     $balance += $value;
1572
1573     # update balance
1574     $query = "UPDATE $table SET $field = $balance WHERE $where";
1575     do_query($self, $dbh, $query, @values);
1576   }
1577   $main::lxdebug->leave_sub();
1578 }
1579
1580 sub update_exchangerate {
1581   $main::lxdebug->enter_sub();
1582
1583   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1584   my ($query);
1585   # some sanity check for currency
1586   if ($curr eq '') {
1587     $main::lxdebug->leave_sub();
1588     return;
1589   }
1590   $query = qq|SELECT name AS curr FROM currencies WHERE id=(SELECT currency_id FROM defaults)|;
1591
1592   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1593
1594   if ($curr eq $defaultcurrency) {
1595     $main::lxdebug->leave_sub();
1596     return;
1597   }
1598
1599   $query = qq|SELECT e.currency_id FROM exchangerate e
1600                  WHERE e.currency_id = (SELECT cu.id FROM currencies cu WHERE cu.name=?) AND e.transdate = ?
1601                  FOR UPDATE|;
1602   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1603
1604   if ($buy == 0) {
1605     $buy = "";
1606   }
1607   if ($sell == 0) {
1608     $sell = "";
1609   }
1610
1611   $buy = conv_i($buy, "NULL");
1612   $sell = conv_i($sell, "NULL");
1613
1614   my $set;
1615   if ($buy != 0 && $sell != 0) {
1616     $set = "buy = $buy, sell = $sell";
1617   } elsif ($buy != 0) {
1618     $set = "buy = $buy";
1619   } elsif ($sell != 0) {
1620     $set = "sell = $sell";
1621   }
1622
1623   if ($sth->fetchrow_array) {
1624     $query = qq|UPDATE exchangerate
1625                 SET $set
1626                 WHERE currency_id = (SELECT id FROM currencies WHERE name = ?)
1627                 AND transdate = ?|;
1628
1629   } else {
1630     $query = qq|INSERT INTO exchangerate (currency_id, buy, sell, transdate)
1631                 VALUES ((SELECT id FROM currencies WHERE name = ?), $buy, $sell, ?)|;
1632   }
1633   $sth->finish;
1634   do_query($self, $dbh, $query, $curr, $transdate);
1635
1636   $main::lxdebug->leave_sub();
1637 }
1638
1639 sub save_exchangerate {
1640   $main::lxdebug->enter_sub();
1641
1642   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1643
1644   SL::DB->client->with_transaction(sub {
1645     my $dbh = SL::DB->client->dbh;
1646
1647     my ($buy, $sell);
1648
1649     $buy  = $rate if $fld eq 'buy';
1650     $sell = $rate if $fld eq 'sell';
1651
1652
1653     $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1654     1;
1655   }) or do { die SL::DB->client->error };
1656
1657   $main::lxdebug->leave_sub();
1658 }
1659
1660 sub get_exchangerate {
1661   $main::lxdebug->enter_sub();
1662
1663   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1664   my ($query);
1665
1666   unless ($transdate && $curr) {
1667     $main::lxdebug->leave_sub();
1668     return 1;
1669   }
1670
1671   $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1672
1673   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1674
1675   if ($curr eq $defaultcurrency) {
1676     $main::lxdebug->leave_sub();
1677     return 1;
1678   }
1679
1680   $query = qq|SELECT e.$fld FROM exchangerate e
1681                  WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1682   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1683
1684
1685
1686   $main::lxdebug->leave_sub();
1687
1688   return $exchangerate;
1689 }
1690
1691 sub check_exchangerate {
1692   $main::lxdebug->enter_sub();
1693
1694   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1695
1696   if ($fld !~/^buy|sell$/) {
1697     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1698   }
1699
1700   unless ($transdate) {
1701     $main::lxdebug->leave_sub();
1702     return "";
1703   }
1704
1705   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1706
1707   if ($currency eq $defaultcurrency) {
1708     $main::lxdebug->leave_sub();
1709     return 1;
1710   }
1711
1712   my $dbh   = $self->get_standard_dbh($myconfig);
1713   my $query = qq|SELECT e.$fld FROM exchangerate e
1714                  WHERE e.currency_id = (SELECT id FROM currencies WHERE name = ?) AND e.transdate = ?|;
1715
1716   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1717
1718   $main::lxdebug->leave_sub();
1719
1720   return $exchangerate;
1721 }
1722
1723 sub get_all_currencies {
1724   $main::lxdebug->enter_sub();
1725
1726   my $self     = shift;
1727   my $myconfig = shift || \%::myconfig;
1728   my $dbh      = $self->get_standard_dbh($myconfig);
1729
1730   my $query = qq|SELECT name FROM currencies|;
1731   my @currencies = map { $_->{name} } selectall_hashref_query($self, $dbh, $query);
1732
1733   $main::lxdebug->leave_sub();
1734
1735   return @currencies;
1736 }
1737
1738 sub get_default_currency {
1739   $main::lxdebug->enter_sub();
1740
1741   my ($self, $myconfig) = @_;
1742   my $dbh      = $self->get_standard_dbh($myconfig);
1743   my $query = qq|SELECT name AS curr FROM currencies WHERE id = (SELECT currency_id FROM defaults)|;
1744
1745   my ($defaultcurrency) = selectrow_query($self, $dbh, $query);
1746
1747   $main::lxdebug->leave_sub();
1748
1749   return $defaultcurrency;
1750 }
1751
1752 sub set_payment_options {
1753   my ($self, $myconfig, $transdate, $type) = @_;
1754
1755   my $terms = $self->{payment_id} ? SL::DB::PaymentTerm->new(id => $self->{payment_id})->load : undef;
1756   return if !$terms;
1757
1758   my $is_invoice                = $type =~ m{invoice}i;
1759
1760   $transdate                  ||= $self->{invdate} || $self->{transdate};
1761   my $due_date                  = $self->{duedate} || $self->{reqdate};
1762
1763   $self->{$_}                   = $terms->$_ for qw(terms_netto terms_skonto percent_skonto);
1764   $self->{payment_description}  = $terms->description;
1765   $self->{netto_date}           = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'net')->to_kivitendo;
1766   $self->{skonto_date}          = $terms->calc_date(reference_date => $transdate, due_date => $due_date, terms => 'discount')->to_kivitendo;
1767
1768   my ($invtotal, $total);
1769   my (%amounts, %formatted_amounts);
1770
1771   if ($self->{type} =~ /_order$/) {
1772     $amounts{invtotal} = $self->{ordtotal};
1773     $amounts{total}    = $self->{ordtotal};
1774
1775   } elsif ($self->{type} =~ /_quotation$/) {
1776     $amounts{invtotal} = $self->{quototal};
1777     $amounts{total}    = $self->{quototal};
1778
1779   } else {
1780     $amounts{invtotal} = $self->{invtotal};
1781     $amounts{total}    = $self->{total};
1782   }
1783   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1784
1785   $amounts{skonto_in_percent}  = 100.0 * $self->{percent_skonto};
1786   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1787   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1788   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1789
1790   foreach (keys %amounts) {
1791     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1792     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1793   }
1794
1795   if ($self->{"language_id"}) {
1796     my $language             = SL::DB::Language->new(id => $self->{language_id})->load;
1797
1798     $self->{payment_terms}   = $type =~ m{invoice}i ? $terms->translated_attribute('description_long_invoice', $language->id) : undef;
1799     $self->{payment_terms} ||= $terms->translated_attribute('description_long', $language->id);
1800
1801     if ($language->output_dateformat) {
1802       foreach my $key (qw(netto_date skonto_date)) {
1803         $self->{$key} = $::locale->reformat_date($myconfig, $self->{$key}, $language->output_dateformat, $language->output_longdates);
1804       }
1805     }
1806
1807     if ($language->output_numberformat && ($language->output_numberformat ne $myconfig->{numberformat})) {
1808       local $myconfig->{numberformat};
1809       $myconfig->{"numberformat"} = $language->output_numberformat;
1810       $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) for keys %amounts;
1811     }
1812   }
1813
1814   $self->{payment_terms} =  $self->{payment_terms} || ($is_invoice ? $terms->description_long_invoice : undef) || $terms->description_long;
1815
1816   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1817   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1818   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1819   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1820   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1821   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1822   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1823   $self->{payment_terms} =~ s/<\%bic\%>/$self->{bic}/g;
1824   $self->{payment_terms} =~ s/<\%iban\%>/$self->{iban}/g;
1825   $self->{payment_terms} =~ s/<\%mandate_date_of_signature\%>/$self->{mandate_date_of_signature}/g;
1826   $self->{payment_terms} =~ s/<\%mandator_id\%>/$self->{mandator_id}/g;
1827
1828   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1829
1830   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1831
1832 }
1833
1834 sub get_template_language {
1835   $main::lxdebug->enter_sub();
1836
1837   my ($self, $myconfig) = @_;
1838
1839   my $template_code = "";
1840
1841   if ($self->{language_id}) {
1842     my $dbh = $self->get_standard_dbh($myconfig);
1843     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1844     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1845   }
1846
1847   $main::lxdebug->leave_sub();
1848
1849   return $template_code;
1850 }
1851
1852 sub get_printer_code {
1853   $main::lxdebug->enter_sub();
1854
1855   my ($self, $myconfig) = @_;
1856
1857   my $template_code = "";
1858
1859   if ($self->{printer_id}) {
1860     my $dbh = $self->get_standard_dbh($myconfig);
1861     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1862     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1863   }
1864
1865   $main::lxdebug->leave_sub();
1866
1867   return $template_code;
1868 }
1869
1870 sub get_shipto {
1871   $main::lxdebug->enter_sub();
1872
1873   my ($self, $myconfig) = @_;
1874
1875   my $template_code = "";
1876
1877   if ($self->{shipto_id}) {
1878     my $dbh = $self->get_standard_dbh($myconfig);
1879     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1880     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1881     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1882
1883     my $cvars = CVar->get_custom_variables(
1884       dbh      => $dbh,
1885       module   => 'ShipTo',
1886       trans_id => $self->{shipto_id},
1887     );
1888     $self->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
1889   }
1890
1891   $main::lxdebug->leave_sub();
1892 }
1893
1894 sub add_shipto {
1895   my ($self, $dbh, $id, $module) = @_;
1896
1897   my $shipto;
1898   my @values;
1899
1900   foreach my $item (qw(name department_1 department_2 street zipcode city country gln
1901                        contact cp_gender phone fax email)) {
1902     if ($self->{"shipto$item"}) {
1903       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1904     }
1905     push(@values, $self->{"shipto${item}"});
1906   }
1907
1908   return if !$shipto;
1909
1910   my $shipto_id = $self->{shipto_id};
1911
1912   if ($self->{shipto_id}) {
1913     my $query = qq|UPDATE shipto set
1914                      shiptoname = ?,
1915                      shiptodepartment_1 = ?,
1916                      shiptodepartment_2 = ?,
1917                      shiptostreet = ?,
1918                      shiptozipcode = ?,
1919                      shiptocity = ?,
1920                      shiptocountry = ?,
1921                      shiptogln = ?,
1922                      shiptocontact = ?,
1923                      shiptocp_gender = ?,
1924                      shiptophone = ?,
1925                      shiptofax = ?,
1926                      shiptoemail = ?
1927                    WHERE shipto_id = ?|;
1928     do_query($self, $dbh, $query, @values, $self->{shipto_id});
1929   } else {
1930     my $query = qq|SELECT * FROM shipto
1931                    WHERE shiptoname = ? AND
1932                      shiptodepartment_1 = ? AND
1933                      shiptodepartment_2 = ? AND
1934                      shiptostreet = ? AND
1935                      shiptozipcode = ? AND
1936                      shiptocity = ? AND
1937                      shiptocountry = ? AND
1938                      shiptogln = ? AND
1939                      shiptocontact = ? AND
1940                      shiptocp_gender = ? AND
1941                      shiptophone = ? AND
1942                      shiptofax = ? AND
1943                      shiptoemail = ? AND
1944                      module = ? AND
1945                      trans_id = ?|;
1946     my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1947     if(!$insert_check){
1948       my $insert_query =
1949         qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1950                                shiptostreet, shiptozipcode, shiptocity, shiptocountry, shiptogln,
1951                                shiptocontact, shiptocp_gender, shiptophone, shiptofax, shiptoemail, module)
1952            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1953       do_query($self, $dbh, $insert_query, $id, @values, $module);
1954
1955       $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1956     }
1957
1958     $shipto_id = $insert_check->{shipto_id};
1959   }
1960
1961   return unless $shipto_id;
1962
1963   CVar->save_custom_variables(
1964     dbh         => $dbh,
1965     module      => 'ShipTo',
1966     trans_id    => $shipto_id,
1967     variables   => $self,
1968     name_prefix => 'shipto',
1969   );
1970 }
1971
1972 sub get_employee {
1973   $main::lxdebug->enter_sub();
1974
1975   my ($self, $dbh) = @_;
1976
1977   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
1978
1979   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1980   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1981   $self->{"employee_id"} *= 1;
1982
1983   $main::lxdebug->leave_sub();
1984 }
1985
1986 sub get_employee_data {
1987   $main::lxdebug->enter_sub();
1988
1989   my $self     = shift;
1990   my %params   = @_;
1991   my $defaults = SL::DB::Default->get;
1992
1993   Common::check_params(\%params, qw(prefix));
1994   Common::check_params_x(\%params, qw(id));
1995
1996   if (!$params{id}) {
1997     $main::lxdebug->leave_sub();
1998     return;
1999   }
2000
2001   my $myconfig = \%main::myconfig;
2002   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
2003
2004   my ($login, $deleted)  = selectrow_query($self, $dbh, qq|SELECT login,deleted FROM employee WHERE id = ?|, conv_i($params{id}));
2005
2006   if ($login) {
2007     # login already fetched and still the same client (mandant) | same for both cases (delete|!delete)
2008     $self->{$params{prefix} . '_login'}   = $login;
2009     $self->{$params{prefix} . "_${_}"}    = $defaults->$_ for qw(address businessnumber co_ustid company duns taxnumber);
2010
2011     if (!$deleted) {
2012       # get employee data from auth.user_config
2013       my $user = User->new(login => $login);
2014       $self->{$params{prefix} . "_${_}"} = $user->{$_} for qw(email fax name signature tel);
2015     } else {
2016       # get saved employee data from employee
2017       my $employee = SL::DB::Manager::Employee->find_by(id => conv_i($params{id}));
2018       $self->{$params{prefix} . "_${_}"} = $employee->{"deleted_$_"} for qw(email fax signature tel);
2019       $self->{$params{prefix} . "_name"} = $employee->name;
2020     }
2021  }
2022   $main::lxdebug->leave_sub();
2023 }
2024
2025 sub _get_contacts {
2026   $main::lxdebug->enter_sub();
2027
2028   my ($self, $dbh, $id, $key) = @_;
2029
2030   $key = "all_contacts" unless ($key);
2031
2032   if (!$id) {
2033     $self->{$key} = [];
2034     $main::lxdebug->leave_sub();
2035     return;
2036   }
2037
2038   my $query =
2039     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2040     qq|FROM contacts | .
2041     qq|WHERE cp_cv_id = ? | .
2042     qq|ORDER BY lower(cp_name)|;
2043
2044   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2045
2046   $main::lxdebug->leave_sub();
2047 }
2048
2049 sub _get_projects {
2050   $main::lxdebug->enter_sub();
2051
2052   my ($self, $dbh, $key) = @_;
2053
2054   my ($all, $old_id, $where, @values);
2055
2056   if (ref($key) eq "HASH") {
2057     my $params = $key;
2058
2059     $key = "ALL_PROJECTS";
2060
2061     foreach my $p (keys(%{$params})) {
2062       if ($p eq "all") {
2063         $all = $params->{$p};
2064       } elsif ($p eq "old_id") {
2065         $old_id = $params->{$p};
2066       } elsif ($p eq "key") {
2067         $key = $params->{$p};
2068       }
2069     }
2070   }
2071
2072   if (!$all) {
2073     $where = "WHERE active ";
2074     if ($old_id) {
2075       if (ref($old_id) eq "ARRAY") {
2076         my @ids = grep({ $_ } @{$old_id});
2077         if (@ids) {
2078           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2079           push(@values, @ids);
2080         }
2081       } else {
2082         $where .= " OR (id = ?) ";
2083         push(@values, $old_id);
2084       }
2085     }
2086   }
2087
2088   my $query =
2089     qq|SELECT id, projectnumber, description, active | .
2090     qq|FROM project | .
2091     $where .
2092     qq|ORDER BY lower(projectnumber)|;
2093
2094   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2095
2096   $main::lxdebug->leave_sub();
2097 }
2098
2099 sub _get_shipto {
2100   $main::lxdebug->enter_sub();
2101
2102   my ($self, $dbh, $vc_id, $key) = @_;
2103
2104   $key = "all_shipto" unless ($key);
2105
2106   if ($vc_id) {
2107     # get shipping addresses
2108     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2109
2110     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2111
2112   } else {
2113     $self->{$key} = [];
2114   }
2115
2116   $main::lxdebug->leave_sub();
2117 }
2118
2119 sub _get_printers {
2120   $main::lxdebug->enter_sub();
2121
2122   my ($self, $dbh, $key) = @_;
2123
2124   $key = "all_printers" unless ($key);
2125
2126   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2127
2128   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2129
2130   $main::lxdebug->leave_sub();
2131 }
2132
2133 sub _get_charts {
2134   $main::lxdebug->enter_sub();
2135
2136   my ($self, $dbh, $params) = @_;
2137   my ($key);
2138
2139   $key = $params->{key};
2140   $key = "all_charts" unless ($key);
2141
2142   my $transdate = quote_db_date($params->{transdate});
2143
2144   my $query =
2145     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2146     qq|FROM chart c | .
2147     qq|LEFT JOIN taxkeys tk ON | .
2148     qq|(tk.id = (SELECT id FROM taxkeys | .
2149     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2150     qq|          ORDER BY startdate DESC LIMIT 1)) | .
2151     qq|ORDER BY c.accno|;
2152
2153   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2154
2155   $main::lxdebug->leave_sub();
2156 }
2157
2158 sub _get_taxcharts {
2159   $main::lxdebug->enter_sub();
2160
2161   my ($self, $dbh, $params) = @_;
2162
2163   my $key = "all_taxcharts";
2164   my @where;
2165
2166   if (ref $params eq 'HASH') {
2167     $key = $params->{key} if ($params->{key});
2168     if ($params->{module} eq 'AR') {
2169       push @where, 'chart_categories ~ \'[ACILQ]\'';
2170
2171     } elsif ($params->{module} eq 'AP') {
2172       push @where, 'chart_categories ~ \'[ACELQ]\'';
2173     }
2174
2175   } elsif ($params) {
2176     $key = $params;
2177   }
2178
2179   my $where = @where ? ' WHERE ' . join(' AND ', map { "($_)" } @where) : '';
2180
2181   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey, rate|;
2182
2183   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2184
2185   $main::lxdebug->leave_sub();
2186 }
2187
2188 sub _get_taxzones {
2189   $main::lxdebug->enter_sub();
2190
2191   my ($self, $dbh, $key) = @_;
2192
2193   $key = "all_taxzones" unless ($key);
2194   my $tzfilter = "";
2195   $tzfilter = "WHERE obsolete is FALSE" if $key eq 'ALL_ACTIVE_TAXZONES';
2196
2197   my $query = qq|SELECT * FROM tax_zones $tzfilter ORDER BY sortkey|;
2198
2199   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2200
2201   $main::lxdebug->leave_sub();
2202 }
2203
2204 sub _get_employees {
2205   $main::lxdebug->enter_sub();
2206
2207   my ($self, $dbh, $params) = @_;
2208
2209   my $deleted = 0;
2210
2211   my $key;
2212   if (ref $params eq 'HASH') {
2213     $key     = $params->{key};
2214     $deleted = $params->{deleted};
2215
2216   } else {
2217     $key = $params;
2218   }
2219
2220   $key     ||= "all_employees";
2221   my $filter = $deleted ? '' : 'WHERE NOT COALESCE(deleted, FALSE)';
2222   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee $filter ORDER BY lower(name)|);
2223
2224   $main::lxdebug->leave_sub();
2225 }
2226
2227 sub _get_business_types {
2228   $main::lxdebug->enter_sub();
2229
2230   my ($self, $dbh, $key) = @_;
2231
2232   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
2233   $options->{key} ||= "all_business_types";
2234   my $where         = '';
2235
2236   if (exists $options->{salesman}) {
2237     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2238   }
2239
2240   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2241
2242   $main::lxdebug->leave_sub();
2243 }
2244
2245 sub _get_languages {
2246   $main::lxdebug->enter_sub();
2247
2248   my ($self, $dbh, $key) = @_;
2249
2250   $key = "all_languages" unless ($key);
2251
2252   my $query = qq|SELECT * FROM language ORDER BY id|;
2253
2254   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2255
2256   $main::lxdebug->leave_sub();
2257 }
2258
2259 sub _get_dunning_configs {
2260   $main::lxdebug->enter_sub();
2261
2262   my ($self, $dbh, $key) = @_;
2263
2264   $key = "all_dunning_configs" unless ($key);
2265
2266   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2267
2268   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2269
2270   $main::lxdebug->leave_sub();
2271 }
2272
2273 sub _get_currencies {
2274 $main::lxdebug->enter_sub();
2275
2276   my ($self, $dbh, $key) = @_;
2277
2278   $key = "all_currencies" unless ($key);
2279
2280   $self->{$key} = [$self->get_all_currencies()];
2281
2282   $main::lxdebug->leave_sub();
2283 }
2284
2285 sub _get_payments {
2286 $main::lxdebug->enter_sub();
2287
2288   my ($self, $dbh, $key) = @_;
2289
2290   $key = "all_payments" unless ($key);
2291
2292   my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
2293
2294   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2295
2296   $main::lxdebug->leave_sub();
2297 }
2298
2299 sub _get_customers {
2300   $main::lxdebug->enter_sub();
2301
2302   my ($self, $dbh, $key) = @_;
2303
2304   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
2305   $options->{key}  ||= "all_customers";
2306   my $limit_clause   = $options->{limit} ? "LIMIT $options->{limit}" : '';
2307
2308   my @where;
2309   push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if  $options->{business_is_salesman};
2310   push @where, qq|NOT obsolete|                                            if !$options->{with_obsolete};
2311   my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2312
2313   my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2314   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2315
2316   $main::lxdebug->leave_sub();
2317 }
2318
2319 sub _get_vendors {
2320   $main::lxdebug->enter_sub();
2321
2322   my ($self, $dbh, $key) = @_;
2323
2324   $key = "all_vendors" unless ($key);
2325
2326   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2327
2328   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2329
2330   $main::lxdebug->leave_sub();
2331 }
2332
2333 sub _get_departments {
2334   $main::lxdebug->enter_sub();
2335
2336   my ($self, $dbh, $key) = @_;
2337
2338   $key = "all_departments" unless ($key);
2339
2340   my $query = qq|SELECT * FROM department ORDER BY description|;
2341
2342   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2343
2344   $main::lxdebug->leave_sub();
2345 }
2346
2347 sub _get_warehouses {
2348   $main::lxdebug->enter_sub();
2349
2350   my ($self, $dbh, $param) = @_;
2351
2352   my ($key, $bins_key);
2353
2354   if ('' eq ref $param) {
2355     $key = $param;
2356
2357   } else {
2358     $key      = $param->{key};
2359     $bins_key = $param->{bins};
2360   }
2361
2362   my $query = qq|SELECT w.* FROM warehouse w
2363                  WHERE (NOT w.invalid) AND
2364                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2365                  ORDER BY w.sortkey|;
2366
2367   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2368
2369   if ($bins_key) {
2370     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?
2371                 ORDER BY description|;
2372     my $sth = prepare_query($self, $dbh, $query);
2373
2374     foreach my $warehouse (@{ $self->{$key} }) {
2375       do_statement($self, $sth, $query, $warehouse->{id});
2376       $warehouse->{$bins_key} = [];
2377
2378       while (my $ref = $sth->fetchrow_hashref()) {
2379         push @{ $warehouse->{$bins_key} }, $ref;
2380       }
2381     }
2382     $sth->finish();
2383   }
2384
2385   $main::lxdebug->leave_sub();
2386 }
2387
2388 sub _get_simple {
2389   $main::lxdebug->enter_sub();
2390
2391   my ($self, $dbh, $table, $key, $sortkey) = @_;
2392
2393   my $query  = qq|SELECT * FROM $table|;
2394   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
2395
2396   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2397
2398   $main::lxdebug->leave_sub();
2399 }
2400
2401 #sub _get_groups {
2402 #  $main::lxdebug->enter_sub();
2403 #
2404 #  my ($self, $dbh, $key) = @_;
2405 #
2406 #  $key ||= "all_groups";
2407 #
2408 #  my $groups = $main::auth->read_groups();
2409 #
2410 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2411 #
2412 #  $main::lxdebug->leave_sub();
2413 #}
2414
2415 sub get_lists {
2416   $main::lxdebug->enter_sub();
2417
2418   my $self = shift;
2419   my %params = @_;
2420
2421   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2422   my ($sth, $query, $ref);
2423
2424   my ($vc, $vc_id);
2425   if ($params{contacts} || $params{shipto}) {
2426     $vc = 'customer' if $self->{"vc"} eq "customer";
2427     $vc = 'vendor'   if $self->{"vc"} eq "vendor";
2428     die "invalid use of get_lists, need 'vc'" unless $vc;
2429     $vc_id = $self->{"${vc}_id"};
2430   }
2431
2432   if ($params{"contacts"}) {
2433     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2434   }
2435
2436   if ($params{"shipto"}) {
2437     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2438   }
2439
2440   if ($params{"projects"} || $params{"all_projects"}) {
2441     $self->_get_projects($dbh, $params{"all_projects"} ?
2442                          $params{"all_projects"} : $params{"projects"},
2443                          $params{"all_projects"} ? 1 : 0);
2444   }
2445
2446   if ($params{"printers"}) {
2447     $self->_get_printers($dbh, $params{"printers"});
2448   }
2449
2450   if ($params{"languages"}) {
2451     $self->_get_languages($dbh, $params{"languages"});
2452   }
2453
2454   if ($params{"charts"}) {
2455     $self->_get_charts($dbh, $params{"charts"});
2456   }
2457
2458   if ($params{"taxcharts"}) {
2459     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2460   }
2461
2462   if ($params{"taxzones"}) {
2463     $self->_get_taxzones($dbh, $params{"taxzones"});
2464   }
2465
2466   if ($params{"employees"}) {
2467     $self->_get_employees($dbh, $params{"employees"});
2468   }
2469
2470   if ($params{"salesmen"}) {
2471     $self->_get_employees($dbh, $params{"salesmen"});
2472   }
2473
2474   if ($params{"business_types"}) {
2475     $self->_get_business_types($dbh, $params{"business_types"});
2476   }
2477
2478   if ($params{"dunning_configs"}) {
2479     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2480   }
2481
2482   if($params{"currencies"}) {
2483     $self->_get_currencies($dbh, $params{"currencies"});
2484   }
2485
2486   if($params{"customers"}) {
2487     $self->_get_customers($dbh, $params{"customers"});
2488   }
2489
2490   if($params{"vendors"}) {
2491     if (ref $params{"vendors"} eq 'HASH') {
2492       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2493     } else {
2494       $self->_get_vendors($dbh, $params{"vendors"});
2495     }
2496   }
2497
2498   if($params{"payments"}) {
2499     $self->_get_payments($dbh, $params{"payments"});
2500   }
2501
2502   if($params{"departments"}) {
2503     $self->_get_departments($dbh, $params{"departments"});
2504   }
2505
2506   if ($params{price_factors}) {
2507     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2508   }
2509
2510   if ($params{warehouses}) {
2511     $self->_get_warehouses($dbh, $params{warehouses});
2512   }
2513
2514 #  if ($params{groups}) {
2515 #    $self->_get_groups($dbh, $params{groups});
2516 #  }
2517
2518   if ($params{partsgroup}) {
2519     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2520   }
2521
2522   $main::lxdebug->leave_sub();
2523 }
2524
2525 # this sub gets the id and name from $table
2526 sub get_name {
2527   $main::lxdebug->enter_sub();
2528
2529   my ($self, $myconfig, $table) = @_;
2530
2531   # connect to database
2532   my $dbh = $self->get_standard_dbh($myconfig);
2533
2534   $table = $table eq "customer" ? "customer" : "vendor";
2535   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2536
2537   my ($query, @values);
2538
2539   if (!$self->{openinvoices}) {
2540     my $where;
2541     if ($self->{customernumber} ne "") {
2542       $where = qq|(vc.customernumber ILIKE ?)|;
2543       push(@values, like($self->{customernumber}));
2544     } else {
2545       $where = qq|(vc.name ILIKE ?)|;
2546       push(@values, like($self->{$table}));
2547     }
2548
2549     $query =
2550       qq~SELECT vc.id, vc.name,
2551            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2552          FROM $table vc
2553          WHERE $where AND (NOT vc.obsolete)
2554          ORDER BY vc.name~;
2555   } else {
2556     $query =
2557       qq~SELECT DISTINCT vc.id, vc.name,
2558            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2559          FROM $arap a
2560          JOIN $table vc ON (a.${table}_id = vc.id)
2561          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2562          ORDER BY vc.name~;
2563     push(@values, like($self->{$table}));
2564   }
2565
2566   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2567
2568   $main::lxdebug->leave_sub();
2569
2570   return scalar(@{ $self->{name_list} });
2571 }
2572
2573 sub new_lastmtime {
2574
2575   my ($self, $table, $provided_dbh) = @_;
2576
2577   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh;
2578   return                                       unless $self->{id};
2579   croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2580
2581   my $query       = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2582   my $ref         = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2583   $ref->{mtime} ||= $ref->{itime};
2584   $self->{lastmtime} = $ref->{mtime};
2585
2586 }
2587
2588 sub mtime_ischanged {
2589   my ($self, $table, $option) = @_;
2590
2591   return                                       unless $self->{id};
2592   croak ("wrong call, no valid table defined") unless $table =~ /^(oe|ar|ap|delivery_orders|parts)$/;
2593
2594   my $query       = "SELECT mtime, itime FROM " . $table . " WHERE id = ?";
2595   my $ref         = selectfirst_hashref_query($self, $self->get_standard_dbh, $query, $self->{id});
2596   $ref->{mtime} ||= $ref->{itime};
2597
2598   if ($self->{lastmtime} && $self->{lastmtime} ne $ref->{mtime} ) {
2599       $self->error(($option eq 'mail') ?
2600         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") :
2601         t8("The document has been changed by another user. Please reopen it in another window and copy the changes to the new window")
2602       );
2603     $::dispatcher->end_request;
2604   }
2605 }
2606
2607 # language_payment duplicates some of the functionality of all_vc (language,
2608 # printer, payment_terms), and at least in the case of sales invoices both
2609 # all_vc and language_payment are called when adding new invoices
2610 sub language_payment {
2611   $main::lxdebug->enter_sub();
2612
2613   my ($self, $myconfig) = @_;
2614
2615   my $dbh = $self->get_standard_dbh($myconfig);
2616   # get languages
2617   my $query = qq|SELECT id, description
2618                  FROM language
2619                  ORDER BY id|;
2620
2621   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2622
2623   # get printer
2624   $query = qq|SELECT printer_description, id
2625               FROM printers
2626               ORDER BY printer_description|;
2627
2628   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2629
2630   # get payment terms
2631   $query = qq|SELECT id, description
2632               FROM payment_terms
2633               WHERE ( obsolete IS FALSE OR id = ? )
2634               ORDER BY sortkey |;
2635   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query, $self->{payment_id} || undef);
2636
2637   # get buchungsgruppen
2638   $query = qq|SELECT id, description
2639               FROM buchungsgruppen|;
2640
2641   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2642
2643   $main::lxdebug->leave_sub();
2644 }
2645
2646 # this is only used for reports
2647 sub all_departments {
2648   $main::lxdebug->enter_sub();
2649
2650   my ($self, $myconfig, $table) = @_;
2651
2652   my $dbh = $self->get_standard_dbh($myconfig);
2653
2654   my $query = qq|SELECT id, description
2655                  FROM department
2656                  ORDER BY description|;
2657   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2658
2659   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2660
2661   $main::lxdebug->leave_sub();
2662 }
2663
2664 sub create_links {
2665   $main::lxdebug->enter_sub();
2666
2667   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2668
2669   my ($fld, $arap);
2670   if ($table eq "customer") {
2671     $fld = "buy";
2672     $arap = "ar";
2673   } else {
2674     $table = "vendor";
2675     $fld = "sell";
2676     $arap = "ap";
2677   }
2678
2679   # get last customers or vendors
2680   my ($query, $sth, $ref);
2681
2682   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2683   my %xkeyref = ();
2684
2685   if (!$self->{id}) {
2686
2687     my $transdate = "current_date";
2688     if ($self->{transdate}) {
2689       $transdate = $dbh->quote($self->{transdate});
2690     }
2691
2692     # now get the account numbers
2693     $query = qq|
2694       SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk2.tax_id
2695         FROM chart c
2696         -- find newest entries in taxkeys
2697         INNER JOIN (
2698           SELECT chart_id, MAX(startdate) AS startdate
2699           FROM taxkeys
2700           WHERE (startdate <= $transdate)
2701           GROUP BY chart_id
2702         ) tk ON (c.id = tk.chart_id)
2703         -- and load all of those entries
2704         INNER JOIN taxkeys tk2
2705            ON (tk.chart_id = tk2.chart_id AND tk.startdate = tk2.startdate)
2706        WHERE (c.link LIKE ?)
2707       ORDER BY c.accno|;
2708
2709     $sth = $dbh->prepare($query);
2710
2711     do_statement($self, $sth, $query, like($module));
2712
2713     $self->{accounts} = "";
2714     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2715
2716       foreach my $key (split(/:/, $ref->{link})) {
2717         if ($key =~ /\Q$module\E/) {
2718
2719           # cross reference for keys
2720           $xkeyref{ $ref->{accno} } = $key;
2721
2722           push @{ $self->{"${module}_links"}{$key} },
2723             { accno       => $ref->{accno},
2724               chart_id    => $ref->{chart_id},
2725               description => $ref->{description},
2726               taxkey      => $ref->{taxkey_id},
2727               tax_id      => $ref->{tax_id} };
2728
2729           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2730         }
2731       }
2732     }
2733   }
2734
2735   # get taxkeys and description
2736   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2737   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2738
2739   if (($module eq "AP") || ($module eq "AR")) {
2740     # get tax rates and description
2741     $query = qq|SELECT * FROM tax|;
2742     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2743   }
2744
2745   my $extra_columns = '';
2746   $extra_columns   .= 'a.direct_debit, ' if ($module eq 'AR') || ($module eq 'AP');
2747
2748   if ($self->{id}) {
2749     $query =
2750       qq|SELECT
2751            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2752            a.duedate, a.ordnumber, a.taxincluded, (SELECT cu.name FROM currencies cu WHERE cu.id=a.currency_id) AS currency, a.notes,
2753            a.mtime, a.itime,
2754            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2755            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2756            a.globalproject_id, ${extra_columns}
2757            c.name AS $table,
2758            d.description AS department,
2759            e.name AS employee
2760          FROM $arap a
2761          JOIN $table c ON (a.${table}_id = c.id)
2762          LEFT JOIN employee e ON (e.id = a.employee_id)
2763          LEFT JOIN department d ON (d.id = a.department_id)
2764          WHERE a.id = ?|;
2765     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2766
2767     foreach my $key (keys %$ref) {
2768       $self->{$key} = $ref->{$key};
2769     }
2770     $self->{mtime}   ||= $self->{itime};
2771     $self->{lastmtime} = $self->{mtime};
2772     my $transdate = "current_date";
2773     if ($self->{transdate}) {
2774       $transdate = $dbh->quote($self->{transdate});
2775     }
2776
2777     # now get the account numbers
2778     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, c.id AS chart_id, tk.tax_id
2779                 FROM chart c
2780                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2781                 WHERE c.link LIKE ?
2782                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2783                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2784                 ORDER BY c.accno|;
2785
2786     $sth = $dbh->prepare($query);
2787     do_statement($self, $sth, $query, like($module));
2788
2789     $self->{accounts} = "";
2790     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2791
2792       foreach my $key (split(/:/, $ref->{link})) {
2793         if ($key =~ /\Q$module\E/) {
2794
2795           # cross reference for keys
2796           $xkeyref{ $ref->{accno} } = $key;
2797
2798           push @{ $self->{"${module}_links"}{$key} },
2799             { accno       => $ref->{accno},
2800               chart_id    => $ref->{chart_id},
2801               description => $ref->{description},
2802               taxkey      => $ref->{taxkey_id},
2803               tax_id      => $ref->{tax_id} };
2804
2805           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2806         }
2807       }
2808     }
2809
2810
2811     # get amounts from individual entries
2812     $query =
2813       qq|SELECT
2814            c.accno, c.description,
2815            a.acc_trans_id, a.source, a.amount, a.memo, a.transdate, a.gldate, a.cleared, a.project_id, a.taxkey, a.chart_id,
2816            p.projectnumber,
2817            t.rate, t.id
2818          FROM acc_trans a
2819          LEFT JOIN chart c ON (c.id = a.chart_id)
2820          LEFT JOIN project p ON (p.id = a.project_id)
2821          LEFT JOIN tax t ON (t.id= a.tax_id)
2822          WHERE a.trans_id = ?
2823          AND a.fx_transaction = '0'
2824          ORDER BY a.acc_trans_id, a.transdate|;
2825     $sth = $dbh->prepare($query);
2826     do_statement($self, $sth, $query, $self->{id});
2827
2828     # get exchangerate for currency
2829     $self->{exchangerate} =
2830       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2831     my $index = 0;
2832
2833     # store amounts in {acc_trans}{$key} for multiple accounts
2834     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2835       $ref->{exchangerate} =
2836         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2837       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2838         $index++;
2839       }
2840       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2841         $ref->{amount} *= -1;
2842       }
2843       $ref->{index} = $index;
2844
2845       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2846     }
2847
2848     $sth->finish;
2849     #check das:
2850     $query =
2851       qq|SELECT
2852            d.closedto, d.revtrans,
2853            (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2854            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2855            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2856            (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2857            (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2858          FROM defaults d|;
2859     $ref = selectfirst_hashref_query($self, $dbh, $query);
2860     map { $self->{$_} = $ref->{$_} } keys %$ref;
2861
2862   } else {
2863
2864     # get date
2865     $query =
2866        qq|SELECT
2867             current_date AS transdate, d.closedto, d.revtrans,
2868             (SELECT cu.name FROM currencies cu WHERE cu.id=d.currency_id) AS defaultcurrency,
2869             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2870             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
2871             (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id) AS rndgain_accno,
2872             (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id) AS rndloss_accno
2873           FROM defaults d|;
2874     $ref = selectfirst_hashref_query($self, $dbh, $query);
2875     map { $self->{$_} = $ref->{$_} } keys %$ref;
2876
2877     if ($self->{"$self->{vc}_id"}) {
2878
2879       # only setup currency
2880       ($self->{currency}) = $self->{defaultcurrency} if !$self->{currency};
2881
2882     } else {
2883
2884       $self->lastname_used($dbh, $myconfig, $table, $module);
2885
2886       # get exchangerate for currency
2887       $self->{exchangerate} =
2888         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2889
2890     }
2891
2892   }
2893
2894   $main::lxdebug->leave_sub();
2895 }
2896
2897 sub lastname_used {
2898   $main::lxdebug->enter_sub();
2899
2900   my ($self, $dbh, $myconfig, $table, $module) = @_;
2901
2902   my ($arap, $where);
2903
2904   $table         = $table eq "customer" ? "customer" : "vendor";
2905   my %column_map = ("a.${table}_id"           => "${table}_id",
2906                     "a.department_id"         => "department_id",
2907                     "d.description"           => "department",
2908                     "ct.name"                 => $table,
2909                     "cu.name"                 => "currency",
2910     );
2911
2912   if ($self->{type} =~ /delivery_order/) {
2913     $arap  = 'delivery_orders';
2914     delete $column_map{"cu.currency"};
2915
2916   } elsif ($self->{type} =~ /_order/) {
2917     $arap  = 'oe';
2918     $where = "quotation = '0'";
2919
2920   } elsif ($self->{type} =~ /_quotation/) {
2921     $arap  = 'oe';
2922     $where = "quotation = '1'";
2923
2924   } elsif ($table eq 'customer') {
2925     $arap  = 'ar';
2926
2927   } else {
2928     $arap  = 'ap';
2929
2930   }
2931
2932   $where           = "($where) AND" if ($where);
2933   my $query        = qq|SELECT MAX(id) FROM $arap
2934                         WHERE $where ${table}_id > 0|;
2935   my ($trans_id)   = selectrow_query($self, $dbh, $query);
2936   $trans_id       *= 1;
2937
2938   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
2939   $query           = qq|SELECT $column_spec
2940                         FROM $arap a
2941                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
2942                         LEFT JOIN department d  ON (a.department_id = d.id)
2943                         LEFT JOIN currencies cu ON (cu.id=ct.currency_id)
2944                         WHERE a.id = ?|;
2945   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
2946
2947   map { $self->{$_} = $ref->{$_} } values %column_map;
2948
2949   $main::lxdebug->leave_sub();
2950 }
2951
2952 sub get_variable_content_types {
2953   my %html_variables  = (
2954       longdescription => 'html',
2955       partnotes       => 'html',
2956       notes           => 'html',
2957       orignotes       => 'html',
2958       notes1          => 'html',
2959       notes2          => 'html',
2960       notes3          => 'html',
2961       notes4          => 'html',
2962       header_text     => 'html',
2963       footer_text     => 'html',
2964   );
2965   return \%html_variables;
2966 }
2967
2968 sub current_date {
2969   $main::lxdebug->enter_sub();
2970
2971   my $self     = shift;
2972   my $myconfig = shift || \%::myconfig;
2973   my ($thisdate, $days) = @_;
2974
2975   my $dbh = $self->get_standard_dbh($myconfig);
2976   my $query;
2977
2978   $days *= 1;
2979   if ($thisdate) {
2980     my $dateformat = $myconfig->{dateformat};
2981     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2982     $thisdate = $dbh->quote($thisdate);
2983     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2984   } else {
2985     $query = qq|SELECT current_date AS thisdate|;
2986   }
2987
2988   ($thisdate) = selectrow_query($self, $dbh, $query);
2989
2990   $main::lxdebug->leave_sub();
2991
2992   return $thisdate;
2993 }
2994
2995 sub redo_rows {
2996   $main::lxdebug->enter_sub();
2997
2998   my ($self, $flds, $new, $count, $numrows) = @_;
2999
3000   my @ndx = ();
3001
3002   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3003
3004   my $i = 0;
3005
3006   # fill rows
3007   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3008     $i++;
3009     my $j = $item->{ndx} - 1;
3010     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3011   }
3012
3013   # delete empty rows
3014   for $i ($count + 1 .. $numrows) {
3015     map { delete $self->{"${_}_$i"} } @{$flds};
3016   }
3017
3018   $main::lxdebug->leave_sub();
3019 }
3020
3021 sub update_status {
3022   $main::lxdebug->enter_sub();
3023
3024   my ($self, $myconfig) = @_;
3025
3026   my ($i, $id);
3027
3028   SL::DB->client->with_transaction(sub {
3029     my $dbh = SL::DB->client->dbh;
3030
3031     my $query = qq|DELETE FROM status
3032                    WHERE (formname = ?) AND (trans_id = ?)|;
3033     my $sth = prepare_query($self, $dbh, $query);
3034
3035     if ($self->{formname} =~ /(check|receipt)/) {
3036       for $i (1 .. $self->{rowcount}) {
3037         do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3038       }
3039     } else {
3040       do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3041     }
3042     $sth->finish();
3043
3044     my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3045     my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3046
3047     my %queued = split / /, $self->{queued};
3048     my @values;
3049
3050     if ($self->{formname} =~ /(check|receipt)/) {
3051
3052       # this is a check or receipt, add one entry for each lineitem
3053       my ($accno) = split /--/, $self->{account};
3054       $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3055                   VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3056       @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3057       $sth = prepare_query($self, $dbh, $query);
3058
3059       for $i (1 .. $self->{rowcount}) {
3060         if ($self->{"checked_$i"}) {
3061           do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3062         }
3063       }
3064       $sth->finish();
3065
3066     } else {
3067       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3068                   VALUES (?, ?, ?, ?, ?)|;
3069       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3070                $queued{$self->{formname}}, $self->{formname});
3071     }
3072     1;
3073   }) or do { die SL::DB->client->error };
3074
3075   $main::lxdebug->leave_sub();
3076 }
3077
3078 sub save_status {
3079   $main::lxdebug->enter_sub();
3080
3081   my ($self, $dbh) = @_;
3082
3083   my ($query, $printed, $emailed);
3084
3085   my $formnames  = $self->{printed};
3086   my $emailforms = $self->{emailed};
3087
3088   $query = qq|DELETE FROM status
3089                  WHERE (formname = ?) AND (trans_id = ?)|;
3090   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3091
3092   # this only applies to the forms
3093   # checks and receipts are posted when printed or queued
3094
3095   if ($self->{queued}) {
3096     my %queued = split / /, $self->{queued};
3097
3098     foreach my $formname (keys %queued) {
3099       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3100       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3101
3102       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3103                   VALUES (?, ?, ?, ?, ?)|;
3104       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3105
3106       $formnames  =~ s/\Q$self->{formname}\E//;
3107       $emailforms =~ s/\Q$self->{formname}\E//;
3108
3109     }
3110   }
3111
3112   # save printed, emailed info
3113   $formnames  =~ s/^ +//g;
3114   $emailforms =~ s/^ +//g;
3115
3116   my %status = ();
3117   map { $status{$_}{printed} = 1 } split / +/, $formnames;
3118   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3119
3120   foreach my $formname (keys %status) {
3121     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
3122     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3123
3124     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3125                 VALUES (?, ?, ?, ?)|;
3126     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3127   }
3128
3129   $main::lxdebug->leave_sub();
3130 }
3131
3132 #--- 4 locale ---#
3133 # $main::locale->text('SAVED')
3134 # $main::locale->text('SCREENED')
3135 # $main::locale->text('DELETED')
3136 # $main::locale->text('ADDED')
3137 # $main::locale->text('PAYMENT POSTED')
3138 # $main::locale->text('POSTED')
3139 # $main::locale->text('POSTED AS NEW')
3140 # $main::locale->text('ELSE')
3141 # $main::locale->text('SAVED FOR DUNNING')
3142 # $main::locale->text('DUNNING STARTED')
3143 # $main::locale->text('PRINTED')
3144 # $main::locale->text('MAILED')
3145 # $main::locale->text('SCREENED')
3146 # $main::locale->text('CANCELED')
3147 # $main::locale->text('IMPORT')
3148 # $main::locale->text('UNIMPORT')
3149 # $main::locale->text('invoice')
3150 # $main::locale->text('proforma')
3151 # $main::locale->text('sales_order')
3152 # $main::locale->text('pick_list')
3153 # $main::locale->text('purchase_order')
3154 # $main::locale->text('bin_list')
3155 # $main::locale->text('sales_quotation')
3156 # $main::locale->text('request_quotation')
3157
3158 sub save_history {
3159   $main::lxdebug->enter_sub();
3160
3161   my $self = shift;
3162   my $dbh  = shift || SL::DB->client->dbh;
3163   SL::DB->client->with_transaction(sub {
3164
3165     if(!exists $self->{employee_id}) {
3166       &get_employee($self, $dbh);
3167     }
3168
3169     my $query =
3170      qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3171      qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3172     my @values = (conv_i($self->{id}), $self->{login},
3173                   $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3174     do_query($self, $dbh, $query, @values);
3175     1;
3176   }) or do { die SL::DB->client->error };
3177
3178   $main::lxdebug->leave_sub();
3179 }
3180
3181 sub get_history {
3182   $main::lxdebug->enter_sub();
3183
3184   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3185   my ($orderBy, $desc) = split(/\-\-/, $order);
3186   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3187   my @tempArray;
3188   my $i = 0;
3189   if ($trans_id ne "") {
3190     my $query =
3191       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 | .
3192       qq|FROM history_erp h | .
3193       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3194       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3195       $order;
3196
3197     my $sth = $dbh->prepare($query) || $self->dberror($query);
3198
3199     $sth->execute() || $self->dberror("$query");
3200
3201     while(my $hash_ref = $sth->fetchrow_hashref()) {
3202       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3203       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3204       my ( $what, $number ) = split /_/, $hash_ref->{snumbers};
3205       $hash_ref->{snumbers} = $number;
3206       $hash_ref->{haslink}  = 'controller.pl?action=EmailJournal/show&id='.$number if $what eq 'emailjournal';
3207       $hash_ref->{snumbers} = $main::locale->text("E-Mail").' '.$number if $what eq 'emailjournal';
3208       $tempArray[$i++] = $hash_ref;
3209     }
3210     $main::lxdebug->leave_sub() and return \@tempArray
3211       if ($i > 0 && $tempArray[0] ne "");
3212   }
3213   $main::lxdebug->leave_sub();
3214   return 0;
3215 }
3216
3217 sub get_partsgroup {
3218   $main::lxdebug->enter_sub();
3219
3220   my ($self, $myconfig, $p) = @_;
3221   my $target = $p->{target} || 'all_partsgroup';
3222
3223   my $dbh = $self->get_standard_dbh($myconfig);
3224
3225   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3226                  FROM partsgroup pg
3227                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
3228   my @values;
3229
3230   if ($p->{searchitems} eq 'part') {
3231     $query .= qq|WHERE p.part_type = 'part'|;
3232   }
3233   if ($p->{searchitems} eq 'service') {
3234     $query .= qq|WHERE p.part_type = 'service'|;
3235   }
3236   if ($p->{searchitems} eq 'assembly') {
3237     $query .= qq|WHERE p.part_type = 'assembly'|;
3238   }
3239
3240   $query .= qq|ORDER BY partsgroup|;
3241
3242   if ($p->{all}) {
3243     $query = qq|SELECT id, partsgroup FROM partsgroup
3244                 ORDER BY partsgroup|;
3245   }
3246
3247   if ($p->{language_code}) {
3248     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3249                   t.description AS translation
3250                 FROM partsgroup pg
3251                 JOIN parts p ON (p.partsgroup_id = pg.id)
3252                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3253                 ORDER BY translation|;
3254     @values = ($p->{language_code});
3255   }
3256
3257   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3258
3259   $main::lxdebug->leave_sub();
3260 }
3261
3262 sub get_pricegroup {
3263   $main::lxdebug->enter_sub();
3264
3265   my ($self, $myconfig, $p) = @_;
3266
3267   my $dbh = $self->get_standard_dbh($myconfig);
3268
3269   my $query = qq|SELECT p.id, p.pricegroup
3270                  FROM pricegroup p|;
3271
3272   $query .= qq| ORDER BY pricegroup|;
3273
3274   if ($p->{all}) {
3275     $query = qq|SELECT id, pricegroup FROM pricegroup
3276                 ORDER BY pricegroup|;
3277   }
3278
3279   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3280
3281   $main::lxdebug->leave_sub();
3282 }
3283
3284 sub all_years {
3285 # usage $form->all_years($myconfig, [$dbh])
3286 # return list of all years where bookings found
3287 # (@all_years)
3288
3289   $main::lxdebug->enter_sub();
3290
3291   my ($self, $myconfig, $dbh) = @_;
3292
3293   $dbh ||= $self->get_standard_dbh($myconfig);
3294
3295   # get years
3296   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3297                    (SELECT MAX(transdate) FROM acc_trans)|;
3298   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3299
3300   if ($myconfig->{dateformat} =~ /^yy/) {
3301     ($startdate) = split /\W/, $startdate;
3302     ($enddate) = split /\W/, $enddate;
3303   } else {
3304     (@_) = split /\W/, $startdate;
3305     $startdate = $_[2];
3306     (@_) = split /\W/, $enddate;
3307     $enddate = $_[2];
3308   }
3309
3310   my @all_years;
3311   $startdate = substr($startdate,0,4);
3312   $enddate = substr($enddate,0,4);
3313
3314   while ($enddate >= $startdate) {
3315     push @all_years, $enddate--;
3316   }
3317
3318   return @all_years;
3319
3320   $main::lxdebug->leave_sub();
3321 }
3322
3323 sub backup_vars {
3324   $main::lxdebug->enter_sub();
3325   my $self = shift;
3326   my @vars = @_;
3327
3328   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3329
3330   $main::lxdebug->leave_sub();
3331 }
3332
3333 sub restore_vars {
3334   $main::lxdebug->enter_sub();
3335
3336   my $self = shift;
3337   my @vars = @_;
3338
3339   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3340
3341   $main::lxdebug->leave_sub();
3342 }
3343
3344 sub prepare_for_printing {
3345   my ($self) = @_;
3346
3347   my $defaults         = SL::DB::Default->get;
3348
3349   $self->{templates} ||= $defaults->templates;
3350   $self->{formname}  ||= $self->{type};
3351   $self->{media}     ||= 'email';
3352
3353   die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
3354
3355   # Several fields that used to reside in %::myconfig (stored in
3356   # auth.user_config) are now stored in defaults. Copy them over for
3357   # compatibility.
3358   $self->{$_} = $defaults->$_ for qw(company address taxnumber co_ustid duns sepa_creditor_id);
3359
3360   $self->{"myconfig_${_}"} = $::myconfig{$_} for grep { $_ ne 'dbpasswd' } keys %::myconfig;
3361
3362   if (!$self->{employee_id}) {
3363     $self->{"employee_${_}"} = $::myconfig{$_} for qw(email tel fax name signature);
3364     $self->{"employee_${_}"} = $defaults->$_   for qw(address businessnumber co_ustid company duns sepa_creditor_id taxnumber);
3365   }
3366
3367   # Load shipping address from database. If shipto_id is set then it's
3368   # one from the customer's/vendor's master data. Otherwise look an a
3369   # customized address linking back to the current record.
3370   my $shipto_module = $self->{type} =~ /_delivery_order$/                                             ? 'DO'
3371                     : $self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/ ? 'OE'
3372                     :                                                                                   'AR';
3373   my $shipto        = $self->{shipto_id} ? SL::DB::Shipto->new(shipto_id => $self->{shipto_id})->load
3374                     :                      SL::DB::Manager::Shipto->get_first(where => [ module => $shipto_module, trans_id => $self->{id} ]);
3375   if ($shipto) {
3376     $self->{$_} = $shipto->$_ for grep { m{^shipto} } map { $_->name } @{ $shipto->meta->columns };
3377     $self->{"shiptocvar_" . $_->config->name} = $_->value_as_text for @{ $shipto->cvars_by_config };
3378   }
3379
3380   my $language = $self->{language} ? '_' . $self->{language} : '';
3381
3382   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
3383   if ($self->{language_id}) {
3384     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
3385   }
3386
3387   $output_dateformat   ||= $::myconfig{dateformat};
3388   $output_numberformat ||= $::myconfig{numberformat};
3389   $output_longdates    //= 1;
3390
3391   $self->{myconfig_output_dateformat}   = $output_dateformat   // $::myconfig{dateformat};
3392   $self->{myconfig_output_longdates}    = $output_longdates    // 1;
3393   $self->{myconfig_output_numberformat} = $output_numberformat // $::myconfig{numberformat};
3394
3395   # Retrieve accounts for tax calculation.
3396   IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
3397
3398   if ($self->{type} =~ /_delivery_order$/) {
3399     DO->order_details(\%::myconfig, $self);
3400   } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
3401     OE->order_details(\%::myconfig, $self);
3402   } else {
3403     IS->invoice_details(\%::myconfig, $self, $::locale);
3404   }
3405
3406   # Chose extension & set source file name
3407   my $extension = 'html';
3408   if ($self->{format} eq 'postscript') {
3409     $self->{postscript}   = 1;
3410     $extension            = 'tex';
3411   } elsif ($self->{"format"} =~ /pdf/) {
3412     $self->{pdf}          = 1;
3413     $extension            = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
3414   } elsif ($self->{"format"} =~ /opendocument/) {
3415     $self->{opendocument} = 1;
3416     $extension            = 'odt';
3417   } elsif ($self->{"format"} =~ /excel/) {
3418     $self->{excel}        = 1;
3419     $extension            = 'xls';
3420   }
3421
3422   my $printer_code    = $self->{printer_code} ? '_' . $self->{printer_code} : '';
3423   my $email_extension = $self->{media} eq 'email' && -f ($defaults->templates . "/$self->{formname}_email${language}.${extension}") ? '_email' : '';
3424   $self->{IN}         = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
3425
3426   # Format dates.
3427   $self->format_dates($output_dateformat, $output_longdates,
3428                       qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate datepaid
3429                          transdate_oe deliverydate_oe employee_startdate employee_enddate),
3430                       grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
3431
3432   $self->reformat_numbers($output_numberformat, 2,
3433                           qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
3434                           grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
3435
3436   $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
3437
3438   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
3439
3440   if (scalar @{ $cvar_date_fields }) {
3441     $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
3442   }
3443
3444   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
3445     $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
3446   }
3447
3448   $self->{template_meta} = {
3449     formname  => $self->{formname},
3450     language  => SL::DB::Manager::Language->find_by_or_create(id => $self->{language_id} || undef),
3451     format    => $self->{format},
3452     media     => $self->{media},
3453     extension => $extension,
3454     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $self->{printer_id} || undef),
3455     today     => DateTime->today,
3456   };
3457
3458   return $self;
3459 }
3460
3461 sub calculate_arap {
3462   my ($self,$buysell,$taxincluded,$exchangerate,$roundplaces) = @_;
3463
3464   # this function is used to calculate netamount, total_tax and amount for AP and
3465   # AR transactions (Kreditoren-/Debitorenbuchungen) by going over all lines
3466   # (1..$rowcount)
3467   # Thus it needs a fully prepared $form to work on.
3468   # calculate_arap assumes $form->{amount_$i} entries still need to be parsed
3469
3470   # The calculated total values are all rounded (default is to 2 places) and
3471   # returned as parameters rather than directly modifying form.  The aim is to
3472   # make the calculation of AP and AR behave identically.  There is a test-case
3473   # for this function in t/form/arap.t
3474
3475   # While calculating the totals $form->{amount_$i} and $form->{tax_$i} are
3476   # modified and formatted and receive the correct sign for writing straight to
3477   # acc_trans, depending on whether they are ar or ap.
3478
3479   # check parameters
3480   die "taxincluded needed in Form->calculate_arap" unless defined $taxincluded;
3481   die "exchangerate needed in Form->calculate_arap" unless defined $exchangerate;
3482   die 'illegal buysell parameter, has to be \"buy\" or \"sell\" in Form->calculate_arap\n' unless $buysell =~ /^(buy|sell)$/;
3483   $roundplaces = 2 unless $roundplaces;
3484
3485   my $sign = 1;  # adjust final results for writing amount to acc_trans
3486   $sign = -1 if $buysell eq 'buy';
3487
3488   my ($netamount,$total_tax,$amount);
3489
3490   my $tax;
3491
3492   # parse and round amounts, setting correct sign for writing to acc_trans
3493   for my $i (1 .. $self->{rowcount}) {
3494     $self->{"amount_$i"} = $self->round_amount($self->parse_amount(\%::myconfig, $self->{"amount_$i"}) * $exchangerate * $sign, $roundplaces);
3495
3496     $amount += $self->{"amount_$i"} * $sign;
3497   }
3498
3499   for my $i (1 .. $self->{rowcount}) {
3500     next unless $self->{"amount_$i"};
3501     ($self->{"tax_id_$i"}) = split /--/, $self->{"taxchart_$i"};
3502     my $tax_id = $self->{"tax_id_$i"};
3503
3504     my $selected_tax = SL::DB::Manager::Tax->find_by(id => "$tax_id");
3505
3506     if ( $selected_tax ) {
3507
3508       if ( $buysell eq 'sell' ) {
3509         $self->{AR_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3510       } else {
3511         $self->{AP_amounts}{"tax_$i"} = $selected_tax->chart->accno if defined $selected_tax->chart;
3512       };
3513
3514       $self->{"taxkey_$i"} = $selected_tax->taxkey;
3515       $self->{"taxrate_$i"} = $selected_tax->rate;
3516     };
3517
3518     ($self->{"amount_$i"}, $self->{"tax_$i"}) = $self->calculate_tax($self->{"amount_$i"},$self->{"taxrate_$i"},$taxincluded,$roundplaces);
3519
3520     $netamount  += $self->{"amount_$i"};
3521     $total_tax  += $self->{"tax_$i"};
3522
3523   }
3524   $amount = $netamount + $total_tax;
3525
3526   # due to $sign amount_$i und tax_$i already have the right sign for acc_trans
3527   # but reverse sign of totals for writing amounts to ar
3528   if ( $buysell eq 'buy' ) {
3529     $netamount *= -1;
3530     $amount    *= -1;
3531     $total_tax *= -1;
3532   };
3533
3534   return($netamount,$total_tax,$amount);
3535 }
3536
3537 sub format_dates {
3538   my ($self, $dateformat, $longformat, @indices) = @_;
3539
3540   $dateformat ||= $::myconfig{dateformat};
3541
3542   foreach my $idx (@indices) {
3543     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3544       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3545         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
3546       }
3547     }
3548
3549     next unless defined $self->{$idx};
3550
3551     if (!ref($self->{$idx})) {
3552       $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
3553
3554     } elsif (ref($self->{$idx}) eq "ARRAY") {
3555       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3556         $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
3557       }
3558     }
3559   }
3560 }
3561
3562 sub reformat_numbers {
3563   my ($self, $numberformat, $places, @indices) = @_;
3564
3565   return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
3566
3567   foreach my $idx (@indices) {
3568     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3569       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3570         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
3571       }
3572     }
3573
3574     next unless defined $self->{$idx};
3575
3576     if (!ref($self->{$idx})) {
3577       $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
3578
3579     } elsif (ref($self->{$idx}) eq "ARRAY") {
3580       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3581         $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
3582       }
3583     }
3584   }
3585
3586   my $saved_numberformat    = $::myconfig{numberformat};
3587   $::myconfig{numberformat} = $numberformat;
3588
3589   foreach my $idx (@indices) {
3590     if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
3591       for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
3592         $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
3593       }
3594     }
3595
3596     next unless defined $self->{$idx};
3597
3598     if (!ref($self->{$idx})) {
3599       $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
3600
3601     } elsif (ref($self->{$idx}) eq "ARRAY") {
3602       for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
3603         $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
3604       }
3605     }
3606   }
3607
3608   $::myconfig{numberformat} = $saved_numberformat;
3609 }
3610
3611 sub create_email_signature {
3612
3613   my $client_signature = $::instance_conf->get_signature;
3614   my $user_signature   = $::myconfig{signature};
3615
3616   my $signature = '';
3617   if ( $client_signature or $user_signature ) {
3618     $signature  = "\n\n-- \n";
3619     $signature .= $user_signature   . "\n" if $user_signature;
3620     $signature .= $client_signature . "\n" if $client_signature;
3621   };
3622   return $signature;
3623
3624 };
3625
3626 sub layout {
3627   my ($self) = @_;
3628   $::lxdebug->enter_sub;
3629
3630   my %style_to_script_map = (
3631     v3  => 'v3',
3632     neu => 'new',
3633   );
3634
3635   my $menu_script = $style_to_script_map{$::myconfig{menustyle}} || '';
3636
3637   package main;
3638   require "bin/mozilla/menu$menu_script.pl";
3639   package Form;
3640   require SL::Controller::FrameHeader;
3641
3642
3643   my $layout = SL::Controller::FrameHeader->new->action_header . ::render();
3644
3645   $::lxdebug->leave_sub;
3646   return $layout;
3647 }
3648
3649 sub calculate_tax {
3650   # this function calculates the net amount and tax for the lines in ar, ap and
3651   # gl and is used for update as well as post. When used with update the return
3652   # value of amount isn't needed
3653
3654   # calculate_tax should always work with positive values, or rather as the user inputs them
3655   # calculate_tax uses db/perl numberformat, i.e. parsed numbers
3656   # convert to negative numbers (when necessary) only when writing to acc_trans
3657   # the amount from $form for ap/ar/gl is currently always rounded to 2 decimals before it reaches here
3658   # for post_transaction amount already contains exchangerate and correct sign and is rounded
3659   # calculate_tax doesn't (need to) know anything about exchangerate
3660
3661   my ($self,$amount,$taxrate,$taxincluded,$roundplaces) = @_;
3662
3663   $roundplaces //= 2;
3664   $taxincluded //= 0;
3665
3666   my $tax;
3667
3668   if ($taxincluded) {
3669     # calculate tax (unrounded), subtract from amount, round amount and round tax
3670     $tax       = $amount - ($amount / ($taxrate + 1)); # equivalent to: taxrate * amount / (taxrate + 1)
3671     $amount    = $self->round_amount($amount - $tax, $roundplaces);
3672     $tax       = $self->round_amount($tax, $roundplaces);
3673   } else {
3674     $tax       = $amount * $taxrate;
3675     $tax       = $self->round_amount($tax, $roundplaces);
3676   }
3677
3678   $tax = 0 unless $tax;
3679
3680   return ($amount,$tax);
3681 };
3682
3683 1;
3684
3685 __END__
3686
3687 =head1 NAME
3688
3689 SL::Form.pm - main data object.
3690
3691 =head1 SYNOPSIS
3692
3693 This is the main data object of kivitendo.
3694 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3695 Points of interest for a beginner are:
3696
3697  - $form->error            - renders a generic error in html. accepts an error message
3698  - $form->get_standard_dbh - returns a database connection for the
3699
3700 =head1 SPECIAL FUNCTIONS
3701
3702 =head2 C<redirect_header> $url
3703
3704 Generates a HTTP redirection header for the new C<$url>. Constructs an
3705 absolute URL including scheme, host name and port. If C<$url> is a
3706 relative URL then it is considered relative to kivitendo base URL.
3707
3708 This function C<die>s if headers have already been created with
3709 C<$::form-E<gt>header>.
3710
3711 Examples:
3712
3713   print $::form->redirect_header('oe.pl?action=edit&id=1234');
3714   print $::form->redirect_header('http://www.lx-office.org/');
3715
3716 =head2 C<header>
3717
3718 Generates a general purpose http/html header and includes most of the scripts
3719 and stylesheets needed. Stylesheets can be added with L<use_stylesheet>.
3720
3721 Only one header will be generated. If the method was already called in this
3722 request it will not output anything and return undef. Also if no
3723 HTTP_USER_AGENT is found, no header is generated.
3724
3725 Although header does not accept parameters itself, it will honor special
3726 hashkeys of its Form instance:
3727
3728 =over 4
3729
3730 =item refresh_time
3731
3732 =item refresh_url
3733
3734 If one of these is set, a http-equiv refresh is generated. Missing parameters
3735 default to 3 seconds and the refering url.
3736
3737 =item stylesheet
3738
3739 Either a scalar or an array ref. Will be inlined into the header. Add
3740 stylesheets with the L<use_stylesheet> function.
3741
3742 =item landscape
3743
3744 If true, a css snippet will be generated that sets the page in landscape mode.
3745
3746 =item favicon
3747
3748 Used to override the default favicon.
3749
3750 =item title
3751
3752 A html page title will be generated from this
3753
3754 =item mtime_ischanged
3755
3756 Tries to avoid concurrent write operations to records by checking the database mtime with a fetched one.
3757
3758 Can be used / called with any table, that has itime and mtime attributes.
3759 Valid C<table> names are: oe, ar, ap, delivery_orders, parts.
3760 Can be called wit C<option> mail to generate a different error message.
3761
3762 Returns undef if no save operation has been done yet ($self->{id} not present).
3763 Returns undef if no concurrent write process is detected otherwise a error message.
3764
3765 =back
3766
3767 =cut