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