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