Alle Dateien durch Perltidy laufen lassen. Die verwendeten Optionen sind am Ende...
[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
40 sub _input_to_hash {
41   $main::lxdebug->enter_sub();
42
43   my $input = $_[0];
44   my %in    = ();
45   my @pairs = split(/&/, $input);
46
47   foreach (@pairs) {
48     my ($name, $value) = split(/=/, $_, 2);
49     $in{$name} = unescape(undef, $value);
50   }
51
52   $main::lxdebug->leave_sub();
53
54   return %in;
55 }
56
57 sub _request_to_hash {
58   $main::lxdebug->enter_sub();
59
60   my ($input) = @_;
61   my ($i,        $loc,  $key,    $val);
62   my (%ATTACH,   $f,    $header, $header_body, $len, $buf);
63   my ($boundary, @list, $size,   $body, $x, $blah, $name);
64
65   if ($ENV{'CONTENT_TYPE'}
66       && ($ENV{'CONTENT_TYPE'} =~ /multipart\/form-data; boundary=(.+)$/)) {
67     $boundary = quotemeta('--' . $1);
68     @list     = split(/$boundary/, $input);
69
70     # For some reason there are always 2 extra, that are empty
71     $size = @list - 2;
72
73     for ($x = 1; $x <= $size; $x++) {
74       $header_body = $list[$x];
75       $header_body =~ /\r\n\r\n|\n\n/;
76
77       # Here we split the header and body
78       $header = $`;
79       $body   = $';    #'
80       $body =~ s/\r\n$//;
81
82       # Now we try to get the file name
83       $name = $header;
84       $name =~ /name=\"(.+)\"/;
85       ($name, $blah) = split(/\"/, $1);
86
87       # If the form name is not attach, then we need to parse this like
88       # regular form data
89       if ($name ne "attach") {
90         $body =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
91         $ATTACH{$name} = $body;
92
93         # Otherwise it is an attachment and we need to finish it up
94       } elsif ($name eq "attach") {
95         $header =~ /filename=\"(.+)\"/;
96         $ATTACH{'FILE_NAME'} = $1;
97         $ATTACH{'FILE_NAME'} =~ s/\"//g;
98         $ATTACH{'FILE_NAME'} =~ s/\s//g;
99         $ATTACH{'FILE_CONTENT'} = $body;
100
101         for ($i = $x; $list[$i]; $i++) {
102           $list[$i] =~ s/^.+name=$//;
103           $list[$i] =~ /\"(\w+)\"/;
104           $ATTACH{$1} = $';    #'
105         }
106       }
107     }
108
109     $main::lxdebug->leave_sub();
110     return %ATTACH;
111
112       } else {
113     $main::lxdebug->leave_sub();
114     return _input_to_hash($input);
115   }
116 }
117
118 sub new {
119   $main::lxdebug->enter_sub();
120
121   my $type = shift;
122
123   my $self = {};
124
125   read(STDIN, $_, $ENV{CONTENT_LENGTH});
126
127   if ($ENV{QUERY_STRING}) {
128     $_ = $ENV{QUERY_STRING};
129   }
130
131   if ($ARGV[0]) {
132     $_ = $ARGV[0];
133   }
134
135   my %parameters = _request_to_hash($_);
136   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
137
138   $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
139
140   $self->{action} = lc $self->{action};
141   $self->{action} =~ s/( |-|,|#)/_/g;
142
143   $self->{version}   = "2.1.2";
144   $self->{dbversion} = "2.1.2";
145
146   $main::lxdebug->leave_sub();
147
148   bless $self, $type;
149 }
150
151 sub debug {
152   $main::lxdebug->enter_sub();
153
154   my ($self) = @_;
155
156   print "\n";
157
158   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
159
160   $main::lxdebug->leave_sub();
161 }
162
163 sub escape {
164   $main::lxdebug->enter_sub();
165
166   my ($self, $str, $beenthere) = @_;
167
168   # for Apache 2 we escape strings twice
169   #if (($ENV{SERVER_SOFTWARE} =~ /Apache\/2/) && !$beenthere) {
170   #  $str = $self->escape($str, 1);
171   #}
172
173   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
174
175   $main::lxdebug->leave_sub();
176
177   return $str;
178 }
179
180 sub unescape {
181   $main::lxdebug->enter_sub();
182
183   my ($self, $str) = @_;
184
185   $str =~ tr/+/ /;
186   $str =~ s/\\$//;
187
188   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
189
190   $main::lxdebug->leave_sub();
191
192   return $str;
193 }
194
195 sub error {
196   $main::lxdebug->enter_sub();
197
198   my ($self, $msg) = @_;
199
200   if ($ENV{HTTP_USER_AGENT}) {
201     $msg =~ s/\n/<br>/g;
202
203     $self->header;
204
205     print qq|
206     <body>
207
208     <h2 class=error>Error!</h2>
209
210     <p><b>$msg</b>
211
212     </body>
213     </html>
214     |;
215
216     die "Error: $msg\n";
217
218   } else {
219
220     if ($self->{error_function}) {
221       &{ $self->{error_function} }($msg);
222     } else {
223       die "Error: $msg\n";
224     }
225   }
226
227   $main::lxdebug->leave_sub();
228 }
229
230 sub info {
231   $main::lxdebug->enter_sub();
232
233   my ($self, $msg) = @_;
234
235   if ($ENV{HTTP_USER_AGENT}) {
236     $msg =~ s/\n/<br>/g;
237
238     if (!$self->{header}) {
239       $self->header;
240       print qq|
241       <body>|;
242     }
243
244     print qq|
245
246     <p><b>$msg</b>
247     |;
248
249   } else {
250
251     if ($self->{info_function}) {
252       &{ $self->{info_function} }($msg);
253     } else {
254       print "$msg\n";
255     }
256   }
257
258   $main::lxdebug->leave_sub();
259 }
260
261 sub numtextrows {
262   $main::lxdebug->enter_sub();
263
264   my ($self, $str, $cols, $maxrows) = @_;
265
266   my $rows = 0;
267
268   map { $rows += int(((length) - 2) / $cols) + 1 } split /\r/, $str;
269
270   $maxrows = $rows unless defined $maxrows;
271
272   $main::lxdebug->leave_sub();
273
274   return ($rows > $maxrows) ? $maxrows : $rows;
275 }
276
277 sub dberror {
278   $main::lxdebug->enter_sub();
279
280   my ($self, $msg) = @_;
281
282   $self->error("$msg\n" . $DBI::errstr);
283
284   $main::lxdebug->leave_sub();
285 }
286
287 sub isblank {
288   $main::lxdebug->enter_sub();
289
290   my ($self, $name, $msg) = @_;
291
292   if ($self->{$name} =~ /^\s*$/) {
293     $self->error($msg);
294   }
295   $main::lxdebug->leave_sub();
296 }
297
298 sub header {
299   $main::lxdebug->enter_sub();
300
301   my ($self) = @_;
302
303   if ($self->{header}) {
304     $main::lxdebug->leave_sub();
305     return;
306   }
307
308   my ($stylesheet, $favicon, $charset);
309
310   if ($ENV{HTTP_USER_AGENT}) {
311
312     if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
313       $stylesheet =
314         qq|<LINK REL="stylesheet" HREF="css/$self->{stylesheet}" TYPE="text/css" TITLE="Lx-Office stylesheet">
315  |;
316     }
317
318     if ($self->{favicon} && (-f "$self->{favicon}")) {
319       $favicon =
320         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
321   |;
322     }
323
324     if ($self->{charset}) {
325       $charset =
326         qq|<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=$self->{charset}">
327   |;
328     }
329     if ($self->{landscape}) {
330       $pagelayout = qq|<style type="text/css">
331                         \@page { size:landscape; }
332                         </style>|;
333     }
334     if ($self->{fokus}) {
335       $fokus = qq|<script type="text/javascript">
336 <!--
337 function fokus(){document.$self->{fokus}.focus();}
338 //-->
339 </script>|;
340     }
341
342     #Set Calendar
343     $jsscript = "";
344     if ($self->{jsscript} == 1) {
345
346       $jsscript = qq|
347         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
348         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
349         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
350         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
351        |;
352     }
353
354     $self->{titlebar} =
355       ($self->{title})
356       ? "$self->{title} - $self->{titlebar}"
357       : $self->{titlebar};
358
359     print qq|Content-Type: text/html
360
361 <head>
362   <title>$self->{titlebar}</title>
363   $stylesheet
364   $pagelayout
365   $favicon
366   $charset
367   $jsscript
368   $fokus
369 </head>
370
371 |;
372   }
373   $self->{header} = 1;
374
375   $main::lxdebug->leave_sub();
376 }
377
378 # write Trigger JavaScript-Code ($qty = 1 - only one Trigger)
379 sub write_trigger {
380   $main::lxdebug->enter_sub();
381
382   my ($self,         $myconfig, $qty,
383       $inputField_1, $align_1,  $button_1,
384       $inputField_2, $align_2,  $button_2)
385     = @_;
386
387   # set dateform for jsscript
388   # default
389   $ifFormat = "%d.%m.%Y";
390   if ($myconfig->{dateformat} eq "dd.mm.yy") {
391     $ifFormat = "%d.%m.%Y";
392   } else {
393     if ($myconfig->{dateformat} eq "dd-mm-yy") {
394       $ifFormat = "%d-%m-%Y";
395     } else {
396       if ($myconfig->{dateformat} eq "dd/mm/yy") {
397         $ifFormat = "%d/%m/%Y";
398       } else {
399         if ($myconfig->{dateformat} eq "mm/dd/yy") {
400           $ifFormat = "%m/%d/%Y";
401         } else {
402           if ($myconfig->{dateformat} eq "mm-dd-yy") {
403             $ifFormat = "%m-%d-%Y";
404           } else {
405             if ($myconfig->{dateformat} eq "yyyy-mm-dd") {
406               $ifFormat = "%Y-%m-%d";
407             }
408           }
409         }
410       }
411     }
412   }
413
414   $trigger_1 = qq|
415        Calendar.setup(
416        {
417          inputField Â : "$inputField_1",
418          ifFormat Â Â Â :"$ifFormat",
419       Â Â Â align Â Â Â : "$align_1", Â Â Â Â 
420          button Â Â Â Â Â : "$button_1"
421        }
422        );
423        |;
424
425   if ($qty == 2) {
426     $trigger_2 = qq|
427        Calendar.setup(
428        {
429   Â Â Â     inputField Â : "$inputField_2",
430     Â     ifFormat Â Â Â :"$ifFormat",
431          align Â Â Â : "$align_2", Â Â Â Â 
432          button Â Â Â Â Â : "$button_2"
433        }
434        );
435         |;
436   }
437   $jsscript = qq|
438        <script type="text/javascript">
439        <!--
440        $trigger_1
441        $trigger_2
442         //-->          
443         </script>
444         |;
445
446   $main::lxdebug->leave_sub();
447
448   return $jsscript;
449 }    #end sub write_trigger
450
451 sub redirect {
452   $main::lxdebug->enter_sub();
453
454   my ($self, $msg) = @_;
455
456   if ($self->{callback}) {
457
458     ($script, $argv) = split(/\?/, $self->{callback});
459     exec("perl", "$script", $argv);
460
461   } else {
462
463     $self->info($msg);
464     exit;
465   }
466
467   $main::lxdebug->leave_sub();
468 }
469
470 # sort of columns removed - empty sub
471 sub sort_columns {
472   $main::lxdebug->enter_sub();
473
474   my ($self, @columns) = @_;
475
476   $main::lxdebug->leave_sub();
477
478   return @columns;
479 }
480
481 sub format_amount {
482   $main::lxdebug->enter_sub();
483
484   my ($self, $myconfig, $amount, $places, $dash) = @_;
485
486   if ($places =~ /\d/) {
487     $amount = $self->round_amount($amount, $places);
488   }
489
490   # is the amount negative
491   my $negative = ($amount < 0);
492
493   if ($amount != 0) {
494     if ($myconfig->{numberformat} && ($myconfig->{numberformat} ne '1000.00'))
495     {
496       my ($whole, $dec) = split /\./, "$amount";
497       $whole =~ s/-//;
498       $amount = join '', reverse split //, $whole;
499
500       if ($myconfig->{numberformat} eq '1,000.00') {
501         $amount =~ s/\d{3,}?/$&,/g;
502         $amount =~ s/,$//;
503         $amount = join '', reverse split //, $amount;
504         $amount .= "\.$dec" if ($dec ne "");
505       }
506
507       if ($myconfig->{numberformat} eq '1.000,00') {
508         $amount =~ s/\d{3,}?/$&./g;
509         $amount =~ s/\.$//;
510         $amount = join '', reverse split //, $amount;
511         $amount .= ",$dec" if ($dec ne "");
512       }
513
514       if ($myconfig->{numberformat} eq '1000,00') {
515         $amount = "$whole";
516         $amount .= ",$dec" if ($dec ne "");
517       }
518
519       if ($dash =~ /-/) {
520         $amount = ($negative) ? "($amount)" : "$amount";
521       } elsif ($dash =~ /DRCR/) {
522         $amount = ($negative) ? "$amount DR" : "$amount CR";
523       } else {
524         $amount = ($negative) ? "-$amount" : "$amount";
525       }
526     }
527   } else {
528     if ($dash eq "0" && $places) {
529       if ($myconfig->{numberformat} eq '1.000,00') {
530         $amount = "0" . "," . "0" x $places;
531       } else {
532         $amount = "0" . "." . "0" x $places;
533       }
534     } else {
535       $amount = ($dash ne "") ? "$dash" : "0";
536     }
537   }
538
539   $main::lxdebug->leave_sub();
540
541   return $amount;
542 }
543
544 sub parse_amount {
545   $main::lxdebug->enter_sub();
546
547   my ($self, $myconfig, $amount) = @_;
548
549   if (!(substr($amount, -3, 1) eq ".")) {
550     if (   ($myconfig->{numberformat} eq '1.000,00')
551         || ($myconfig->{numberformat} eq '1000,00')) {
552       $amount =~ s/\.//g;
553       $amount =~ s/,/\./;
554     }
555
556     $amount =~ s/,//g;
557   }
558
559   $main::lxdebug->leave_sub();
560
561   return ($amount * 1);
562 }
563
564 sub round_amount {
565   $main::lxdebug->enter_sub();
566
567   my ($self, $amount, $places) = @_;
568   my $rc;
569
570   #  $places = 3 if $places == 2;
571
572   if (($places * 1) >= 0) {
573
574     # add 1/10^$places+3
575     $rc =
576       sprintf("%.${places}f",
577               $amount + (1 / (10**($places + 3))) * (($amount > 0) ? 1 : -1));
578   } else {
579     $places *= -1;
580     $rc =
581       sprintf("%.f", $amount / (10**$places) + (($amount > 0) ? 0.1 : -0.1)) *
582       (10**$places);
583   }
584
585   $main::lxdebug->leave_sub();
586
587   return $rc;
588 }
589
590 sub parse_template {
591   $main::lxdebug->enter_sub();
592
593   my ($self, $myconfig, $userspath) = @_;
594
595   # { Moritz Bunkus
596   # Some variables used for page breaks
597   my ($chars_per_line, $lines_on_first_page, $lines_on_second_page) =
598     (0, 0, 0);
599   my ($current_page, $current_line) = (1, 1);
600   my $pagebreak = "";
601   my $sum       = 0;
602
603   # } Moritz Bunkus
604
605   # Make sure that all *notes* (intnotes, partnotes_*, notes etc) are converted to markup correctly.
606   $self->format_string(grep(/notes/, keys(%{$self})));
607
608   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
609   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
610
611   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
612       qw(email tel fax name signature));
613
614   open(IN, "$self->{templates}/$self->{IN}")
615     or $self->error("$self->{IN} : $!");
616
617   @_ = <IN>;
618   close(IN);
619
620   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
621
622   # OUT is used for the media, screen, printer, email
623   # for postscript we store a copy in a temporary file
624   my $fileid = time;
625   $self->{tmpfile} = "$userspath/${fileid}.$self->{IN}";
626   if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
627     $out = $self->{OUT};
628     $self->{OUT} = ">$self->{tmpfile}";
629   }
630
631   if ($self->{OUT}) {
632     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
633   } else {
634     open(OUT, ">-") or $self->error("STDOUT : $!");
635     $self->header;
636   }
637
638   # Do we have to run LaTeX two times? This is needed if
639   # the template contains page references.
640   $two_passes = 0;
641
642   # first we generate a tmpfile
643   # read file and replace <%variable%>
644   while ($_ = shift) {
645
646     $par = "";
647     $var = $_;
648
649     $two_passes = 1 if (/\\pageref/);
650
651     # { Moritz Bunkus
652     # detect pagebreak block and its parameters
653     if (/\s*<%pagebreak ([0-9]+) ([0-9]+) ([0-9]+)%>/) {
654       $chars_per_line       = $1;
655       $lines_on_first_page  = $2;
656       $lines_on_second_page = $3;
657
658       while ($_ = shift) {
659         last if (/\s*<%end pagebreak%>/);
660         $pagebreak .= $_;
661       }
662     }
663
664     # } Moritz Bunkus
665
666     if (/\s*<%foreach /) {
667
668       # this one we need for the count
669       chomp $var;
670       $var =~ s/\s*<%foreach (.+?)%>/$1/;
671       while ($_ = shift) {
672         last if (/\s*<%end /);
673
674         # store line in $par
675         $par .= $_;
676       }
677
678       # display contents of $self->{number}[] array
679       for $i (0 .. $#{ $self->{$var} }) {
680
681         # { Moritz Bunkus
682         # Try to detect whether a manual page break is necessary
683         # but only if there was a <%pagebreak ...%> block before
684
685         if ($chars_per_line) {
686           my $lines =
687             int(length($self->{"description"}[$i]) / $chars_per_line + 0.95);
688           my $lpp;
689
690           my $_description = $self->{"description"}[$i];
691           while ($_description =~ /\\newline/) {
692             $lines++;
693             $_description =~ s/\\newline//;
694           }
695           $self->{"description"}[$i] =~ s/(\\newline\s?)*$//;
696
697           if ($current_page == 1) {
698             $lpp = $lines_on_first_page;
699           } else {
700             $lpp = $lines_on_second_page;
701           }
702
703           # Yes we need a manual page break
704           if (($current_line + $lines) > $lpp) {
705             my $pb = $pagebreak;
706
707             # replace the special variables <%sumcarriedforward%>
708             # and <%lastpage%>
709
710             my $psum = $self->format_amount($myconfig, $sum, 2);
711             $pb =~ s/<%sumcarriedforward%>/$psum/g;
712             $pb =~ s/<%lastpage%>/$current_page/g;
713
714             # only "normal" variables are supported here
715             # (no <%if, no <%foreach, no <%include)
716
717             $pb =~ s/<%(.+?)%>/$self->{$1}/g;
718
719             # page break block is ready to rock
720             print(OUT $pb);
721             $current_page++;
722             $current_line = 1;
723           }
724           $current_line += $lines;
725         }
726         $sum += $self->parse_amount($myconfig, $self->{"linetotal"}[$i]);
727
728         # } Moritz Bunkus
729
730         # don't parse par, we need it for each line
731         $_ = $par;
732         s/<%(.+?)%>/$self->{$1}[$i]/mg;
733         print OUT;
734       }
735       next;
736     }
737
738     # if not comes before if!
739     if (/\s*<%if not /) {
740
741       # check if it is not set and display
742       chop;
743       s/\s*<%if not (.+?)%>/$1/;
744
745       unless ($self->{$_}) {
746         while ($_ = shift) {
747           last if (/\s*<%end /);
748
749           # store line in $par
750           $par .= $_;
751         }
752
753         $_ = $par;
754
755       } else {
756         while ($_ = shift) {
757           last if (/\s*<%end /);
758         }
759         next;
760       }
761     }
762
763     if (/\s*<%if /) {
764
765       # check if it is set and display
766       chop;
767       s/\s*<%if (.+?)%>/$1/;
768
769       if ($self->{$_}) {
770         while ($_ = shift) {
771           last if (/\s*<%end /);
772
773           # store line in $par
774           $par .= $_;
775         }
776
777         $_ = $par;
778
779       } else {
780         while ($_ = shift) {
781           last if (/\s*<%end /);
782         }
783         next;
784       }
785     }
786
787     # check for <%include filename%>
788     if (/\s*<%include /) {
789
790       # get the filename
791       chomp $var;
792       $var =~ s/\s*<%include (.+?)%>/$1/;
793
794       # mangle filename
795       $var =~ s/(\/|\.\.)//g;
796
797       # prevent the infinite loop!
798       next if ($self->{"$var"});
799
800       open(INC, "$self->{templates}/$var")
801         or $self->error($self->cleanup . "$self->{templates}/$var : $!");
802       unshift(@_, <INC>);
803       close(INC);
804
805       $self->{"$var"} = 1;
806
807       next;
808     }
809
810     s/<%(.+?)%>/$self->{$1}/g;
811     print OUT;
812   }
813
814   close(OUT);
815
816   # { Moritz Bunkus
817   # Convert the tex file to postscript
818   if ($self->{format} =~ /(postscript|pdf)/) {
819
820     use Cwd;
821     $self->{cwd}    = cwd();
822     $self->{tmpdir} = "$self->{cwd}/$userspath";
823
824     chdir("$userspath") or $self->error($self->cleanup . "chdir : $!");
825
826     $self->{tmpfile} =~ s/$userspath\///g;
827
828     if ($self->{format} eq 'postscript') {
829       system(
830         "latex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
831       );
832       $self->error($self->cleanup) if ($?);
833       if ($two_passes) {
834         system(
835           "latex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
836         );
837         $self->error($self->cleanup) if ($?);
838       }
839
840       $self->{tmpfile} =~ s/tex$/dvi/;
841
842       system("dvips $self->{tmpfile} -o -q > /dev/null");
843       $self->error($self->cleanup . "dvips : $!") if ($?);
844       $self->{tmpfile} =~ s/dvi$/ps/;
845     }
846     if ($self->{format} eq 'pdf') {
847       system(
848         "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
849       );
850       $self->error($self->cleanup) if ($?);
851       if ($two_passes) {
852         system(
853           "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
854         );
855         $self->error($self->cleanup) if ($?);
856       }
857       $self->{tmpfile} =~ s/tex$/pdf/;
858     }
859
860   }
861
862   if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
863
864     if ($self->{media} eq 'email') {
865
866       use SL::Mailer;
867
868       my $mail = new Mailer;
869
870       map { $mail->{$_} = $self->{$_} }
871         qw(cc bcc subject message version format charset);
872       $mail->{to}     = qq|$self->{email}|;
873       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
874       $mail->{fileid} = "$fileid.";
875
876       # if we send html or plain text inline
877       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
878         $mail->{contenttype} = "text/html";
879
880         $mail->{message}       =~ s/\r\n/<br>\n/g;
881         $myconfig->{signature} =~ s/\\n/<br>\n/g;
882         $mail->{message} .= "<br>\n--<br>\n$myconfig->{signature}\n<br>";
883
884         open(IN, $self->{tmpfile})
885           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
886         while (<IN>) {
887           $mail->{message} .= $_;
888         }
889
890         close(IN);
891
892       } else {
893
894         @{ $mail->{attachments} } = ($self->{tmpfile});
895
896         $myconfig->{signature} =~ s/\\n/\r\n/g;
897         $mail->{message} .= "\r\n--\r\n$myconfig->{signature}";
898
899       }
900
901       my $err = $mail->send($out);
902       $self->error($self->cleanup . "$err") if ($err);
903
904     } else {
905
906       $self->{OUT} = $out;
907
908       my $numbytes = (-s $self->{tmpfile});
909       open(IN, $self->{tmpfile})
910         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
911
912       $self->{copies} = 1 unless $self->{media} eq 'printer';
913
914       chdir("$self->{cwd}");
915
916       for my $i (1 .. $self->{copies}) {
917         if ($self->{OUT}) {
918           open(OUT, $self->{OUT})
919             or $self->error($self->cleanup . "$self->{OUT} : $!");
920         } else {
921
922           # launch application
923           print qq|Content-Type: application/$self->{format}
924 Content-Disposition: attachment; filename="$self->{tmpfile}"
925 Content-Length: $numbytes
926
927 |;
928
929           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
930
931         }
932
933         while (<IN>) {
934           print OUT $_;
935         }
936
937         close(OUT);
938
939         seek IN, 0, 0;
940       }
941
942       close(IN);
943     }
944
945     $self->cleanup;
946
947   }
948
949   chdir("$self->{cwd}");
950   $main::lxdebug->leave_sub();
951 }
952
953 sub cleanup {
954   $main::lxdebug->enter_sub();
955
956   my $self = shift;
957
958   chdir("$self->{tmpdir}");
959
960   my @err = ();
961   if (-f "$self->{tmpfile}.err") {
962     open(FH, "$self->{tmpfile}.err");
963     @err = <FH>;
964     close(FH);
965   }
966
967   if ($self->{tmpfile}) {
968
969     # strip extension
970     $self->{tmpfile} =~ s/\.\w+$//g;
971     my $tmpfile = $self->{tmpfile};
972     unlink(<$tmpfile.*>);
973   }
974
975   chdir("$self->{cwd}");
976
977   $main::lxdebug->leave_sub();
978
979   return "@err";
980 }
981
982 sub format_string {
983   $main::lxdebug->enter_sub();
984
985   my ($self, @fields) = @_;
986   my %unique_fields;
987
988   %unique_fields = map({ $_ => 1 } @fields);
989   @fields = keys(%unique_fields);
990   my $format = $self->{format};
991   if ($self->{format} =~ /(postscript|pdf)/) {
992     $format = 'tex';
993   }
994
995   my %replace = (
996     'order' => {
997       'html' => [
998         '<', '>', quotemeta('\n'), '
999 '
1000       ],
1001       'tex' => [
1002         '&', quotemeta('\n'), '
1003 ',
1004         '"', '\$', '%', '_', '#', quotemeta('^'),
1005         '{', '}',  '<', '>', '£', "\r"
1006       ]
1007     },
1008     'html' => {
1009       '<'             => '&lt;',
1010       '>'             => '&gt;',
1011       quotemeta('\n') => '<br>',
1012       '
1013 ' => '<br>'
1014     },
1015     'tex' => {
1016       '"'             => "''",
1017       '&'             => '\&',
1018       '\$'            => '\$',
1019       '%'             => '\%',
1020       '_'             => '\_',
1021       '#'             => '\#',
1022       quotemeta('^')  => '\^\\',
1023       '{'             => '\{',
1024       '}'             => '\}',
1025       '<'             => '$<$',
1026       '>'             => '$>$',
1027       quotemeta('\n') => '\newline ',
1028       '
1029 '          => '\newline ',
1030       '£'  => '\pounds ',
1031       "\r" => ""
1032     });
1033
1034   foreach my $key (@{ $replace{order}{$format} }) {
1035     map { $self->{$_} =~ s/$key/$replace{$format}{$key}/g; } @fields;
1036   }
1037
1038   $main::lxdebug->leave_sub();
1039 }
1040
1041 sub datetonum {
1042   $main::lxdebug->enter_sub();
1043
1044   my ($self, $date, $myconfig) = @_;
1045
1046   if ($date && $date =~ /\D/) {
1047
1048     if ($myconfig->{dateformat} =~ /^yy/) {
1049       ($yy, $mm, $dd) = split /\D/, $date;
1050     }
1051     if ($myconfig->{dateformat} =~ /^mm/) {
1052       ($mm, $dd, $yy) = split /\D/, $date;
1053     }
1054     if ($myconfig->{dateformat} =~ /^dd/) {
1055       ($dd, $mm, $yy) = split /\D/, $date;
1056     }
1057
1058     $dd *= 1;
1059     $mm *= 1;
1060     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1061     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1062
1063     $dd = "0$dd" if ($dd < 10);
1064     $mm = "0$mm" if ($mm < 10);
1065
1066     $date = "$yy$mm$dd";
1067   }
1068
1069   $main::lxdebug->leave_sub();
1070
1071   return $date;
1072 }
1073
1074 # Database routines used throughout
1075
1076 sub dbconnect {
1077   $main::lxdebug->enter_sub();
1078
1079   my ($self, $myconfig) = @_;
1080
1081   # connect to database
1082   my $dbh =
1083     DBI->connect($myconfig->{dbconnect},
1084                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1085     or $self->dberror;
1086
1087   # set db options
1088   if ($myconfig->{dboptions}) {
1089     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1090   }
1091
1092   $main::lxdebug->leave_sub();
1093
1094   return $dbh;
1095 }
1096
1097 sub dbconnect_noauto {
1098   $main::lxdebug->enter_sub();
1099
1100   my ($self, $myconfig) = @_;
1101
1102   # connect to database
1103   $dbh =
1104     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1105                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1106     or $self->dberror;
1107
1108   # set db options
1109   if ($myconfig->{dboptions}) {
1110     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1111   }
1112
1113   $main::lxdebug->leave_sub();
1114
1115   return $dbh;
1116 }
1117
1118 sub update_balance {
1119   $main::lxdebug->enter_sub();
1120
1121   my ($self, $dbh, $table, $field, $where, $value) = @_;
1122
1123   # if we have a value, go do it
1124   if ($value != 0) {
1125
1126     # retrieve balance from table
1127     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1128     my $sth   = $dbh->prepare($query);
1129
1130     $sth->execute || $self->dberror($query);
1131     my ($balance) = $sth->fetchrow_array;
1132     $sth->finish;
1133
1134     $balance += $value;
1135
1136     # update balance
1137     $query = "UPDATE $table SET $field = $balance WHERE $where";
1138     $dbh->do($query) || $self->dberror($query);
1139   }
1140   $main::lxdebug->leave_sub();
1141 }
1142
1143 sub update_exchangerate {
1144   $main::lxdebug->enter_sub();
1145
1146   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1147
1148   # some sanity check for currency
1149   if ($curr eq '') {
1150     $main::lxdebug->leave_sub();
1151     return;
1152   }
1153
1154   my $query = qq|SELECT e.curr FROM exchangerate e
1155                  WHERE e.curr = '$curr'
1156                  AND e.transdate = '$transdate'
1157                  FOR UPDATE|;
1158   my $sth = $dbh->prepare($query);
1159   $sth->execute || $self->dberror($query);
1160
1161   my $set;
1162   if ($buy != 0 && $sell != 0) {
1163     $set = "buy = $buy, sell = $sell";
1164   } elsif ($buy != 0) {
1165     $set = "buy = $buy";
1166   } elsif ($sell != 0) {
1167     $set = "sell = $sell";
1168   }
1169
1170   if ($sth->fetchrow_array) {
1171     $query = qq|UPDATE exchangerate
1172                 SET $set
1173                 WHERE curr = '$curr'
1174                 AND transdate = '$transdate'|;
1175   } else {
1176     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1177                 VALUES ('$curr', $buy, $sell, '$transdate')|;
1178   }
1179   $sth->finish;
1180   $dbh->do($query) || $self->dberror($query);
1181
1182   $main::lxdebug->leave_sub();
1183 }
1184
1185 sub save_exchangerate {
1186   $main::lxdebug->enter_sub();
1187
1188   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1189
1190   my $dbh = $self->dbconnect($myconfig);
1191
1192   my ($buy, $sell) = (0, 0);
1193   $buy  = $rate if $fld eq 'buy';
1194   $sell = $rate if $fld eq 'sell';
1195
1196   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1197
1198   $dbh->disconnect;
1199
1200   $main::lxdebug->leave_sub();
1201 }
1202
1203 sub get_exchangerate {
1204   $main::lxdebug->enter_sub();
1205
1206   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1207
1208   my $query = qq|SELECT e.$fld FROM exchangerate e
1209                  WHERE e.curr = '$curr'
1210                  AND e.transdate = '$transdate'|;
1211   my $sth = $dbh->prepare($query);
1212   $sth->execute || $self->dberror($query);
1213
1214   my ($exchangerate) = $sth->fetchrow_array;
1215   $sth->finish;
1216
1217   $main::lxdebug->leave_sub();
1218
1219   return $exchangerate;
1220 }
1221
1222 sub check_exchangerate {
1223   $main::lxdebug->enter_sub();
1224
1225   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1226
1227   unless ($transdate) {
1228     $main::lxdebug->leave_sub();
1229     return "";
1230   }
1231
1232   my $dbh = $self->dbconnect($myconfig);
1233
1234   my $query = qq|SELECT e.$fld FROM exchangerate e
1235                  WHERE e.curr = '$currency'
1236                  AND e.transdate = '$transdate'|;
1237   my $sth = $dbh->prepare($query);
1238   $sth->execute || $self->dberror($query);
1239
1240   my ($exchangerate) = $sth->fetchrow_array;
1241   $sth->finish;
1242   $dbh->disconnect;
1243
1244   $main::lxdebug->leave_sub();
1245
1246   return $exchangerate;
1247 }
1248
1249 sub add_shipto {
1250   $main::lxdebug->enter_sub();
1251
1252   my ($self, $dbh, $id) = @_;
1253 ##LINET
1254   my $shipto;
1255   foreach
1256     my $item (qw(name street zipcode city country contact phone fax email)) {
1257     if ($self->{"shipto$item"}) {
1258       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1259     }
1260     $self->{"shipto$item"} =~ s/\'/\'\'/g;
1261   }
1262
1263   if ($shipto) {
1264     my $query = qq|INSERT INTO shipto (trans_id, shiptoname, shiptostreet,
1265                    shiptozipcode, shiptocity, shiptocountry, shiptocontact,
1266                    shiptophone, shiptofax, shiptoemail) VALUES ($id,
1267                    '$self->{shiptoname}', '$self->{shiptostreet}',
1268                    '$self->{shiptozipcode}', '$self->{shiptocity}',
1269                    '$self->{shiptocountry}', '$self->{shiptocontact}',
1270                    '$self->{shiptophone}', '$self->{shiptofax}',
1271                    '$self->{shiptoemail}')|;
1272     $dbh->do($query) || $self->dberror($query);
1273   }
1274 ##/LINET
1275   $main::lxdebug->leave_sub();
1276 }
1277
1278 sub get_employee {
1279   $main::lxdebug->enter_sub();
1280
1281   my ($self, $dbh) = @_;
1282
1283   my $query = qq|SELECT e.id, e.name FROM employee e
1284                  WHERE e.login = '$self->{login}'|;
1285   my $sth = $dbh->prepare($query);
1286   $sth->execute || $self->dberror($query);
1287
1288   ($self->{employee_id}, $self->{employee}) = $sth->fetchrow_array;
1289   $self->{employee_id} *= 1;
1290
1291   $sth->finish;
1292
1293   $main::lxdebug->leave_sub();
1294 }
1295
1296 # get other contact for transaction and form - html/tex
1297 sub get_contact {
1298   $main::lxdebug->enter_sub();
1299
1300   my ($self, $dbh, $id) = @_;
1301
1302   my $query = qq|SELECT c.*
1303               FROM contacts c 
1304               WHERE cp_id=$id|;
1305   $sth = $dbh->prepare($query);
1306   $sth->execute || $self->dberror($query);
1307
1308   $ref = $sth->fetchrow_hashref(NAME_lc);
1309
1310   push @{ $self->{$_} }, $ref;
1311
1312   $sth->finish;
1313   $main::lxdebug->leave_sub();
1314 }
1315
1316 # get contacts for id, if no contact return {"","","","",""}
1317 sub get_contacts {
1318   $main::lxdebug->enter_sub();
1319
1320   my ($self, $dbh, $id) = @_;
1321
1322   my $query = qq|SELECT c.cp_id, c.cp_cv_id, c.cp_name, c.cp_givenname 
1323               FROM contacts c 
1324               WHERE cp_cv_id=$id|;
1325   my $sth = $dbh->prepare($query);
1326   $sth->execute || $self->dberror($query);
1327
1328   my $i = 0;
1329   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1330     push @{ $self->{all_contacts} }, $ref;
1331     $i++;
1332   }
1333
1334   if ($i == 0) {
1335     push @{ $self->{all_contacts} }, { { "", "", "", "", "" } };
1336   }
1337   $sth->finish;
1338   $main::lxdebug->leave_sub();
1339 }
1340
1341 # this sub gets the id and name from $table
1342 sub get_name {
1343   $main::lxdebug->enter_sub();
1344
1345   my ($self, $myconfig, $table) = @_;
1346
1347   # connect to database
1348   my $dbh = $self->dbconnect($myconfig);
1349
1350   my $name           = $self->like(lc $self->{$table});
1351   my $customernumber = $self->like(lc $self->{customernumber});
1352
1353   if ($self->{customernumber} ne "") {
1354     $query = qq~SELECT c.id, c.name,
1355                   c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1356                   FROM $table c
1357                   WHERE (lower(c.customernumber) LIKE '$customernumber') AND (not c.obsolete)
1358                   ORDER BY c.name~;
1359   } else {
1360     $query = qq~SELECT c.id, c.name,
1361                  c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1362                  FROM $table c
1363                  WHERE (lower(c.name) LIKE '$name') AND (not c.obsolete)
1364                  ORDER BY c.name~;
1365   }
1366
1367   if ($self->{openinvoices}) {
1368     $query = qq~SELECT DISTINCT c.id, c.name,
1369                 c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1370                 FROM $self->{arap} a
1371                 JOIN $table c ON (a.${table}_id = c.id)
1372                 WHERE NOT a.amount = a.paid
1373                 AND lower(c.name) LIKE '$name'
1374                 ORDER BY c.name~;
1375   }
1376   my $sth = $dbh->prepare($query);
1377
1378   $sth->execute || $self->dberror($query);
1379
1380   my $i = 0;
1381   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1382     push(@{ $self->{name_list} }, $ref);
1383     $i++;
1384   }
1385   $sth->finish;
1386   $dbh->disconnect;
1387
1388   $main::lxdebug->leave_sub();
1389
1390   return $i;
1391 }
1392
1393 # the selection sub is used in the AR, AP, IS, IR and OE module
1394 #
1395 sub all_vc {
1396   $main::lxdebug->enter_sub();
1397
1398   my ($self, $myconfig, $table, $module) = @_;
1399
1400   my $ref;
1401   my $dbh = $self->dbconnect($myconfig);
1402
1403   my $query = qq|SELECT count(*) FROM $table|;
1404   my $sth   = $dbh->prepare($query);
1405   $sth->execute || $self->dberror($query);
1406   my ($count) = $sth->fetchrow_array;
1407   $sth->finish;
1408
1409   # build selection list
1410   if ($count < $myconfig->{vclimit}) {
1411     $query = qq|SELECT id, name
1412                 FROM $table WHERE not obsolete
1413                 ORDER BY name|;
1414     $sth = $dbh->prepare($query);
1415     $sth->execute || $self->dberror($query);
1416
1417     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1418       push @{ $self->{"all_$table"} }, $ref;
1419     }
1420
1421     $sth->finish;
1422
1423   }
1424
1425   # get self
1426   $self->get_employee($dbh);
1427
1428   # setup sales contacts
1429   $query = qq|SELECT e.id, e.name
1430               FROM employee e
1431               WHERE e.sales = '1'
1432               AND NOT e.id = $self->{employee_id}|;
1433   $sth = $dbh->prepare($query);
1434   $sth->execute || $self->dberror($query);
1435
1436   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1437     push @{ $self->{all_employees} }, $ref;
1438   }
1439   $sth->finish;
1440
1441   # this is for self
1442   push @{ $self->{all_employees} },
1443     { id   => $self->{employee_id},
1444       name => $self->{employee} };
1445
1446   # sort the whole thing
1447   @{ $self->{all_employees} } =
1448     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
1449
1450   if ($module eq 'AR') {
1451
1452     # prepare query for departments
1453     $query = qq|SELECT d.id, d.description
1454                 FROM department d
1455                 WHERE d.role = 'P'
1456                 ORDER BY 2|;
1457
1458   } else {
1459     $query = qq|SELECT d.id, d.description
1460                 FROM department d
1461                 ORDER BY 2|;
1462   }
1463
1464   $sth = $dbh->prepare($query);
1465   $sth->execute || $self->dberror($query);
1466
1467   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1468     push @{ $self->{all_departments} }, $ref;
1469   }
1470   $sth->finish;
1471
1472   $dbh->disconnect;
1473   $main::lxdebug->leave_sub();
1474 }
1475
1476 # this is only used for reports
1477 sub all_departments {
1478   $main::lxdebug->enter_sub();
1479
1480   my ($self, $myconfig, $table) = @_;
1481
1482   my $dbh   = $self->dbconnect($myconfig);
1483   my $where = "1 = 1";
1484
1485   if (defined $table) {
1486     if ($table eq 'customer') {
1487       $where = " d.role = 'P'";
1488     }
1489   }
1490
1491   my $query = qq|SELECT d.id, d.description
1492                  FROM department d
1493                  WHERE $where
1494                  ORDER BY 2|;
1495   my $sth = $dbh->prepare($query);
1496   $sth->execute || $self->dberror($query);
1497
1498   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1499     push @{ $self->{all_departments} }, $ref;
1500   }
1501   $sth->finish;
1502
1503   $dbh->disconnect;
1504
1505   $main::lxdebug->leave_sub();
1506 }
1507
1508 sub create_links {
1509   $main::lxdebug->enter_sub();
1510
1511   my ($self, $module, $myconfig, $table) = @_;
1512
1513   $self->all_vc($myconfig, $table, $module);
1514
1515   # get last customers or vendors
1516   my ($query, $sth);
1517
1518   my $dbh = $self->dbconnect($myconfig);
1519
1520   my %xkeyref = ();
1521
1522   # now get the account numbers
1523   $query =
1524     qq|SELECT c.accno, SUBSTRING(c.description,1,50) as description, c.link, c.taxkey_id
1525               FROM chart c
1526               WHERE c.link LIKE '%$module%'
1527               ORDER BY c.accno|;
1528
1529   $sth = $dbh->prepare($query);
1530   $sth->execute || $self->dberror($query);
1531
1532   $self->{accounts} = "";
1533   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1534
1535     foreach my $key (split /:/, $ref->{link}) {
1536       if ($key =~ /$module/) {
1537
1538         # cross reference for keys
1539         $xkeyref{ $ref->{accno} } = $key;
1540
1541         push @{ $self->{"${module}_links"}{$key} },
1542           { accno       => $ref->{accno},
1543             description => $ref->{description},
1544             taxkey      => $ref->{taxkey_id} };
1545
1546         $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
1547       }
1548     }
1549   }
1550   $sth->finish;
1551
1552   if (($module eq "AP") || ($module eq "AR")) {
1553
1554     # get tax rates and description
1555     $query = qq| SELECT * FROM tax t|;
1556     $sth   = $dbh->prepare($query);
1557     $sth->execute || $self->dberror($query);
1558     $form->{TAX} = ();
1559     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1560       push @{ $self->{TAX} }, $ref;
1561     }
1562     $sth->finish;
1563   }
1564
1565   if ($self->{id}) {
1566     my $arap = ($table eq 'customer') ? 'ar' : 'ap';
1567
1568     $query = qq|SELECT a.cp_id, a.invnumber, a.transdate,
1569                 a.${table}_id, a.datepaid, a.duedate, a.ordnumber,
1570                 a.taxincluded, a.curr AS currency, a.notes, a.intnotes,
1571                 c.name AS $table, a.department_id, d.description AS department,
1572                 a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
1573                 a.employee_id, e.name AS employee, a.gldate
1574                 FROM $arap a
1575                 JOIN $table c ON (a.${table}_id = c.id)
1576                 LEFT JOIN employee e ON (e.id = a.employee_id)
1577                 LEFT JOIN department d ON (d.id = a.department_id)
1578                 WHERE a.id = $self->{id}|;
1579     $sth = $dbh->prepare($query);
1580     $sth->execute || $self->dberror($query);
1581
1582     $ref = $sth->fetchrow_hashref(NAME_lc);
1583     foreach $key (keys %$ref) {
1584       $self->{$key} = $ref->{$key};
1585     }
1586     $sth->finish;
1587
1588     # get amounts from individual entries
1589     $query = qq|SELECT c.accno, c.description, a.source, a.amount, a.memo,
1590                 a.transdate, a.cleared, a.project_id, p.projectnumber, a.taxkey, t.rate
1591                 FROM acc_trans a
1592                 JOIN chart c ON (c.id = a.chart_id)
1593                 LEFT JOIN project p ON (p.id = a.project_id)
1594                 LEFT Join tax t ON (a.taxkey = t.taxkey)
1595                 WHERE a.trans_id = $self->{id}
1596                 AND a.fx_transaction = '0'
1597                 ORDER BY a.transdate|;
1598     $sth = $dbh->prepare($query);
1599     $sth->execute || $self->dberror($query);
1600
1601     my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1602
1603     # get exchangerate for currency
1604     $self->{exchangerate} =
1605       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1606                               $fld);
1607
1608     # store amounts in {acc_trans}{$key} for multiple accounts
1609     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1610       $ref->{exchangerate} =
1611         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate},
1612                                 $fld);
1613
1614       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
1615     }
1616     $sth->finish;
1617
1618     $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans,
1619                   (SELECT c.accno FROM chart c
1620                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1621                   (SELECT c.accno FROM chart c
1622                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1623                 FROM defaults d|;
1624     $sth = $dbh->prepare($query);
1625     $sth->execute || $self->dberror($query);
1626
1627     $ref = $sth->fetchrow_hashref(NAME_lc);
1628     map { $self->{$_} = $ref->{$_} } keys %$ref;
1629     $sth->finish;
1630
1631   } else {
1632
1633     # get date
1634     $query = qq|SELECT current_date AS transdate,
1635                 d.curr AS currencies, d.closedto, d.revtrans,
1636                   (SELECT c.accno FROM chart c
1637                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1638                   (SELECT c.accno FROM chart c
1639                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1640                 FROM defaults d|;
1641     $sth = $dbh->prepare($query);
1642     $sth->execute || $self->dberror($query);
1643
1644     $ref = $sth->fetchrow_hashref(NAME_lc);
1645     map { $self->{$_} = $ref->{$_} } keys %$ref;
1646     $sth->finish;
1647
1648     if ($self->{"$self->{vc}_id"}) {
1649
1650       # only setup currency
1651       ($self->{currency}) = split /:/, $self->{currencies};
1652
1653     } else {
1654
1655       $self->lastname_used($dbh, $myconfig, $table, $module);
1656
1657       my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1658
1659       # get exchangerate for currency
1660       $self->{exchangerate} =
1661         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1662                                 $fld);
1663
1664     }
1665
1666   }
1667
1668   $dbh->disconnect;
1669
1670   $main::lxdebug->leave_sub();
1671 }
1672
1673 sub lastname_used {
1674   $main::lxdebug->enter_sub();
1675
1676   my ($self, $dbh, $myconfig, $table, $module) = @_;
1677
1678   my $arap  = ($table eq 'customer') ? "ar" : "ap";
1679   my $where = "1 = 1";
1680
1681   if ($self->{type} =~ /_order/) {
1682     $arap  = 'oe';
1683     $where = "quotation = '0'";
1684   }
1685   if ($self->{type} =~ /_quotation/) {
1686     $arap  = 'oe';
1687     $where = "quotation = '1'";
1688   }
1689
1690   my $query = qq|SELECT id FROM $arap 
1691                  WHERE id IN (SELECT MAX(id) FROM $arap
1692                               WHERE $where
1693                               AND ${table}_id > 0)|;
1694   my $sth = $dbh->prepare($query);
1695   $sth->execute || $self->dberror($query);
1696
1697   my ($trans_id) = $sth->fetchrow_array;
1698   $sth->finish;
1699
1700   $trans_id *= 1;
1701   $query = qq|SELECT ct.name, a.curr, a.${table}_id,
1702               current_date + ct.terms AS duedate, a.department_id,
1703               d.description AS department
1704               FROM $arap a
1705               JOIN $table ct ON (a.${table}_id = ct.id)
1706               LEFT JOIN department d ON (a.department_id = d.id)
1707               WHERE a.id = $trans_id|;
1708   $sth = $dbh->prepare($query);
1709   $sth->execute || $self->dberror($query);
1710
1711   ($self->{$table},  $self->{currency},      $self->{"${table}_id"},
1712    $self->{duedate}, $self->{department_id}, $self->{department})
1713     = $sth->fetchrow_array;
1714   $sth->finish;
1715
1716   $main::lxdebug->leave_sub();
1717 }
1718
1719 sub current_date {
1720   $main::lxdebug->enter_sub();
1721
1722   my ($self, $myconfig, $thisdate, $days) = @_;
1723
1724   my $dbh = $self->dbconnect($myconfig);
1725   my ($sth, $query);
1726
1727   $days *= 1;
1728   if ($thisdate) {
1729     my $dateformat = $myconfig->{dateformat};
1730     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1731
1732     $query = qq|SELECT to_date('$thisdate', '$dateformat') + $days AS thisdate
1733                 FROM defaults|;
1734     $sth = $dbh->prepare($query);
1735     $sth->execute || $self->dberror($query);
1736   } else {
1737     $query = qq|SELECT current_date AS thisdate
1738                 FROM defaults|;
1739     $sth = $dbh->prepare($query);
1740     $sth->execute || $self->dberror($query);
1741   }
1742
1743   ($thisdate) = $sth->fetchrow_array;
1744   $sth->finish;
1745
1746   $dbh->disconnect;
1747
1748   $main::lxdebug->leave_sub();
1749
1750   return $thisdate;
1751 }
1752
1753 sub like {
1754   $main::lxdebug->enter_sub();
1755
1756   my ($self, $string) = @_;
1757
1758   if ($string !~ /%/) {
1759     $string = "%$string%";
1760   }
1761
1762   $string =~ s/\'/\'\'/g;
1763
1764   $main::lxdebug->leave_sub();
1765
1766   return $string;
1767 }
1768
1769 sub redo_rows {
1770   $main::lxdebug->enter_sub();
1771
1772   my ($self, $flds, $new, $count, $numrows) = @_;
1773
1774   my @ndx = ();
1775
1776   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
1777     (1 .. $count);
1778
1779   my $i = 0;
1780
1781   # fill rows
1782   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
1783     $i++;
1784     $j = $item->{ndx} - 1;
1785     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
1786   }
1787
1788   # delete empty rows
1789   for $i ($count + 1 .. $numrows) {
1790     map { delete $self->{"${_}_$i"} } @{$flds};
1791   }
1792
1793   $main::lxdebug->leave_sub();
1794 }
1795
1796 sub update_status {
1797   $main::lxdebug->enter_sub();
1798
1799   my ($self, $myconfig) = @_;
1800
1801   my ($i, $id);
1802
1803   my $dbh = $self->dbconnect_noauto($myconfig);
1804
1805   my $query = qq|DELETE FROM status
1806                  WHERE formname = '$self->{formname}'
1807                  AND trans_id = ?|;
1808   my $sth = $dbh->prepare($query) || $self->dberror($query);
1809
1810   if ($self->{formname} =~ /(check|receipt)/) {
1811     for $i (1 .. $self->{rowcount}) {
1812       $sth->execute($self->{"id_$i"} * 1) || $self->dberror($query);
1813       $sth->finish;
1814     }
1815   } else {
1816     $sth->execute($self->{id}) || $self->dberror($query);
1817     $sth->finish;
1818   }
1819
1820   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
1821   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
1822
1823   my %queued = split / /, $self->{queued};
1824
1825   if ($self->{formname} =~ /(check|receipt)/) {
1826
1827     # this is a check or receipt, add one entry for each lineitem
1828     my ($accno) = split /--/, $self->{account};
1829     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname,
1830                 chart_id) VALUES (?, '$printed',
1831                 '$queued{$self->{formname}}', '$self->{prinform}',
1832                 (SELECT c.id FROM chart c WHERE c.accno = '$accno'))|;
1833     $sth = $dbh->prepare($query) || $self->dberror($query);
1834
1835     for $i (1 .. $self->{rowcount}) {
1836       if ($self->{"checked_$i"}) {
1837         $sth->execute($self->{"id_$i"}) || $self->dberror($query);
1838         $sth->finish;
1839       }
1840     }
1841   } else {
1842     $query = qq|INSERT INTO status (trans_id, printed, emailed,
1843                 spoolfile, formname)
1844                 VALUES ($self->{id}, '$printed', '$emailed',
1845                 '$queued{$self->{formname}}', '$self->{formname}')|;
1846     $dbh->do($query) || $self->dberror($query);
1847   }
1848
1849   $dbh->commit;
1850   $dbh->disconnect;
1851
1852   $main::lxdebug->leave_sub();
1853 }
1854
1855 sub save_status {
1856   $main::lxdebug->enter_sub();
1857
1858   my ($self, $dbh) = @_;
1859
1860   my ($query, $printed, $emailed);
1861
1862   my $formnames  = $self->{printed};
1863   my $emailforms = $self->{emailed};
1864
1865   my $query = qq|DELETE FROM status
1866                  WHERE formname = '$self->{formname}'
1867                  AND trans_id = $self->{id}|;
1868   $dbh->do($query) || $self->dberror($query);
1869
1870   # this only applies to the forms
1871   # checks and receipts are posted when printed or queued
1872
1873   if ($self->{queued}) {
1874     my %queued = split / /, $self->{queued};
1875
1876     foreach my $formname (keys %queued) {
1877       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
1878       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
1879
1880       $query = qq|INSERT INTO status (trans_id, printed, emailed,
1881                   spoolfile, formname)
1882                   VALUES ($self->{id}, '$printed', '$emailed',
1883                   '$queued{$formname}', '$formname')|;
1884       $dbh->do($query) || $self->dberror($query);
1885
1886       $formnames  =~ s/$self->{formname}//;
1887       $emailforms =~ s/$self->{formname}//;
1888
1889     }
1890   }
1891
1892   # save printed, emailed info
1893   $formnames  =~ s/^ +//g;
1894   $emailforms =~ s/^ +//g;
1895
1896   my %status = ();
1897   map { $status{$_}{printed} = 1 } split / +/, $formnames;
1898   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
1899
1900   foreach my $formname (keys %status) {
1901     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
1902     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
1903
1904     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
1905                 VALUES ($self->{id}, '$printed', '$emailed', '$formname')|;
1906     $dbh->do($query) || $self->dberror($query);
1907   }
1908
1909   $main::lxdebug->leave_sub();
1910 }
1911
1912 sub update_defaults {
1913   $main::lxdebug->enter_sub();
1914
1915   my ($self, $myconfig, $fld) = @_;
1916
1917   my $dbh   = $self->dbconnect_noauto($myconfig);
1918   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
1919   my $sth   = $dbh->prepare($query);
1920
1921   $sth->execute || $self->dberror($query);
1922   my ($var) = $sth->fetchrow_array;
1923   $sth->finish;
1924
1925   $var++;
1926
1927   $query = qq|UPDATE defaults
1928               SET $fld = '$var'|;
1929   $dbh->do($query) || $form->dberror($query);
1930
1931   $dbh->commit;
1932   $dbh->disconnect;
1933
1934   $main::lxdebug->leave_sub();
1935
1936   return $var;
1937 }
1938
1939 sub update_business {
1940   $main::lxdebug->enter_sub();
1941
1942   my ($self, $myconfig, $business_id) = @_;
1943
1944   my $dbh   = $self->dbconnect_noauto($myconfig);
1945   my $query =
1946     qq|SELECT customernumberinit FROM business  WHERE id=$business_id FOR UPDATE|;
1947   my $sth = $dbh->prepare($query);
1948
1949   $sth->execute || $self->dberror($query);
1950   my ($var) = $sth->fetchrow_array;
1951   $sth->finish;
1952   if ($var ne "") {
1953     $var++;
1954   }
1955   $query = qq|UPDATE business
1956               SET customernumberinit = '$var' WHERE id=$business_id|;
1957   $dbh->do($query) || $form->dberror($query);
1958
1959   $dbh->commit;
1960   $dbh->disconnect;
1961
1962   $main::lxdebug->leave_sub();
1963
1964   return $var;
1965 }
1966
1967 sub get_salesman {
1968   $main::lxdebug->enter_sub();
1969
1970   my ($self, $myconfig, $salesman) = @_;
1971
1972   my $dbh   = $self->dbconnect($myconfig);
1973   my $query =
1974     qq|SELECT id, name FROM customer  WHERE (customernumber ilike '%$salesman%' OR name ilike '%$salesman%') AND business_id in (SELECT id from business WHERE salesman)|;
1975   my $sth = $dbh->prepare($query);
1976   $sth->execute || $self->dberror($query);
1977
1978   my $i = 0;
1979   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1980     push(@{ $self->{salesman_list} }, $ref);
1981     $i++;
1982   }
1983   $dbh->commit;
1984   $main::lxdebug->leave_sub();
1985
1986   return $i;
1987 }
1988
1989 sub get_partsgroup {
1990   $main::lxdebug->enter_sub();
1991
1992   my ($self, $myconfig, $p) = @_;
1993
1994   my $dbh = $self->dbconnect($myconfig);
1995
1996   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
1997                  FROM partsgroup pg
1998                  JOIN parts p ON (p.partsgroup_id = pg.id)|;
1999
2000   if ($p->{searchitems} eq 'part') {
2001     $query .= qq|
2002                  WHERE p.inventory_accno_id > 0|;
2003   }
2004   if ($p->{searchitems} eq 'service') {
2005     $query .= qq|
2006                  WHERE p.inventory_accno_id IS NULL|;
2007   }
2008   if ($p->{searchitems} eq 'assembly') {
2009     $query .= qq|
2010                  WHERE p.assembly = '1'|;
2011   }
2012   if ($p->{searchitems} eq 'labor') {
2013     $query .= qq|
2014                  WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
2015   }
2016
2017   $query .= qq|
2018                  ORDER BY partsgroup|;
2019
2020   if ($p->{all}) {
2021     $query = qq|SELECT id, partsgroup FROM partsgroup
2022                 ORDER BY partsgroup|;
2023   }
2024
2025   if ($p->{language_code}) {
2026     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2027                 t.description AS translation
2028                 FROM partsgroup pg
2029                 JOIN parts p ON (p.partsgroup_id = pg.id)
2030                 LEFT JOIN translation t ON (t.trans_id = pg.id AND t.language_code = '$p->{language_code}')
2031                 ORDER BY translation|;
2032   }
2033
2034   my $sth = $dbh->prepare($query);
2035   $sth->execute || $self->dberror($query);
2036
2037   $self->{all_partsgroup} = ();
2038   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2039     push @{ $self->{all_partsgroup} }, $ref;
2040   }
2041   $sth->finish;
2042   $dbh->disconnect;
2043   $main::lxdebug->leave_sub();
2044 }
2045
2046 package Locale;
2047
2048 sub new {
2049   $main::lxdebug->enter_sub();
2050
2051   my ($type, $country, $NLS_file) = @_;
2052   my $self = {};
2053
2054   %self = ();
2055   if ($country && -d "locale/$country") {
2056     $self->{countrycode} = $country;
2057     eval { require "locale/$country/$NLS_file"; };
2058   }
2059
2060   $self->{NLS_file} = $NLS_file;
2061
2062   push @{ $self->{LONG_MONTH} },
2063     ("January",   "February", "March",    "April",
2064      "May ",      "June",     "July",     "August",
2065      "September", "October",  "November", "December");
2066   push @{ $self->{SHORT_MONTH} },
2067     (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
2068
2069   $main::lxdebug->leave_sub();
2070
2071   bless $self, $type;
2072 }
2073
2074 sub text {
2075   my ($self, $text) = @_;
2076
2077   return (exists $self{texts}{$text}) ? $self{texts}{$text} : $text;
2078 }
2079
2080 sub findsub {
2081   $main::lxdebug->enter_sub();
2082
2083   my ($self, $text) = @_;
2084
2085   if (exists $self{subs}{$text}) {
2086     $text = $self{subs}{$text};
2087   } else {
2088     if ($self->{countrycode} && $self->{NLS_file}) {
2089       Form->error(
2090          "$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
2091     }
2092   }
2093
2094   $main::lxdebug->leave_sub();
2095
2096   return $text;
2097 }
2098
2099 sub date {
2100   $main::lxdebug->enter_sub();
2101
2102   my ($self, $myconfig, $date, $longformat) = @_;
2103
2104   my $longdate  = "";
2105   my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
2106
2107   if ($date) {
2108
2109     # get separator
2110     $spc = $myconfig->{dateformat};
2111     $spc =~ s/\w//g;
2112     $spc = substr($spc, 1, 1);
2113
2114     if ($date =~ /\D/) {
2115       if ($myconfig->{dateformat} =~ /^yy/) {
2116         ($yy, $mm, $dd) = split /\D/, $date;
2117       }
2118       if ($myconfig->{dateformat} =~ /^mm/) {
2119         ($mm, $dd, $yy) = split /\D/, $date;
2120       }
2121       if ($myconfig->{dateformat} =~ /^dd/) {
2122         ($dd, $mm, $yy) = split /\D/, $date;
2123       }
2124     } else {
2125       $date = substr($date, 2);
2126       ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2127     }
2128
2129     $dd *= 1;
2130     $mm--;
2131     $yy = ($yy < 70) ? $yy + 2000 : $yy;
2132     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2133
2134     if ($myconfig->{dateformat} =~ /^dd/) {
2135       if (defined $longformat && $longformat == 0) {
2136         $mm++;
2137         $dd = "0$dd" if ($dd < 10);
2138         $mm = "0$mm" if ($mm < 10);
2139         $longdate = "$dd$spc$mm$spc$yy";
2140       } else {
2141         $longdate = "$dd";
2142         $longdate .= ($spc eq '.') ? ". " : " ";
2143         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2144       }
2145     } elsif ($myconfig->{dateformat} eq "yyyy-mm-dd") {
2146
2147       # Use German syntax with the ISO date style "yyyy-mm-dd" because
2148       # Lx-Office is mainly used in Germany or German speaking countries.
2149       if (defined $longformat && $longformat == 0) {
2150         $mm++;
2151         $dd = "0$dd" if ($dd < 10);
2152         $mm = "0$mm" if ($mm < 10);
2153         $longdate = "$yy-$mm-$dd";
2154       } else {
2155         $longdate = "$dd. ";
2156         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2157       }
2158     } else {
2159       if (defined $longformat && $longformat == 0) {
2160         $mm++;
2161         $dd = "0$dd" if ($dd < 10);
2162         $mm = "0$mm" if ($mm < 10);
2163         $longdate = "$mm$spc$dd$spc$yy";
2164       } else {
2165         $longdate = &text($self, $self->{$longmonth}[$mm]) . " $dd, $yy";
2166       }
2167     }
2168
2169   }
2170
2171   $main::lxdebug->leave_sub();
2172
2173   return $longdate;
2174 }
2175
2176 sub parse_date {
2177   $main::lxdebug->enter_sub();
2178
2179   my ($self, $myconfig, $date, $longformat) = @_;
2180
2181   unless ($date) {
2182     $main::lxdebug->leave_sub();
2183     return ();
2184   }
2185
2186   # get separator
2187   $spc = $myconfig->{dateformat};
2188   $spc =~ s/\w//g;
2189   $spc = substr($spc, 1, 1);
2190
2191   if ($date =~ /\D/) {
2192     if ($myconfig->{dateformat} =~ /^yy/) {
2193       ($yy, $mm, $dd) = split /\D/, $date;
2194     } elsif ($myconfig->{dateformat} =~ /^mm/) {
2195       ($mm, $dd, $yy) = split /\D/, $date;
2196     } elsif ($myconfig->{dateformat} =~ /^dd/) {
2197       ($dd, $mm, $yy) = split /\D/, $date;
2198     }
2199   } else {
2200     $date = substr($date, 2);
2201     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2202   }
2203
2204   $dd *= 1;
2205   $mm *= 1;
2206   $yy = ($yy < 70) ? $yy + 2000 : $yy;
2207   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2208
2209   $main::lxdebug->leave_sub();
2210   return ($yy, $mm, $dd);
2211 }
2212
2213 1;
2214