Backup aus dem Menue entfernt, da noch fehlerbehaftet
[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 $round_amount;
569
570   # Rounding like "Kaufmannsrunden"
571   # Descr. http://de.wikipedia.org/wiki/Rundung
572   # Inspired by 
573   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
574   # Solves Bug: 189
575   # Udo Spallek
576   $amount       = $amount * (10 ** ($places));
577   $round_amount = int($amount + .5 * ($amount <=> 0))/(10**($places));
578
579   $main::lxdebug->leave_sub();
580
581   return $round_amount;
582 }
583
584 sub parse_template {
585   $main::lxdebug->enter_sub();
586
587   my ($self, $myconfig, $userspath) = @_;
588
589   # { Moritz Bunkus
590   # Some variables used for page breaks
591   my ($chars_per_line, $lines_on_first_page, $lines_on_second_page) =
592     (0, 0, 0);
593   my ($current_page, $current_line) = (1, 1);
594   my $pagebreak = "";
595   my $sum       = 0;
596
597   # } Moritz Bunkus
598
599   # Make sure that all *notes* (intnotes, partnotes_*, notes etc) are converted to markup correctly.
600   $self->format_string(grep(/notes/, keys(%{$self})));
601
602   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
603   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
604
605   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
606       qw(email tel fax name signature));
607
608   open(IN, "$self->{templates}/$self->{IN}")
609     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
658     # } Moritz Bunkus
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 =
681             int(length($self->{"description"}[$i]) / $chars_per_line + 0.95);
682           my $lpp;
683
684           my $_description = $self->{"description"}[$i];
685           while ($_description =~ /\\newline/) {
686             $lines++;
687             $_description =~ s/\\newline//;
688           }
689           $self->{"description"}[$i] =~ s/(\\newline\s?)*$//;
690
691           if ($current_page == 1) {
692             $lpp = $lines_on_first_page;
693           } else {
694             $lpp = $lines_on_second_page;
695           }
696
697           # Yes we need a manual page break
698           if (($current_line + $lines) > $lpp) {
699             my $pb = $pagebreak;
700
701             # replace the special variables <%sumcarriedforward%>
702             # and <%lastpage%>
703
704             my $psum = $self->format_amount($myconfig, $sum, 2);
705             $pb =~ s/<%sumcarriedforward%>/$psum/g;
706             $pb =~ s/<%lastpage%>/$current_page/g;
707
708             # only "normal" variables are supported here
709             # (no <%if, no <%foreach, no <%include)
710
711             $pb =~ s/<%(.+?)%>/$self->{$1}/g;
712
713             # page break block is ready to rock
714             print(OUT $pb);
715             $current_page++;
716             $current_line = 1;
717           }
718           $current_line += $lines;
719         }
720         $sum += $self->parse_amount($myconfig, $self->{"linetotal"}[$i]);
721
722         # } Moritz Bunkus
723
724         # don't parse par, we need it for each line
725         $_ = $par;
726         s/<%(.+?)%>/$self->{$1}[$i]/mg;
727         print OUT;
728       }
729       next;
730     }
731
732     # if not comes before if!
733     if (/\s*<%if not /) {
734
735       # check if it is not set and display
736       chop;
737       s/\s*<%if not (.+?)%>/$1/;
738
739       unless ($self->{$_}) {
740         while ($_ = shift) {
741           last if (/\s*<%end /);
742
743           # store line in $par
744           $par .= $_;
745         }
746
747         $_ = $par;
748
749       } else {
750         while ($_ = shift) {
751           last if (/\s*<%end /);
752         }
753         next;
754       }
755     }
756
757     if (/\s*<%if /) {
758
759       # check if it is set and display
760       chop;
761       s/\s*<%if (.+?)%>/$1/;
762
763       if ($self->{$_}) {
764         while ($_ = shift) {
765           last if (/\s*<%end /);
766
767           # store line in $par
768           $par .= $_;
769         }
770
771         $_ = $par;
772
773       } else {
774         while ($_ = shift) {
775           last if (/\s*<%end /);
776         }
777         next;
778       }
779     }
780
781     # check for <%include filename%>
782     if (/\s*<%include /) {
783
784       # get the filename
785       chomp $var;
786       $var =~ s/\s*<%include (.+?)%>/$1/;
787
788       # mangle filename
789       $var =~ s/(\/|\.\.)//g;
790
791       # prevent the infinite loop!
792       next if ($self->{"$var"});
793
794       open(INC, "$self->{templates}/$var")
795         or $self->error($self->cleanup . "$self->{templates}/$var : $!");
796       unshift(@_, <INC>);
797       close(INC);
798
799       $self->{"$var"} = 1;
800
801       next;
802     }
803
804     s/<%(.+?)%>/$self->{$1}/g;
805     print OUT;
806   }
807
808   close(OUT);
809
810   # { Moritz Bunkus
811   # Convert the tex file to postscript
812   if ($self->{format} =~ /(postscript|pdf)/) {
813
814     use Cwd;
815     $self->{cwd}    = cwd();
816     $self->{tmpdir} = "$self->{cwd}/$userspath";
817
818     chdir("$userspath") or $self->error($self->cleanup . "chdir : $!");
819
820     $self->{tmpfile} =~ s/$userspath\///g;
821
822     if ($self->{format} eq 'postscript') {
823       system(
824         "latex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
825       );
826       $self->error($self->cleanup) if ($?);
827       if ($two_passes) {
828         system(
829           "latex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
830         );
831         $self->error($self->cleanup) if ($?);
832       }
833
834       $self->{tmpfile} =~ s/tex$/dvi/;
835
836       system("dvips $self->{tmpfile} -o -q > /dev/null");
837       $self->error($self->cleanup . "dvips : $!") if ($?);
838       $self->{tmpfile} =~ s/dvi$/ps/;
839     }
840     if ($self->{format} eq 'pdf') {
841       system(
842         "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
843       );
844       $self->error($self->cleanup) if ($?);
845       if ($two_passes) {
846         system(
847           "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
848         );
849         $self->error($self->cleanup) if ($?);
850       }
851       $self->{tmpfile} =~ s/tex$/pdf/;
852     }
853
854   }
855
856   if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
857
858     if ($self->{media} eq 'email') {
859
860       use SL::Mailer;
861
862       my $mail = new Mailer;
863
864       map { $mail->{$_} = $self->{$_} }
865         qw(cc bcc subject message version format charset);
866       $mail->{to}     = qq|$self->{email}|;
867       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
868       $mail->{fileid} = "$fileid.";
869
870       # if we send html or plain text inline
871       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
872         $mail->{contenttype} = "text/html";
873
874         $mail->{message}       =~ s/\r\n/<br>\n/g;
875         $myconfig->{signature} =~ s/\\n/<br>\n/g;
876         $mail->{message} .= "<br>\n--<br>\n$myconfig->{signature}\n<br>";
877
878         open(IN, $self->{tmpfile})
879           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
880         while (<IN>) {
881           $mail->{message} .= $_;
882         }
883
884         close(IN);
885
886       } else {
887
888         @{ $mail->{attachments} } = ($self->{tmpfile});
889
890         $myconfig->{signature} =~ s/\\n/\r\n/g;
891         $mail->{message} .= "\r\n--\r\n$myconfig->{signature}";
892
893       }
894
895       my $err = $mail->send($out);
896       $self->error($self->cleanup . "$err") if ($err);
897
898     } else {
899
900       $self->{OUT} = $out;
901
902       my $numbytes = (-s $self->{tmpfile});
903       open(IN, $self->{tmpfile})
904         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
905
906       $self->{copies} = 1 unless $self->{media} eq 'printer';
907
908       chdir("$self->{cwd}");
909
910       for my $i (1 .. $self->{copies}) {
911         if ($self->{OUT}) {
912           open(OUT, $self->{OUT})
913             or $self->error($self->cleanup . "$self->{OUT} : $!");
914         } else {
915
916           # launch application
917           print qq|Content-Type: application/$self->{format}
918 Content-Disposition: attachment; filename="$self->{tmpfile}"
919 Content-Length: $numbytes
920
921 |;
922
923           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
924
925         }
926
927         while (<IN>) {
928           print OUT $_;
929         }
930
931         close(OUT);
932
933         seek IN, 0, 0;
934       }
935
936       close(IN);
937     }
938
939     $self->cleanup;
940
941   }
942
943   chdir("$self->{cwd}");
944   $main::lxdebug->leave_sub();
945 }
946
947 sub cleanup {
948   $main::lxdebug->enter_sub();
949
950   my $self = shift;
951
952   chdir("$self->{tmpdir}");
953
954   my @err = ();
955   if (-f "$self->{tmpfile}.err") {
956     open(FH, "$self->{tmpfile}.err");
957     @err = <FH>;
958     close(FH);
959   }
960
961   if ($self->{tmpfile}) {
962
963     # strip extension
964     $self->{tmpfile} =~ s/\.\w+$//g;
965     my $tmpfile = $self->{tmpfile};
966     unlink(<$tmpfile.*>);
967   }
968
969   chdir("$self->{cwd}");
970
971   $main::lxdebug->leave_sub();
972
973   return "@err";
974 }
975
976 sub format_string {
977   $main::lxdebug->enter_sub();
978
979   my ($self, @fields) = @_;
980   my %unique_fields;
981
982   %unique_fields = map({ $_ => 1 } @fields);
983   @fields = keys(%unique_fields);
984   my $format = $self->{format};
985   if ($self->{format} =~ /(postscript|pdf)/) {
986     $format = 'tex';
987   }
988
989   my %replace = (
990     'order' => {
991       'html' => [
992         '<', '>', quotemeta('\n'), '
993 '
994       ],
995       'tex' => [
996         '&', quotemeta('\n'), '
997 ',
998         '"', '\$', '%', '_', '#', quotemeta('^'),
999         '{', '}',  '<', '>', '£', "\r"
1000       ]
1001     },
1002     'html' => {
1003       '<'             => '&lt;',
1004       '>'             => '&gt;',
1005       quotemeta('\n') => '<br>',
1006       '
1007 ' => '<br>'
1008     },
1009     'tex' => {
1010       '"'             => "''",
1011       '&'             => '\&',
1012       '\$'            => '\$',
1013       '%'             => '\%',
1014       '_'             => '\_',
1015       '#'             => '\#',
1016       quotemeta('^')  => '\^\\',
1017       '{'             => '\{',
1018       '}'             => '\}',
1019       '<'             => '$<$',
1020       '>'             => '$>$',
1021       quotemeta('\n') => '\newline ',
1022       '
1023 '          => '\newline ',
1024       '£'  => '\pounds ',
1025       "\r" => ""
1026     });
1027
1028   foreach my $key (@{ $replace{order}{$format} }) {
1029     map { $self->{$_} =~ s/$key/$replace{$format}{$key}/g; } @fields;
1030   }
1031
1032   $main::lxdebug->leave_sub();
1033 }
1034
1035 sub datetonum {
1036   $main::lxdebug->enter_sub();
1037
1038   my ($self, $date, $myconfig) = @_;
1039
1040   if ($date && $date =~ /\D/) {
1041
1042     if ($myconfig->{dateformat} =~ /^yy/) {
1043       ($yy, $mm, $dd) = split /\D/, $date;
1044     }
1045     if ($myconfig->{dateformat} =~ /^mm/) {
1046       ($mm, $dd, $yy) = split /\D/, $date;
1047     }
1048     if ($myconfig->{dateformat} =~ /^dd/) {
1049       ($dd, $mm, $yy) = split /\D/, $date;
1050     }
1051
1052     $dd *= 1;
1053     $mm *= 1;
1054     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1055     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1056
1057     $dd = "0$dd" if ($dd < 10);
1058     $mm = "0$mm" if ($mm < 10);
1059
1060     $date = "$yy$mm$dd";
1061   }
1062
1063   $main::lxdebug->leave_sub();
1064
1065   return $date;
1066 }
1067
1068 # Database routines used throughout
1069
1070 sub dbconnect {
1071   $main::lxdebug->enter_sub();
1072
1073   my ($self, $myconfig) = @_;
1074
1075   # connect to database
1076   my $dbh =
1077     DBI->connect($myconfig->{dbconnect},
1078                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1079     or $self->dberror;
1080
1081   # set db options
1082   if ($myconfig->{dboptions}) {
1083     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1084   }
1085
1086   $main::lxdebug->leave_sub();
1087
1088   return $dbh;
1089 }
1090
1091 sub dbconnect_noauto {
1092   $main::lxdebug->enter_sub();
1093
1094   my ($self, $myconfig) = @_;
1095
1096   # connect to database
1097   $dbh =
1098     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1099                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1100     or $self->dberror;
1101
1102   # set db options
1103   if ($myconfig->{dboptions}) {
1104     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1105   }
1106
1107   $main::lxdebug->leave_sub();
1108
1109   return $dbh;
1110 }
1111
1112 sub update_balance {
1113   $main::lxdebug->enter_sub();
1114
1115   my ($self, $dbh, $table, $field, $where, $value) = @_;
1116
1117   # if we have a value, go do it
1118   if ($value != 0) {
1119
1120     # retrieve balance from table
1121     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1122     my $sth   = $dbh->prepare($query);
1123
1124     $sth->execute || $self->dberror($query);
1125     my ($balance) = $sth->fetchrow_array;
1126     $sth->finish;
1127
1128     $balance += $value;
1129
1130     # update balance
1131     $query = "UPDATE $table SET $field = $balance WHERE $where";
1132     $dbh->do($query) || $self->dberror($query);
1133   }
1134   $main::lxdebug->leave_sub();
1135 }
1136
1137 sub update_exchangerate {
1138   $main::lxdebug->enter_sub();
1139
1140   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1141
1142   # some sanity check for currency
1143   if ($curr eq '') {
1144     $main::lxdebug->leave_sub();
1145     return;
1146   }
1147
1148   my $query = qq|SELECT e.curr FROM exchangerate e
1149                  WHERE e.curr = '$curr'
1150                  AND e.transdate = '$transdate'
1151                  FOR UPDATE|;
1152   my $sth = $dbh->prepare($query);
1153   $sth->execute || $self->dberror($query);
1154
1155   my $set;
1156   if ($buy != 0 && $sell != 0) {
1157     $set = "buy = $buy, sell = $sell";
1158   } elsif ($buy != 0) {
1159     $set = "buy = $buy";
1160   } elsif ($sell != 0) {
1161     $set = "sell = $sell";
1162   }
1163
1164   if ($sth->fetchrow_array) {
1165     $query = qq|UPDATE exchangerate
1166                 SET $set
1167                 WHERE curr = '$curr'
1168                 AND transdate = '$transdate'|;
1169   } else {
1170     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1171                 VALUES ('$curr', $buy, $sell, '$transdate')|;
1172   }
1173   $sth->finish;
1174   $dbh->do($query) || $self->dberror($query);
1175
1176   $main::lxdebug->leave_sub();
1177 }
1178
1179 sub save_exchangerate {
1180   $main::lxdebug->enter_sub();
1181
1182   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1183
1184   my $dbh = $self->dbconnect($myconfig);
1185
1186   my ($buy, $sell) = (0, 0);
1187   $buy  = $rate if $fld eq 'buy';
1188   $sell = $rate if $fld eq 'sell';
1189
1190   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1191
1192   $dbh->disconnect;
1193
1194   $main::lxdebug->leave_sub();
1195 }
1196
1197 sub get_exchangerate {
1198   $main::lxdebug->enter_sub();
1199
1200   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1201
1202   my $query = qq|SELECT e.$fld FROM exchangerate e
1203                  WHERE e.curr = '$curr'
1204                  AND e.transdate = '$transdate'|;
1205   my $sth = $dbh->prepare($query);
1206   $sth->execute || $self->dberror($query);
1207
1208   my ($exchangerate) = $sth->fetchrow_array;
1209   $sth->finish;
1210
1211   $main::lxdebug->leave_sub();
1212
1213   return $exchangerate;
1214 }
1215
1216 sub check_exchangerate {
1217   $main::lxdebug->enter_sub();
1218
1219   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1220
1221   unless ($transdate) {
1222     $main::lxdebug->leave_sub();
1223     return "";
1224   }
1225
1226   my $dbh = $self->dbconnect($myconfig);
1227
1228   my $query = qq|SELECT e.$fld FROM exchangerate e
1229                  WHERE e.curr = '$currency'
1230                  AND e.transdate = '$transdate'|;
1231   my $sth = $dbh->prepare($query);
1232   $sth->execute || $self->dberror($query);
1233
1234   my ($exchangerate) = $sth->fetchrow_array;
1235   $sth->finish;
1236   $dbh->disconnect;
1237
1238   $main::lxdebug->leave_sub();
1239
1240   return $exchangerate;
1241 }
1242
1243 sub add_shipto {
1244   $main::lxdebug->enter_sub();
1245
1246   my ($self, $dbh, $id) = @_;
1247 ##LINET
1248   my $shipto;
1249   foreach
1250     my $item (qw(name department_1 department_2 street zipcode city country contact phone fax email)) {
1251     if ($self->{"shipto$item"}) {
1252       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1253     }
1254     $self->{"shipto$item"} =~ s/\'/\'\'/g;
1255   }
1256
1257   if ($shipto) {
1258     my $query = qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2, shiptostreet,
1259                    shiptozipcode, shiptocity, shiptocountry, shiptocontact,
1260                    shiptophone, shiptofax, shiptoemail) VALUES ($id,
1261                    '$self->{shiptoname}', '$self->{shiptodepartment_1}', '$self->{shiptodepartment_2}', '$self->{shiptostreet}',
1262                    '$self->{shiptozipcode}', '$self->{shiptocity}',
1263                    '$self->{shiptocountry}', '$self->{shiptocontact}',
1264                    '$self->{shiptophone}', '$self->{shiptofax}',
1265                    '$self->{shiptoemail}')|;
1266     $dbh->do($query) || $self->dberror($query);
1267   }
1268 ##/LINET
1269   $main::lxdebug->leave_sub();
1270 }
1271
1272 sub get_employee {
1273   $main::lxdebug->enter_sub();
1274
1275   my ($self, $dbh) = @_;
1276
1277   my $query = qq|SELECT e.id, e.name FROM employee e
1278                  WHERE e.login = '$self->{login}'|;
1279   my $sth = $dbh->prepare($query);
1280   $sth->execute || $self->dberror($query);
1281
1282   ($self->{employee_id}, $self->{employee}) = $sth->fetchrow_array;
1283   $self->{employee_id} *= 1;
1284
1285   $sth->finish;
1286
1287   $main::lxdebug->leave_sub();
1288 }
1289
1290 # get other contact for transaction and form - html/tex
1291 sub get_contact {
1292   $main::lxdebug->enter_sub();
1293
1294   my ($self, $dbh, $id) = @_;
1295
1296   my $query = qq|SELECT c.*
1297               FROM contacts c
1298               WHERE cp_id=$id|;
1299   $sth = $dbh->prepare($query);
1300   $sth->execute || $self->dberror($query);
1301
1302   $ref = $sth->fetchrow_hashref(NAME_lc);
1303
1304   push @{ $self->{$_} }, $ref;
1305
1306   $sth->finish;
1307   $main::lxdebug->leave_sub();
1308 }
1309
1310 # get contacts for id, if no contact return {"","","","",""}
1311 sub get_contacts {
1312   $main::lxdebug->enter_sub();
1313
1314   my ($self, $dbh, $id) = @_;
1315
1316   my $query = qq|SELECT c.cp_id, c.cp_cv_id, c.cp_name, c.cp_givenname
1317               FROM contacts c
1318               WHERE cp_cv_id=$id|;
1319   my $sth = $dbh->prepare($query);
1320   $sth->execute || $self->dberror($query);
1321
1322   my $i = 0;
1323   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1324     push @{ $self->{all_contacts} }, $ref;
1325     $i++;
1326   }
1327
1328   if ($i == 0) {
1329     push @{ $self->{all_contacts} }, { { "", "", "", "", "" } };
1330   }
1331   $sth->finish;
1332   $main::lxdebug->leave_sub();
1333 }
1334
1335 # this sub gets the id and name from $table
1336 sub get_name {
1337   $main::lxdebug->enter_sub();
1338
1339   my ($self, $myconfig, $table) = @_;
1340
1341   # connect to database
1342   my $dbh = $self->dbconnect($myconfig);
1343
1344   my $name           = $self->like(lc $self->{$table});
1345   my $customernumber = $self->like(lc $self->{customernumber});
1346
1347   if ($self->{customernumber} ne "") {
1348     $query = qq~SELECT c.id, c.name,
1349                   c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1350                   FROM $table c
1351                   WHERE (lower(c.customernumber) LIKE '$customernumber') AND (not c.obsolete)
1352                   ORDER BY c.name~;
1353   } else {
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.name) LIKE '$name') AND (not c.obsolete)
1358                  ORDER BY c.name~;
1359   }
1360
1361   if ($self->{openinvoices}) {
1362     $query = qq~SELECT DISTINCT c.id, c.name,
1363                 c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1364                 FROM $self->{arap} a
1365                 JOIN $table c ON (a.${table}_id = c.id)
1366                 WHERE NOT a.amount = a.paid
1367                 AND lower(c.name) LIKE '$name'
1368                 ORDER BY c.name~;
1369   }
1370   my $sth = $dbh->prepare($query);
1371
1372   $sth->execute || $self->dberror($query);
1373
1374   my $i = 0;
1375   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1376     push(@{ $self->{name_list} }, $ref);
1377     $i++;
1378   }
1379   $sth->finish;
1380   $dbh->disconnect;
1381
1382   $main::lxdebug->leave_sub();
1383
1384   return $i;
1385 }
1386
1387 # the selection sub is used in the AR, AP, IS, IR and OE module
1388 #
1389 sub all_vc {
1390   $main::lxdebug->enter_sub();
1391
1392   my ($self, $myconfig, $table, $module) = @_;
1393
1394   my $ref;
1395   my $dbh = $self->dbconnect($myconfig);
1396
1397   my $query = qq|SELECT count(*) FROM $table|;
1398   my $sth   = $dbh->prepare($query);
1399   $sth->execute || $self->dberror($query);
1400   my ($count) = $sth->fetchrow_array;
1401   $sth->finish;
1402
1403   # build selection list
1404   if ($count < $myconfig->{vclimit}) {
1405     $query = qq|SELECT id, name
1406                 FROM $table WHERE not obsolete
1407                 ORDER BY name|;
1408     $sth = $dbh->prepare($query);
1409     $sth->execute || $self->dberror($query);
1410
1411     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1412       push @{ $self->{"all_$table"} }, $ref;
1413     }
1414
1415     $sth->finish;
1416
1417   }
1418
1419   # get self
1420   $self->get_employee($dbh);
1421
1422   # setup sales contacts
1423   $query = qq|SELECT e.id, e.name
1424               FROM employee e
1425               WHERE e.sales = '1'
1426               AND NOT e.id = $self->{employee_id}|;
1427   $sth = $dbh->prepare($query);
1428   $sth->execute || $self->dberror($query);
1429
1430   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1431     push @{ $self->{all_employees} }, $ref;
1432   }
1433   $sth->finish;
1434
1435   # this is for self
1436   push @{ $self->{all_employees} },
1437     { id   => $self->{employee_id},
1438       name => $self->{employee} };
1439
1440   # sort the whole thing
1441   @{ $self->{all_employees} } =
1442     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
1443
1444   if ($module eq 'AR') {
1445
1446     # prepare query for departments
1447     $query = qq|SELECT d.id, d.description
1448                 FROM department d
1449                 WHERE d.role = 'P'
1450                 ORDER BY 2|;
1451
1452   } else {
1453     $query = qq|SELECT d.id, d.description
1454                 FROM department d
1455                 ORDER BY 2|;
1456   }
1457
1458   $sth = $dbh->prepare($query);
1459   $sth->execute || $self->dberror($query);
1460
1461   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1462     push @{ $self->{all_departments} }, $ref;
1463   }
1464   $sth->finish;
1465
1466   $dbh->disconnect;
1467   $main::lxdebug->leave_sub();
1468 }
1469
1470 # this is only used for reports
1471 sub all_departments {
1472   $main::lxdebug->enter_sub();
1473
1474   my ($self, $myconfig, $table) = @_;
1475
1476   my $dbh   = $self->dbconnect($myconfig);
1477   my $where = "1 = 1";
1478
1479   if (defined $table) {
1480     if ($table eq 'customer') {
1481       $where = " d.role = 'P'";
1482     }
1483   }
1484
1485   my $query = qq|SELECT d.id, d.description
1486                  FROM department d
1487                  WHERE $where
1488                  ORDER BY 2|;
1489   my $sth = $dbh->prepare($query);
1490   $sth->execute || $self->dberror($query);
1491
1492   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1493     push @{ $self->{all_departments} }, $ref;
1494   }
1495   $sth->finish;
1496
1497   $dbh->disconnect;
1498
1499   $main::lxdebug->leave_sub();
1500 }
1501
1502 sub create_links {
1503   $main::lxdebug->enter_sub();
1504
1505   my ($self, $module, $myconfig, $table) = @_;
1506
1507   $self->all_vc($myconfig, $table, $module);
1508
1509   # get last customers or vendors
1510   my ($query, $sth);
1511
1512   my $dbh = $self->dbconnect($myconfig);
1513
1514   my %xkeyref = ();
1515
1516   # now get the account numbers
1517   $query =
1518     qq|SELECT c.accno, SUBSTRING(c.description,1,50) as description, c.link, c.taxkey_id
1519               FROM chart c
1520               WHERE c.link LIKE '%$module%'
1521               ORDER BY c.accno|;
1522
1523   $sth = $dbh->prepare($query);
1524   $sth->execute || $self->dberror($query);
1525
1526   $self->{accounts} = "";
1527   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1528
1529     foreach my $key (split /:/, $ref->{link}) {
1530       if ($key =~ /$module/) {
1531
1532         # cross reference for keys
1533         $xkeyref{ $ref->{accno} } = $key;
1534
1535         push @{ $self->{"${module}_links"}{$key} },
1536           { accno       => $ref->{accno},
1537             description => $ref->{description},
1538             taxkey      => $ref->{taxkey_id} };
1539
1540         $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
1541       }
1542     }
1543   }
1544   $sth->finish;
1545
1546   if (($module eq "AP") || ($module eq "AR")) {
1547
1548     # get tax rates and description
1549     $query = qq| SELECT * FROM tax t|;
1550     $sth   = $dbh->prepare($query);
1551     $sth->execute || $self->dberror($query);
1552     $form->{TAX} = ();
1553     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1554       push @{ $self->{TAX} }, $ref;
1555     }
1556     $sth->finish;
1557   }
1558
1559   if ($self->{id}) {
1560     my $arap = ($table eq 'customer') ? 'ar' : 'ap';
1561
1562     $query = qq|SELECT a.cp_id, a.invnumber, a.transdate,
1563                 a.${table}_id, a.datepaid, a.duedate, a.ordnumber,
1564                 a.taxincluded, a.curr AS currency, a.notes, a.intnotes,
1565                 c.name AS $table, a.department_id, d.description AS department,
1566                 a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
1567                 a.employee_id, e.name AS employee, a.gldate
1568                 FROM $arap a
1569                 JOIN $table c ON (a.${table}_id = c.id)
1570                 LEFT JOIN employee e ON (e.id = a.employee_id)
1571                 LEFT JOIN department d ON (d.id = a.department_id)
1572                 WHERE a.id = $self->{id}|;
1573     $sth = $dbh->prepare($query);
1574     $sth->execute || $self->dberror($query);
1575
1576     $ref = $sth->fetchrow_hashref(NAME_lc);
1577     foreach $key (keys %$ref) {
1578       $self->{$key} = $ref->{$key};
1579     }
1580     $sth->finish;
1581
1582     # get amounts from individual entries
1583     $query = qq|SELECT c.accno, c.description, a.source, a.amount, a.memo,
1584                 a.transdate, a.cleared, a.project_id, p.projectnumber, a.taxkey, t.rate
1585                 FROM acc_trans a
1586                 JOIN chart c ON (c.id = a.chart_id)
1587                 LEFT JOIN project p ON (p.id = a.project_id)
1588                 LEFT Join tax t ON (a.taxkey = t.taxkey)
1589                 WHERE a.trans_id = $self->{id}
1590                 AND a.fx_transaction = '0'
1591                 ORDER BY a.transdate|;
1592     $sth = $dbh->prepare($query);
1593     $sth->execute || $self->dberror($query);
1594
1595     my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1596
1597     # get exchangerate for currency
1598     $self->{exchangerate} =
1599       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1600                               $fld);
1601
1602     # store amounts in {acc_trans}{$key} for multiple accounts
1603     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1604       $ref->{exchangerate} =
1605         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate},
1606                                 $fld);
1607
1608       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
1609     }
1610     $sth->finish;
1611
1612     $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans,
1613                   (SELECT c.accno FROM chart c
1614                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1615                   (SELECT c.accno FROM chart c
1616                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1617                 FROM defaults d|;
1618     $sth = $dbh->prepare($query);
1619     $sth->execute || $self->dberror($query);
1620
1621     $ref = $sth->fetchrow_hashref(NAME_lc);
1622     map { $self->{$_} = $ref->{$_} } keys %$ref;
1623     $sth->finish;
1624
1625   } else {
1626
1627     # get date
1628     $query = qq|SELECT current_date AS transdate,
1629                 d.curr AS currencies, d.closedto, d.revtrans,
1630                   (SELECT c.accno FROM chart c
1631                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1632                   (SELECT c.accno FROM chart c
1633                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1634                 FROM defaults d|;
1635     $sth = $dbh->prepare($query);
1636     $sth->execute || $self->dberror($query);
1637
1638     $ref = $sth->fetchrow_hashref(NAME_lc);
1639     map { $self->{$_} = $ref->{$_} } keys %$ref;
1640     $sth->finish;
1641
1642     if ($self->{"$self->{vc}_id"}) {
1643
1644       # only setup currency
1645       ($self->{currency}) = split /:/, $self->{currencies};
1646
1647     } else {
1648
1649       $self->lastname_used($dbh, $myconfig, $table, $module);
1650
1651       my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1652
1653       # get exchangerate for currency
1654       $self->{exchangerate} =
1655         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1656                                 $fld);
1657
1658     }
1659
1660   }
1661
1662   $dbh->disconnect;
1663
1664   $main::lxdebug->leave_sub();
1665 }
1666
1667 sub lastname_used {
1668   $main::lxdebug->enter_sub();
1669
1670   my ($self, $dbh, $myconfig, $table, $module) = @_;
1671
1672   my $arap  = ($table eq 'customer') ? "ar" : "ap";
1673   my $where = "1 = 1";
1674
1675   if ($self->{type} =~ /_order/) {
1676     $arap  = 'oe';
1677     $where = "quotation = '0'";
1678   }
1679   if ($self->{type} =~ /_quotation/) {
1680     $arap  = 'oe';
1681     $where = "quotation = '1'";
1682   }
1683
1684   my $query = qq|SELECT id FROM $arap
1685                  WHERE id IN (SELECT MAX(id) FROM $arap
1686                               WHERE $where
1687                               AND ${table}_id > 0)|;
1688   my $sth = $dbh->prepare($query);
1689   $sth->execute || $self->dberror($query);
1690
1691   my ($trans_id) = $sth->fetchrow_array;
1692   $sth->finish;
1693
1694   $trans_id *= 1;
1695   $query = qq|SELECT ct.name, a.curr, a.${table}_id,
1696               current_date + ct.terms AS duedate, a.department_id,
1697               d.description AS department
1698               FROM $arap a
1699               JOIN $table ct ON (a.${table}_id = ct.id)
1700               LEFT JOIN department d ON (a.department_id = d.id)
1701               WHERE a.id = $trans_id|;
1702   $sth = $dbh->prepare($query);
1703   $sth->execute || $self->dberror($query);
1704
1705   ($self->{$table},  $self->{currency},      $self->{"${table}_id"},
1706    $self->{duedate}, $self->{department_id}, $self->{department})
1707     = $sth->fetchrow_array;
1708   $sth->finish;
1709
1710   $main::lxdebug->leave_sub();
1711 }
1712
1713 sub current_date {
1714   $main::lxdebug->enter_sub();
1715
1716   my ($self, $myconfig, $thisdate, $days) = @_;
1717
1718   my $dbh = $self->dbconnect($myconfig);
1719   my ($sth, $query);
1720
1721   $days *= 1;
1722   if ($thisdate) {
1723     my $dateformat = $myconfig->{dateformat};
1724     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1725
1726     $query = qq|SELECT to_date('$thisdate', '$dateformat') + $days AS thisdate
1727                 FROM defaults|;
1728     $sth = $dbh->prepare($query);
1729     $sth->execute || $self->dberror($query);
1730   } else {
1731     $query = qq|SELECT current_date AS thisdate
1732                 FROM defaults|;
1733     $sth = $dbh->prepare($query);
1734     $sth->execute || $self->dberror($query);
1735   }
1736
1737   ($thisdate) = $sth->fetchrow_array;
1738   $sth->finish;
1739
1740   $dbh->disconnect;
1741
1742   $main::lxdebug->leave_sub();
1743
1744   return $thisdate;
1745 }
1746
1747 sub like {
1748   $main::lxdebug->enter_sub();
1749
1750   my ($self, $string) = @_;
1751
1752   if ($string !~ /%/) {
1753     $string = "%$string%";
1754   }
1755
1756   $string =~ s/\'/\'\'/g;
1757
1758   $main::lxdebug->leave_sub();
1759
1760   return $string;
1761 }
1762
1763 sub redo_rows {
1764   $main::lxdebug->enter_sub();
1765
1766   my ($self, $flds, $new, $count, $numrows) = @_;
1767
1768   my @ndx = ();
1769
1770   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
1771     (1 .. $count);
1772
1773   my $i = 0;
1774
1775   # fill rows
1776   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
1777     $i++;
1778     $j = $item->{ndx} - 1;
1779     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
1780   }
1781
1782   # delete empty rows
1783   for $i ($count + 1 .. $numrows) {
1784     map { delete $self->{"${_}_$i"} } @{$flds};
1785   }
1786
1787   $main::lxdebug->leave_sub();
1788 }
1789
1790 sub update_status {
1791   $main::lxdebug->enter_sub();
1792
1793   my ($self, $myconfig) = @_;
1794
1795   my ($i, $id);
1796
1797   my $dbh = $self->dbconnect_noauto($myconfig);
1798
1799   my $query = qq|DELETE FROM status
1800                  WHERE formname = '$self->{formname}'
1801                  AND trans_id = ?|;
1802   my $sth = $dbh->prepare($query) || $self->dberror($query);
1803
1804   if ($self->{formname} =~ /(check|receipt)/) {
1805     for $i (1 .. $self->{rowcount}) {
1806       $sth->execute($self->{"id_$i"} * 1) || $self->dberror($query);
1807       $sth->finish;
1808     }
1809   } else {
1810     $sth->execute($self->{id}) || $self->dberror($query);
1811     $sth->finish;
1812   }
1813
1814   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
1815   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
1816
1817   my %queued = split / /, $self->{queued};
1818
1819   if ($self->{formname} =~ /(check|receipt)/) {
1820
1821     # this is a check or receipt, add one entry for each lineitem
1822     my ($accno) = split /--/, $self->{account};
1823     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname,
1824                 chart_id) VALUES (?, '$printed',
1825                 '$queued{$self->{formname}}', '$self->{prinform}',
1826                 (SELECT c.id FROM chart c WHERE c.accno = '$accno'))|;
1827     $sth = $dbh->prepare($query) || $self->dberror($query);
1828
1829     for $i (1 .. $self->{rowcount}) {
1830       if ($self->{"checked_$i"}) {
1831         $sth->execute($self->{"id_$i"}) || $self->dberror($query);
1832         $sth->finish;
1833       }
1834     }
1835   } else {
1836     $query = qq|INSERT INTO status (trans_id, printed, emailed,
1837                 spoolfile, formname)
1838                 VALUES ($self->{id}, '$printed', '$emailed',
1839                 '$queued{$self->{formname}}', '$self->{formname}')|;
1840     $dbh->do($query) || $self->dberror($query);
1841   }
1842
1843   $dbh->commit;
1844   $dbh->disconnect;
1845
1846   $main::lxdebug->leave_sub();
1847 }
1848
1849 sub save_status {
1850   $main::lxdebug->enter_sub();
1851
1852   my ($self, $dbh) = @_;
1853
1854   my ($query, $printed, $emailed);
1855
1856   my $formnames  = $self->{printed};
1857   my $emailforms = $self->{emailed};
1858
1859   my $query = qq|DELETE FROM status
1860                  WHERE formname = '$self->{formname}'
1861                  AND trans_id = $self->{id}|;
1862   $dbh->do($query) || $self->dberror($query);
1863
1864   # this only applies to the forms
1865   # checks and receipts are posted when printed or queued
1866
1867   if ($self->{queued}) {
1868     my %queued = split / /, $self->{queued};
1869
1870     foreach my $formname (keys %queued) {
1871       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
1872       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
1873
1874       $query = qq|INSERT INTO status (trans_id, printed, emailed,
1875                   spoolfile, formname)
1876                   VALUES ($self->{id}, '$printed', '$emailed',
1877                   '$queued{$formname}', '$formname')|;
1878       $dbh->do($query) || $self->dberror($query);
1879
1880       $formnames  =~ s/$self->{formname}//;
1881       $emailforms =~ s/$self->{formname}//;
1882
1883     }
1884   }
1885
1886   # save printed, emailed info
1887   $formnames  =~ s/^ +//g;
1888   $emailforms =~ s/^ +//g;
1889
1890   my %status = ();
1891   map { $status{$_}{printed} = 1 } split / +/, $formnames;
1892   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
1893
1894   foreach my $formname (keys %status) {
1895     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
1896     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
1897
1898     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
1899                 VALUES ($self->{id}, '$printed', '$emailed', '$formname')|;
1900     $dbh->do($query) || $self->dberror($query);
1901   }
1902
1903   $main::lxdebug->leave_sub();
1904 }
1905
1906 sub update_defaults {
1907   $main::lxdebug->enter_sub();
1908
1909   my ($self, $myconfig, $fld) = @_;
1910
1911   my $dbh   = $self->dbconnect_noauto($myconfig);
1912   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
1913   my $sth   = $dbh->prepare($query);
1914
1915   $sth->execute || $self->dberror($query);
1916   my ($var) = $sth->fetchrow_array;
1917   $sth->finish;
1918
1919   $var++;
1920
1921   $query = qq|UPDATE defaults
1922               SET $fld = '$var'|;
1923   $dbh->do($query) || $form->dberror($query);
1924
1925   $dbh->commit;
1926   $dbh->disconnect;
1927
1928   $main::lxdebug->leave_sub();
1929
1930   return $var;
1931 }
1932
1933 sub update_business {
1934   $main::lxdebug->enter_sub();
1935
1936   my ($self, $myconfig, $business_id) = @_;
1937
1938   my $dbh   = $self->dbconnect_noauto($myconfig);
1939   my $query =
1940     qq|SELECT customernumberinit FROM business  WHERE id=$business_id FOR UPDATE|;
1941   my $sth = $dbh->prepare($query);
1942
1943   $sth->execute || $self->dberror($query);
1944   my ($var) = $sth->fetchrow_array;
1945   $sth->finish;
1946   if ($var ne "") {
1947     $var++;
1948   }
1949   $query = qq|UPDATE business
1950               SET customernumberinit = '$var' WHERE id=$business_id|;
1951   $dbh->do($query) || $form->dberror($query);
1952
1953   $dbh->commit;
1954   $dbh->disconnect;
1955
1956   $main::lxdebug->leave_sub();
1957
1958   return $var;
1959 }
1960
1961 sub get_salesman {
1962   $main::lxdebug->enter_sub();
1963
1964   my ($self, $myconfig, $salesman) = @_;
1965
1966   my $dbh   = $self->dbconnect($myconfig);
1967   my $query =
1968     qq|SELECT id, name FROM customer  WHERE (customernumber ilike '%$salesman%' OR name ilike '%$salesman%') AND business_id in (SELECT id from business WHERE salesman)|;
1969   my $sth = $dbh->prepare($query);
1970   $sth->execute || $self->dberror($query);
1971
1972   my $i = 0;
1973   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1974     push(@{ $self->{salesman_list} }, $ref);
1975     $i++;
1976   }
1977   $dbh->commit;
1978   $main::lxdebug->leave_sub();
1979
1980   return $i;
1981 }
1982
1983 sub get_partsgroup {
1984   $main::lxdebug->enter_sub();
1985
1986   my ($self, $myconfig, $p) = @_;
1987
1988   my $dbh = $self->dbconnect($myconfig);
1989
1990   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
1991                  FROM partsgroup pg
1992                  JOIN parts p ON (p.partsgroup_id = pg.id)|;
1993
1994   if ($p->{searchitems} eq 'part') {
1995     $query .= qq|
1996                  WHERE p.inventory_accno_id > 0|;
1997   }
1998   if ($p->{searchitems} eq 'service') {
1999     $query .= qq|
2000                  WHERE p.inventory_accno_id IS NULL|;
2001   }
2002   if ($p->{searchitems} eq 'assembly') {
2003     $query .= qq|
2004                  WHERE p.assembly = '1'|;
2005   }
2006   if ($p->{searchitems} eq 'labor') {
2007     $query .= qq|
2008                  WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
2009   }
2010
2011   $query .= qq|
2012                  ORDER BY partsgroup|;
2013
2014   if ($p->{all}) {
2015     $query = qq|SELECT id, partsgroup FROM partsgroup
2016                 ORDER BY partsgroup|;
2017   }
2018
2019   if ($p->{language_code}) {
2020     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2021                 t.description AS translation
2022                 FROM partsgroup pg
2023                 JOIN parts p ON (p.partsgroup_id = pg.id)
2024                 LEFT JOIN translation t ON (t.trans_id = pg.id AND t.language_code = '$p->{language_code}')
2025                 ORDER BY translation|;
2026   }
2027
2028   my $sth = $dbh->prepare($query);
2029   $sth->execute || $self->dberror($query);
2030
2031   $self->{all_partsgroup} = ();
2032   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2033     push @{ $self->{all_partsgroup} }, $ref;
2034   }
2035   $sth->finish;
2036   $dbh->disconnect;
2037   $main::lxdebug->leave_sub();
2038 }
2039
2040 package Locale;
2041
2042 sub new {
2043   $main::lxdebug->enter_sub();
2044
2045   my ($type, $country, $NLS_file) = @_;
2046   my $self = {};
2047
2048   %self = ();
2049   if ($country && -d "locale/$country") {
2050     $self->{countrycode} = $country;
2051     eval { require "locale/$country/$NLS_file"; };
2052   }
2053
2054   $self->{NLS_file} = $NLS_file;
2055
2056   push @{ $self->{LONG_MONTH} },
2057     ("January",   "February", "March",    "April",
2058      "May ",      "June",     "July",     "August",
2059      "September", "October",  "November", "December");
2060   push @{ $self->{SHORT_MONTH} },
2061     (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
2062
2063   $main::lxdebug->leave_sub();
2064
2065   bless $self, $type;
2066 }
2067
2068 sub text {
2069   my ($self, $text) = @_;
2070
2071   return (exists $self{texts}{$text}) ? $self{texts}{$text} : $text;
2072 }
2073
2074 sub findsub {
2075   $main::lxdebug->enter_sub();
2076
2077   my ($self, $text) = @_;
2078
2079   if (exists $self{subs}{$text}) {
2080     $text = $self{subs}{$text};
2081   } else {
2082     if ($self->{countrycode} && $self->{NLS_file}) {
2083       Form->error(
2084          "$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
2085     }
2086   }
2087
2088   $main::lxdebug->leave_sub();
2089
2090   return $text;
2091 }
2092
2093 sub date {
2094   $main::lxdebug->enter_sub();
2095
2096   my ($self, $myconfig, $date, $longformat) = @_;
2097
2098   my $longdate  = "";
2099   my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
2100
2101   if ($date) {
2102
2103     # get separator
2104     $spc = $myconfig->{dateformat};
2105     $spc =~ s/\w//g;
2106     $spc = substr($spc, 1, 1);
2107
2108     if ($date =~ /\D/) {
2109       if ($myconfig->{dateformat} =~ /^yy/) {
2110         ($yy, $mm, $dd) = split /\D/, $date;
2111       }
2112       if ($myconfig->{dateformat} =~ /^mm/) {
2113         ($mm, $dd, $yy) = split /\D/, $date;
2114       }
2115       if ($myconfig->{dateformat} =~ /^dd/) {
2116         ($dd, $mm, $yy) = split /\D/, $date;
2117       }
2118     } else {
2119       $date = substr($date, 2);
2120       ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2121     }
2122
2123     $dd *= 1;
2124     $mm--;
2125     $yy = ($yy < 70) ? $yy + 2000 : $yy;
2126     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2127
2128     if ($myconfig->{dateformat} =~ /^dd/) {
2129       if (defined $longformat && $longformat == 0) {
2130         $mm++;
2131         $dd = "0$dd" if ($dd < 10);
2132         $mm = "0$mm" if ($mm < 10);
2133         $longdate = "$dd$spc$mm$spc$yy";
2134       } else {
2135         $longdate = "$dd";
2136         $longdate .= ($spc eq '.') ? ". " : " ";
2137         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2138       }
2139     } elsif ($myconfig->{dateformat} eq "yyyy-mm-dd") {
2140
2141       # Use German syntax with the ISO date style "yyyy-mm-dd" because
2142       # Lx-Office is mainly used in Germany or German speaking countries.
2143       if (defined $longformat && $longformat == 0) {
2144         $mm++;
2145         $dd = "0$dd" if ($dd < 10);
2146         $mm = "0$mm" if ($mm < 10);
2147         $longdate = "$yy-$mm-$dd";
2148       } else {
2149         $longdate = "$dd. ";
2150         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2151       }
2152     } else {
2153       if (defined $longformat && $longformat == 0) {
2154         $mm++;
2155         $dd = "0$dd" if ($dd < 10);
2156         $mm = "0$mm" if ($mm < 10);
2157         $longdate = "$mm$spc$dd$spc$yy";
2158       } else {
2159         $longdate = &text($self, $self->{$longmonth}[$mm]) . " $dd, $yy";
2160       }
2161     }
2162
2163   }
2164
2165   $main::lxdebug->leave_sub();
2166
2167   return $longdate;
2168 }
2169
2170 sub parse_date {
2171   $main::lxdebug->enter_sub();
2172
2173   my ($self, $myconfig, $date, $longformat) = @_;
2174
2175   unless ($date) {
2176     $main::lxdebug->leave_sub();
2177     return ();
2178   }
2179
2180   # get separator
2181   $spc = $myconfig->{dateformat};
2182   $spc =~ s/\w//g;
2183   $spc = substr($spc, 1, 1);
2184
2185   if ($date =~ /\D/) {
2186     if ($myconfig->{dateformat} =~ /^yy/) {
2187       ($yy, $mm, $dd) = split /\D/, $date;
2188     } elsif ($myconfig->{dateformat} =~ /^mm/) {
2189       ($mm, $dd, $yy) = split /\D/, $date;
2190     } elsif ($myconfig->{dateformat} =~ /^dd/) {
2191       ($dd, $mm, $yy) = split /\D/, $date;
2192     }
2193   } else {
2194     $date = substr($date, 2);
2195     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2196   }
2197
2198   $dd *= 1;
2199   $mm *= 1;
2200   $yy = ($yy < 70) ? $yy + 2000 : $yy;
2201   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2202
2203   $main::lxdebug->leave_sub();
2204   return ($yy, $mm, $dd);
2205 }
2206
2207 1;