Pfadkomponenten entfernen, bevor exec aufgerufen wird, damit nicht beliebige Perlscri...
[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., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #======================================================================
32 # Utilities for parsing forms
33 # and supporting routines for linking account numbers
34 # used in AR, AP and IS, IR modules
35 #
36 #======================================================================
37
38 package Form;
39 use Data::Dumper;
40
41 use Cwd;
42 use HTML::Template;
43 use Template;
44 use SL::Template;
45 use CGI::Ajax;
46 use SL::DBUtils;
47 use SL::Mailer;
48 use SL::Menu;
49 use SL::User;
50 use SL::Common;
51 use CGI;
52
53 my $standard_dbh;
54
55 sub DESTROY {
56   if ($standard_dbh) {
57     $standard_dbh->disconnect();
58     undef $standard_dbh;
59   }
60 }
61
62 sub _input_to_hash {
63   $main::lxdebug->enter_sub(2);
64
65   my $input = $_[0];
66   my %in    = ();
67   my @pairs = split(/&/, $input);
68
69   foreach (@pairs) {
70     my ($name, $value) = split(/=/, $_, 2);
71     $in{$name} = unescape(undef, $value);
72   }
73
74   $main::lxdebug->leave_sub(2);
75
76   return %in;
77 }
78
79 sub _request_to_hash {
80   $main::lxdebug->enter_sub(2);
81
82   my ($input) = @_;
83
84   if (!$ENV{'CONTENT_TYPE'}
85       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
86     $main::lxdebug->leave_sub(2);
87     return _input_to_hash($input);
88   }
89
90   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr);
91   my %params;
92
93   my $boundary = '--' . $1;
94
95   foreach my $line (split m/\n/, $input) {
96     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
97
98     if (($line eq $boundary) || ($line eq "$boundary\r")) {
99       $params{$name} =~ s|\r?\n$|| if $name;
100
101       undef $name, $filename;
102
103       $headers_done   = 0;
104       $content_type   = "text/plain";
105       $boundary_found = 1;
106       $need_cr        = 0;
107
108       next;
109     }
110
111     next unless $boundary_found;
112
113     if (!$headers_done) {
114       $line =~ s/[\r\n]*$//;
115
116       if (!$line) {
117         $headers_done = 1;
118         next;
119       }
120
121       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
122         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
123           $filename = $1;
124           substr $line, $-[0], $+[0] - $-[0], "";
125         }
126
127         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
128           $name = $1;
129           substr $line, $-[0], $+[0] - $-[0], "";
130         }
131
132         $params{$name}    = "";
133         $params{FILENAME} = $filename if ($filename);
134
135         next;
136       }
137
138       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
139         $content_type = $1;
140       }
141
142       next;
143     }
144
145     next unless $name;
146
147     $params{$name} .= "${line}\n";
148   }
149
150   $params{$name} =~ s|\r?\n$|| if $name;
151
152   $main::lxdebug->leave_sub(2);
153   return %params;
154 }
155
156 sub new {
157   $main::lxdebug->enter_sub();
158
159   my $type = shift;
160
161   my $self = {};
162
163   if ($LXDebug::watch_form) {
164     require SL::Watchdog;
165     tie %{ $self }, 'SL::Watchdog';
166   }
167
168   read(STDIN, $_, $ENV{CONTENT_LENGTH});
169
170   if ($ENV{QUERY_STRING}) {
171     $_ = $ENV{QUERY_STRING};
172   }
173
174   if ($ARGV[0]) {
175     $_ = $ARGV[0];
176   }
177
178   my %parameters = _request_to_hash($_);
179   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
180
181   $self->{action} = lc $self->{action};
182   $self->{action} =~ s/( |-|,|\#)/_/g;
183
184   $self->{version}   = "2.4.3";
185
186   $main::lxdebug->leave_sub();
187
188   bless $self, $type;
189 }
190
191 sub debug {
192   $main::lxdebug->enter_sub();
193
194   my ($self) = @_;
195
196   print "\n";
197
198   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
199
200   $main::lxdebug->leave_sub();
201 }
202
203 sub escape {
204   $main::lxdebug->enter_sub(2);
205
206   my ($self, $str) = @_;
207
208   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
209
210   $main::lxdebug->leave_sub(2);
211
212   return $str;
213 }
214
215 sub unescape {
216   $main::lxdebug->enter_sub(2);
217
218   my ($self, $str) = @_;
219
220   $str =~ tr/+/ /;
221   $str =~ s/\\$//;
222
223   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
224
225   $main::lxdebug->leave_sub(2);
226
227   return $str;
228 }
229
230 sub quote {
231   my ($self, $str) = @_;
232
233   if ($str && !ref($str)) {
234     $str =~ s/\"/&quot;/g;
235   }
236
237   $str;
238
239 }
240
241 sub unquote {
242   my ($self, $str) = @_;
243
244   if ($str && !ref($str)) {
245     $str =~ s/&quot;/\"/g;
246   }
247
248   $str;
249
250 }
251
252 sub quote_html {
253   $main::lxdebug->enter_sub(2);
254
255   my ($self, $str) = @_;
256
257   my %replace =
258     ('order' => ['"', '<', '>'],
259      '<'             => '&lt;',
260      '>'             => '&gt;',
261      '"'             => '&quot;',
262     );
263
264   map({ $str =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
265
266   $main::lxdebug->leave_sub(2);
267
268   return $str;
269 }
270
271 sub hide_form {
272   my $self = shift;
273
274   if (@_) {
275     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
276   } else {
277     for (sort keys %$self) {
278       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
279       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
280     }
281   }
282
283 }
284
285 sub error {
286   $main::lxdebug->enter_sub();
287
288   $main::lxdebug->show_backtrace();
289
290   my ($self, $msg) = @_;
291   if ($ENV{HTTP_USER_AGENT}) {
292     $msg =~ s/\n/<br>/g;
293     $self->show_generic_error($msg);
294
295   } else {
296
297     if ($self->{error_function}) {
298       &{ $self->{error_function} }($msg);
299     } else {
300       die "Error: $msg\n";
301     }
302   }
303
304   $main::lxdebug->leave_sub();
305 }
306
307 sub info {
308   $main::lxdebug->enter_sub();
309
310   my ($self, $msg) = @_;
311
312   if ($ENV{HTTP_USER_AGENT}) {
313     $msg =~ s/\n/<br>/g;
314
315     if (!$self->{header}) {
316       $self->header;
317       print qq|
318       <body>|;
319     }
320
321     print qq|
322
323     <p><b>$msg</b>
324     |;
325
326   } else {
327
328     if ($self->{info_function}) {
329       &{ $self->{info_function} }($msg);
330     } else {
331       print "$msg\n";
332     }
333   }
334
335   $main::lxdebug->leave_sub();
336 }
337
338 sub numtextrows {
339   $main::lxdebug->enter_sub();
340
341   my ($self, $str, $cols, $maxrows) = @_;
342
343   my $rows = 0;
344
345   map { $rows += int(((length) - 2) / $cols) + 1 } split /\r/, $str;
346
347   $maxrows = $rows unless defined $maxrows;
348
349   $main::lxdebug->leave_sub();
350
351   return ($rows > $maxrows) ? $maxrows : $rows;
352 }
353
354 sub dberror {
355   $main::lxdebug->enter_sub();
356
357   my ($self, $msg) = @_;
358
359   $self->error("$msg\n" . $DBI::errstr);
360
361   $main::lxdebug->leave_sub();
362 }
363
364 sub isblank {
365   $main::lxdebug->enter_sub();
366
367   my ($self, $name, $msg) = @_;
368
369   if ($self->{$name} =~ /^\s*$/) {
370     $self->error($msg);
371   }
372   $main::lxdebug->leave_sub();
373 }
374
375 sub header {
376   $main::lxdebug->enter_sub();
377
378   my ($self, $extra_code) = @_;
379
380   if ($self->{header}) {
381     $main::lxdebug->leave_sub();
382     return;
383   }
384
385   my ($stylesheet, $favicon);
386
387   if ($ENV{HTTP_USER_AGENT}) {
388
389     if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
390       $stylesheet =
391         qq|<LINK REL="stylesheet" HREF="css/$self->{stylesheet}" TYPE="text/css" TITLE="Lx-Office stylesheet">
392  |;
393     }
394
395     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
396
397     if ($self->{favicon} && (-f "$self->{favicon}")) {
398       $favicon =
399         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
400   |;
401     }
402
403     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
404
405     if ($self->{landscape}) {
406       $pagelayout = qq|<style type="text/css">
407                         \@page { size:landscape; }
408                         </style>|;
409     }
410
411     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
412
413     #Set Calendar
414     my $jsscript = "";
415     if ($self->{jsscript} == 1) {
416
417       $jsscript = qq|
418         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
419         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
420         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
421         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
422         $self->{javascript}
423        |;
424     }
425
426     $self->{titlebar} =
427       ($self->{title})
428       ? "$self->{title} - $self->{titlebar}"
429       : $self->{titlebar};
430     my $ajax = "";
431     foreach $item (@ { $self->{AJAX} }) {
432       $ajax .= $item->show_javascript();
433     }
434     print qq|Content-Type: text/html; charset=${db_charset};
435
436 <html>
437 <head>
438   <title>$self->{titlebar}</title>
439   $stylesheet
440   $pagelayout
441   $favicon
442   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
443   $jsscript
444   $ajax
445
446   <script type="text/javascript">
447   <!--
448     function fokus() {
449       $fokus
450     }
451   //-->
452   </script>
453
454   <meta name="robots" content="noindex,nofollow" />
455   <script type="text/javascript" src="js/highlight_input.js"></script>
456   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
457
458   <script type="text/javascript" src="js/tabcontent.js">
459
460   /***********************************************
461   * Tab Content script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
462   * This notice MUST stay intact for legal use
463   * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
464   ***********************************************/
465
466   </script>
467
468   $extra_code
469 </head>
470
471 |;
472   }
473   $self->{header} = 1;
474
475   $main::lxdebug->leave_sub();
476 }
477
478 sub _prepare_html_template {
479   $main::lxdebug->enter_sub();
480
481   my ($self, $file, $additional_params) = @_;
482   my $language;
483
484   if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
485     $language = $main::language;
486   } else {
487     $language = $main::myconfig{"countrycode"};
488   }
489   $language = "de" unless ($language);
490
491   if (-f "templates/webpages/${file}_${language}.html") {
492     if ((-f ".developer") &&
493         (-f "templates/webpages/${file}_master.html") &&
494         ((stat("templates/webpages/${file}_master.html"))[9] >
495          (stat("templates/webpages/${file}_${language}.html"))[9])) {
496       my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
497         "Please re-run 'locales.pl' in 'locale/${language}'.";
498       print(qq|<pre>$info</pre>|);
499       die($info);
500     }
501
502     $file = "templates/webpages/${file}_${language}.html";
503   } elsif (-f "templates/webpages/${file}.html") {
504     $file = "templates/webpages/${file}.html";
505   } else {
506     my $info = "Web page template '${file}' not found.\n" .
507       "Please re-run 'locales.pl' in 'locale/${language}'.";
508     print(qq|<pre>$info</pre>|);
509     die($info);
510   }
511
512   if ($self->{"DEBUG"}) {
513     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
514   }
515
516   if ($additional_params->{"DEBUG"}) {
517     $additional_params->{"DEBUG"} =
518       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
519   }
520
521   if (%main::myconfig) {
522     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
523     my $jsc_dateformat = $main::myconfig{"dateformat"};
524     $jsc_dateformat =~ s/d+/\%d/gi;
525     $jsc_dateformat =~ s/m+/\%m/gi;
526     $jsc_dateformat =~ s/y+/\%Y/gi;
527     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
528   }
529
530   $additional_params->{"conf_webdav"}                 = $main::webdav;
531   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
532   $additional_params->{"conf_latex_templates"}        = $main::latex;
533   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
534
535   if (%main::debug_options) {
536     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
537   }
538
539   $main::lxdebug->leave_sub();
540
541   return $file;
542 }
543
544 sub parse_html_template {
545   $main::lxdebug->enter_sub();
546
547   my ($self, $file, $additional_params) = @_;
548
549   $additional_params ||= { };
550
551   $file = $self->_prepare_html_template($file, $additional_params);
552
553   my $template = HTML::Template->new("filename" => $file,
554                                      "die_on_bad_params" => 0,
555                                      "strict" => 0,
556                                      "case_sensitive" => 1,
557                                      "loop_context_vars" => 1,
558                                      "global_vars" => 1);
559
560   foreach my $key ($template->param()) {
561     my $param = $additional_params->{$key} || $self->{$key};
562     $param = [] if (($template->query("name" => $key) eq "LOOP") && (ref($param) ne "ARRAY"));
563     $template->param($key => $param);
564   }
565
566   my $output = $template->output();
567
568   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
569
570   $main::lxdebug->leave_sub();
571
572   return $output;
573 }
574
575 sub parse_html_template2 {
576   $main::lxdebug->enter_sub();
577
578   my ($self, $file, $additional_params) = @_;
579
580   $additional_params ||= { };
581
582   $file = $self->_prepare_html_template($file, $additional_params);
583
584   my $template = Template->new({ 'INTERPOLATE' => 0,
585                                  'EVAL_PERL'   => 0,
586                                  'ABSOLUTE'    => 1,
587                                  'CACHE_SIZE'  => 0,
588                                }) || die;
589
590   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
591
592   my $output;
593   $template->process($file, $additional_params, \$output);
594
595   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
596
597   $main::lxdebug->leave_sub();
598
599   return $output;
600 }
601
602 sub show_generic_error {
603   my ($self, $error, $title, $action) = @_;
604
605   my $add_params = {};
606   $add_params->{"title"} = $title if ($title);
607   $self->{"label_error"} = $error;
608
609   my @vars;
610   if ($action) {
611     map({ delete($self->{$_}); } qw(action));
612     map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
613             if (!ref($self->{$_})); }
614         keys(%{$self}));
615     $add_params->{"SHOW_BUTTON"} = 1;
616     $add_params->{"BUTTON_LABEL"} = $action;
617   }
618   $add_params->{"VARIABLES"} = \@vars;
619
620   $self->header();
621   print($self->parse_html_template("generic/error", $add_params));
622
623   die("Error: $error\n");
624 }
625
626 sub show_generic_information {
627   my ($self, $error, $title) = @_;
628
629   my $add_params = {};
630   $add_params->{"title"} = $title if ($title);
631   $self->{"label_information"} = $error;
632
633   $self->header();
634   print($self->parse_html_template("generic/information", $add_params));
635
636   die("Information: $error\n");
637 }
638
639 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
640 # changed it to accept an arbitrary number of triggers - sschoeling
641 sub write_trigger {
642   $main::lxdebug->enter_sub();
643
644   my $self     = shift;
645   my $myconfig = shift;
646   my $qty      = shift;
647
648   # set dateform for jsscript
649   # default
650   my %dateformats = (
651     "dd.mm.yy" => "%d.%m.%Y",
652     "dd-mm-yy" => "%d-%m-%Y",
653     "dd/mm/yy" => "%d/%m/%Y",
654     "mm/dd/yy" => "%m/%d/%Y",
655     "mm-dd-yy" => "%m-%d-%Y",
656     "yyyy-mm-dd" => "%Y-%m-%d",
657     );
658
659   my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
660     $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
661
662   my @triggers;
663   while ($#_ >= 2) {
664     push @triggers, qq|
665        Calendar.setup(
666       {
667       inputField : "| . (shift) . qq|",
668       ifFormat :"$ifFormat",
669       align : "| .  (shift) . qq|",
670       button : "| . (shift) . qq|"
671       }
672       );
673        |;
674   }
675   my $jsscript = qq|
676        <script type="text/javascript">
677        <!--| . join("", @triggers) . qq|//-->
678         </script>
679         |;
680
681   $main::lxdebug->leave_sub();
682
683   return $jsscript;
684 }    #end sub write_trigger
685
686 sub redirect {
687   $main::lxdebug->enter_sub();
688
689   my ($self, $msg) = @_;
690
691   if ($self->{callback}) {
692
693     ($script, $argv) = split(/\?/, $self->{callback}, 2);
694     $script =~ s|.*/||;
695     exec("perl", "$script", $argv);
696
697   } else {
698
699     $self->info($msg);
700     exit;
701   }
702
703   $main::lxdebug->leave_sub();
704 }
705
706 # sort of columns removed - empty sub
707 sub sort_columns {
708   $main::lxdebug->enter_sub();
709
710   my ($self, @columns) = @_;
711
712   $main::lxdebug->leave_sub();
713
714   return @columns;
715 }
716 #
717 sub format_amount {
718   $main::lxdebug->enter_sub(2);
719
720   my ($self, $myconfig, $amount, $places, $dash) = @_;
721
722   if ($amount eq "") {
723     $amount = 0;
724   }
725   my $neg = ($amount =~ s/-//);
726
727   if (defined($places) && ($places ne '')) {
728     if ($places < 0) {
729       $amount *= 1;
730       $places *= -1;
731
732       my ($actual_places) = ($amount =~ /\.(\d+)/);
733       $actual_places = length($actual_places);
734       $places = $actual_places > $places ? $actual_places : $places;
735     }
736
737     $amount = $self->round_amount($amount, $places);
738   }
739
740   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
741   my @p = split(/\./, $amount); # split amount at decimal point
742
743   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
744
745   $amount = $p[0];
746   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
747
748   $amount = do {
749     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
750     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
751                         ($neg ? "-$amount"   : "$amount" )    ;
752   };
753
754
755   $main::lxdebug->leave_sub(2);
756   return $amount;
757 }
758 #
759 sub parse_amount {
760   $main::lxdebug->enter_sub(2);
761
762   my ($self, $myconfig, $amount) = @_;
763
764   if (   ($myconfig->{numberformat} eq '1.000,00')
765       || ($myconfig->{numberformat} eq '1000,00')) {
766     $amount =~ s/\.//g;
767     $amount =~ s/,/\./;
768   }
769
770   if ($myconfig->{numberformat} eq "1'000.00") {
771     $amount =~ s/\'//g;
772   }
773
774   $amount =~ s/,//g;
775
776   $main::lxdebug->leave_sub(2);
777
778   return ($amount * 1);
779 }
780
781 sub round_amount {
782   $main::lxdebug->enter_sub(2);
783
784   my ($self, $amount, $places) = @_;
785   my $round_amount;
786
787   # Rounding like "Kaufmannsrunden"
788   # Descr. http://de.wikipedia.org/wiki/Rundung
789   # Inspired by
790   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
791   # Solves Bug: 189
792   # Udo Spallek
793   $amount = $amount * (10**($places));
794   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
795
796   $main::lxdebug->leave_sub(2);
797
798   return $round_amount;
799
800 }
801
802 sub parse_template {
803   $main::lxdebug->enter_sub();
804
805   my ($self, $myconfig, $userspath) = @_;
806   my ($template, $out);
807
808   local (*IN, *OUT);
809
810   $self->{"cwd"} = getcwd();
811   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
812
813   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
814     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
815   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
816     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
817     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
818   } elsif (($self->{"format"} =~ /html/i) ||
819            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
820     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
821   } elsif (($self->{"format"} =~ /xml/i) ||
822              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
823     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
824   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
825     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
826   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
827     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
828   } elsif ( defined $self->{'format'}) {
829     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
830   } elsif ( $self->{'format'} eq '' ) {
831     $self->error("No Outputformat given: $self->{'format'}");
832   } else { #Catch the rest
833     $self->error("Outputformat not defined: $self->{'format'}");
834   }
835
836   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
837   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
838
839   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
840       qw(email tel fax name signature company address businessnumber
841          co_ustid taxnumber duns));
842   map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; }
843       qw(company address signature));
844   map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature));
845
846   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
847
848   # OUT is used for the media, screen, printer, email
849   # for postscript we store a copy in a temporary file
850   my $fileid = time;
851   my $prepend_userspath;
852
853   if (!$self->{tmpfile}) {
854     $self->{tmpfile}   = "${fileid}.$self->{IN}";
855     $prepend_userspath = 1;
856   }
857
858   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
859
860   $self->{tmpfile} =~ s|.*/||;
861   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
862   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
863
864   if ($template->uses_temp_file() || $self->{media} eq 'email') {
865     $out = $self->{OUT};
866     $self->{OUT} = ">$self->{tmpfile}";
867   }
868
869   if ($self->{OUT}) {
870     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
871   } else {
872     open(OUT, ">-") or $self->error("STDOUT : $!");
873     $self->header;
874   }
875
876   if (!$template->parse(*OUT)) {
877     $self->cleanup();
878     $self->error("$self->{IN} : " . $template->get_error());
879   }
880
881   close(OUT);
882
883   if ($template->uses_temp_file() || $self->{media} eq 'email') {
884
885     if ($self->{media} eq 'email') {
886
887       my $mail = new Mailer;
888
889       map { $mail->{$_} = $self->{$_} }
890         qw(cc bcc subject message version format);
891       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
892       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
893       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
894       $mail->{fileid} = "$fileid.";
895       $myconfig->{signature} =~ s/\\r\\n/\\n/g;
896
897       # if we send html or plain text inline
898       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
899         $mail->{contenttype} = "text/html";
900
901         $mail->{message}       =~ s/\r\n/<br>\n/g;
902         $myconfig->{signature} =~ s/\\n/<br>\n/g;
903         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
904
905         open(IN, $self->{tmpfile})
906           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
907         while (<IN>) {
908           $mail->{message} .= $_;
909         }
910
911         close(IN);
912
913       } else {
914
915         if (!$self->{"do_not_attach"}) {
916           @{ $mail->{attachments} } =
917             ({ "filename" => $self->{"tmpfile"},
918                "name" => $self->{"attachment_filename"} ?
919                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
920         }
921
922         $mail->{message}       =~ s/\r\n/\n/g;
923         $myconfig->{signature} =~ s/\\n/\n/g;
924         $mail->{message} .= "\n-- \n$myconfig->{signature}";
925
926       }
927
928       my $err = $mail->send();
929       $self->error($self->cleanup . "$err") if ($err);
930
931     } else {
932
933       $self->{OUT} = $out;
934
935       my $numbytes = (-s $self->{tmpfile});
936       open(IN, $self->{tmpfile})
937         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
938
939       $self->{copies} = 1 unless $self->{media} eq 'printer';
940
941       chdir("$self->{cwd}");
942       #print(STDERR "Kopien $self->{copies}\n");
943       #print(STDERR "OUT $self->{OUT}\n");
944       for my $i (1 .. $self->{copies}) {
945         if ($self->{OUT}) {
946           open(OUT, $self->{OUT})
947             or $self->error($self->cleanup . "$self->{OUT} : $!");
948         } else {
949           $self->{attachment_filename} = ($self->{attachment_filename}) 
950                                        ? $self->{attachment_filename}
951                                        : $self->generate_attachment_filename();
952
953           # launch application
954           print qq|Content-Type: | . $template->get_mime_type() . qq|
955 Content-Disposition: attachment; filename="$self->{attachment_filename}"
956 Content-Length: $numbytes
957
958 |;
959
960           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
961
962         }
963
964         while (<IN>) {
965           print OUT $_;
966         }
967
968         close(OUT);
969
970         seek IN, 0, 0;
971       }
972
973       close(IN);
974     }
975
976   }
977
978   $self->cleanup;
979
980   chdir("$self->{cwd}");
981   $main::lxdebug->leave_sub();
982 }
983
984 sub generate_attachment_filename {
985   my ($self) = @_;
986
987   my %formname_translations = (
988      bin_list            => $main::locale->text('Bin List'),
989      credit_note         => $main::locale->text('Credit Note'),
990      invoice             => $main::locale->text('Invoice'),
991      packing_list        => $main::locale->text('Packing List'),
992      pick_list           => $main::locale->text('Pick List'),
993      proforma            => $main::locale->text('Proforma Invoice'),
994      purchase_order      => $main::locale->text('Purchase Order'),
995      request_quotation   => $main::locale->text('RFQ'),
996      sales_order         => $main::locale->text('Confirmation'),
997      sales_quotation     => $main::locale->text('Quotation'),
998      storno_invoice      => $main::locale->text('Storno Invoice'),
999      storno_packing_list => $main::locale->text('Storno Packing List'),
1000   );
1001
1002   my $attachment_filename = $formname_translations{$self->{"formname"}};
1003   my $prefix = 
1004       (grep { $self->{"type"} eq $_ } qw(invoice credit_note)) ? "inv"
1005     : ($self->{"type"} =~ /_quotation$/)                       ? "quo"
1006     :                                                            "ord";
1007
1008   if ($attachment_filename && $self->{"${prefix}number"}) {
1009     $attachment_filename .= "_" . $self->{"${prefix}number"}
1010                             . (  $self->{format} =~ /pdf/i          ? ".pdf"
1011                                : $self->{format} =~ /postscript/i   ? ".ps"
1012                                : $self->{format} =~ /opendocument/i ? ".odt"
1013                                : $self->{format} =~ /html/i         ? ".html"
1014                                :                                      "");
1015     $attachment_filename =~ s/ /_/g;
1016     my %umlaute = ( "ä" => "ae", "ö" => "oe", "ü" => "ue", 
1017                     "Ä" => "Ae", "Ö" => "Oe", "Ãœ" => "Ue", "ß" => "ss");
1018     map { $attachment_filename =~ s/$_/$umlaute{$_}/g } keys %umlaute;
1019   } else {
1020     $attachment_filename = "";
1021   }
1022
1023   return $attachment_filename;
1024 }
1025
1026 sub cleanup {
1027   $main::lxdebug->enter_sub();
1028
1029   my $self = shift;
1030
1031   chdir("$self->{tmpdir}");
1032
1033   my @err = ();
1034   if (-f "$self->{tmpfile}.err") {
1035     open(FH, "$self->{tmpfile}.err");
1036     @err = <FH>;
1037     close(FH);
1038   }
1039
1040   if ($self->{tmpfile}) {
1041     $self->{tmpfile} =~ s|.*/||g;
1042     # strip extension
1043     $self->{tmpfile} =~ s/\.\w+$//g;
1044     my $tmpfile = $self->{tmpfile};
1045     unlink(<$tmpfile.*>);
1046   }
1047
1048   chdir("$self->{cwd}");
1049
1050   $main::lxdebug->leave_sub();
1051
1052   return "@err";
1053 }
1054
1055 sub datetonum {
1056   $main::lxdebug->enter_sub();
1057
1058   my ($self, $date, $myconfig) = @_;
1059
1060   if ($date && $date =~ /\D/) {
1061
1062     if ($myconfig->{dateformat} =~ /^yy/) {
1063       ($yy, $mm, $dd) = split /\D/, $date;
1064     }
1065     if ($myconfig->{dateformat} =~ /^mm/) {
1066       ($mm, $dd, $yy) = split /\D/, $date;
1067     }
1068     if ($myconfig->{dateformat} =~ /^dd/) {
1069       ($dd, $mm, $yy) = split /\D/, $date;
1070     }
1071
1072     $dd *= 1;
1073     $mm *= 1;
1074     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1075     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1076
1077     $dd = "0$dd" if ($dd < 10);
1078     $mm = "0$mm" if ($mm < 10);
1079
1080     $date = "$yy$mm$dd";
1081   }
1082
1083   $main::lxdebug->leave_sub();
1084
1085   return $date;
1086 }
1087
1088 # Database routines used throughout
1089
1090 sub dbconnect {
1091   $main::lxdebug->enter_sub(2);
1092
1093   my ($self, $myconfig) = @_;
1094
1095   # connect to database
1096   my $dbh =
1097     DBI->connect($myconfig->{dbconnect},
1098                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1099     or $self->dberror;
1100
1101   # set db options
1102   if ($myconfig->{dboptions}) {
1103     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1104   }
1105
1106   $main::lxdebug->leave_sub(2);
1107
1108   return $dbh;
1109 }
1110
1111 sub dbconnect_noauto {
1112   $main::lxdebug->enter_sub();
1113
1114   my ($self, $myconfig) = @_;
1115   
1116   # connect to database
1117   $dbh =
1118     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1119                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1120     or $self->dberror;
1121
1122   # set db options
1123   if ($myconfig->{dboptions}) {
1124     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1125   }
1126
1127   $main::lxdebug->leave_sub();
1128
1129   return $dbh;
1130 }
1131
1132 sub get_standard_dbh {
1133   $main::lxdebug->enter_sub(2);
1134
1135   my ($self, $myconfig) = @_;
1136
1137   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1138
1139   $main::lxdebug->leave_sub(2);
1140
1141   return $standard_dbh;
1142 }
1143
1144 sub update_balance {
1145   $main::lxdebug->enter_sub();
1146
1147   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1148
1149   # if we have a value, go do it
1150   if ($value != 0) {
1151
1152     # retrieve balance from table
1153     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1154     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1155     my ($balance) = $sth->fetchrow_array;
1156     $sth->finish;
1157
1158     $balance += $value;
1159
1160     # update balance
1161     $query = "UPDATE $table SET $field = $balance WHERE $where";
1162     do_query($self, $dbh, $query, @values);
1163   }
1164   $main::lxdebug->leave_sub();
1165 }
1166
1167 sub update_exchangerate {
1168   $main::lxdebug->enter_sub();
1169
1170   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1171
1172   # some sanity check for currency
1173   if ($curr eq '') {
1174     $main::lxdebug->leave_sub();
1175     return;
1176   }  
1177   my $query = qq|SELECT curr FROM defaults|;
1178
1179   my ($currency) = selectrow_query($self, $dbh, $query);
1180   my ($defaultcurrency) = split m/:/, $currency;
1181
1182
1183   if ($curr eq $defaultcurrency) {
1184     $main::lxdebug->leave_sub();
1185     return;
1186   }
1187
1188   my $query = qq|SELECT e.curr FROM exchangerate e
1189                  WHERE e.curr = ? AND e.transdate = ?
1190                  FOR UPDATE|;
1191   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1192
1193   if ($buy == 0) {
1194     $buy = "";
1195   }
1196   if ($sell == 0) {
1197     $sell = "";
1198   }
1199
1200   $buy = conv_i($buy, "NULL");
1201   $sell = conv_i($sell, "NULL");
1202
1203   my $set;
1204   if ($buy != 0 && $sell != 0) {
1205     $set = "buy = $buy, sell = $sell";
1206   } elsif ($buy != 0) {
1207     $set = "buy = $buy";
1208   } elsif ($sell != 0) {
1209     $set = "sell = $sell";
1210   }
1211
1212   if ($sth->fetchrow_array) {
1213     $query = qq|UPDATE exchangerate
1214                 SET $set
1215                 WHERE curr = ?
1216                 AND transdate = ?|;
1217     
1218   } else {
1219     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1220                 VALUES (?, $buy, $sell, ?)|;
1221   }
1222   $sth->finish;
1223   do_query($self, $dbh, $query, $curr, $transdate);
1224
1225   $main::lxdebug->leave_sub();
1226 }
1227
1228 sub save_exchangerate {
1229   $main::lxdebug->enter_sub();
1230
1231   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1232
1233   my $dbh = $self->dbconnect($myconfig);
1234
1235   my ($buy, $sell);
1236
1237   $buy  = $rate if $fld eq 'buy';
1238   $sell = $rate if $fld eq 'sell';
1239
1240
1241   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1242
1243
1244   $dbh->disconnect;
1245
1246   $main::lxdebug->leave_sub();
1247 }
1248
1249 sub get_exchangerate {
1250   $main::lxdebug->enter_sub();
1251
1252   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1253
1254   unless ($transdate) {
1255     $main::lxdebug->leave_sub();
1256     return 1;
1257   }
1258
1259   my $query = qq|SELECT curr FROM defaults|;
1260
1261   my ($currency) = selectrow_query($self, $dbh, $query);
1262   my ($defaultcurrency) = split m/:/, $currency;
1263
1264   if ($currency eq $defaultcurrency) {
1265     $main::lxdebug->leave_sub();
1266     return 1;
1267   }
1268
1269   my $query = qq|SELECT e.$fld FROM exchangerate e
1270                  WHERE e.curr = ? AND e.transdate = ?|;
1271   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1272
1273
1274
1275   $main::lxdebug->leave_sub();
1276
1277   return $exchangerate;
1278 }
1279
1280 sub check_exchangerate {
1281   $main::lxdebug->enter_sub();
1282
1283   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1284
1285   unless ($transdate) {
1286     $main::lxdebug->leave_sub();
1287     return "";
1288   }
1289
1290   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1291
1292   if ($currency eq $defaultcurrency) {
1293     $main::lxdebug->leave_sub();
1294     return 1;
1295   }
1296
1297   my $dbh   = $self->get_standard_dbh($myconfig);
1298   my $query = qq|SELECT e.$fld FROM exchangerate e
1299                  WHERE e.curr = ? AND e.transdate = ?|;
1300
1301   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1302
1303   $exchangerate = 1 if ($exchangerate eq "");
1304
1305   $main::lxdebug->leave_sub();
1306
1307   return $exchangerate;
1308 }
1309
1310 sub get_default_currency {
1311   $main::lxdebug->enter_sub();
1312
1313   my ($self, $myconfig) = @_;
1314   my $dbh = $self->get_standard_dbh($myconfig);
1315
1316   my $query = qq|SELECT curr FROM defaults|;
1317
1318   my ($curr)            = selectrow_query($self, $dbh, $query);
1319   my ($defaultcurrency) = split m/:/, $curr;
1320
1321   $main::lxdebug->leave_sub();
1322
1323   return $defaultcurrency;
1324 }
1325
1326
1327 sub set_payment_options {
1328   $main::lxdebug->enter_sub();
1329
1330   my ($self, $myconfig, $transdate) = @_;
1331
1332   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1333
1334   my $dbh = $self->get_standard_dbh($myconfig);
1335
1336   my $query =
1337     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1338     qq|FROM payment_terms p | .
1339     qq|WHERE p.id = ?|;
1340
1341   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1342    $self->{payment_terms}) =
1343      selectrow_query($self, $dbh, $query, $self->{payment_id});
1344
1345   if ($transdate eq "") {
1346     if ($self->{invdate}) {
1347       $transdate = $self->{invdate};
1348     } else {
1349       $transdate = $self->{transdate};
1350     }
1351   }
1352
1353   $query =
1354     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1355     qq|FROM payment_terms|;
1356   ($self->{netto_date}, $self->{skonto_date}) =
1357     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1358
1359   my $total = ($self->{invtotal}) ? $self->{invtotal} : $self->{ordtotal};
1360   my $skonto_amount = $self->parse_amount($myconfig, $total) *
1361     $self->{percent_skonto};
1362
1363   $self->{skonto_amount} =
1364     $self->format_amount($myconfig, $skonto_amount, 2);
1365
1366   if ($self->{"language_id"}) {
1367     $query =
1368       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1369       qq|FROM translation_payment_terms t | .
1370       qq|LEFT JOIN language l ON t.language_id = l.id | .
1371       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1372     my ($description_long, $output_numberformat, $output_dateformat,
1373       $output_longdates) =
1374       selectrow_query($self, $dbh, $query,
1375                       $self->{"language_id"}, $self->{"payment_id"});
1376
1377     $self->{payment_terms} = $description_long if ($description_long);
1378
1379     if ($output_dateformat) {
1380       foreach my $key (qw(netto_date skonto_date)) {
1381         $self->{$key} =
1382           $main::locale->reformat_date($myconfig, $self->{$key},
1383                                        $output_dateformat,
1384                                        $output_longdates);
1385       }
1386     }
1387
1388     if ($output_numberformat &&
1389         ($output_numberformat ne $myconfig->{"numberformat"})) {
1390       my $saved_numberformat = $myconfig->{"numberformat"};
1391       $myconfig->{"numberformat"} = $output_numberformat;
1392       $self->{skonto_amount} =
1393         $self->format_amount($myconfig, $skonto_amount, 2);
1394       $myconfig->{"numberformat"} = $saved_numberformat;
1395     }
1396   }
1397
1398   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1399   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1400   $self->{payment_terms} =~ s/<%skonto_amount%>/$self->{skonto_amount}/g;
1401   $self->{payment_terms} =~ s/<%total%>/$self->{total}/g;
1402   $self->{payment_terms} =~ s/<%invtotal%>/$self->{invtotal}/g;
1403   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1404   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1405   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1406   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1407   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1408
1409   $main::lxdebug->leave_sub();
1410
1411 }
1412
1413 sub get_template_language {
1414   $main::lxdebug->enter_sub();
1415
1416   my ($self, $myconfig) = @_;
1417
1418   my $template_code = "";
1419
1420   if ($self->{language_id}) {
1421     my $dbh = $self->get_standard_dbh($myconfig);
1422     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1423     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1424   }
1425
1426   $main::lxdebug->leave_sub();
1427
1428   return $template_code;
1429 }
1430
1431 sub get_printer_code {
1432   $main::lxdebug->enter_sub();
1433
1434   my ($self, $myconfig) = @_;
1435
1436   my $template_code = "";
1437
1438   if ($self->{printer_id}) {
1439     my $dbh = $self->get_standard_dbh($myconfig);
1440     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1441     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1442   }
1443
1444   $main::lxdebug->leave_sub();
1445
1446   return $template_code;
1447 }
1448
1449 sub get_shipto {
1450   $main::lxdebug->enter_sub();
1451
1452   my ($self, $myconfig) = @_;
1453
1454   my $template_code = "";
1455
1456   if ($self->{shipto_id}) {
1457     my $dbh = $self->get_standard_dbh($myconfig);
1458     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1459     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1460     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1461   }
1462
1463   $main::lxdebug->leave_sub();
1464 }
1465
1466 sub add_shipto {
1467   $main::lxdebug->enter_sub();
1468
1469   my ($self, $dbh, $id, $module) = @_;
1470
1471   my $shipto;
1472   my @values;
1473
1474   foreach my $item (qw(name department_1 department_2 street zipcode city country
1475                        contact phone fax email)) {
1476     if ($self->{"shipto$item"}) {
1477       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1478     }
1479     push(@values, $self->{"shipto${item}"});
1480   }
1481
1482   if ($shipto) {
1483     if ($self->{shipto_id}) {
1484       my $query = qq|UPDATE shipto set
1485                        shiptoname = ?,
1486                        shiptodepartment_1 = ?,
1487                        shiptodepartment_2 = ?,
1488                        shiptostreet = ?,
1489                        shiptozipcode = ?,
1490                        shiptocity = ?,
1491                        shiptocountry = ?,
1492                        shiptocontact = ?,
1493                        shiptophone = ?,
1494                        shiptofax = ?,
1495                        shiptoemail = ?
1496                      WHERE shipto_id = ?|;
1497       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1498     } else {
1499       my $query = qq|SELECT * FROM shipto
1500                      WHERE shiptoname = ? AND
1501                        shiptodepartment_1 = ? AND
1502                        shiptodepartment_2 = ? AND
1503                        shiptostreet = ? AND
1504                        shiptozipcode = ? AND
1505                        shiptocity = ? AND
1506                        shiptocountry = ? AND
1507                        shiptocontact = ? AND
1508                        shiptophone = ? AND
1509                        shiptofax = ? AND
1510                        shiptoemail = ? AND
1511                        module = ? AND 
1512                        trans_id = ?|;
1513       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1514       if(!$insert_check){
1515         $query =
1516           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1517                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1518                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1519              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1520         do_query($self, $dbh, $query, $id, @values, $module);
1521       }
1522     }
1523   }
1524
1525   $main::lxdebug->leave_sub();
1526 }
1527
1528 sub get_employee {
1529   $main::lxdebug->enter_sub();
1530
1531   my ($self, $dbh) = @_;
1532
1533   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1534   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1535   $self->{"employee_id"} *= 1;
1536
1537   $main::lxdebug->leave_sub();
1538 }
1539
1540 sub get_salesman {
1541   $main::lxdebug->enter_sub();
1542
1543   my ($self, $myconfig, $salesman_id) = @_;
1544
1545   $main::lxdebug->leave_sub() and return unless $salesman_id;
1546
1547   my $dbh = $self->get_standard_dbh($myconfig);
1548
1549   my ($login) =
1550     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
1551                     $salesman_id);
1552
1553   if ($login) {
1554     my $user = new User($main::memberfile, $login);
1555     map({ $self->{"salesman_$_"} = $user->{$_}; }
1556         qw(address businessnumber co_ustid company duns email fax name
1557            taxnumber tel));
1558     $self->{salesman_login} = $login;
1559
1560     $self->{salesman_name} = $login
1561       if ($self->{salesman_name} eq "");
1562
1563     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
1564   }
1565
1566   $main::lxdebug->leave_sub();
1567 }
1568
1569 sub get_duedate {
1570   $main::lxdebug->enter_sub();
1571
1572   my ($self, $myconfig) = @_;
1573
1574   my $dbh = $self->get_standard_dbh($myconfig);
1575   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1576   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1577
1578   $main::lxdebug->leave_sub();
1579 }
1580
1581 sub _get_contacts {
1582   $main::lxdebug->enter_sub();
1583
1584   my ($self, $dbh, $id, $key) = @_;
1585
1586   $key = "all_contacts" unless ($key);
1587
1588   my $query =
1589     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1590     qq|FROM contacts | .
1591     qq|WHERE cp_cv_id = ? | .
1592     qq|ORDER BY lower(cp_name)|;
1593
1594   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1595
1596   $main::lxdebug->leave_sub();
1597 }
1598
1599 sub _get_projects {
1600   $main::lxdebug->enter_sub();
1601
1602   my ($self, $dbh, $key) = @_;
1603
1604   my ($all, $old_id, $where, @values);
1605
1606   if (ref($key) eq "HASH") {
1607     my $params = $key;
1608
1609     $key = "ALL_PROJECTS";
1610
1611     foreach my $p (keys(%{$params})) {
1612       if ($p eq "all") {
1613         $all = $params->{$p};
1614       } elsif ($p eq "old_id") {
1615         $old_id = $params->{$p};
1616       } elsif ($p eq "key") {
1617         $key = $params->{$p};
1618       }
1619     }
1620   }
1621
1622   if (!$all) {
1623     $where = "WHERE active ";
1624     if ($old_id) {
1625       if (ref($old_id) eq "ARRAY") {
1626         my @ids = grep({ $_ } @{$old_id});
1627         if (@ids) {
1628           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1629           push(@values, @ids);
1630         }
1631       } else {
1632         $where .= " OR (id = ?) ";
1633         push(@values, $old_id);
1634       }
1635     }
1636   }
1637
1638   my $query =
1639     qq|SELECT id, projectnumber, description, active | .
1640     qq|FROM project | .
1641     $where .
1642     qq|ORDER BY lower(projectnumber)|;
1643
1644   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1645
1646   $main::lxdebug->leave_sub();
1647 }
1648
1649 sub _get_shipto {
1650   $main::lxdebug->enter_sub();
1651
1652   my ($self, $dbh, $vc_id, $key) = @_;
1653
1654   $key = "all_shipto" unless ($key);
1655
1656   # get shipping addresses
1657   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
1658
1659   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
1660
1661   $main::lxdebug->leave_sub();
1662 }
1663
1664 sub _get_printers {
1665   $main::lxdebug->enter_sub();
1666
1667   my ($self, $dbh, $key) = @_;
1668
1669   $key = "all_printers" unless ($key);
1670
1671   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1672
1673   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1674
1675   $main::lxdebug->leave_sub();
1676 }
1677
1678 sub _get_charts {
1679   $main::lxdebug->enter_sub();
1680
1681   my ($self, $dbh, $params) = @_;
1682
1683   $key = $params->{key};
1684   $key = "all_charts" unless ($key);
1685
1686   my $transdate = quote_db_date($params->{transdate});
1687
1688   my $query =
1689     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
1690     qq|FROM chart c | .
1691     qq|LEFT JOIN taxkeys tk ON | .
1692     qq|(tk.id = (SELECT id FROM taxkeys | .
1693     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1694     qq|          ORDER BY startdate DESC LIMIT 1)) | .
1695     qq|ORDER BY c.accno|;
1696
1697   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1698
1699   $main::lxdebug->leave_sub();
1700 }
1701
1702 sub _get_taxcharts {
1703   $main::lxdebug->enter_sub();
1704
1705   my ($self, $dbh, $key) = @_;
1706
1707   $key = "all_taxcharts" unless ($key);
1708
1709   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
1710
1711   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1712
1713   $main::lxdebug->leave_sub();
1714 }
1715
1716 sub _get_taxzones {
1717   $main::lxdebug->enter_sub();
1718
1719   my ($self, $dbh, $key) = @_;
1720
1721   $key = "all_taxzones" unless ($key);
1722
1723   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
1724
1725   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1726
1727   $main::lxdebug->leave_sub();
1728 }
1729
1730 sub _get_employees {
1731   $main::lxdebug->enter_sub();
1732
1733   my ($self, $dbh, $default_key, $key) = @_;
1734
1735   $key = $default_key unless ($key);
1736   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
1737
1738   $main::lxdebug->leave_sub();
1739 }
1740
1741 sub _get_business_types {
1742   $main::lxdebug->enter_sub();
1743
1744   my ($self, $dbh, $key) = @_;
1745
1746   $key = "all_business_types" unless ($key);
1747   $self->{$key} =
1748     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
1749
1750   $main::lxdebug->leave_sub();
1751 }
1752
1753 sub _get_languages {
1754   $main::lxdebug->enter_sub();
1755
1756   my ($self, $dbh, $key) = @_;
1757
1758   $key = "all_languages" unless ($key);
1759
1760   my $query = qq|SELECT * FROM language ORDER BY id|;
1761
1762   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1763
1764   $main::lxdebug->leave_sub();
1765 }
1766
1767 sub _get_dunning_configs {
1768   $main::lxdebug->enter_sub();
1769
1770   my ($self, $dbh, $key) = @_;
1771
1772   $key = "all_dunning_configs" unless ($key);
1773
1774   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
1775
1776   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1777
1778   $main::lxdebug->leave_sub();
1779 }
1780
1781 sub _get_currencies {
1782 $main::lxdebug->enter_sub();
1783
1784   my ($self, $dbh, $key) = @_;
1785
1786   $key = "all_currencies" unless ($key);
1787
1788   my $query = qq|SELECT curr AS currency FROM defaults|;
1789  
1790   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
1791
1792   $main::lxdebug->leave_sub();
1793 }
1794
1795 sub _get_payments {
1796 $main::lxdebug->enter_sub();
1797
1798   my ($self, $dbh, $key) = @_;
1799
1800   $key = "all_payments" unless ($key);
1801
1802   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
1803  
1804   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1805
1806   $main::lxdebug->leave_sub();
1807 }
1808
1809 sub _get_customers {
1810   $main::lxdebug->enter_sub();
1811
1812   my ($self, $dbh, $key) = @_;
1813
1814   $key = "all_customers" unless ($key);
1815
1816   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name|;
1817
1818   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1819
1820   $main::lxdebug->leave_sub();
1821 }
1822
1823 sub _get_vendors {
1824   $main::lxdebug->enter_sub();
1825
1826   my ($self, $dbh, $key) = @_;
1827
1828   $key = "all_vendors" unless ($key);
1829
1830   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
1831
1832   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1833
1834   $main::lxdebug->leave_sub();
1835 }
1836
1837 sub _get_departments {
1838   $main::lxdebug->enter_sub();
1839
1840   my ($self, $dbh, $key) = @_;
1841
1842   $key = "all_departments" unless ($key);
1843
1844   my $query = qq|SELECT * FROM department ORDER BY description|;
1845
1846   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1847
1848   $main::lxdebug->leave_sub();
1849 }
1850
1851 sub get_lists {
1852   $main::lxdebug->enter_sub();
1853
1854   my $self = shift;
1855   my %params = @_;
1856
1857   my $dbh = $self->get_standard_dbh(\%main::myconfig);
1858   my ($sth, $query, $ref);
1859
1860   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
1861   my $vc_id = $self->{"${vc}_id"};
1862
1863   if ($params{"contacts"}) {
1864     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
1865   }
1866
1867   if ($params{"shipto"}) {
1868     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
1869   }
1870
1871   if ($params{"projects"} || $params{"all_projects"}) {
1872     $self->_get_projects($dbh, $params{"all_projects"} ?
1873                          $params{"all_projects"} : $params{"projects"},
1874                          $params{"all_projects"} ? 1 : 0);
1875   }
1876
1877   if ($params{"printers"}) {
1878     $self->_get_printers($dbh, $params{"printers"});
1879   }
1880
1881   if ($params{"languages"}) {
1882     $self->_get_languages($dbh, $params{"languages"});
1883   }
1884
1885   if ($params{"charts"}) {
1886     $self->_get_charts($dbh, $params{"charts"});
1887   }
1888
1889   if ($params{"taxcharts"}) {
1890     $self->_get_taxcharts($dbh, $params{"taxcharts"});
1891   }
1892
1893   if ($params{"taxzones"}) {
1894     $self->_get_taxzones($dbh, $params{"taxzones"});
1895   }
1896
1897   if ($params{"employees"}) {
1898     $self->_get_employees($dbh, "all_employees", $params{"employees"});
1899   }
1900   
1901   if ($params{"salesmen"}) {
1902     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
1903   }
1904
1905   if ($params{"business_types"}) {
1906     $self->_get_business_types($dbh, $params{"business_types"});
1907   }
1908
1909   if ($params{"dunning_configs"}) {
1910     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
1911   }
1912   
1913   if($params{"currencies"}) {
1914     $self->_get_currencies($dbh, $params{"currencies"});
1915   }
1916   
1917   if($params{"customers"}) {
1918     $self->_get_customers($dbh, $params{"customers"});
1919   }
1920   
1921   if($params{"vendors"}) {
1922     $self->_get_vendors($dbh, $params{"vendors"});
1923   }
1924   
1925   if($params{"payments"}) {
1926     $self->_get_payments($dbh, $params{"payments"});
1927   }
1928
1929   if($params{"departments"}) {
1930     $self->_get_departments($dbh, $params{"departments"});
1931   }
1932
1933   $main::lxdebug->leave_sub();
1934 }
1935
1936 # this sub gets the id and name from $table
1937 sub get_name {
1938   $main::lxdebug->enter_sub();
1939
1940   my ($self, $myconfig, $table) = @_;
1941
1942   # connect to database
1943   my $dbh = $self->get_standard_dbh($myconfig);
1944
1945   $table = $table eq "customer" ? "customer" : "vendor";
1946   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
1947
1948   my ($query, @values);
1949
1950   if (!$self->{openinvoices}) {
1951     my $where;
1952     if ($self->{customernumber} ne "") {
1953       $where = qq|(vc.customernumber ILIKE ?)|;
1954       push(@values, '%' . $self->{customernumber} . '%');
1955     } else {
1956       $where = qq|(vc.name ILIKE ?)|;
1957       push(@values, '%' . $self->{$table} . '%');
1958     }
1959
1960     $query =
1961       qq~SELECT vc.id, vc.name,
1962            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1963          FROM $table vc
1964          WHERE $where AND (NOT vc.obsolete)
1965          ORDER BY vc.name~;
1966   } else {
1967     $query =
1968       qq~SELECT DISTINCT vc.id, vc.name,
1969            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
1970          FROM $arap a
1971          JOIN $table vc ON (a.${table}_id = vc.id)
1972          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
1973          ORDER BY vc.name~;
1974     push(@values, '%' . $self->{$table} . '%');
1975   }
1976
1977   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
1978
1979   $main::lxdebug->leave_sub();
1980
1981   return scalar(@{ $self->{name_list} });
1982 }
1983
1984 # the selection sub is used in the AR, AP, IS, IR and OE module
1985 #
1986 sub all_vc {
1987   $main::lxdebug->enter_sub();
1988
1989   my ($self, $myconfig, $table, $module) = @_;
1990
1991   my $ref;
1992   my $dbh = $self->get_standard_dbh($myconfig);
1993
1994   $table = $table eq "customer" ? "customer" : "vendor";
1995
1996   my $query = qq|SELECT count(*) FROM $table|;
1997   my ($count) = selectrow_query($self, $dbh, $query);
1998
1999   # build selection list
2000   if ($count < $myconfig->{vclimit}) {
2001     $query = qq|SELECT id, name, salesman_id
2002                 FROM $table WHERE NOT obsolete
2003                 ORDER BY name|;
2004     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2005   }
2006
2007   # get self
2008   $self->get_employee($dbh);
2009
2010   # setup sales contacts
2011   $query = qq|SELECT e.id, e.name
2012               FROM employee e
2013               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2014   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2015
2016   # this is for self
2017   push(@{ $self->{all_employees} },
2018        { id   => $self->{employee_id},
2019          name => $self->{employee} });
2020
2021   # sort the whole thing
2022   @{ $self->{all_employees} } =
2023     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2024
2025   if ($module eq 'AR') {
2026
2027     # prepare query for departments
2028     $query = qq|SELECT id, description
2029                 FROM department
2030                 WHERE role = 'P'
2031                 ORDER BY description|;
2032
2033   } else {
2034     $query = qq|SELECT id, description
2035                 FROM department
2036                 ORDER BY description|;
2037   }
2038
2039   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2040
2041   # get languages
2042   $query = qq|SELECT id, description
2043               FROM language
2044               ORDER BY id|;
2045
2046   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2047
2048   # get printer
2049   $query = qq|SELECT printer_description, id
2050               FROM printers
2051               ORDER BY printer_description|;
2052
2053   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2054
2055   # get payment terms
2056   $query = qq|SELECT id, description
2057               FROM payment_terms
2058               ORDER BY sortkey|;
2059
2060   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2061
2062   $main::lxdebug->leave_sub();
2063 }
2064
2065 sub language_payment {
2066   $main::lxdebug->enter_sub();
2067
2068   my ($self, $myconfig) = @_;
2069
2070   my $dbh = $self->get_standard_dbh($myconfig);
2071   # get languages
2072   my $query = qq|SELECT id, description
2073                  FROM language
2074                  ORDER BY id|;
2075
2076   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2077
2078   # get printer
2079   $query = qq|SELECT printer_description, id
2080               FROM printers
2081               ORDER BY printer_description|;
2082
2083   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2084
2085   # get payment terms
2086   $query = qq|SELECT id, description
2087               FROM payment_terms
2088               ORDER BY sortkey|;
2089
2090   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2091
2092   # get buchungsgruppen
2093   $query = qq|SELECT id, description
2094               FROM buchungsgruppen|;
2095
2096   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2097
2098   $main::lxdebug->leave_sub();
2099 }
2100
2101 # this is only used for reports
2102 sub all_departments {
2103   $main::lxdebug->enter_sub();
2104
2105   my ($self, $myconfig, $table) = @_;
2106
2107   my $dbh = $self->get_standard_dbh($myconfig);
2108   my $where;
2109
2110   if ($table eq 'customer') {
2111     $where = "WHERE role = 'P' ";
2112   }
2113
2114   my $query = qq|SELECT id, description
2115                  FROM department
2116                  $where
2117                  ORDER BY description|;
2118   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2119
2120   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2121
2122   $main::lxdebug->leave_sub();
2123 }
2124
2125 sub create_links {
2126   $main::lxdebug->enter_sub();
2127
2128   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2129
2130   my ($fld, $arap);
2131   if ($table eq "customer") {
2132     $fld = "buy";
2133     $arap = "ar";
2134   } else {
2135     $table = "vendor";
2136     $fld = "sell";
2137     $arap = "ap";
2138   }
2139
2140   $self->all_vc($myconfig, $table, $module);
2141
2142   # get last customers or vendors
2143   my ($query, $sth, $ref);
2144
2145   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2146   my %xkeyref = ();
2147
2148   if (!$self->{id}) {
2149
2150     my $transdate = "current_date";
2151     if ($self->{transdate}) {
2152       $transdate = $dbh->quote($self->{transdate});
2153     }
2154
2155     # now get the account numbers
2156     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2157                 FROM chart c, taxkeys tk
2158                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2159                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2160                 ORDER BY c.accno|;
2161
2162     $sth = $dbh->prepare($query);
2163
2164     do_statement($self, $sth, $query, '%' . $module . '%');
2165
2166     $self->{accounts} = "";
2167     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2168
2169       foreach my $key (split(/:/, $ref->{link})) {
2170         if ($key =~ /$module/) {
2171
2172           # cross reference for keys
2173           $xkeyref{ $ref->{accno} } = $key;
2174
2175           push @{ $self->{"${module}_links"}{$key} },
2176             { accno       => $ref->{accno},
2177               description => $ref->{description},
2178               taxkey      => $ref->{taxkey_id},
2179               tax_id      => $ref->{tax_id} };
2180
2181           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2182         }
2183       }
2184     }
2185   }
2186
2187   # get taxkeys and description
2188   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2189   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2190
2191   if (($module eq "AP") || ($module eq "AR")) {
2192     # get tax rates and description
2193     $query = qq|SELECT * FROM tax|;
2194     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2195   }
2196
2197   if ($self->{id}) {
2198     $query =
2199       qq|SELECT
2200            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2201            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2202            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2203            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2204            c.name AS $table,
2205            d.description AS department,
2206            e.name AS employee
2207          FROM $arap a
2208          JOIN $table c ON (a.${table}_id = c.id)
2209          LEFT JOIN employee e ON (e.id = a.employee_id)
2210          LEFT JOIN department d ON (d.id = a.department_id)
2211          WHERE a.id = ?|;
2212     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2213
2214     foreach $key (keys %$ref) {
2215       $self->{$key} = $ref->{$key};
2216     }
2217
2218     my $transdate = "current_date";
2219     if ($self->{transdate}) {
2220       $transdate = $dbh->quote($self->{transdate});
2221     }
2222
2223     # now get the account numbers
2224     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2225                 FROM chart c
2226                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2227                 WHERE c.link LIKE ?
2228                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2229                     OR c.link LIKE '%_tax%')
2230                 ORDER BY c.accno|;
2231
2232     $sth = $dbh->prepare($query);
2233     do_statement($self, $sth, $query, "%$module%");
2234
2235     $self->{accounts} = "";
2236     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2237
2238       foreach my $key (split(/:/, $ref->{link})) {
2239         if ($key =~ /$module/) {
2240
2241           # cross reference for keys
2242           $xkeyref{ $ref->{accno} } = $key;
2243
2244           push @{ $self->{"${module}_links"}{$key} },
2245             { accno       => $ref->{accno},
2246               description => $ref->{description},
2247               taxkey      => $ref->{taxkey_id},
2248               tax_id      => $ref->{tax_id} };
2249
2250           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2251         }
2252       }
2253     }
2254
2255
2256     # get amounts from individual entries
2257     $query =
2258       qq|SELECT
2259            c.accno, c.description,
2260            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2261            p.projectnumber,
2262            t.rate, t.id
2263          FROM acc_trans a
2264          LEFT JOIN chart c ON (c.id = a.chart_id)
2265          LEFT JOIN project p ON (p.id = a.project_id)
2266          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2267                                     WHERE (tk.taxkey_id=a.taxkey) AND
2268                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2269                                         THEN tk.chart_id = a.chart_id
2270                                         ELSE 1 = 1
2271                                         END)
2272                                        OR (c.link='%tax%')) AND
2273                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2274          WHERE a.trans_id = ?
2275          AND a.fx_transaction = '0'
2276          ORDER BY a.oid, a.transdate|;
2277     $sth = $dbh->prepare($query);
2278     do_statement($self, $sth, $query, $self->{id});
2279
2280     # get exchangerate for currency
2281     $self->{exchangerate} =
2282       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2283     my $index = 0;
2284
2285     # store amounts in {acc_trans}{$key} for multiple accounts
2286     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2287       $ref->{exchangerate} =
2288         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2289       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2290         $index++;
2291       }
2292       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2293         $ref->{amount} *= -1;
2294       }
2295       $ref->{index} = $index;
2296
2297       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2298     }
2299
2300     $sth->finish;
2301     $query =
2302       qq|SELECT
2303            d.curr AS currencies, d.closedto, d.revtrans,
2304            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2305            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2306          FROM defaults d|;
2307     $ref = selectfirst_hashref_query($self, $dbh, $query);
2308     map { $self->{$_} = $ref->{$_} } keys %$ref;
2309
2310   } else {
2311
2312     # get date
2313     $query =
2314        qq|SELECT
2315             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2316             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2317             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2318           FROM defaults d|;
2319     $ref = selectfirst_hashref_query($self, $dbh, $query);
2320     map { $self->{$_} = $ref->{$_} } keys %$ref;
2321
2322     if ($self->{"$self->{vc}_id"}) {
2323
2324       # only setup currency
2325       ($self->{currency}) = split(/:/, $self->{currencies});
2326
2327     } else {
2328
2329       $self->lastname_used($dbh, $myconfig, $table, $module);
2330
2331       # get exchangerate for currency
2332       $self->{exchangerate} =
2333         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2334
2335     }
2336
2337   }
2338
2339   $main::lxdebug->leave_sub();
2340 }
2341
2342 sub lastname_used {
2343   $main::lxdebug->enter_sub();
2344
2345   my ($self, $dbh, $myconfig, $table, $module) = @_;
2346
2347   my $arap  = ($table eq 'customer') ? "ar" : "ap";
2348   $table = $table eq "customer" ? "customer" : "vendor";
2349   my $where = "1 = 1";
2350
2351   if ($self->{type} =~ /_order/) {
2352     $arap  = 'oe';
2353     $where = "quotation = '0'";
2354   }
2355   if ($self->{type} =~ /_quotation/) {
2356     $arap  = 'oe';
2357     $where = "quotation = '1'";
2358   }
2359
2360   my $query = qq|SELECT MAX(id) FROM $arap
2361                  WHERE $where AND ${table}_id > 0|;
2362   my ($trans_id) = selectrow_query($self, $dbh, $query);
2363
2364   $trans_id *= 1;
2365   $query =
2366     qq|SELECT
2367          a.curr, a.${table}_id, a.department_id,
2368          d.description AS department,
2369          ct.name, current_date + ct.terms AS duedate
2370        FROM $arap a
2371        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2372        LEFT JOIN department d ON (a.department_id = d.id)
2373        WHERE a.id = ?|;
2374   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
2375    $self->{department}, $self->{$table},        $self->{duedate})
2376     = selectrow_query($self, $dbh, $query, $trans_id);
2377
2378   $main::lxdebug->leave_sub();
2379 }
2380
2381 sub current_date {
2382   $main::lxdebug->enter_sub();
2383
2384   my ($self, $myconfig, $thisdate, $days) = @_;
2385
2386   my $dbh = $self->get_standard_dbh($myconfig);
2387   my $query;
2388
2389   $days *= 1;
2390   if ($thisdate) {
2391     my $dateformat = $myconfig->{dateformat};
2392     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2393     $thisdate = $dbh->quote($thisdate);
2394     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2395   } else {
2396     $query = qq|SELECT current_date AS thisdate|;
2397   }
2398
2399   ($thisdate) = selectrow_query($self, $dbh, $query);
2400
2401   $main::lxdebug->leave_sub();
2402
2403   return $thisdate;
2404 }
2405
2406 sub like {
2407   $main::lxdebug->enter_sub();
2408
2409   my ($self, $string) = @_;
2410
2411   if ($string !~ /%/) {
2412     $string = "%$string%";
2413   }
2414
2415   $string =~ s/\'/\'\'/g;
2416
2417   $main::lxdebug->leave_sub();
2418
2419   return $string;
2420 }
2421
2422 sub redo_rows {
2423   $main::lxdebug->enter_sub();
2424
2425   my ($self, $flds, $new, $count, $numrows) = @_;
2426
2427   my @ndx = ();
2428
2429   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
2430     (1 .. $count);
2431
2432   my $i = 0;
2433
2434   # fill rows
2435   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2436     $i++;
2437     $j = $item->{ndx} - 1;
2438     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2439   }
2440
2441   # delete empty rows
2442   for $i ($count + 1 .. $numrows) {
2443     map { delete $self->{"${_}_$i"} } @{$flds};
2444   }
2445
2446   $main::lxdebug->leave_sub();
2447 }
2448
2449 sub update_status {
2450   $main::lxdebug->enter_sub();
2451
2452   my ($self, $myconfig) = @_;
2453
2454   my ($i, $id);
2455
2456   my $dbh = $self->dbconnect_noauto($myconfig);
2457
2458   my $query = qq|DELETE FROM status
2459                  WHERE (formname = ?) AND (trans_id = ?)|;
2460   my $sth = prepare_query($self, $dbh, $query);
2461
2462   if ($self->{formname} =~ /(check|receipt)/) {
2463     for $i (1 .. $self->{rowcount}) {
2464       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2465     }
2466   } else {
2467     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2468   }
2469   $sth->finish();
2470
2471   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2472   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2473
2474   my %queued = split / /, $self->{queued};
2475   my @values;
2476
2477   if ($self->{formname} =~ /(check|receipt)/) {
2478
2479     # this is a check or receipt, add one entry for each lineitem
2480     my ($accno) = split /--/, $self->{account};
2481     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2482                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2483     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2484     $sth = prepare_query($self, $dbh, $query);
2485
2486     for $i (1 .. $self->{rowcount}) {
2487       if ($self->{"checked_$i"}) {
2488         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2489       }
2490     }
2491     $sth->finish();
2492
2493   } else {
2494     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2495                 VALUES (?, ?, ?, ?, ?)|;
2496     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2497              $queued{$self->{formname}}, $self->{formname});
2498   }
2499
2500   $dbh->commit;
2501   $dbh->disconnect;
2502
2503   $main::lxdebug->leave_sub();
2504 }
2505
2506 sub save_status {
2507   $main::lxdebug->enter_sub();
2508
2509   my ($self, $dbh) = @_;
2510
2511   my ($query, $printed, $emailed);
2512
2513   my $formnames  = $self->{printed};
2514   my $emailforms = $self->{emailed};
2515
2516   my $query = qq|DELETE FROM status
2517                  WHERE (formname = ?) AND (trans_id = ?)|;
2518   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2519
2520   # this only applies to the forms
2521   # checks and receipts are posted when printed or queued
2522
2523   if ($self->{queued}) {
2524     my %queued = split / /, $self->{queued};
2525
2526     foreach my $formname (keys %queued) {
2527       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2528       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2529
2530       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2531                   VALUES (?, ?, ?, ?, ?)|;
2532       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2533
2534       $formnames  =~ s/$self->{formname}//;
2535       $emailforms =~ s/$self->{formname}//;
2536
2537     }
2538   }
2539
2540   # save printed, emailed info
2541   $formnames  =~ s/^ +//g;
2542   $emailforms =~ s/^ +//g;
2543
2544   my %status = ();
2545   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2546   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2547
2548   foreach my $formname (keys %status) {
2549     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2550     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2551
2552     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2553                 VALUES (?, ?, ?, ?)|;
2554     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2555   }
2556
2557   $main::lxdebug->leave_sub();
2558 }
2559
2560 #--- 4 locale ---#
2561 # $main::locale->text('SAVED')
2562 # $main::locale->text('DELETED')
2563 # $main::locale->text('ADDED')
2564 # $main::locale->text('PAYMENT POSTED')
2565 # $main::locale->text('POSTED')
2566 # $main::locale->text('POSTED AS NEW')
2567 # $main::locale->text('ELSE')
2568 # $main::locale->text('SAVED FOR DUNNING')
2569 # $main::locale->text('DUNNING STARTED')
2570 # $main::locale->text('PRINTED')
2571 # $main::locale->text('MAILED')
2572 # $main::locale->text('SCREENED')
2573 # $main::locale->text('CANCELED')
2574 # $main::locale->text('invoice')
2575 # $main::locale->text('proforma')
2576 # $main::locale->text('sales_order')
2577 # $main::locale->text('packing_list')
2578 # $main::locale->text('pick_list')
2579 # $main::locale->text('purchase_order')
2580 # $main::locale->text('bin_list')
2581 # $main::locale->text('sales_quotation')
2582 # $main::locale->text('request_quotation')
2583
2584 sub save_history {
2585   $main::lxdebug->enter_sub();
2586
2587   my $self = shift();
2588   my $dbh = shift();
2589
2590   if(!exists $self->{employee_id}) {
2591     &get_employee($self, $dbh);
2592   }
2593
2594   my $query =
2595    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2596    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
2597   my @values = (conv_i($self->{id}), $self->{login},
2598                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
2599   do_query($self, $dbh, $query, @values);
2600
2601   $main::lxdebug->leave_sub();
2602 }
2603
2604 sub get_history {
2605   $main::lxdebug->enter_sub();
2606
2607   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
2608   my ($orderBy, $desc) = split(/\-\-/, $order);
2609   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
2610   my @tempArray;
2611   my $i = 0;
2612   if ($trans_id ne "") {
2613     my $query =
2614       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 | .
2615       qq|FROM history_erp h | .
2616       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
2617       qq|WHERE trans_id = | . $trans_id
2618       . $restriction . qq| |
2619       . $order;
2620       
2621     my $sth = $dbh->prepare($query) || $self->dberror($query);
2622
2623     $sth->execute() || $self->dberror("$query");
2624
2625     while(my $hash_ref = $sth->fetchrow_hashref()) {
2626       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
2627       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
2628       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
2629       $tempArray[$i++] = $hash_ref;
2630     }
2631     $main::lxdebug->leave_sub() and return \@tempArray 
2632       if ($i > 0 && $tempArray[0] ne "");
2633   }
2634   $main::lxdebug->leave_sub();
2635   return 0;
2636 }
2637
2638 sub update_defaults {
2639   $main::lxdebug->enter_sub();
2640
2641   my ($self, $myconfig, $fld, $provided_dbh) = @_;
2642
2643   my $dbh;
2644   if ($provided_dbh) {
2645     $dbh = $provided_dbh;
2646   } else {
2647     $dbh = $self->dbconnect_noauto($myconfig);
2648   }
2649   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2650   my $sth   = $dbh->prepare($query);
2651
2652   $sth->execute || $self->dberror($query);
2653   my ($var) = $sth->fetchrow_array;
2654   $sth->finish;
2655
2656   if ($var =~ m/\d+$/) {
2657     my $new_var  = (substr $var, $-[0]) * 1 + 1;
2658     my $len_diff = length($var) - $-[0] - length($new_var);
2659     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
2660
2661   } else {
2662     $var = $var . '1';
2663   }
2664
2665   $query = qq|UPDATE defaults SET $fld = ?|;
2666   do_query($self, $dbh, $query, $var);
2667
2668   if (!$provided_dbh) {
2669     $dbh->commit;
2670     $dbh->disconnect;
2671   }
2672
2673   $main::lxdebug->leave_sub();
2674
2675   return $var;
2676 }
2677
2678 sub update_business {
2679   $main::lxdebug->enter_sub();
2680
2681   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
2682
2683   my $dbh;
2684   if ($provided_dbh) {
2685     $dbh = $provided_dbh;
2686   } else {
2687     $dbh = $self->dbconnect_noauto($myconfig);
2688   }
2689   my $query =
2690     qq|SELECT customernumberinit FROM business
2691        WHERE id = ? FOR UPDATE|;
2692   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
2693
2694   if ($var =~ m/\d+$/) {
2695     my $new_var  = (substr $var, $-[0]) * 1 + 1;
2696     my $len_diff = length($var) - $-[0] - length($new_var);
2697     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
2698
2699   } else {
2700     $var = $var . '1';
2701   }
2702
2703   $query = qq|UPDATE business
2704               SET customernumberinit = ?
2705               WHERE id = ?|;
2706   do_query($self, $dbh, $query, $var, $business_id);
2707
2708   if (!$provided_dbh) {
2709     $dbh->commit;
2710     $dbh->disconnect;
2711   }
2712
2713   $main::lxdebug->leave_sub();
2714
2715   return $var;
2716 }
2717
2718 sub get_partsgroup {
2719   $main::lxdebug->enter_sub();
2720
2721   my ($self, $myconfig, $p) = @_;
2722
2723   my $dbh = $self->get_standard_dbh($myconfig);
2724
2725   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2726                  FROM partsgroup pg
2727                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
2728   my @values;
2729
2730   if ($p->{searchitems} eq 'part') {
2731     $query .= qq|WHERE p.inventory_accno_id > 0|;
2732   }
2733   if ($p->{searchitems} eq 'service') {
2734     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
2735   }
2736   if ($p->{searchitems} eq 'assembly') {
2737     $query .= qq|WHERE p.assembly = '1'|;
2738   }
2739   if ($p->{searchitems} eq 'labor') {
2740     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
2741   }
2742
2743   $query .= qq|ORDER BY partsgroup|;
2744
2745   if ($p->{all}) {
2746     $query = qq|SELECT id, partsgroup FROM partsgroup
2747                 ORDER BY partsgroup|;
2748   }
2749
2750   if ($p->{language_code}) {
2751     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2752                   t.description AS translation
2753                 FROM partsgroup pg
2754                 JOIN parts p ON (p.partsgroup_id = pg.id)
2755                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
2756                 ORDER BY translation|;
2757     @values = ($p->{language_code});
2758   }
2759
2760   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
2761
2762   $main::lxdebug->leave_sub();
2763 }
2764
2765 sub get_pricegroup {
2766   $main::lxdebug->enter_sub();
2767
2768   my ($self, $myconfig, $p) = @_;
2769
2770   my $dbh = $self->get_standard_dbh($myconfig);
2771
2772   my $query = qq|SELECT p.id, p.pricegroup
2773                  FROM pricegroup p|;
2774
2775   $query .= qq| ORDER BY pricegroup|;
2776
2777   if ($p->{all}) {
2778     $query = qq|SELECT id, pricegroup FROM pricegroup
2779                 ORDER BY pricegroup|;
2780   }
2781
2782   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
2783
2784   $main::lxdebug->leave_sub();
2785 }
2786
2787 sub all_years {
2788 # usage $form->all_years($myconfig, [$dbh])
2789 # return list of all years where bookings found
2790 # (@all_years)
2791
2792   $main::lxdebug->enter_sub();
2793
2794   my ($self, $myconfig, $dbh) = @_;
2795
2796   $dbh ||= $self->get_standard_dbh($myconfig);
2797
2798   # get years
2799   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
2800                    (SELECT MAX(transdate) FROM acc_trans)|;
2801   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
2802
2803   if ($myconfig->{dateformat} =~ /^yy/) {
2804     ($startdate) = split /\W/, $startdate;
2805     ($enddate) = split /\W/, $enddate;
2806   } else {
2807     (@_) = split /\W/, $startdate;
2808     $startdate = $_[2];
2809     (@_) = split /\W/, $enddate;
2810     $enddate = $_[2];
2811   }
2812
2813   my @all_years;
2814   $startdate = substr($startdate,0,4);
2815   $enddate = substr($enddate,0,4);
2816
2817   while ($enddate >= $startdate) {
2818     push @all_years, $enddate--;
2819   }
2820
2821   return @all_years;
2822
2823   $main::lxdebug->leave_sub();
2824 }
2825
2826 1;