Vorbereitungen zu den Variablenanpassungen.
[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   # The old fixed notation of <%variable%> is changed to a new dynamic one.
755   my ${pre} = '<%'; # Variable Prefix, must be regex save!
756   my ${suf} = '%>'; # Variable Suffix, must be regex save!
757
758
759   # Make sure that all *notes* (intnotes, partnotes_*, notes etc) are converted to markup correctly.
760   $self->format_string(grep(/notes/, keys(%{$self})));
761
762   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
763   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
764
765   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
766       qw(email tel fax name signature company address businessnumber));
767
768   open(IN, "$self->{templates}/$self->{IN}")
769     or $self->error("$self->{IN} : $!");
770
771   @_ = <IN>;
772   close(IN);
773
774   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
775
776   # OUT is used for the media, screen, printer, email
777   # for postscript we store a copy in a temporary file
778   my $fileid = time;
779   $self->{tmpfile} = "$userspath/${fileid}.$self->{IN}";
780   if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
781     $out = $self->{OUT};
782     $self->{OUT} = ">$self->{tmpfile}";
783   }
784
785   if ($self->{OUT}) {
786     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
787   } else {
788     open(OUT, ">-") or $self->error("STDOUT : $!");
789     $self->header;
790   }
791
792   # Do we have to run LaTeX two times? This is needed if
793   # the template contains page references.
794   $two_passes = 0;
795
796   # first we generate a tmpfile
797   # read file and replace ${pre}variable${suf}
798   while ($_ = shift) {
799
800     $par = "";
801     $var = $_;
802  
803     # Switch ${pre}analyse${suf} for template checking
804     # If ${pre}analyse${suf} is set in the template, you'll find the 
805     # parsed output in the user Directory for analysing
806     # Latex errors
807     # ${pre}analyse${suf} is a switch (allways off, on if set), not a Variable
808     # Set $form->{analysing}="" for system state: never analyse.
809     # Set $form->{analysing}="1" for system state: ever analyse.
810     $self->{analysing} = "1" if (/${pre}analyse${suf}/ && !defined $self->{analysing});    
811     
812     $two_passes = 1 if (/\\pageref/);
813
814     # { Moritz Bunkus
815     # detect pagebreak block and its parameters
816     if (/\s*${pre}pagebreak ([0-9]+) ([0-9]+) ([0-9]+)${suf}/) {
817       $chars_per_line       = $1;
818       $lines_on_first_page  = $2;
819       $lines_on_second_page = $3;
820
821       while ($_ = shift) {
822         last if (/\s*${pre}end pagebreak${suf}/);
823         $pagebreak .= $_;
824       }
825     }
826
827     # } Moritz Bunkus
828     
829     if (/\s*${pre}foreach /) {
830
831       # this one we need for the count
832       chomp $var;
833       $var =~ s/\s*${pre}foreach (.+?)${suf}/$1/;
834       while ($_ = shift) {
835         last if (/\s*${pre}end /);
836
837         # store line in $par
838         $par .= $_;
839       }
840
841       # display contents of $self->{number}[] array
842       for $i (0 .. $#{ $self->{$var} }) {
843
844         # { Moritz Bunkus
845         # Try to detect whether a manual page break is necessary
846         # but only if there was a ${pre}pagebreak ...${suf} block before
847
848         if ($chars_per_line) {
849           my $lines =
850             int(length($self->{"description"}[$i]) / $chars_per_line + 0.95);
851           my $lpp;
852
853           my $_description = $self->{"description"}[$i];
854           while ($_description =~ /\\newline/) {
855             $lines++;
856             $_description =~ s/\\newline//;
857           }
858           $self->{"description"}[$i] =~ s/(\\newline\s?)*$//;
859
860           if ($current_page == 1) {
861             $lpp = $lines_on_first_page;
862           } else {
863             $lpp = $lines_on_second_page;
864           }
865
866           # Yes we need a manual page break -- or the user has forced one
867           if (
868              (($current_line + $lines) > $lpp)
869              || ($self->{"_forced_pagebreaks"}
870                && grep(/^${current_row}$/, @{ $self->{"_forced_pagebreaks"} }))
871             ) {
872             my $pb = $pagebreak;
873
874             # replace the special variables ${pre}sumcarriedforward${suf}
875             # and ${pre}lastpage${suf}
876
877             my $psum = $self->format_amount($myconfig, $sum, 2);
878             $pb =~ s/${pre}sumcarriedforward${suf}/$psum/g;
879             $pb =~ s/${pre}lastpage${suf}/$current_page/g;
880
881             # only "normal" variables are supported here
882             # (no ${pre}if, no ${pre}foreach, no ${pre}include)
883
884             $pb =~ s/${pre}(.+?)${suf}/$self->{$1}/g;
885
886             # page break block is ready to rock
887             print(OUT $pb);
888             $current_page++;
889             $current_line = 1;
890           }
891           $current_line += $lines;
892           $current_row++;
893         }
894         $sum += $self->parse_amount($myconfig, $self->{"linetotal"}[$i]);
895
896         # } Moritz Bunkus
897
898         # don't parse par, we need it for each line
899         $_ = $par;
900         s/${pre}(.+?)${suf}/$self->{$1}[$i]/mg;
901         print OUT;
902       }
903       next;
904     }
905
906     # if not comes before if!
907     if (/\s*${pre}if not /) {
908
909       # check if it is not set and display
910       chop;
911       s/\s*${pre}if not (.+?)${suf}/$1/;
912
913       unless ($self->{$_}) {
914         while ($_ = shift) {
915           last if (/\s*${pre}end /);
916
917           # store line in $par
918           $par .= $_;
919         }
920
921         $_ = $par;
922
923       } else {
924         while ($_ = shift) {
925           last if (/\s*${pre}end /);
926         }
927         next;
928       }
929     }
930
931     if (/\s*${pre}if /) {
932
933       # check if it is set and display
934       chop;
935       s/\s*${pre}if (.+?)${suf}/$1/;
936
937       if ($self->{$_}) {
938         while ($_ = shift) {
939           last if (/\s*${pre}end /);
940
941           # store line in $par
942           $par .= $_;
943         }
944
945         $_ = $par;
946
947       } else {
948         while ($_ = shift) {
949           last if (/\s*${pre}end /);
950         }
951         next;
952       }
953     }
954
955     # check for ${pre}include filename${suf}
956     if (/\s*${pre}include /) {
957
958       # get the directory/filename
959       chomp $var;
960       $var =~ s/\s*${pre}include (.+?)${suf}/$1/;
961
962       # mangle filename on basedir
963       $var =~ s/^(\/|\.\.)//g;
964
965       # prevent the infinite loop!
966       next if ($self->{"$var"});
967
968       open(INC, "$self->{templates}/$var")
969         or $self->error($self->cleanup . "$self->{templates}/$var : $!");
970       unshift(@_, <INC>);
971       close(INC);
972
973       $self->{"$var"} = 1;
974
975       next;
976     }
977
978     s/${pre}(.+?)${suf}/$self->{$1}/g;
979     s/<nobr><\/nobr>/&nbsp;/g;
980     print OUT;
981   }
982
983   close(OUT);
984
985   # { Moritz Bunkus
986   # Convert the tex file to postscript
987   if ($self->{format} =~ /(postscript|pdf)/) {
988
989     use Cwd;
990     $self->{cwd}    = cwd();
991     $self->{tmpdir} = "$self->{cwd}/$userspath";
992
993     chdir("$userspath") or $self->error($self->cleanup . "chdir : $!");
994
995     $self->{tmpfile} =~ s/$userspath\///g;
996
997     if ($self->{format} eq 'postscript') {
998       system(
999         "latex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
1000       );
1001       $self->error($self->cleanup) if ($?);
1002       if ($two_passes) {
1003         system(
1004           "latex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
1005         );
1006         $self->error($self->cleanup) if ($?);
1007       }
1008
1009       $self->{tmpfile} =~ s/tex$/dvi/;
1010
1011       system("dvips $self->{tmpfile} -o -q > /dev/null");
1012       $self->error($self->cleanup . "dvips : $!") if ($?);
1013       $self->{tmpfile} =~ s/dvi$/ps/;
1014     }
1015     if ($self->{format} eq 'pdf') {
1016       system(
1017         "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
1018       );
1019       $self->error($self->cleanup) if ($?);
1020       if ($two_passes) {
1021         system(
1022           "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
1023         );
1024         $self->error($self->cleanup) if ($?);
1025       }
1026       $self->{tmpfile} =~ s/tex$/pdf/;
1027     }
1028
1029   }
1030
1031   if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
1032
1033     if ($self->{media} eq 'email') {
1034
1035       use SL::Mailer;
1036
1037       my $mail = new Mailer;
1038
1039       map { $mail->{$_} = $self->{$_} }
1040         qw(cc bcc subject message version format charset);
1041       $mail->{to}     = qq|$self->{email}|;
1042       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1043       $mail->{fileid} = "$fileid.";
1044
1045       # if we send html or plain text inline
1046       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1047         $mail->{contenttype} = "text/html";
1048
1049         $mail->{message}       =~ s/\r\n/<br>\n/g;
1050         $myconfig->{signature} =~ s/\\n/<br>\n/g;
1051         $mail->{message} .= "<br>\n--<br>\n$myconfig->{signature}\n<br>";
1052
1053         open(IN, $self->{tmpfile})
1054           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1055         while (<IN>) {
1056           $mail->{message} .= $_;
1057         }
1058
1059         close(IN);
1060
1061       } else {
1062
1063         @{ $mail->{attachments} } = ($self->{tmpfile});
1064
1065         $myconfig->{signature} =~ s/\\n/\r\n/g;
1066         $mail->{message} .= "\r\n--\r\n$myconfig->{signature}";
1067
1068       }
1069
1070       my $err = $mail->send($out);
1071       $self->error($self->cleanup . "$err") if ($err);
1072
1073     } else {
1074
1075       $self->{OUT} = $out;
1076
1077       my $numbytes = (-s $self->{tmpfile});
1078       open(IN, $self->{tmpfile})
1079         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1080
1081       $self->{copies} = 1 unless $self->{media} eq 'printer';
1082
1083       chdir("$self->{cwd}");
1084
1085       for my $i (1 .. $self->{copies}) {
1086         if ($self->{OUT}) {
1087           open(OUT, $self->{OUT})
1088             or $self->error($self->cleanup . "$self->{OUT} : $!");
1089         } else {
1090
1091           # launch application
1092           print qq|Content-Type: application/$self->{format}
1093 Content-Disposition: attachment; filename="$self->{tmpfile}"
1094 Content-Length: $numbytes
1095
1096 |;
1097
1098           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1099
1100         }
1101
1102         while (<IN>) {
1103           print OUT $_;
1104         }
1105
1106         close(OUT);
1107
1108         seek IN, 0, 0;
1109       }
1110
1111       close(IN);
1112     }
1113
1114   }
1115
1116   $self->cleanup;
1117
1118   chdir("$self->{cwd}");
1119   $main::lxdebug->leave_sub();
1120 }
1121
1122 sub cleanup {
1123   $main::lxdebug->enter_sub();
1124
1125   my $self = shift;
1126
1127   chdir("$self->{tmpdir}");
1128
1129   my @err = ();
1130   if (-f "$self->{tmpfile}.err") {
1131     open(FH, "$self->{tmpfile}.err");
1132     @err = <FH>;
1133     close(FH);
1134   }
1135
1136   if ($self->{analysing} eq "") {
1137     if ($self->{tmpfile}) {
1138
1139       # strip extension
1140       $self->{tmpfile} =~ s/\.\w+$//g;  
1141       my $tmpfile = $self->{tmpfile};
1142       unlink(<$tmpfile.*>);
1143     }
1144   }
1145
1146   chdir("$self->{cwd}");
1147
1148   $main::lxdebug->leave_sub();
1149
1150   return "@err";
1151 }
1152
1153 sub format_string {
1154   $main::lxdebug->enter_sub();
1155
1156   my ($self, @fields) = @_;
1157   my %unique_fields;
1158
1159   %unique_fields = map({ $_ => 1 } @fields);
1160   @fields        = keys(%unique_fields);
1161
1162   foreach my $field (@fields) {
1163     next unless ($self->{$field} =~ /\<pagebreak\>/);
1164     $self->{$field} =~ s/\<pagebreak\>//g;
1165     if ($field =~ /.*_(\d+)$/) {
1166       if (!$self->{"_forced_pagebreaks"}) {
1167         $self->{"_forced_pagebreaks"} = [];
1168       }
1169       push(@{ $self->{"_forced_pagebreaks"} }, "$1");
1170     }
1171   }
1172
1173   my $format = $self->{format};
1174   if ($self->{format} =~ /(postscript|pdf)/) {
1175     $format = 'tex';
1176   }
1177
1178   my %replace = (
1179     'order' => {
1180       'html' => [
1181         '<', '>', quotemeta('\n'), '
1182 '
1183       ],
1184       'tex' => [
1185         '&', quotemeta('\n'), '
1186 ',
1187         '"', '\$', '%', '_', '#', quotemeta('^'),
1188         '{', '}',  '<', '>', '£', "\r", '²'
1189       ]
1190     },
1191     'html' => {
1192       '<'             => '&lt;',
1193       '>'             => '&gt;',
1194       quotemeta('\n') => '<br>',
1195       '
1196 ' => '<br>'
1197     },
1198     'tex' => {
1199       '"'             => "''",
1200       '&'             => '\&',
1201       '\$'            => '\$',
1202       '%'             => '\%',
1203       '_'             => '\_',
1204       '#'             => '\#',
1205       quotemeta('^')  => '\^\\',
1206       '{'             => '\{',
1207       '}'             => '\}',
1208       '<'             => '$<$',
1209       '>'             => '$>$',
1210       quotemeta('\n') => '\newline ',
1211       '
1212 '          => '\newline ',
1213       '£'  => '\pounds ',
1214       '²'  => '$^2$',
1215       "\r" => ""
1216     });
1217
1218   foreach my $key (@{ $replace{order}{$format} }) {
1219     map { $self->{$_} =~ s/$key/$replace{$format}{$key}/g; } @fields;
1220   }
1221
1222   # Allow some HTML markup to be converted into the output format's
1223   # corresponding markup code, e.g. bold or italic.
1224   if ('html' eq $format) {
1225     my @markup_replace = ('b', 'i', 's', 'u');
1226
1227     foreach my $key (@markup_replace) {
1228       map({ $self->{$_} =~ s/\&lt;(\/?)${key}\&gt;/<$1${key}>/g } @fields);
1229     }
1230
1231   } elsif ('tex' eq $format) {
1232     my %markup_replace = ('b' => 'textbf',
1233                           'i' => 'textit',
1234                           'u' => 'underline');
1235
1236     foreach my $field (@fields) {
1237       foreach my $key (keys(%markup_replace)) {
1238         my $new = $markup_replace{$key};
1239         $self->{$field} =~
1240           s/\$\<\$${key}\$\>\$(.*?)\$<\$\/${key}\$>\$/\\${new}\{$1\}/gi;
1241       }
1242     }
1243   }
1244
1245   $main::lxdebug->leave_sub();
1246 }
1247
1248 sub datetonum {
1249   $main::lxdebug->enter_sub();
1250
1251   my ($self, $date, $myconfig) = @_;
1252
1253   if ($date && $date =~ /\D/) {
1254
1255     if ($myconfig->{dateformat} =~ /^yy/) {
1256       ($yy, $mm, $dd) = split /\D/, $date;
1257     }
1258     if ($myconfig->{dateformat} =~ /^mm/) {
1259       ($mm, $dd, $yy) = split /\D/, $date;
1260     }
1261     if ($myconfig->{dateformat} =~ /^dd/) {
1262       ($dd, $mm, $yy) = split /\D/, $date;
1263     }
1264
1265     $dd *= 1;
1266     $mm *= 1;
1267     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1268     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1269
1270     $dd = "0$dd" if ($dd < 10);
1271     $mm = "0$mm" if ($mm < 10);
1272
1273     $date = "$yy$mm$dd";
1274   }
1275
1276   $main::lxdebug->leave_sub();
1277
1278   return $date;
1279 }
1280
1281 # Database routines used throughout
1282
1283 sub dbconnect {
1284   $main::lxdebug->enter_sub();
1285
1286   my ($self, $myconfig) = @_;
1287
1288   # connect to database
1289   my $dbh =
1290     DBI->connect($myconfig->{dbconnect},
1291                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1292     or $self->dberror;
1293
1294   # set db options
1295   if ($myconfig->{dboptions}) {
1296     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1297   }
1298
1299   $main::lxdebug->leave_sub();
1300
1301   return $dbh;
1302 }
1303
1304 sub dbconnect_noauto {
1305   $main::lxdebug->enter_sub();
1306
1307   my ($self, $myconfig) = @_;
1308
1309   # connect to database
1310   $dbh =
1311     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1312                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1313     or $self->dberror;
1314
1315   # set db options
1316   if ($myconfig->{dboptions}) {
1317     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1318   }
1319
1320   $main::lxdebug->leave_sub();
1321
1322   return $dbh;
1323 }
1324
1325 sub update_balance {
1326   $main::lxdebug->enter_sub();
1327
1328   my ($self, $dbh, $table, $field, $where, $value) = @_;
1329
1330   # if we have a value, go do it
1331   if ($value != 0) {
1332
1333     # retrieve balance from table
1334     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1335     my $sth   = $dbh->prepare($query);
1336
1337     $sth->execute || $self->dberror($query);
1338     my ($balance) = $sth->fetchrow_array;
1339     $sth->finish;
1340
1341     $balance += $value;
1342
1343     # update balance
1344     $query = "UPDATE $table SET $field = $balance WHERE $where";
1345     $dbh->do($query) || $self->dberror($query);
1346   }
1347   $main::lxdebug->leave_sub();
1348 }
1349
1350 sub update_exchangerate {
1351   $main::lxdebug->enter_sub();
1352
1353   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1354
1355   # some sanity check for currency
1356   if ($curr eq '') {
1357     $main::lxdebug->leave_sub();
1358     return;
1359   }
1360
1361   my $query = qq|SELECT e.curr FROM exchangerate e
1362                  WHERE e.curr = '$curr'
1363                  AND e.transdate = '$transdate'
1364                  FOR UPDATE|;
1365   my $sth = $dbh->prepare($query);
1366   $sth->execute || $self->dberror($query);
1367
1368   my $set;
1369   if ($buy != 0 && $sell != 0) {
1370     $set = "buy = $buy, sell = $sell";
1371   } elsif ($buy != 0) {
1372     $set = "buy = $buy";
1373   } elsif ($sell != 0) {
1374     $set = "sell = $sell";
1375   }
1376
1377   if ($sth->fetchrow_array) {
1378     $query = qq|UPDATE exchangerate
1379                 SET $set
1380                 WHERE curr = '$curr'
1381                 AND transdate = '$transdate'|;
1382   } else {
1383     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1384                 VALUES ('$curr', $buy, $sell, '$transdate')|;
1385   }
1386   $sth->finish;
1387   $dbh->do($query) || $self->dberror($query);
1388
1389   $main::lxdebug->leave_sub();
1390 }
1391
1392 sub save_exchangerate {
1393   $main::lxdebug->enter_sub();
1394
1395   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1396
1397   my $dbh = $self->dbconnect($myconfig);
1398
1399   my ($buy, $sell) = (0, 0);
1400   $buy  = $rate if $fld eq 'buy';
1401   $sell = $rate if $fld eq 'sell';
1402
1403   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1404
1405   $dbh->disconnect;
1406
1407   $main::lxdebug->leave_sub();
1408 }
1409
1410 sub get_exchangerate {
1411   $main::lxdebug->enter_sub();
1412
1413   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1414
1415   unless ($transdate) {
1416     $main::lxdebug->leave_sub();
1417     return "";
1418   }
1419
1420   my $query = qq|SELECT e.$fld FROM exchangerate e
1421                  WHERE e.curr = '$curr'
1422                  AND e.transdate = '$transdate'|;
1423   my $sth = $dbh->prepare($query);
1424   $sth->execute || $self->dberror($query);
1425
1426   my ($exchangerate) = $sth->fetchrow_array;
1427   $sth->finish;
1428
1429   $main::lxdebug->leave_sub();
1430
1431   return $exchangerate;
1432 }
1433
1434 sub check_exchangerate {
1435   $main::lxdebug->enter_sub();
1436
1437   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1438
1439   unless ($transdate) {
1440     $main::lxdebug->leave_sub();
1441     return "";
1442   }
1443
1444   my $dbh = $self->dbconnect($myconfig);
1445
1446   my $query = qq|SELECT e.$fld FROM exchangerate e
1447                  WHERE e.curr = '$currency'
1448                  AND e.transdate = '$transdate'|;
1449   my $sth = $dbh->prepare($query);
1450   $sth->execute || $self->dberror($query);
1451
1452   my ($exchangerate) = $sth->fetchrow_array;
1453   $sth->finish;
1454   $dbh->disconnect;
1455
1456   $main::lxdebug->leave_sub();
1457
1458   return $exchangerate;
1459 }
1460
1461 sub add_shipto {
1462   $main::lxdebug->enter_sub();
1463
1464   my ($self, $dbh, $id) = @_;
1465 ##LINET
1466   my $shipto;
1467   foreach my $item (
1468     qw(name department_1 department_2 street zipcode city country contact phone fax email)
1469     ) {
1470     if ($self->{"shipto$item"}) {
1471       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1472     }
1473     $self->{"shipto$item"} =~ s/\'/\'\'/g;
1474   }
1475
1476   if ($shipto) {
1477     my $query =
1478       qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2, shiptostreet,
1479                    shiptozipcode, shiptocity, shiptocountry, shiptocontact,
1480                    shiptophone, shiptofax, shiptoemail) VALUES ($id,
1481                    '$self->{shiptoname}', '$self->{shiptodepartment_1}', '$self->{shiptodepartment_2}', '$self->{shiptostreet}',
1482                    '$self->{shiptozipcode}', '$self->{shiptocity}',
1483                    '$self->{shiptocountry}', '$self->{shiptocontact}',
1484                    '$self->{shiptophone}', '$self->{shiptofax}',
1485                    '$self->{shiptoemail}')|;
1486     $dbh->do($query) || $self->dberror($query);
1487   }
1488 ##/LINET
1489   $main::lxdebug->leave_sub();
1490 }
1491
1492 sub get_employee {
1493   $main::lxdebug->enter_sub();
1494
1495   my ($self, $dbh) = @_;
1496
1497   my $query = qq|SELECT e.id, e.name FROM employee e
1498                  WHERE e.login = '$self->{login}'|;
1499   my $sth = $dbh->prepare($query);
1500   $sth->execute || $self->dberror($query);
1501
1502   ($self->{employee_id}, $self->{employee}) = $sth->fetchrow_array;
1503   $self->{employee_id} *= 1;
1504
1505   $sth->finish;
1506
1507   $main::lxdebug->leave_sub();
1508 }
1509
1510 # get other contact for transaction and form - html/tex
1511 sub get_contact {
1512   $main::lxdebug->enter_sub();
1513
1514   my ($self, $dbh, $id) = @_;
1515
1516   my $query = qq|SELECT c.*
1517               FROM contacts c
1518               WHERE cp_id=$id|;
1519   $sth = $dbh->prepare($query);
1520   $sth->execute || $self->dberror($query);
1521
1522   $ref = $sth->fetchrow_hashref(NAME_lc);
1523
1524   push @{ $self->{$_} }, $ref;
1525
1526   $sth->finish;
1527   $main::lxdebug->leave_sub();
1528 }
1529
1530 # get contacts for id, if no contact return {"","","","",""}
1531 sub get_contacts {
1532   $main::lxdebug->enter_sub();
1533
1534   my ($self, $dbh, $id) = @_;
1535
1536   my $query = qq|SELECT c.cp_id, c.cp_cv_id, c.cp_name, c.cp_givenname
1537               FROM contacts c
1538               WHERE cp_cv_id=$id|;
1539   my $sth = $dbh->prepare($query);
1540   $sth->execute || $self->dberror($query);
1541
1542   my $i = 0;
1543   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1544     push @{ $self->{all_contacts} }, $ref;
1545     $i++;
1546   }
1547
1548   if ($i == 0) {
1549     push @{ $self->{all_contacts} }, { { "", "", "", "", "" } };
1550   }
1551   $sth->finish;
1552   $main::lxdebug->leave_sub();
1553 }
1554
1555 # this sub gets the id and name from $table
1556 sub get_name {
1557   $main::lxdebug->enter_sub();
1558
1559   my ($self, $myconfig, $table) = @_;
1560
1561   # connect to database
1562   my $dbh = $self->dbconnect($myconfig);
1563
1564   my $name           = $self->like(lc $self->{$table});
1565   my $customernumber = $self->like(lc $self->{customernumber});
1566
1567   if ($self->{customernumber} ne "") {
1568     $query = qq~SELECT c.id, c.name,
1569                   c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1570                   FROM $table c
1571                   WHERE (lower(c.customernumber) LIKE '$customernumber') AND (not c.obsolete)
1572                   ORDER BY c.name~;
1573   } else {
1574     $query = qq~SELECT c.id, c.name,
1575                  c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1576                  FROM $table c
1577                  WHERE (lower(c.name) LIKE '$name') AND (not c.obsolete)
1578                  ORDER BY c.name~;
1579   }
1580
1581   if ($self->{openinvoices}) {
1582     $query = qq~SELECT DISTINCT c.id, c.name,
1583                 c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1584                 FROM $self->{arap} a
1585                 JOIN $table c ON (a.${table}_id = c.id)
1586                 WHERE NOT a.amount = a.paid
1587                 AND lower(c.name) LIKE '$name'
1588                 ORDER BY c.name~;
1589   }
1590   my $sth = $dbh->prepare($query);
1591
1592   $sth->execute || $self->dberror($query);
1593
1594   my $i = 0;
1595   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1596     push(@{ $self->{name_list} }, $ref);
1597     $i++;
1598   }
1599   $sth->finish;
1600   $dbh->disconnect;
1601
1602   $main::lxdebug->leave_sub();
1603
1604   return $i;
1605 }
1606
1607 # the selection sub is used in the AR, AP, IS, IR and OE module
1608 #
1609 sub all_vc {
1610   $main::lxdebug->enter_sub();
1611
1612   my ($self, $myconfig, $table, $module) = @_;
1613
1614   my $ref;
1615   my $dbh = $self->dbconnect($myconfig);
1616
1617   my $query = qq|SELECT count(*) FROM $table|;
1618   my $sth   = $dbh->prepare($query);
1619   $sth->execute || $self->dberror($query);
1620   my ($count) = $sth->fetchrow_array;
1621   $sth->finish;
1622
1623   # build selection list
1624   if ($count < $myconfig->{vclimit}) {
1625     $query = qq|SELECT id, name
1626                 FROM $table WHERE not obsolete
1627                 ORDER BY name|;
1628     $sth = $dbh->prepare($query);
1629     $sth->execute || $self->dberror($query);
1630
1631     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1632       push @{ $self->{"all_$table"} }, $ref;
1633     }
1634
1635     $sth->finish;
1636
1637   }
1638
1639   # get self
1640   $self->get_employee($dbh);
1641
1642   # setup sales contacts
1643   $query = qq|SELECT e.id, e.name
1644               FROM employee e
1645               WHERE e.sales = '1'
1646               AND NOT e.id = $self->{employee_id}|;
1647   $sth = $dbh->prepare($query);
1648   $sth->execute || $self->dberror($query);
1649
1650   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1651     push @{ $self->{all_employees} }, $ref;
1652   }
1653   $sth->finish;
1654
1655   # this is for self
1656   push @{ $self->{all_employees} },
1657     { id   => $self->{employee_id},
1658       name => $self->{employee} };
1659
1660   # sort the whole thing
1661   @{ $self->{all_employees} } =
1662     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
1663
1664   if ($module eq 'AR') {
1665
1666     # prepare query for departments
1667     $query = qq|SELECT d.id, d.description
1668                 FROM department d
1669                 WHERE d.role = 'P'
1670                 ORDER BY 2|;
1671
1672   } else {
1673     $query = qq|SELECT d.id, d.description
1674                 FROM department d
1675                 ORDER BY 2|;
1676   }
1677
1678   $sth = $dbh->prepare($query);
1679   $sth->execute || $self->dberror($query);
1680
1681   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1682     push @{ $self->{all_departments} }, $ref;
1683   }
1684   $sth->finish;
1685
1686   $dbh->disconnect;
1687   $main::lxdebug->leave_sub();
1688 }
1689
1690 # this is only used for reports
1691 sub all_departments {
1692   $main::lxdebug->enter_sub();
1693
1694   my ($self, $myconfig, $table) = @_;
1695
1696   my $dbh   = $self->dbconnect($myconfig);
1697   my $where = "1 = 1";
1698
1699   if (defined $table) {
1700     if ($table eq 'customer') {
1701       $where = " d.role = 'P'";
1702     }
1703   }
1704
1705   my $query = qq|SELECT d.id, d.description
1706                  FROM department d
1707                  WHERE $where
1708                  ORDER BY 2|;
1709   my $sth = $dbh->prepare($query);
1710   $sth->execute || $self->dberror($query);
1711
1712   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1713     push @{ $self->{all_departments} }, $ref;
1714   }
1715   $sth->finish;
1716
1717   $dbh->disconnect;
1718
1719   $main::lxdebug->leave_sub();
1720 }
1721
1722 sub create_links {
1723   $main::lxdebug->enter_sub();
1724
1725   my ($self, $module, $myconfig, $table) = @_;
1726
1727   $self->all_vc($myconfig, $table, $module);
1728
1729   # get last customers or vendors
1730   my ($query, $sth);
1731
1732   my $dbh = $self->dbconnect($myconfig);
1733
1734   my %xkeyref = ();
1735
1736   # now get the account numbers
1737   $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id
1738               FROM chart c
1739               WHERE c.link LIKE '%$module%'
1740               ORDER BY c.accno|;
1741
1742   $sth = $dbh->prepare($query);
1743   $sth->execute || $self->dberror($query);
1744
1745   $self->{accounts} = "";
1746   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1747
1748     foreach my $key (split /:/, $ref->{link}) {
1749       if ($key =~ /$module/) {
1750
1751         # cross reference for keys
1752         $xkeyref{ $ref->{accno} } = $key;
1753
1754         push @{ $self->{"${module}_links"}{$key} },
1755           { accno       => $ref->{accno},
1756             description => $ref->{description},
1757             taxkey      => $ref->{taxkey_id} };
1758
1759         $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
1760       }
1761     }
1762   }
1763   $sth->finish;
1764
1765   if (($module eq "AP") || ($module eq "AR")) {
1766
1767     # get tax rates and description
1768     $query = qq| SELECT * FROM tax t|;
1769     $sth   = $dbh->prepare($query);
1770     $sth->execute || $self->dberror($query);
1771     $self->{TAX} = ();
1772     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1773       push @{ $self->{TAX} }, $ref;
1774     }
1775     $sth->finish;
1776   }
1777
1778   if ($self->{id}) {
1779     my $arap = ($table eq 'customer') ? 'ar' : 'ap';
1780
1781     $query = qq|SELECT a.cp_id, a.invnumber, a.transdate,
1782                 a.${table}_id, a.datepaid, a.duedate, a.ordnumber,
1783                 a.taxincluded, a.curr AS currency, a.notes, a.intnotes,
1784                 c.name AS $table, a.department_id, d.description AS department,
1785                 a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
1786                 a.employee_id, e.name AS employee, a.gldate
1787                 FROM $arap a
1788                 JOIN $table c ON (a.${table}_id = c.id)
1789                 LEFT JOIN employee e ON (e.id = a.employee_id)
1790                 LEFT JOIN department d ON (d.id = a.department_id)
1791                 WHERE a.id = $self->{id}|;
1792     $sth = $dbh->prepare($query);
1793     $sth->execute || $self->dberror($query);
1794
1795     $ref = $sth->fetchrow_hashref(NAME_lc);
1796     foreach $key (keys %$ref) {
1797       $self->{$key} = $ref->{$key};
1798     }
1799     $sth->finish;
1800
1801     # get amounts from individual entries
1802     $query = qq|SELECT c.accno, c.description, a.source, a.amount, a.memo,
1803                 a.transdate, a.cleared, a.project_id, p.projectnumber, a.taxkey, t.rate
1804                 FROM acc_trans a
1805                 JOIN chart c ON (c.id = a.chart_id)
1806                 LEFT JOIN project p ON (p.id = a.project_id)
1807                 LEFT Join tax t ON (a.taxkey = t.taxkey)
1808                 WHERE a.trans_id = $self->{id}
1809                 AND a.fx_transaction = '0'
1810                 ORDER BY a.oid,a.transdate|;
1811     $sth = $dbh->prepare($query);
1812     $sth->execute || $self->dberror($query);
1813
1814     my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1815
1816     # get exchangerate for currency
1817     $self->{exchangerate} =
1818       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1819                               $fld);
1820     my $index = 0;
1821
1822     # store amounts in {acc_trans}{$key} for multiple accounts
1823     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1824       $ref->{exchangerate} =
1825         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate},
1826                                 $fld);
1827       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
1828         $index++;
1829       }
1830       $ref->{index} = $index;
1831
1832       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
1833     }
1834     $sth->finish;
1835
1836     $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans,
1837                   (SELECT c.accno FROM chart c
1838                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1839                   (SELECT c.accno FROM chart c
1840                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1841                 FROM defaults d|;
1842     $sth = $dbh->prepare($query);
1843     $sth->execute || $self->dberror($query);
1844
1845     $ref = $sth->fetchrow_hashref(NAME_lc);
1846     map { $self->{$_} = $ref->{$_} } keys %$ref;
1847     $sth->finish;
1848
1849   } else {
1850
1851     # get date
1852     $query = qq|SELECT current_date AS transdate,
1853                 d.curr AS currencies, d.closedto, d.revtrans,
1854                   (SELECT c.accno FROM chart c
1855                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1856                   (SELECT c.accno FROM chart c
1857                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1858                 FROM defaults d|;
1859     $sth = $dbh->prepare($query);
1860     $sth->execute || $self->dberror($query);
1861
1862     $ref = $sth->fetchrow_hashref(NAME_lc);
1863     map { $self->{$_} = $ref->{$_} } keys %$ref;
1864     $sth->finish;
1865
1866     if ($self->{"$self->{vc}_id"}) {
1867
1868       # only setup currency
1869       ($self->{currency}) = split /:/, $self->{currencies};
1870
1871     } else {
1872
1873       $self->lastname_used($dbh, $myconfig, $table, $module);
1874
1875       my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1876
1877       # get exchangerate for currency
1878       $self->{exchangerate} =
1879         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1880                                 $fld);
1881
1882     }
1883
1884   }
1885
1886   $dbh->disconnect;
1887
1888   $main::lxdebug->leave_sub();
1889 }
1890
1891 sub lastname_used {
1892   $main::lxdebug->enter_sub();
1893
1894   my ($self, $dbh, $myconfig, $table, $module) = @_;
1895
1896   my $arap  = ($table eq 'customer') ? "ar" : "ap";
1897   my $where = "1 = 1";
1898
1899   if ($self->{type} =~ /_order/) {
1900     $arap  = 'oe';
1901     $where = "quotation = '0'";
1902   }
1903   if ($self->{type} =~ /_quotation/) {
1904     $arap  = 'oe';
1905     $where = "quotation = '1'";
1906   }
1907
1908   my $query = qq|SELECT MAX(id) FROM $arap
1909                               WHERE $where
1910                               AND ${table}_id > 0|;
1911   my $sth = $dbh->prepare($query);
1912   $sth->execute || $self->dberror($query);
1913
1914   my ($trans_id) = $sth->fetchrow_array;
1915   $sth->finish;
1916
1917   $trans_id *= 1;
1918   $query = qq|SELECT ct.name, a.curr, a.${table}_id,
1919               current_date + ct.terms AS duedate, a.department_id,
1920               d.description AS department
1921               FROM $arap a
1922               JOIN $table ct ON (a.${table}_id = ct.id)
1923               LEFT JOIN department d ON (a.department_id = d.id)
1924               WHERE a.id = $trans_id|;
1925   $sth = $dbh->prepare($query);
1926   $sth->execute || $self->dberror($query);
1927
1928   ($self->{$table},  $self->{currency},      $self->{"${table}_id"},
1929    $self->{duedate}, $self->{department_id}, $self->{department})
1930     = $sth->fetchrow_array;
1931   $sth->finish;
1932
1933   $main::lxdebug->leave_sub();
1934 }
1935
1936 sub current_date {
1937   $main::lxdebug->enter_sub();
1938
1939   my ($self, $myconfig, $thisdate, $days) = @_;
1940
1941   my $dbh = $self->dbconnect($myconfig);
1942   my ($sth, $query);
1943
1944   $days *= 1;
1945   if ($thisdate) {
1946     my $dateformat = $myconfig->{dateformat};
1947     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1948
1949     $query = qq|SELECT to_date('$thisdate', '$dateformat') + $days AS thisdate
1950                 FROM defaults|;
1951     $sth = $dbh->prepare($query);
1952     $sth->execute || $self->dberror($query);
1953   } else {
1954     $query = qq|SELECT current_date AS thisdate
1955                 FROM defaults|;
1956     $sth = $dbh->prepare($query);
1957     $sth->execute || $self->dberror($query);
1958   }
1959
1960   ($thisdate) = $sth->fetchrow_array;
1961   $sth->finish;
1962
1963   $dbh->disconnect;
1964
1965   $main::lxdebug->leave_sub();
1966
1967   return $thisdate;
1968 }
1969
1970 sub like {
1971   $main::lxdebug->enter_sub();
1972
1973   my ($self, $string) = @_;
1974
1975   if ($string !~ /%/) {
1976     $string = "%$string%";
1977   }
1978
1979   $string =~ s/\'/\'\'/g;
1980
1981   $main::lxdebug->leave_sub();
1982
1983   return $string;
1984 }
1985
1986 sub redo_rows {
1987   $main::lxdebug->enter_sub();
1988
1989   my ($self, $flds, $new, $count, $numrows) = @_;
1990
1991   my @ndx = ();
1992
1993   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
1994     (1 .. $count);
1995
1996   my $i = 0;
1997
1998   # fill rows
1999   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2000     $i++;
2001     $j = $item->{ndx} - 1;
2002     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2003   }
2004
2005   # delete empty rows
2006   for $i ($count + 1 .. $numrows) {
2007     map { delete $self->{"${_}_$i"} } @{$flds};
2008   }
2009
2010   $main::lxdebug->leave_sub();
2011 }
2012
2013 sub update_status {
2014   $main::lxdebug->enter_sub();
2015
2016   my ($self, $myconfig) = @_;
2017
2018   my ($i, $id);
2019
2020   my $dbh = $self->dbconnect_noauto($myconfig);
2021
2022   my $query = qq|DELETE FROM status
2023                  WHERE formname = '$self->{formname}'
2024                  AND trans_id = ?|;
2025   my $sth = $dbh->prepare($query) || $self->dberror($query);
2026
2027   if ($self->{formname} =~ /(check|receipt)/) {
2028     for $i (1 .. $self->{rowcount}) {
2029       $sth->execute($self->{"id_$i"} * 1) || $self->dberror($query);
2030       $sth->finish;
2031     }
2032   } else {
2033     $sth->execute($self->{id}) || $self->dberror($query);
2034     $sth->finish;
2035   }
2036
2037   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2038   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2039
2040   my %queued = split / /, $self->{queued};
2041
2042   if ($self->{formname} =~ /(check|receipt)/) {
2043
2044     # this is a check or receipt, add one entry for each lineitem
2045     my ($accno) = split /--/, $self->{account};
2046     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname,
2047                 chart_id) VALUES (?, '$printed',
2048                 '$queued{$self->{formname}}', '$self->{prinform}',
2049                 (SELECT c.id FROM chart c WHERE c.accno = '$accno'))|;
2050     $sth = $dbh->prepare($query) || $self->dberror($query);
2051
2052     for $i (1 .. $self->{rowcount}) {
2053       if ($self->{"checked_$i"}) {
2054         $sth->execute($self->{"id_$i"}) || $self->dberror($query);
2055         $sth->finish;
2056       }
2057     }
2058   } else {
2059     $query = qq|INSERT INTO status (trans_id, printed, emailed,
2060                 spoolfile, formname)
2061                 VALUES ($self->{id}, '$printed', '$emailed',
2062                 '$queued{$self->{formname}}', '$self->{formname}')|;
2063     $dbh->do($query) || $self->dberror($query);
2064   }
2065
2066   $dbh->commit;
2067   $dbh->disconnect;
2068
2069   $main::lxdebug->leave_sub();
2070 }
2071
2072 sub save_status {
2073   $main::lxdebug->enter_sub();
2074
2075   my ($self, $dbh) = @_;
2076
2077   my ($query, $printed, $emailed);
2078
2079   my $formnames  = $self->{printed};
2080   my $emailforms = $self->{emailed};
2081
2082   my $query = qq|DELETE FROM status
2083                  WHERE formname = '$self->{formname}'
2084                  AND trans_id = $self->{id}|;
2085   $dbh->do($query) || $self->dberror($query);
2086
2087   # this only applies to the forms
2088   # checks and receipts are posted when printed or queued
2089
2090   if ($self->{queued}) {
2091     my %queued = split / /, $self->{queued};
2092
2093     foreach my $formname (keys %queued) {
2094       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
2095       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
2096
2097       $query = qq|INSERT INTO status (trans_id, printed, emailed,
2098                   spoolfile, formname)
2099                   VALUES ($self->{id}, '$printed', '$emailed',
2100                   '$queued{$formname}', '$formname')|;
2101       $dbh->do($query) || $self->dberror($query);
2102
2103       $formnames  =~ s/$self->{formname}//;
2104       $emailforms =~ s/$self->{formname}//;
2105
2106     }
2107   }
2108
2109   # save printed, emailed info
2110   $formnames  =~ s/^ +//g;
2111   $emailforms =~ s/^ +//g;
2112
2113   my %status = ();
2114   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2115   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2116
2117   foreach my $formname (keys %status) {
2118     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2119     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2120
2121     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2122                 VALUES ($self->{id}, '$printed', '$emailed', '$formname')|;
2123     $dbh->do($query) || $self->dberror($query);
2124   }
2125
2126   $main::lxdebug->leave_sub();
2127 }
2128
2129 sub update_defaults {
2130   $main::lxdebug->enter_sub();
2131
2132   my ($self, $myconfig, $fld) = @_;
2133
2134   my $dbh   = $self->dbconnect_noauto($myconfig);
2135   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2136   my $sth   = $dbh->prepare($query);
2137
2138   $sth->execute || $self->dberror($query);
2139   my ($var) = $sth->fetchrow_array;
2140   $sth->finish;
2141
2142   $var++;
2143
2144   $query = qq|UPDATE defaults
2145               SET $fld = '$var'|;
2146   $dbh->do($query) || $self->dberror($query);
2147
2148   $dbh->commit;
2149   $dbh->disconnect;
2150
2151   $main::lxdebug->leave_sub();
2152
2153   return $var;
2154 }
2155
2156 sub update_business {
2157   $main::lxdebug->enter_sub();
2158
2159   my ($self, $myconfig, $business_id) = @_;
2160
2161   my $dbh   = $self->dbconnect_noauto($myconfig);
2162   my $query =
2163     qq|SELECT customernumberinit FROM business  WHERE id=$business_id FOR UPDATE|;
2164   my $sth = $dbh->prepare($query);
2165
2166   $sth->execute || $self->dberror($query);
2167   my ($var) = $sth->fetchrow_array;
2168   $sth->finish;
2169   if ($var ne "") {
2170     $var++;
2171   }
2172   $query = qq|UPDATE business
2173               SET customernumberinit = '$var' WHERE id=$business_id|;
2174   $dbh->do($query) || $self->dberror($query);
2175
2176   $dbh->commit;
2177   $dbh->disconnect;
2178
2179   $main::lxdebug->leave_sub();
2180
2181   return $var;
2182 }
2183
2184 sub get_salesman {
2185   $main::lxdebug->enter_sub();
2186
2187   my ($self, $myconfig, $salesman) = @_;
2188
2189   my $dbh   = $self->dbconnect($myconfig);
2190   my $query =
2191     qq|SELECT id, name FROM customer  WHERE (customernumber ilike '%$salesman%' OR name ilike '%$salesman%') AND business_id in (SELECT id from business WHERE salesman)|;
2192   my $sth = $dbh->prepare($query);
2193   $sth->execute || $self->dberror($query);
2194
2195   my $i = 0;
2196   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2197     push(@{ $self->{salesman_list} }, $ref);
2198     $i++;
2199   }
2200   $dbh->commit;
2201   $main::lxdebug->leave_sub();
2202
2203   return $i;
2204 }
2205
2206 sub get_partsgroup {
2207   $main::lxdebug->enter_sub();
2208
2209   my ($self, $myconfig, $p) = @_;
2210
2211   my $dbh = $self->dbconnect($myconfig);
2212
2213   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2214                  FROM partsgroup pg
2215                  JOIN parts p ON (p.partsgroup_id = pg.id)|;
2216
2217   if ($p->{searchitems} eq 'part') {
2218     $query .= qq|
2219                  WHERE p.inventory_accno_id > 0|;
2220   }
2221   if ($p->{searchitems} eq 'service') {
2222     $query .= qq|
2223                  WHERE p.inventory_accno_id IS NULL|;
2224   }
2225   if ($p->{searchitems} eq 'assembly') {
2226     $query .= qq|
2227                  WHERE p.assembly = '1'|;
2228   }
2229   if ($p->{searchitems} eq 'labor') {
2230     $query .= qq|
2231                  WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
2232   }
2233
2234   $query .= qq|
2235                  ORDER BY partsgroup|;
2236
2237   if ($p->{all}) {
2238     $query = qq|SELECT id, partsgroup FROM partsgroup
2239                 ORDER BY partsgroup|;
2240   }
2241
2242   if ($p->{language_code}) {
2243     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2244                 t.description AS translation
2245                 FROM partsgroup pg
2246                 JOIN parts p ON (p.partsgroup_id = pg.id)
2247                 LEFT JOIN translation t ON (t.trans_id = pg.id AND t.language_code = '$p->{language_code}')
2248                 ORDER BY translation|;
2249   }
2250
2251   my $sth = $dbh->prepare($query);
2252   $sth->execute || $self->dberror($query);
2253
2254   $self->{all_partsgroup} = ();
2255   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2256     push @{ $self->{all_partsgroup} }, $ref;
2257   }
2258   $sth->finish;
2259   $dbh->disconnect;
2260   $main::lxdebug->leave_sub();
2261 }
2262
2263 sub get_pricegroup {
2264   $main::lxdebug->enter_sub();
2265
2266   my ($self, $myconfig, $p) = @_;
2267
2268   my $dbh = $self->dbconnect($myconfig);
2269
2270   my $query = qq|SELECT p.id, p.pricegroup
2271                  FROM pricegroup p|;
2272
2273   $query .= qq|
2274                  ORDER BY pricegroup|;
2275
2276   if ($p->{all}) {
2277     $query = qq|SELECT id, pricegroup FROM pricegroup
2278                 ORDER BY pricegroup|;
2279   }
2280
2281   my $sth = $dbh->prepare($query);
2282   $sth->execute || $self->dberror($query);
2283
2284   $self->{all_pricegroup} = ();
2285   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2286     push @{ $self->{all_pricegroup} }, $ref;
2287   }
2288   $sth->finish;
2289   $dbh->disconnect;
2290
2291   $main::lxdebug->leave_sub();
2292 }
2293
2294 sub audittrail {
2295   my ($self, $dbh, $myconfig, $audittrail) = @_;
2296
2297   # table, $reference, $formname, $action, $id, $transdate) = @_;
2298
2299   my $query;
2300   my $rv;
2301   my $disconnect;
2302
2303   if (!$dbh) {
2304     $dbh        = $self->dbconnect($myconfig);
2305     $disconnect = 1;
2306   }
2307
2308   # if we have an id add audittrail, otherwise get a new timestamp
2309
2310   if ($audittrail->{id}) {
2311
2312     $query = qq|SELECT audittrail FROM defaults|;
2313
2314     if ($dbh->selectrow_array($query)) {
2315       my ($null, $employee_id) = $self->get_employee($dbh);
2316
2317       if ($self->{audittrail} && !$myconfig) {
2318         chop $self->{audittrail};
2319
2320         my @a = split /\|/, $self->{audittrail};
2321         my %newtrail = ();
2322         my $key;
2323         my $i;
2324         my @flds = qw(tablename reference formname action transdate);
2325
2326         # put into hash and remove dups
2327         while (@a) {
2328           $key = "$a[2]$a[3]";
2329           $i   = 0;
2330           $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
2331           splice @a, 0, 5;
2332         }
2333
2334         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2335                     formname, action, employee_id, transdate)
2336                     VALUES ($audittrail->{id}, ?, ?,
2337                     ?, ?, $employee_id, ?)|;
2338         my $sth = $dbh->prepare($query) || $self->dberror($query);
2339
2340         foreach $key (
2341           sort {
2342             $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
2343           } keys %newtrail
2344           ) {
2345           $i = 1;
2346           for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
2347
2348           $sth->execute || $self->dberror;
2349           $sth->finish;
2350         }
2351       }
2352
2353       if ($audittrail->{transdate}) {
2354         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2355                     formname, action, employee_id, transdate) VALUES (
2356                     $audittrail->{id}, '$audittrail->{tablename}', |
2357           . $dbh->quote($audittrail->{reference}) . qq|,
2358                     '$audittrail->{formname}', '$audittrail->{action}',
2359                     $employee_id, '$audittrail->{transdate}')|;
2360       } else {
2361         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2362                     formname, action, employee_id) VALUES ($audittrail->{id},
2363                     '$audittrail->{tablename}', |
2364           . $dbh->quote($audittrail->{reference}) . qq|,
2365                     '$audittrail->{formname}', '$audittrail->{action}',
2366                     $employee_id)|;
2367       }
2368       $dbh->do($query);
2369     }
2370   } else {
2371
2372     $query = qq|SELECT current_timestamp FROM defaults|;
2373     my ($timestamp) = $dbh->selectrow_array($query);
2374
2375     $rv =
2376       "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
2377   }
2378
2379   $dbh->disconnect if $disconnect;
2380
2381   $rv;
2382
2383 }
2384
2385 package Locale;
2386
2387 sub new {
2388   $main::lxdebug->enter_sub();
2389
2390   my ($type, $country, $NLS_file) = @_;
2391   my $self = {};
2392
2393   %self = ();
2394   if ($country && -d "locale/$country") {
2395     $self->{countrycode} = $country;
2396     eval { require "locale/$country/$NLS_file"; };
2397   }
2398
2399   $self->{NLS_file} = $NLS_file;
2400
2401   push @{ $self->{LONG_MONTH} },
2402     ("January",   "February", "March",    "April",
2403      "May ",      "June",     "July",     "August",
2404      "September", "October",  "November", "December");
2405   push @{ $self->{SHORT_MONTH} },
2406     (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
2407
2408   $main::lxdebug->leave_sub();
2409
2410   bless $self, $type;
2411 }
2412
2413 sub text {
2414   my ($self, $text) = @_;
2415
2416   return (exists $self{texts}{$text}) ? $self{texts}{$text} : $text;
2417 }
2418
2419 sub findsub {
2420   $main::lxdebug->enter_sub();
2421
2422   my ($self, $text) = @_;
2423
2424   if (exists $self{subs}{$text}) {
2425     $text = $self{subs}{$text};
2426   } else {
2427     if ($self->{countrycode} && $self->{NLS_file}) {
2428       Form->error(
2429          "$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
2430     }
2431   }
2432
2433   $main::lxdebug->leave_sub();
2434
2435   return $text;
2436 }
2437
2438 sub date {
2439   $main::lxdebug->enter_sub();
2440
2441   my ($self, $myconfig, $date, $longformat) = @_;
2442
2443   my $longdate  = "";
2444   my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
2445
2446   if ($date) {
2447
2448     # get separator
2449     $spc = $myconfig->{dateformat};
2450     $spc =~ s/\w//g;
2451     $spc = substr($spc, 1, 1);
2452
2453     if ($date =~ /\D/) {
2454       if ($myconfig->{dateformat} =~ /^yy/) {
2455         ($yy, $mm, $dd) = split /\D/, $date;
2456       }
2457       if ($myconfig->{dateformat} =~ /^mm/) {
2458         ($mm, $dd, $yy) = split /\D/, $date;
2459       }
2460       if ($myconfig->{dateformat} =~ /^dd/) {
2461         ($dd, $mm, $yy) = split /\D/, $date;
2462       }
2463     } else {
2464       $date = substr($date, 2);
2465       ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2466     }
2467
2468     $dd *= 1;
2469     $mm--;
2470     $yy = ($yy < 70) ? $yy + 2000 : $yy;
2471     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2472
2473     if ($myconfig->{dateformat} =~ /^dd/) {
2474       if (defined $longformat && $longformat == 0) {
2475         $mm++;
2476         $dd = "0$dd" if ($dd < 10);
2477         $mm = "0$mm" if ($mm < 10);
2478         $longdate = "$dd$spc$mm$spc$yy";
2479       } else {
2480         $longdate = "$dd";
2481         $longdate .= ($spc eq '.') ? ". " : " ";
2482         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2483       }
2484     } elsif ($myconfig->{dateformat} eq "yyyy-mm-dd") {
2485
2486       # Use German syntax with the ISO date style "yyyy-mm-dd" because
2487       # Lx-Office is mainly used in Germany or German speaking countries.
2488       if (defined $longformat && $longformat == 0) {
2489         $mm++;
2490         $dd = "0$dd" if ($dd < 10);
2491         $mm = "0$mm" if ($mm < 10);
2492         $longdate = "$yy-$mm-$dd";
2493       } else {
2494         $longdate = "$dd. ";
2495         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2496       }
2497     } else {
2498       if (defined $longformat && $longformat == 0) {
2499         $mm++;
2500         $dd = "0$dd" if ($dd < 10);
2501         $mm = "0$mm" if ($mm < 10);
2502         $longdate = "$mm$spc$dd$spc$yy";
2503       } else {
2504         $longdate = &text($self, $self->{$longmonth}[$mm]) . " $dd, $yy";
2505       }
2506     }
2507
2508   }
2509
2510   $main::lxdebug->leave_sub();
2511
2512   return $longdate;
2513 }
2514
2515 sub parse_date {
2516   $main::lxdebug->enter_sub();
2517
2518   my ($self, $myconfig, $date, $longformat) = @_;
2519
2520   unless ($date) {
2521     $main::lxdebug->leave_sub();
2522     return ();
2523   }
2524
2525   # get separator
2526   $spc = $myconfig->{dateformat};
2527   $spc =~ s/\w//g;
2528   $spc = substr($spc, 1, 1);
2529
2530   if ($date =~ /\D/) {
2531     if ($myconfig->{dateformat} =~ /^yy/) {
2532       ($yy, $mm, $dd) = split /\D/, $date;
2533     } elsif ($myconfig->{dateformat} =~ /^mm/) {
2534       ($mm, $dd, $yy) = split /\D/, $date;
2535     } elsif ($myconfig->{dateformat} =~ /^dd/) {
2536       ($dd, $mm, $yy) = split /\D/, $date;
2537     }
2538   } else {
2539     $date = substr($date, 2);
2540     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2541   }
2542
2543   $dd *= 1;
2544   $mm *= 1;
2545   $yy = ($yy < 70) ? $yy + 2000 : $yy;
2546   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2547
2548   $main::lxdebug->leave_sub();
2549   return ($yy, $mm, $dd);
2550 }
2551
2552 1;