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