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