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