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