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