f893c63aabf5ac5a1ea975276b8402bb276a6a3e
[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 use Data::Dumper;
40
41 use Cwd;
42 use Template;
43 use SL::Template;
44 use CGI::Ajax;
45 use SL::DBUtils;
46 use SL::Mailer;
47 use SL::Menu;
48 use SL::User;
49 use SL::Common;
50 use CGI;
51 use List::Util qw(max min sum);
52
53 my $standard_dbh;
54
55 sub DESTROY {
56   if ($standard_dbh) {
57     $standard_dbh->disconnect();
58     undef $standard_dbh;
59   }
60 }
61
62 sub _store_value {
63   $main::lxdebug->enter_sub(2);
64
65   my $self  = shift;
66   my $key   = shift;
67   my $value = shift;
68
69   my $curr  = $self;
70
71   while ($key =~ /\[\+?\]\.|\./) {
72     substr($key, 0, $+[0]) = '';
73
74     if ($& eq '.') {
75       $curr->{$`} ||= { };
76       $curr         = $curr->{$`};
77
78     } else {
79       $curr->{$`} ||= [ ];
80       if (!scalar @{ $curr->{$`} } || $& eq '[+].') {
81         push @{ $curr->{$`} }, { };
82       }
83
84       $curr = $curr->{$`}->[-1];
85     }
86   }
87
88   $curr->{$key} = $value;
89
90   $main::lxdebug->leave_sub(2);
91
92   return \$curr->{$key};
93 }
94
95 sub _input_to_hash {
96   $main::lxdebug->enter_sub(2);
97
98   my $self  = shift;
99   my $input = shift;
100
101   my @pairs = split(/&/, $input);
102
103   foreach (@pairs) {
104     my ($key, $value) = split(/=/, $_, 2);
105     $self->_store_value($self->unescape($key), $self->unescape($value));
106   }
107
108   $main::lxdebug->leave_sub(2);
109 }
110
111 sub _request_to_hash {
112   $main::lxdebug->enter_sub(2);
113
114   my $self  = shift;
115   my $input = shift;
116
117   if (!$ENV{'CONTENT_TYPE'}
118       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
119
120     $self->_input_to_hash($input);
121
122     $main::lxdebug->leave_sub(2);
123     return;
124   }
125
126   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
127
128   my $boundary = '--' . $1;
129
130   foreach my $line (split m/\n/, $input) {
131     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
132
133     if (($line eq $boundary) || ($line eq "$boundary\r")) {
134       ${ $previous } =~ s|\r?\n$|| if $previous;
135
136       undef $previous;
137       undef $filename;
138
139       $headers_done   = 0;
140       $content_type   = "text/plain";
141       $boundary_found = 1;
142       $need_cr        = 0;
143
144       next;
145     }
146
147     next unless $boundary_found;
148
149     if (!$headers_done) {
150       $line =~ s/[\r\n]*$//;
151
152       if (!$line) {
153         $headers_done = 1;
154         next;
155       }
156
157       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
158         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
159           $filename = $1;
160           substr $line, $-[0], $+[0] - $-[0], "";
161         }
162
163         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
164           $name = $1;
165           substr $line, $-[0], $+[0] - $-[0], "";
166         }
167
168         $previous         = $self->_store_value($name, '');
169         $self->{FILENAME} = $filename if ($filename);
170
171         next;
172       }
173
174       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
175         $content_type = $1;
176       }
177
178       next;
179     }
180
181     next unless $previous;
182
183     ${ $previous } .= "${line}\n";
184   }
185
186   ${ $previous } =~ s|\r?\n$|| if $previous;
187
188   $main::lxdebug->leave_sub(2);
189 }
190
191 sub new {
192   $main::lxdebug->enter_sub();
193
194   my $type = shift;
195
196   my $self = {};
197
198   if ($LXDebug::watch_form) {
199     require SL::Watchdog;
200     tie %{ $self }, 'SL::Watchdog';
201   }
202
203   read(STDIN, $_, $ENV{CONTENT_LENGTH});
204
205   if ($ENV{QUERY_STRING}) {
206     $_ = $ENV{QUERY_STRING};
207   }
208
209   if ($ARGV[0]) {
210     $_ = $ARGV[0];
211   }
212
213   bless $self, $type;
214
215   $self->_request_to_hash($_);
216
217   $self->{action}  =  lc $self->{action};
218   $self->{action}  =~ s/( |-|,|\#)/_/g;
219
220   $self->{version} =  "2.4.3";
221
222   $main::lxdebug->leave_sub();
223
224   return $self;
225 }
226
227 sub _flatten_variables_rec {
228   $main::lxdebug->enter_sub(2);
229
230   my $self   = shift;
231   my $curr   = shift;
232   my $prefix = shift;
233   my $key    = shift;
234
235   my @result;
236
237   if ('' eq ref $curr->{$key}) {
238     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
239
240   } elsif ('HASH' eq ref $curr->{$key}) {
241     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
242       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
243     }
244
245   } else {
246     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
247       my $first_array_entry = 1;
248
249       foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
250         push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
251         $first_array_entry = 0;
252       }
253     }
254   }
255
256   $main::lxdebug->leave_sub(2);
257
258   return @result;
259 }
260
261 sub flatten_variables {
262   $main::lxdebug->enter_sub(2);
263
264   my $self = shift;
265   my @keys = @_;
266
267   my @variables;
268
269   foreach (@keys) {
270     push @variables, $self->_flatten_variables_rec($self, '', $_);
271   }
272
273   $main::lxdebug->leave_sub(2);
274
275   return @variables;
276 }
277
278
279 sub debug {
280   $main::lxdebug->enter_sub();
281
282   my ($self) = @_;
283
284   print "\n";
285
286   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
287
288   $main::lxdebug->leave_sub();
289 }
290
291 sub escape {
292   $main::lxdebug->enter_sub(2);
293
294   my ($self, $str) = @_;
295
296   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
297
298   $main::lxdebug->leave_sub(2);
299
300   return $str;
301 }
302
303 sub unescape {
304   $main::lxdebug->enter_sub(2);
305
306   my ($self, $str) = @_;
307
308   $str =~ tr/+/ /;
309   $str =~ s/\\$//;
310
311   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
312
313   $main::lxdebug->leave_sub(2);
314
315   return $str;
316 }
317
318 sub quote {
319   my ($self, $str) = @_;
320
321   if ($str && !ref($str)) {
322     $str =~ s/\"/&quot;/g;
323   }
324
325   $str;
326
327 }
328
329 sub unquote {
330   my ($self, $str) = @_;
331
332   if ($str && !ref($str)) {
333     $str =~ s/&quot;/\"/g;
334   }
335
336   $str;
337
338 }
339
340 sub quote_html {
341   $main::lxdebug->enter_sub(2);
342
343   my ($self, $str) = @_;
344
345   my %replace =
346     ('order' => ['"', '<', '>'],
347      '<'             => '&lt;',
348      '>'             => '&gt;',
349      '"'             => '&quot;',
350     );
351
352   map({ $str =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
353
354   $main::lxdebug->leave_sub(2);
355
356   return $str;
357 }
358
359 sub hide_form {
360   my $self = shift;
361
362   if (@_) {
363     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
364   } else {
365     for (sort keys %$self) {
366       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
367       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
368     }
369   }
370
371 }
372
373 sub error {
374   $main::lxdebug->enter_sub();
375
376   $main::lxdebug->show_backtrace();
377
378   my ($self, $msg) = @_;
379   if ($ENV{HTTP_USER_AGENT}) {
380     $msg =~ s/\n/<br>/g;
381     $self->show_generic_error($msg);
382
383   } else {
384
385     die "Error: $msg\n";
386   }
387
388   $main::lxdebug->leave_sub();
389 }
390
391 sub info {
392   $main::lxdebug->enter_sub();
393
394   my ($self, $msg) = @_;
395
396   if ($ENV{HTTP_USER_AGENT}) {
397     $msg =~ s/\n/<br>/g;
398
399     if (!$self->{header}) {
400       $self->header;
401       print qq|
402       <body>|;
403     }
404
405     print qq|
406
407     <p><b>$msg</b>
408     |;
409
410   } else {
411
412     if ($self->{info_function}) {
413       &{ $self->{info_function} }($msg);
414     } else {
415       print "$msg\n";
416     }
417   }
418
419   $main::lxdebug->leave_sub();
420 }
421
422 # calculates the number of rows in a textarea based on the content and column number
423 # can be capped with maxrows
424 sub numtextrows {
425   $main::lxdebug->enter_sub();
426   my ($self, $str, $cols, $maxrows) = @_;
427
428   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
429   $maxrows ||= $rows;
430
431   $main::lxdebug->leave_sub();
432   return min $rows, $maxrows;
433 }
434
435 sub dberror {
436   $main::lxdebug->enter_sub();
437
438   my ($self, $msg) = @_;
439
440   $self->error("$msg\n" . $DBI::errstr);
441
442   $main::lxdebug->leave_sub();
443 }
444
445 sub isblank {
446   $main::lxdebug->enter_sub();
447
448   my ($self, $name, $msg) = @_;
449
450   my $curr = $self;
451   foreach my $part (split '.', $name) {
452     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
453       $self->error($msg);
454     }
455     $curr = $curr->{$part};
456   }
457
458   $main::lxdebug->leave_sub();
459 }
460
461 sub header {
462   $main::lxdebug->enter_sub();
463
464   my ($self, $extra_code) = @_;
465
466   if ($self->{header}) {
467     $main::lxdebug->leave_sub();
468     return;
469   }
470
471   my ($stylesheet, $favicon);
472
473   if ($ENV{HTTP_USER_AGENT}) {
474     my $doctype;
475
476     if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
477       # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
478       $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
479     }
480
481     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
482
483     $stylesheets =~ s|^\s*||;
484     $stylesheets =~ s|\s*$||;
485     foreach my $file (split m/\s+/, $stylesheets) {
486       $file =~ s|.*/||;
487       next if (! -f "css/$file");
488
489       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
490     }
491
492     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
493
494     if ($self->{favicon} && (-f "$self->{favicon}")) {
495       $favicon =
496         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
497   |;
498     }
499
500     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
501
502     if ($self->{landscape}) {
503       $pagelayout = qq|<style type="text/css">
504                         \@page { size:landscape; }
505                         </style>|;
506     }
507
508     my $fokus = qq|  document.$self->{fokus}.focus();| if ($self->{"fokus"});
509
510     #Set Calendar
511     my $jsscript = "";
512     if ($self->{jsscript} == 1) {
513
514       $jsscript = qq|
515         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
516         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
517         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
518         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
519         $self->{javascript}
520        |;
521     }
522
523     $self->{titlebar} =
524       ($self->{title})
525       ? "$self->{title} - $self->{titlebar}"
526       : $self->{titlebar};
527     my $ajax = "";
528     foreach $item (@ { $self->{AJAX} }) {
529       $ajax .= $item->show_javascript();
530     }
531     print qq|Content-Type: text/html; charset=${db_charset};
532
533 ${doctype}<html>
534 <head>
535   <title>$self->{titlebar}</title>
536   $stylesheet
537   $pagelayout
538   $favicon
539   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
540   $jsscript
541   $ajax
542
543   <script type="text/javascript">
544   <!--
545     function fokus() {
546       $fokus
547     }
548   //-->
549   </script>
550
551   <meta name="robots" content="noindex,nofollow" />
552   <script type="text/javascript" src="js/highlight_input.js"></script>
553   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
554
555   <script type="text/javascript" src="js/tabcontent.js">
556
557   /***********************************************
558   * Tab Content script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
559   * This notice MUST stay intact for legal use
560   * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
561   ***********************************************/
562
563   </script>
564
565   $extra_code
566 </head>
567
568 |;
569   }
570   $self->{header} = 1;
571
572   $main::lxdebug->leave_sub();
573 }
574
575 sub _prepare_html_template {
576   $main::lxdebug->enter_sub();
577
578   my ($self, $file, $additional_params) = @_;
579   my $language;
580
581   if (!defined(%main::myconfig) || !defined($main::myconfig{"countrycode"})) {
582     $language = $main::language;
583   } else {
584     $language = $main::myconfig{"countrycode"};
585   }
586   $language = "de" unless ($language);
587
588   if (-f "templates/webpages/${file}_${language}.html") {
589     if ((-f ".developer") &&
590         (-f "templates/webpages/${file}_master.html") &&
591         ((stat("templates/webpages/${file}_master.html"))[9] >
592          (stat("templates/webpages/${file}_${language}.html"))[9])) {
593       my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
594         "Please re-run 'locales.pl' in 'locale/${language}'.";
595       print(qq|<pre>$info</pre>|);
596       die($info);
597     }
598
599     $file = "templates/webpages/${file}_${language}.html";
600   } elsif (-f "templates/webpages/${file}.html") {
601     $file = "templates/webpages/${file}.html";
602   } else {
603     my $info = "Web page template '${file}' not found.\n" .
604       "Please re-run 'locales.pl' in 'locale/${language}'.";
605     print(qq|<pre>$info</pre>|);
606     die($info);
607   }
608
609   if ($self->{"DEBUG"}) {
610     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
611   }
612
613   if ($additional_params->{"DEBUG"}) {
614     $additional_params->{"DEBUG"} =
615       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
616   }
617
618   if (%main::myconfig) {
619     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
620     my $jsc_dateformat = $main::myconfig{"dateformat"};
621     $jsc_dateformat =~ s/d+/\%d/gi;
622     $jsc_dateformat =~ s/m+/\%m/gi;
623     $jsc_dateformat =~ s/y+/\%Y/gi;
624     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
625   }
626
627   $additional_params->{"conf_webdav"}                 = $main::webdav;
628   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
629   $additional_params->{"conf_latex_templates"}        = $main::latex;
630   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
631
632   if (%main::debug_options) {
633     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
634   }
635
636   $main::lxdebug->leave_sub();
637
638   return $file;
639 }
640
641 sub parse_html_template {
642   $main::lxdebug->enter_sub();
643
644   my ($self, $file, $additional_params) = @_;
645
646   $additional_params ||= { };
647
648   $file = $self->_prepare_html_template($file, $additional_params);
649
650   my $template = Template->new({ 'INTERPOLATE'  => 0,
651                                  'EVAL_PERL'    => 0,
652                                  'ABSOLUTE'     => 1,
653                                  'CACHE_SIZE'   => 0,
654                                  'PLUGIN_BASE'  => 'SL::Template::Plugin',
655                                  'INCLUDE_PATH' => '.:templates/webpages',
656                                }) || die;
657
658   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
659
660   my $output;
661   if (!$template->process($file, $additional_params, \$output)) {
662     print STDERR $template->error();
663   }
664
665   $output = $main::locale->{iconv}->convert($output) if ($main::locale);
666
667   $main::lxdebug->leave_sub();
668
669   return $output;
670 }
671
672 sub show_generic_error {
673   my ($self, $error, $title, $action) = @_;
674
675   my $add_params = {
676     'title_error' => $title,
677     'label_error' => $error,
678   };
679
680   my @vars;
681   if ($action) {
682     map({ delete($self->{$_}); } qw(action));
683     map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
684             if (!ref($self->{$_})); }
685         keys(%{$self}));
686     $add_params->{"SHOW_BUTTON"} = 1;
687     $add_params->{"BUTTON_LABEL"} = $action;
688   }
689   $add_params->{"VARIABLES"} = \@vars;
690
691   $self->{title} = $title if ($title);
692
693   $self->header();
694   print $self->parse_html_template("generic/error", $add_params);
695
696   die("Error: $error\n");
697 }
698
699 sub show_generic_information {
700   my ($self, $text, $title) = @_;
701
702   my $add_params = {
703     'title_information' => $title,
704     'label_information' => $text,
705   };
706
707   $self->{title} = $title if ($title);
708
709   $self->header();
710   print $self->parse_html_template("generic/information", $add_params);
711
712   die("Information: $error\n");
713 }
714
715 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
716 # changed it to accept an arbitrary number of triggers - sschoeling
717 sub write_trigger {
718   $main::lxdebug->enter_sub();
719
720   my $self     = shift;
721   my $myconfig = shift;
722   my $qty      = shift;
723
724   # set dateform for jsscript
725   # default
726   my %dateformats = (
727     "dd.mm.yy" => "%d.%m.%Y",
728     "dd-mm-yy" => "%d-%m-%Y",
729     "dd/mm/yy" => "%d/%m/%Y",
730     "mm/dd/yy" => "%m/%d/%Y",
731     "mm-dd-yy" => "%m-%d-%Y",
732     "yyyy-mm-dd" => "%Y-%m-%d",
733     );
734
735   my $ifFormat = defined($dateformats{$myconfig{"dateformat"}}) ?
736     $dateformats{$myconfig{"dateformat"}} : "%d.%m.%Y";
737
738   my @triggers;
739   while ($#_ >= 2) {
740     push @triggers, qq|
741        Calendar.setup(
742       {
743       inputField : "| . (shift) . qq|",
744       ifFormat :"$ifFormat",
745       align : "| .  (shift) . qq|",
746       button : "| . (shift) . qq|"
747       }
748       );
749        |;
750   }
751   my $jsscript = qq|
752        <script type="text/javascript">
753        <!--| . join("", @triggers) . qq|//-->
754         </script>
755         |;
756
757   $main::lxdebug->leave_sub();
758
759   return $jsscript;
760 }    #end sub write_trigger
761
762 sub redirect {
763   $main::lxdebug->enter_sub();
764
765   my ($self, $msg) = @_;
766
767   if ($self->{callback}) {
768
769     ($script, $argv) = split(/\?/, $self->{callback}, 2);
770     $script =~ s|.*/||;
771     $script =~ s|[^a-zA-Z0-9_\.]||g;
772     exec("perl", "$script", $argv);
773
774   } else {
775
776     $self->info($msg);
777     exit;
778   }
779
780   $main::lxdebug->leave_sub();
781 }
782
783 # sort of columns removed - empty sub
784 sub sort_columns {
785   $main::lxdebug->enter_sub();
786
787   my ($self, @columns) = @_;
788
789   $main::lxdebug->leave_sub();
790
791   return @columns;
792 }
793 #
794 sub format_amount {
795   $main::lxdebug->enter_sub(2);
796
797   my ($self, $myconfig, $amount, $places, $dash) = @_;
798
799   if ($amount eq "") {
800     $amount = 0;
801   }
802   
803   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
804   
805   my $neg = ($amount =~ s/^-//);
806   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
807   
808   if (defined($places) && ($places ne '')) {
809     if (not $exp) {
810       if ($places < 0) {
811         $amount *= 1;
812         $places *= -1;
813
814         my ($actual_places) = ($amount =~ /\.(\d+)/);
815         $actual_places = length($actual_places);
816         $places = $actual_places > $places ? $actual_places : $places;
817       }
818     }
819     $amount = $self->round_amount($amount, $places);
820   }
821
822   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
823   my @p = split(/\./, $amount); # split amount at decimal point
824
825   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
826
827   $amount = $p[0];
828   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
829
830   $amount = do {
831     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
832     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
833                         ($neg ? "-$amount"   : "$amount" )    ;
834   };
835
836
837   $main::lxdebug->leave_sub(2);
838   return $amount;
839 }
840 #
841
842 sub format_string {
843   $main::lxdebug->enter_sub(2);
844
845   my $self  = shift;
846   my $input = shift;
847
848   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
849   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
850   $input =~ s/\#\#/\#/g;
851
852   $main::lxdebug->leave_sub(2);
853
854   return $input;
855 }
856
857 sub parse_amount {
858   $main::lxdebug->enter_sub(2);
859
860   my ($self, $myconfig, $amount) = @_;
861
862   if (   ($myconfig->{numberformat} eq '1.000,00')
863       || ($myconfig->{numberformat} eq '1000,00')) {
864     $amount =~ s/\.//g;
865     $amount =~ s/,/\./;
866   }
867
868   if ($myconfig->{numberformat} eq "1'000.00") {
869     $amount =~ s/\'//g;
870   }
871
872   $amount =~ s/,//g;
873
874   $main::lxdebug->leave_sub(2);
875
876   return ($amount * 1);
877 }
878
879 sub round_amount {
880   $main::lxdebug->enter_sub(2);
881
882   my ($self, $amount, $places) = @_;
883   my $round_amount;
884
885   # Rounding like "Kaufmannsrunden"
886   # Descr. http://de.wikipedia.org/wiki/Rundung
887   # Inspired by
888   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
889   # Solves Bug: 189
890   # Udo Spallek
891   $amount = $amount * (10**($places));
892   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
893
894   $main::lxdebug->leave_sub(2);
895
896   return $round_amount;
897
898 }
899
900 sub parse_template {
901   $main::lxdebug->enter_sub();
902
903   my ($self, $myconfig, $userspath) = @_;
904   my ($template, $out);
905
906   local (*IN, *OUT);
907
908   $self->{"cwd"} = getcwd();
909   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
910
911   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
912     $template = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
913   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
914     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
915     $template = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
916   } elsif (($self->{"format"} =~ /html/i) ||
917            (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
918     $template = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
919   } elsif (($self->{"format"} =~ /xml/i) ||
920              (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
921     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
922   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
923     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
924   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
925     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
926   } elsif ( defined $self->{'format'}) {
927     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
928   } elsif ( $self->{'format'} eq '' ) {
929     $self->error("No Outputformat given: $self->{'format'}");
930   } else { #Catch the rest
931     $self->error("Outputformat not defined: $self->{'format'}");
932   }
933
934   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
935   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
936
937   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
938       qw(email tel fax name signature company address businessnumber
939          co_ustid taxnumber duns));
940   map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; }
941       qw(company address signature));
942   map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature));
943
944   map({ $self->{"${_}"} = $myconfig->{$_}; }
945       qw(co_ustid));
946               
947
948   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
949
950   # OUT is used for the media, screen, printer, email
951   # for postscript we store a copy in a temporary file
952   my $fileid = time;
953   my $prepend_userspath;
954
955   if (!$self->{tmpfile}) {
956     $self->{tmpfile}   = "${fileid}.$self->{IN}";
957     $prepend_userspath = 1;
958   }
959
960   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
961
962   $self->{tmpfile} =~ s|.*/||;
963   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
964   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
965
966   if ($template->uses_temp_file() || $self->{media} eq 'email') {
967     $out = $self->{OUT};
968     $self->{OUT} = ">$self->{tmpfile}";
969   }
970
971   if ($self->{OUT}) {
972     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
973   } else {
974     open(OUT, ">-") or $self->error("STDOUT : $!");
975     $self->header;
976   }
977
978   if (!$template->parse(*OUT)) {
979     $self->cleanup();
980     $self->error("$self->{IN} : " . $template->get_error());
981   }
982
983   close(OUT);
984
985   if ($template->uses_temp_file() || $self->{media} eq 'email') {
986
987     if ($self->{media} eq 'email') {
988
989       my $mail = new Mailer;
990
991       map { $mail->{$_} = $self->{$_} }
992         qw(cc bcc subject message version format);
993       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
994       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
995       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
996       $mail->{fileid} = "$fileid.";
997       $myconfig->{signature} =~ s/\\r\\n/\\n/g;
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         if (!$self->{"do_not_attach"}) {
1018           @{ $mail->{attachments} } =
1019             ({ "filename" => $self->{"tmpfile"},
1020                "name" => $self->{"attachment_filename"} ?
1021                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
1022         }
1023
1024         $mail->{message}       =~ s/\r\n/\n/g;
1025         $myconfig->{signature} =~ s/\\n/\n/g;
1026         $mail->{message} .= "\n-- \n$myconfig->{signature}";
1027
1028       }
1029
1030       my $err = $mail->send();
1031       $self->error($self->cleanup . "$err") if ($err);
1032
1033     } else {
1034
1035       $self->{OUT} = $out;
1036
1037       my $numbytes = (-s $self->{tmpfile});
1038       open(IN, $self->{tmpfile})
1039         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1040
1041       $self->{copies} = 1 unless $self->{media} eq 'printer';
1042
1043       chdir("$self->{cwd}");
1044       #print(STDERR "Kopien $self->{copies}\n");
1045       #print(STDERR "OUT $self->{OUT}\n");
1046       for my $i (1 .. $self->{copies}) {
1047         if ($self->{OUT}) {
1048           open(OUT, $self->{OUT})
1049             or $self->error($self->cleanup . "$self->{OUT} : $!");
1050         } else {
1051           $self->{attachment_filename} = ($self->{attachment_filename}) 
1052                                        ? $self->{attachment_filename}
1053                                        : $self->generate_attachment_filename();
1054
1055           # launch application
1056           print qq|Content-Type: | . $template->get_mime_type() . qq|
1057 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1058 Content-Length: $numbytes
1059
1060 |;
1061
1062           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
1063
1064         }
1065
1066         while (<IN>) {
1067           print OUT $_;
1068         }
1069
1070         close(OUT);
1071
1072         seek IN, 0, 0;
1073       }
1074
1075       close(IN);
1076     }
1077
1078   }
1079
1080   $self->cleanup;
1081
1082   chdir("$self->{cwd}");
1083   $main::lxdebug->leave_sub();
1084 }
1085
1086 sub get_formname_translation {
1087   my ($self, $formname) = @_;
1088
1089   $formname ||= $self->{formname};
1090
1091   my %formname_translations = (
1092     bin_list            => $main::locale->text('Bin List'),
1093     credit_note         => $main::locale->text('Credit Note'),
1094     invoice             => $main::locale->text('Invoice'),
1095     packing_list        => $main::locale->text('Packing List'),
1096     pick_list           => $main::locale->text('Pick List'),
1097     proforma            => $main::locale->text('Proforma Invoice'),
1098     purchase_order      => $main::locale->text('Purchase Order'),
1099     request_quotation   => $main::locale->text('RFQ'),
1100     sales_order         => $main::locale->text('Confirmation'),
1101     sales_quotation     => $main::locale->text('Quotation'),
1102     storno_invoice      => $main::locale->text('Storno Invoice'),
1103     storno_packing_list => $main::locale->text('Storno Packing List'),
1104   );
1105
1106   return $formname_translations{$formname}
1107 }
1108
1109 sub generate_attachment_filename {
1110   my ($self) = @_;
1111
1112   my $attachment_filename = $self->get_formname_translation();
1113   my $prefix = 
1114       (grep { $self->{"type"} eq $_ } qw(invoice credit_note)) ? "inv"
1115     : ($self->{"type"} =~ /_quotation$/)                       ? "quo"
1116     :                                                            "ord";
1117
1118   if ($attachment_filename && $self->{"${prefix}number"}) {
1119     $attachment_filename .= "_" . $self->{"${prefix}number"}
1120                             . (  $self->{format} =~ /pdf/i          ? ".pdf"
1121                                : $self->{format} =~ /postscript/i   ? ".ps"
1122                                : $self->{format} =~ /opendocument/i ? ".odt"
1123                                : $self->{format} =~ /html/i         ? ".html"
1124                                :                                      "");
1125     $attachment_filename =~ s/ /_/g;
1126     my %umlaute = ( "ä" => "ae", "ö" => "oe", "ü" => "ue", 
1127                     "Ä" => "Ae", "Ö" => "Oe", "Ãœ" => "Ue", "ß" => "ss");
1128     map { $attachment_filename =~ s/$_/$umlaute{$_}/g } keys %umlaute;
1129   } else {
1130     $attachment_filename = "";
1131   }
1132
1133   return $attachment_filename;
1134 }
1135
1136 sub cleanup {
1137   $main::lxdebug->enter_sub();
1138
1139   my $self = shift;
1140
1141   chdir("$self->{tmpdir}");
1142
1143   my @err = ();
1144   if (-f "$self->{tmpfile}.err") {
1145     open(FH, "$self->{tmpfile}.err");
1146     @err = <FH>;
1147     close(FH);
1148   }
1149
1150   if ($self->{tmpfile}) {
1151     $self->{tmpfile} =~ s|.*/||g;
1152     # strip extension
1153     $self->{tmpfile} =~ s/\.\w+$//g;
1154     my $tmpfile = $self->{tmpfile};
1155     unlink(<$tmpfile.*>);
1156   }
1157
1158   chdir("$self->{cwd}");
1159
1160   $main::lxdebug->leave_sub();
1161
1162   return "@err";
1163 }
1164
1165 sub datetonum {
1166   $main::lxdebug->enter_sub();
1167
1168   my ($self, $date, $myconfig) = @_;
1169
1170   if ($date && $date =~ /\D/) {
1171
1172     if ($myconfig->{dateformat} =~ /^yy/) {
1173       ($yy, $mm, $dd) = split /\D/, $date;
1174     }
1175     if ($myconfig->{dateformat} =~ /^mm/) {
1176       ($mm, $dd, $yy) = split /\D/, $date;
1177     }
1178     if ($myconfig->{dateformat} =~ /^dd/) {
1179       ($dd, $mm, $yy) = split /\D/, $date;
1180     }
1181
1182     $dd *= 1;
1183     $mm *= 1;
1184     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1185     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1186
1187     $dd = "0$dd" if ($dd < 10);
1188     $mm = "0$mm" if ($mm < 10);
1189
1190     $date = "$yy$mm$dd";
1191   }
1192
1193   $main::lxdebug->leave_sub();
1194
1195   return $date;
1196 }
1197
1198 # Database routines used throughout
1199
1200 sub dbconnect {
1201   $main::lxdebug->enter_sub(2);
1202
1203   my ($self, $myconfig) = @_;
1204
1205   # connect to database
1206   my $dbh =
1207     DBI->connect($myconfig->{dbconnect},
1208                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1209     or $self->dberror;
1210
1211   # set db options
1212   if ($myconfig->{dboptions}) {
1213     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1214   }
1215
1216   $main::lxdebug->leave_sub(2);
1217
1218   return $dbh;
1219 }
1220
1221 sub dbconnect_noauto {
1222   $main::lxdebug->enter_sub();
1223
1224   my ($self, $myconfig) = @_;
1225   
1226   # connect to database
1227   $dbh =
1228     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1229                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1230     or $self->dberror;
1231
1232   # set db options
1233   if ($myconfig->{dboptions}) {
1234     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1235   }
1236
1237   $main::lxdebug->leave_sub();
1238
1239   return $dbh;
1240 }
1241
1242 sub get_standard_dbh {
1243   $main::lxdebug->enter_sub(2);
1244
1245   my ($self, $myconfig) = @_;
1246
1247   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1248
1249   $main::lxdebug->leave_sub(2);
1250
1251   return $standard_dbh;
1252 }
1253
1254 sub update_balance {
1255   $main::lxdebug->enter_sub();
1256
1257   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1258
1259   # if we have a value, go do it
1260   if ($value != 0) {
1261
1262     # retrieve balance from table
1263     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1264     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1265     my ($balance) = $sth->fetchrow_array;
1266     $sth->finish;
1267
1268     $balance += $value;
1269
1270     # update balance
1271     $query = "UPDATE $table SET $field = $balance WHERE $where";
1272     do_query($self, $dbh, $query, @values);
1273   }
1274   $main::lxdebug->leave_sub();
1275 }
1276
1277 sub update_exchangerate {
1278   $main::lxdebug->enter_sub();
1279
1280   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1281   my ($query);
1282   # some sanity check for currency
1283   if ($curr eq '') {
1284     $main::lxdebug->leave_sub();
1285     return;
1286   }  
1287   $query = qq|SELECT curr FROM defaults|;
1288
1289   my ($currency) = selectrow_query($self, $dbh, $query);
1290   my ($defaultcurrency) = split m/:/, $currency;
1291
1292
1293   if ($curr eq $defaultcurrency) {
1294     $main::lxdebug->leave_sub();
1295     return;
1296   }
1297
1298   $query = qq|SELECT e.curr FROM exchangerate e
1299                  WHERE e.curr = ? AND e.transdate = ?
1300                  FOR UPDATE|;
1301   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1302
1303   if ($buy == 0) {
1304     $buy = "";
1305   }
1306   if ($sell == 0) {
1307     $sell = "";
1308   }
1309
1310   $buy = conv_i($buy, "NULL");
1311   $sell = conv_i($sell, "NULL");
1312
1313   my $set;
1314   if ($buy != 0 && $sell != 0) {
1315     $set = "buy = $buy, sell = $sell";
1316   } elsif ($buy != 0) {
1317     $set = "buy = $buy";
1318   } elsif ($sell != 0) {
1319     $set = "sell = $sell";
1320   }
1321
1322   if ($sth->fetchrow_array) {
1323     $query = qq|UPDATE exchangerate
1324                 SET $set
1325                 WHERE curr = ?
1326                 AND transdate = ?|;
1327     
1328   } else {
1329     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1330                 VALUES (?, $buy, $sell, ?)|;
1331   }
1332   $sth->finish;
1333   do_query($self, $dbh, $query, $curr, $transdate);
1334
1335   $main::lxdebug->leave_sub();
1336 }
1337
1338 sub save_exchangerate {
1339   $main::lxdebug->enter_sub();
1340
1341   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1342
1343   my $dbh = $self->dbconnect($myconfig);
1344
1345   my ($buy, $sell);
1346
1347   $buy  = $rate if $fld eq 'buy';
1348   $sell = $rate if $fld eq 'sell';
1349
1350
1351   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1352
1353
1354   $dbh->disconnect;
1355
1356   $main::lxdebug->leave_sub();
1357 }
1358
1359 sub get_exchangerate {
1360   $main::lxdebug->enter_sub();
1361
1362   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1363   my ($query);
1364
1365   unless ($transdate) {
1366     $main::lxdebug->leave_sub();
1367     return 1;
1368   }
1369
1370   $query = qq|SELECT curr FROM defaults|;
1371
1372   my ($currency) = selectrow_query($self, $dbh, $query);
1373   my ($defaultcurrency) = split m/:/, $currency;
1374
1375   if ($currency eq $defaultcurrency) {
1376     $main::lxdebug->leave_sub();
1377     return 1;
1378   }
1379
1380   $query = qq|SELECT e.$fld FROM exchangerate e
1381                  WHERE e.curr = ? AND e.transdate = ?|;
1382   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1383
1384
1385
1386   $main::lxdebug->leave_sub();
1387
1388   return $exchangerate;
1389 }
1390
1391 sub check_exchangerate {
1392   $main::lxdebug->enter_sub();
1393
1394   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1395
1396   unless ($transdate) {
1397     $main::lxdebug->leave_sub();
1398     return "";
1399   }
1400
1401   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1402
1403   if ($currency eq $defaultcurrency) {
1404     $main::lxdebug->leave_sub();
1405     return 1;
1406   }
1407
1408   my $dbh   = $self->get_standard_dbh($myconfig);
1409   my $query = qq|SELECT e.$fld FROM exchangerate e
1410                  WHERE e.curr = ? AND e.transdate = ?|;
1411
1412   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1413
1414   $exchangerate = 1 if ($exchangerate eq "");
1415
1416   $main::lxdebug->leave_sub();
1417
1418   return $exchangerate;
1419 }
1420
1421 sub get_default_currency {
1422   $main::lxdebug->enter_sub();
1423
1424   my ($self, $myconfig) = @_;
1425   my $dbh = $self->get_standard_dbh($myconfig);
1426
1427   my $query = qq|SELECT curr FROM defaults|;
1428
1429   my ($curr)            = selectrow_query($self, $dbh, $query);
1430   my ($defaultcurrency) = split m/:/, $curr;
1431
1432   $main::lxdebug->leave_sub();
1433
1434   return $defaultcurrency;
1435 }
1436
1437
1438 sub set_payment_options {
1439   $main::lxdebug->enter_sub();
1440
1441   my ($self, $myconfig, $transdate) = @_;
1442
1443   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1444
1445   my $dbh = $self->get_standard_dbh($myconfig);
1446
1447   my $query =
1448     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1449     qq|FROM payment_terms p | .
1450     qq|WHERE p.id = ?|;
1451
1452   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1453    $self->{payment_terms}) =
1454      selectrow_query($self, $dbh, $query, $self->{payment_id});
1455
1456   if ($transdate eq "") {
1457     if ($self->{invdate}) {
1458       $transdate = $self->{invdate};
1459     } else {
1460       $transdate = $self->{transdate};
1461     }
1462   }
1463
1464   $query =
1465     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1466     qq|FROM payment_terms|;
1467   ($self->{netto_date}, $self->{skonto_date}) =
1468     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1469
1470   my ($invtotal, $total);
1471   my (%amounts, %formatted_amounts);
1472
1473   if ($self->{type} =~ /_order$/) {
1474     $amounts{invtotal} = $self->{ordtotal};
1475     $amounts{total}    = $self->{ordtotal};
1476
1477   } elsif ($self->{type} =~ /_quotation$/) {
1478     $amounts{invtotal} = $self->{quototal};
1479     $amounts{total}    = $self->{quototal};
1480
1481   } else {
1482     $amounts{invtotal} = $self->{invtotal};
1483     $amounts{total}    = $self->{total};
1484   }
1485
1486   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1487
1488   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1489   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1490   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1491
1492   foreach (keys %amounts) {
1493     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1494     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1495   }
1496
1497   if ($self->{"language_id"}) {
1498     $query =
1499       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1500       qq|FROM translation_payment_terms t | .
1501       qq|LEFT JOIN language l ON t.language_id = l.id | .
1502       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1503     my ($description_long, $output_numberformat, $output_dateformat,
1504       $output_longdates) =
1505       selectrow_query($self, $dbh, $query,
1506                       $self->{"language_id"}, $self->{"payment_id"});
1507
1508     $self->{payment_terms} = $description_long if ($description_long);
1509
1510     if ($output_dateformat) {
1511       foreach my $key (qw(netto_date skonto_date)) {
1512         $self->{$key} =
1513           $main::locale->reformat_date($myconfig, $self->{$key},
1514                                        $output_dateformat,
1515                                        $output_longdates);
1516       }
1517     }
1518
1519     if ($output_numberformat &&
1520         ($output_numberformat ne $myconfig->{"numberformat"})) {
1521       my $saved_numberformat = $myconfig->{"numberformat"};
1522       $myconfig->{"numberformat"} = $output_numberformat;
1523       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1524       $myconfig->{"numberformat"} = $saved_numberformat;
1525     }
1526   }
1527
1528   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1529   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1530   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1531   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1532   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1533   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1534   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1535
1536   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1537
1538   $main::lxdebug->leave_sub();
1539
1540 }
1541
1542 sub get_template_language {
1543   $main::lxdebug->enter_sub();
1544
1545   my ($self, $myconfig) = @_;
1546
1547   my $template_code = "";
1548
1549   if ($self->{language_id}) {
1550     my $dbh = $self->get_standard_dbh($myconfig);
1551     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1552     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1553   }
1554
1555   $main::lxdebug->leave_sub();
1556
1557   return $template_code;
1558 }
1559
1560 sub get_printer_code {
1561   $main::lxdebug->enter_sub();
1562
1563   my ($self, $myconfig) = @_;
1564
1565   my $template_code = "";
1566
1567   if ($self->{printer_id}) {
1568     my $dbh = $self->get_standard_dbh($myconfig);
1569     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1570     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1571   }
1572
1573   $main::lxdebug->leave_sub();
1574
1575   return $template_code;
1576 }
1577
1578 sub get_shipto {
1579   $main::lxdebug->enter_sub();
1580
1581   my ($self, $myconfig) = @_;
1582
1583   my $template_code = "";
1584
1585   if ($self->{shipto_id}) {
1586     my $dbh = $self->get_standard_dbh($myconfig);
1587     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1588     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1589     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1590   }
1591
1592   $main::lxdebug->leave_sub();
1593 }
1594
1595 sub add_shipto {
1596   $main::lxdebug->enter_sub();
1597
1598   my ($self, $dbh, $id, $module) = @_;
1599
1600   my $shipto;
1601   my @values;
1602
1603   foreach my $item (qw(name department_1 department_2 street zipcode city country
1604                        contact phone fax email)) {
1605     if ($self->{"shipto$item"}) {
1606       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1607     }
1608     push(@values, $self->{"shipto${item}"});
1609   }
1610
1611   if ($shipto) {
1612     if ($self->{shipto_id}) {
1613       my $query = qq|UPDATE shipto set
1614                        shiptoname = ?,
1615                        shiptodepartment_1 = ?,
1616                        shiptodepartment_2 = ?,
1617                        shiptostreet = ?,
1618                        shiptozipcode = ?,
1619                        shiptocity = ?,
1620                        shiptocountry = ?,
1621                        shiptocontact = ?,
1622                        shiptophone = ?,
1623                        shiptofax = ?,
1624                        shiptoemail = ?
1625                      WHERE shipto_id = ?|;
1626       do_query($self, $dbh, $query, @values, $self->{shipto_id});
1627     } else {
1628       my $query = qq|SELECT * FROM shipto
1629                      WHERE shiptoname = ? AND
1630                        shiptodepartment_1 = ? AND
1631                        shiptodepartment_2 = ? AND
1632                        shiptostreet = ? AND
1633                        shiptozipcode = ? AND
1634                        shiptocity = ? AND
1635                        shiptocountry = ? AND
1636                        shiptocontact = ? AND
1637                        shiptophone = ? AND
1638                        shiptofax = ? AND
1639                        shiptoemail = ? AND
1640                        module = ? AND 
1641                        trans_id = ?|;
1642       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
1643       if(!$insert_check){
1644         $query =
1645           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
1646                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
1647                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
1648              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1649         do_query($self, $dbh, $query, $id, @values, $module);
1650       }
1651     }
1652   }
1653
1654   $main::lxdebug->leave_sub();
1655 }
1656
1657 sub get_employee {
1658   $main::lxdebug->enter_sub();
1659
1660   my ($self, $dbh) = @_;
1661
1662   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
1663   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
1664   $self->{"employee_id"} *= 1;
1665
1666   $main::lxdebug->leave_sub();
1667 }
1668
1669 sub get_salesman {
1670   $main::lxdebug->enter_sub();
1671
1672   my ($self, $myconfig, $salesman_id) = @_;
1673
1674   $main::lxdebug->leave_sub() and return unless $salesman_id;
1675
1676   my $dbh = $self->get_standard_dbh($myconfig);
1677
1678   my ($login) =
1679     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
1680                     $salesman_id);
1681
1682   if ($login) {
1683     my $user = new User($main::memberfile, $login);
1684     map({ $self->{"salesman_$_"} = $user->{$_}; }
1685         qw(address businessnumber co_ustid company duns email fax name
1686            taxnumber tel));
1687     $self->{salesman_login} = $login;
1688
1689     $self->{salesman_name} = $login
1690       if ($self->{salesman_name} eq "");
1691
1692     map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
1693   }
1694
1695   $main::lxdebug->leave_sub();
1696 }
1697
1698 sub get_duedate {
1699   $main::lxdebug->enter_sub();
1700
1701   my ($self, $myconfig) = @_;
1702
1703   my $dbh = $self->get_standard_dbh($myconfig);
1704   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
1705   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
1706
1707   $main::lxdebug->leave_sub();
1708 }
1709
1710 sub _get_contacts {
1711   $main::lxdebug->enter_sub();
1712
1713   my ($self, $dbh, $id, $key) = @_;
1714
1715   $key = "all_contacts" unless ($key);
1716
1717   my $query =
1718     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
1719     qq|FROM contacts | .
1720     qq|WHERE cp_cv_id = ? | .
1721     qq|ORDER BY lower(cp_name)|;
1722
1723   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
1724
1725   $main::lxdebug->leave_sub();
1726 }
1727
1728 sub _get_projects {
1729   $main::lxdebug->enter_sub();
1730
1731   my ($self, $dbh, $key) = @_;
1732
1733   my ($all, $old_id, $where, @values);
1734
1735   if (ref($key) eq "HASH") {
1736     my $params = $key;
1737
1738     $key = "ALL_PROJECTS";
1739
1740     foreach my $p (keys(%{$params})) {
1741       if ($p eq "all") {
1742         $all = $params->{$p};
1743       } elsif ($p eq "old_id") {
1744         $old_id = $params->{$p};
1745       } elsif ($p eq "key") {
1746         $key = $params->{$p};
1747       }
1748     }
1749   }
1750
1751   if (!$all) {
1752     $where = "WHERE active ";
1753     if ($old_id) {
1754       if (ref($old_id) eq "ARRAY") {
1755         my @ids = grep({ $_ } @{$old_id});
1756         if (@ids) {
1757           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
1758           push(@values, @ids);
1759         }
1760       } else {
1761         $where .= " OR (id = ?) ";
1762         push(@values, $old_id);
1763       }
1764     }
1765   }
1766
1767   my $query =
1768     qq|SELECT id, projectnumber, description, active | .
1769     qq|FROM project | .
1770     $where .
1771     qq|ORDER BY lower(projectnumber)|;
1772
1773   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
1774
1775   $main::lxdebug->leave_sub();
1776 }
1777
1778 sub _get_shipto {
1779   $main::lxdebug->enter_sub();
1780
1781   my ($self, $dbh, $vc_id, $key) = @_;
1782
1783   $key = "all_shipto" unless ($key);
1784
1785   # get shipping addresses
1786   my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
1787
1788   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
1789
1790   $main::lxdebug->leave_sub();
1791 }
1792
1793 sub _get_printers {
1794   $main::lxdebug->enter_sub();
1795
1796   my ($self, $dbh, $key) = @_;
1797
1798   $key = "all_printers" unless ($key);
1799
1800   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
1801
1802   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1803
1804   $main::lxdebug->leave_sub();
1805 }
1806
1807 sub _get_charts {
1808   $main::lxdebug->enter_sub();
1809
1810   my ($self, $dbh, $params) = @_;
1811
1812   $key = $params->{key};
1813   $key = "all_charts" unless ($key);
1814
1815   my $transdate = quote_db_date($params->{transdate});
1816
1817   my $query =
1818     qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
1819     qq|FROM chart c | .
1820     qq|LEFT JOIN taxkeys tk ON | .
1821     qq|(tk.id = (SELECT id FROM taxkeys | .
1822     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
1823     qq|          ORDER BY startdate DESC LIMIT 1)) | .
1824     qq|ORDER BY c.accno|;
1825
1826   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1827
1828   $main::lxdebug->leave_sub();
1829 }
1830
1831 sub _get_taxcharts {
1832   $main::lxdebug->enter_sub();
1833
1834   my ($self, $dbh, $key) = @_;
1835
1836   $key = "all_taxcharts" unless ($key);
1837
1838   my $query = qq|SELECT * FROM tax ORDER BY taxkey|;
1839
1840   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1841
1842   $main::lxdebug->leave_sub();
1843 }
1844
1845 sub _get_taxzones {
1846   $main::lxdebug->enter_sub();
1847
1848   my ($self, $dbh, $key) = @_;
1849
1850   $key = "all_taxzones" unless ($key);
1851
1852   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
1853
1854   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1855
1856   $main::lxdebug->leave_sub();
1857 }
1858
1859 sub _get_employees {
1860   $main::lxdebug->enter_sub();
1861
1862   my ($self, $dbh, $default_key, $key) = @_;
1863
1864   $key = $default_key unless ($key);
1865   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY name|);
1866
1867   $main::lxdebug->leave_sub();
1868 }
1869
1870 sub _get_business_types {
1871   $main::lxdebug->enter_sub();
1872
1873   my ($self, $dbh, $key) = @_;
1874
1875   $key = "all_business_types" unless ($key);
1876   $self->{$key} =
1877     selectall_hashref_query($self, $dbh, qq|SELECT * FROM business|);
1878
1879   $main::lxdebug->leave_sub();
1880 }
1881
1882 sub _get_languages {
1883   $main::lxdebug->enter_sub();
1884
1885   my ($self, $dbh, $key) = @_;
1886
1887   $key = "all_languages" unless ($key);
1888
1889   my $query = qq|SELECT * FROM language ORDER BY id|;
1890
1891   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1892
1893   $main::lxdebug->leave_sub();
1894 }
1895
1896 sub _get_dunning_configs {
1897   $main::lxdebug->enter_sub();
1898
1899   my ($self, $dbh, $key) = @_;
1900
1901   $key = "all_dunning_configs" unless ($key);
1902
1903   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
1904
1905   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1906
1907   $main::lxdebug->leave_sub();
1908 }
1909
1910 sub _get_currencies {
1911 $main::lxdebug->enter_sub();
1912
1913   my ($self, $dbh, $key) = @_;
1914
1915   $key = "all_currencies" unless ($key);
1916
1917   my $query = qq|SELECT curr AS currency FROM defaults|;
1918  
1919   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
1920
1921   $main::lxdebug->leave_sub();
1922 }
1923
1924 sub _get_payments {
1925 $main::lxdebug->enter_sub();
1926
1927   my ($self, $dbh, $key) = @_;
1928
1929   $key = "all_payments" unless ($key);
1930
1931   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
1932  
1933   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1934
1935   $main::lxdebug->leave_sub();
1936 }
1937
1938 sub _get_customers {
1939   $main::lxdebug->enter_sub();
1940
1941   my ($self, $dbh, $key, $limit) = @_;
1942
1943   $key = "all_customers" unless ($key);
1944   $limit_clause = "LIMIT $limit" if $limit;
1945
1946   my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
1947
1948   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1949
1950   $main::lxdebug->leave_sub();
1951 }
1952
1953 sub _get_vendors {
1954   $main::lxdebug->enter_sub();
1955
1956   my ($self, $dbh, $key) = @_;
1957
1958   $key = "all_vendors" unless ($key);
1959
1960   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
1961
1962   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1963
1964   $main::lxdebug->leave_sub();
1965 }
1966
1967 sub _get_departments {
1968   $main::lxdebug->enter_sub();
1969
1970   my ($self, $dbh, $key) = @_;
1971
1972   $key = "all_departments" unless ($key);
1973
1974   my $query = qq|SELECT * FROM department ORDER BY description|;
1975
1976   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1977
1978   $main::lxdebug->leave_sub();
1979 }
1980
1981 sub _get_price_factors {
1982   $main::lxdebug->enter_sub();
1983
1984   my ($self, $dbh, $key) = @_;
1985
1986   $key ||= "all_price_factors";
1987
1988   my $query = qq|SELECT * FROM price_factors ORDER BY sortkey|;
1989
1990   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
1991
1992   $main::lxdebug->leave_sub();
1993 }
1994
1995 sub get_lists {
1996   $main::lxdebug->enter_sub();
1997
1998   my $self = shift;
1999   my %params = @_;
2000
2001   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2002   my ($sth, $query, $ref);
2003
2004   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2005   my $vc_id = $self->{"${vc}_id"};
2006
2007   if ($params{"contacts"}) {
2008     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2009   }
2010
2011   if ($params{"shipto"}) {
2012     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2013   }
2014
2015   if ($params{"projects"} || $params{"all_projects"}) {
2016     $self->_get_projects($dbh, $params{"all_projects"} ?
2017                          $params{"all_projects"} : $params{"projects"},
2018                          $params{"all_projects"} ? 1 : 0);
2019   }
2020
2021   if ($params{"printers"}) {
2022     $self->_get_printers($dbh, $params{"printers"});
2023   }
2024
2025   if ($params{"languages"}) {
2026     $self->_get_languages($dbh, $params{"languages"});
2027   }
2028
2029   if ($params{"charts"}) {
2030     $self->_get_charts($dbh, $params{"charts"});
2031   }
2032
2033   if ($params{"taxcharts"}) {
2034     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2035   }
2036
2037   if ($params{"taxzones"}) {
2038     $self->_get_taxzones($dbh, $params{"taxzones"});
2039   }
2040
2041   if ($params{"employees"}) {
2042     $self->_get_employees($dbh, "all_employees", $params{"employees"});
2043   }
2044   
2045   if ($params{"salesmen"}) {
2046     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2047   }
2048
2049   if ($params{"business_types"}) {
2050     $self->_get_business_types($dbh, $params{"business_types"});
2051   }
2052
2053   if ($params{"dunning_configs"}) {
2054     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2055   }
2056   
2057   if($params{"currencies"}) {
2058     $self->_get_currencies($dbh, $params{"currencies"});
2059   }
2060   
2061   if($params{"customers"}) {
2062     if (ref $params{"customers"} eq 'HASH') {
2063       $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
2064     } else {
2065       $self->_get_customers($dbh, $params{"customers"});
2066     }
2067   }
2068   
2069   if($params{"vendors"}) {
2070     if (ref $params{"vendors"} eq 'HASH') {
2071       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2072     } else {
2073       $self->_get_vendors($dbh, $params{"vendors"});
2074     }
2075   }
2076   
2077   if($params{"payments"}) {
2078     $self->_get_payments($dbh, $params{"payments"});
2079   }
2080
2081   if($params{"departments"}) {
2082     $self->_get_departments($dbh, $params{"departments"});
2083   }
2084
2085   if ($params{price_factors}) {
2086     $self->_get_price_factors($dbh, $params{price_factors});
2087   }
2088
2089   $main::lxdebug->leave_sub();
2090 }
2091
2092 # this sub gets the id and name from $table
2093 sub get_name {
2094   $main::lxdebug->enter_sub();
2095
2096   my ($self, $myconfig, $table) = @_;
2097
2098   # connect to database
2099   my $dbh = $self->get_standard_dbh($myconfig);
2100
2101   $table = $table eq "customer" ? "customer" : "vendor";
2102   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2103
2104   my ($query, @values);
2105
2106   if (!$self->{openinvoices}) {
2107     my $where;
2108     if ($self->{customernumber} ne "") {
2109       $where = qq|(vc.customernumber ILIKE ?)|;
2110       push(@values, '%' . $self->{customernumber} . '%');
2111     } else {
2112       $where = qq|(vc.name ILIKE ?)|;
2113       push(@values, '%' . $self->{$table} . '%');
2114     }
2115
2116     $query =
2117       qq~SELECT vc.id, vc.name,
2118            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2119          FROM $table vc
2120          WHERE $where AND (NOT vc.obsolete)
2121          ORDER BY vc.name~;
2122   } else {
2123     $query =
2124       qq~SELECT DISTINCT vc.id, vc.name,
2125            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2126          FROM $arap a
2127          JOIN $table vc ON (a.${table}_id = vc.id)
2128          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2129          ORDER BY vc.name~;
2130     push(@values, '%' . $self->{$table} . '%');
2131   }
2132
2133   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2134
2135   $main::lxdebug->leave_sub();
2136
2137   return scalar(@{ $self->{name_list} });
2138 }
2139
2140 # the selection sub is used in the AR, AP, IS, IR and OE module
2141 #
2142 sub all_vc {
2143   $main::lxdebug->enter_sub();
2144
2145   my ($self, $myconfig, $table, $module) = @_;
2146
2147   my $ref;
2148   my $dbh = $self->get_standard_dbh($myconfig);
2149
2150   $table = $table eq "customer" ? "customer" : "vendor";
2151
2152   my $query = qq|SELECT count(*) FROM $table|;
2153   my ($count) = selectrow_query($self, $dbh, $query);
2154
2155   # build selection list
2156   if ($count < $myconfig->{vclimit}) {
2157     $query = qq|SELECT id, name, salesman_id
2158                 FROM $table WHERE NOT obsolete
2159                 ORDER BY name|;
2160     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2161   }
2162
2163   # get self
2164   $self->get_employee($dbh);
2165
2166   # setup sales contacts
2167   $query = qq|SELECT e.id, e.name
2168               FROM employee e
2169               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2170   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2171
2172   # this is for self
2173   push(@{ $self->{all_employees} },
2174        { id   => $self->{employee_id},
2175          name => $self->{employee} });
2176
2177   # sort the whole thing
2178   @{ $self->{all_employees} } =
2179     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2180
2181   if ($module eq 'AR') {
2182
2183     # prepare query for departments
2184     $query = qq|SELECT id, description
2185                 FROM department
2186                 WHERE role = 'P'
2187                 ORDER BY description|;
2188
2189   } else {
2190     $query = qq|SELECT id, description
2191                 FROM department
2192                 ORDER BY description|;
2193   }
2194
2195   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2196
2197   # get languages
2198   $query = qq|SELECT id, description
2199               FROM language
2200               ORDER BY id|;
2201
2202   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2203
2204   # get printer
2205   $query = qq|SELECT printer_description, id
2206               FROM printers
2207               ORDER BY printer_description|;
2208
2209   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2210
2211   # get payment terms
2212   $query = qq|SELECT id, description
2213               FROM payment_terms
2214               ORDER BY sortkey|;
2215
2216   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2217
2218   $main::lxdebug->leave_sub();
2219 }
2220
2221 sub language_payment {
2222   $main::lxdebug->enter_sub();
2223
2224   my ($self, $myconfig) = @_;
2225
2226   my $dbh = $self->get_standard_dbh($myconfig);
2227   # get languages
2228   my $query = qq|SELECT id, description
2229                  FROM language
2230                  ORDER BY id|;
2231
2232   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2233
2234   # get printer
2235   $query = qq|SELECT printer_description, id
2236               FROM printers
2237               ORDER BY printer_description|;
2238
2239   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2240
2241   # get payment terms
2242   $query = qq|SELECT id, description
2243               FROM payment_terms
2244               ORDER BY sortkey|;
2245
2246   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2247
2248   # get buchungsgruppen
2249   $query = qq|SELECT id, description
2250               FROM buchungsgruppen|;
2251
2252   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2253
2254   $main::lxdebug->leave_sub();
2255 }
2256
2257 # this is only used for reports
2258 sub all_departments {
2259   $main::lxdebug->enter_sub();
2260
2261   my ($self, $myconfig, $table) = @_;
2262
2263   my $dbh = $self->get_standard_dbh($myconfig);
2264   my $where;
2265
2266   if ($table eq 'customer') {
2267     $where = "WHERE role = 'P' ";
2268   }
2269
2270   my $query = qq|SELECT id, description
2271                  FROM department
2272                  $where
2273                  ORDER BY description|;
2274   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2275
2276   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
2277
2278   $main::lxdebug->leave_sub();
2279 }
2280
2281 sub create_links {
2282   $main::lxdebug->enter_sub();
2283
2284   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2285
2286   my ($fld, $arap);
2287   if ($table eq "customer") {
2288     $fld = "buy";
2289     $arap = "ar";
2290   } else {
2291     $table = "vendor";
2292     $fld = "sell";
2293     $arap = "ap";
2294   }
2295
2296   $self->all_vc($myconfig, $table, $module);
2297
2298   # get last customers or vendors
2299   my ($query, $sth, $ref);
2300
2301   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2302   my %xkeyref = ();
2303
2304   if (!$self->{id}) {
2305
2306     my $transdate = "current_date";
2307     if ($self->{transdate}) {
2308       $transdate = $dbh->quote($self->{transdate});
2309     }
2310
2311     # now get the account numbers
2312     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2313                 FROM chart c, taxkeys tk
2314                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2315                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2316                 ORDER BY c.accno|;
2317
2318     $sth = $dbh->prepare($query);
2319
2320     do_statement($self, $sth, $query, '%' . $module . '%');
2321
2322     $self->{accounts} = "";
2323     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2324
2325       foreach my $key (split(/:/, $ref->{link})) {
2326         if ($key =~ /\Q$module\E/) {
2327
2328           # cross reference for keys
2329           $xkeyref{ $ref->{accno} } = $key;
2330
2331           push @{ $self->{"${module}_links"}{$key} },
2332             { accno       => $ref->{accno},
2333               description => $ref->{description},
2334               taxkey      => $ref->{taxkey_id},
2335               tax_id      => $ref->{tax_id} };
2336
2337           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2338         }
2339       }
2340     }
2341   }
2342
2343   # get taxkeys and description
2344   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2345   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2346
2347   if (($module eq "AP") || ($module eq "AR")) {
2348     # get tax rates and description
2349     $query = qq|SELECT * FROM tax|;
2350     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2351   }
2352
2353   if ($self->{id}) {
2354     $query =
2355       qq|SELECT
2356            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2357            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2358            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2359            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2360            c.name AS $table,
2361            d.description AS department,
2362            e.name AS employee
2363          FROM $arap a
2364          JOIN $table c ON (a.${table}_id = c.id)
2365          LEFT JOIN employee e ON (e.id = a.employee_id)
2366          LEFT JOIN department d ON (d.id = a.department_id)
2367          WHERE a.id = ?|;
2368     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2369
2370     foreach $key (keys %$ref) {
2371       $self->{$key} = $ref->{$key};
2372     }
2373
2374     my $transdate = "current_date";
2375     if ($self->{transdate}) {
2376       $transdate = $dbh->quote($self->{transdate});
2377     }
2378
2379     # now get the account numbers
2380     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2381                 FROM chart c
2382                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2383                 WHERE c.link LIKE ?
2384                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2385                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2386                 ORDER BY c.accno|;
2387
2388     $sth = $dbh->prepare($query);
2389     do_statement($self, $sth, $query, "%$module%");
2390
2391     $self->{accounts} = "";
2392     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2393
2394       foreach my $key (split(/:/, $ref->{link})) {
2395         if ($key =~ /\Q$module\E/) {
2396
2397           # cross reference for keys
2398           $xkeyref{ $ref->{accno} } = $key;
2399
2400           push @{ $self->{"${module}_links"}{$key} },
2401             { accno       => $ref->{accno},
2402               description => $ref->{description},
2403               taxkey      => $ref->{taxkey_id},
2404               tax_id      => $ref->{tax_id} };
2405
2406           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2407         }
2408       }
2409     }
2410
2411
2412     # get amounts from individual entries
2413     $query =
2414       qq|SELECT
2415            c.accno, c.description,
2416            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2417            p.projectnumber,
2418            t.rate, t.id
2419          FROM acc_trans a
2420          LEFT JOIN chart c ON (c.id = a.chart_id)
2421          LEFT JOIN project p ON (p.id = a.project_id)
2422          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2423                                     WHERE (tk.taxkey_id=a.taxkey) AND
2424                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2425                                         THEN tk.chart_id = a.chart_id
2426                                         ELSE 1 = 1
2427                                         END)
2428                                        OR (c.link='%tax%')) AND
2429                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2430          WHERE a.trans_id = ?
2431          AND a.fx_transaction = '0'
2432          ORDER BY a.oid, a.transdate|;
2433     $sth = $dbh->prepare($query);
2434     do_statement($self, $sth, $query, $self->{id});
2435
2436     # get exchangerate for currency
2437     $self->{exchangerate} =
2438       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2439     my $index = 0;
2440
2441     # store amounts in {acc_trans}{$key} for multiple accounts
2442     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2443       $ref->{exchangerate} =
2444         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2445       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2446         $index++;
2447       }
2448       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2449         $ref->{amount} *= -1;
2450       }
2451       $ref->{index} = $index;
2452
2453       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2454     }
2455
2456     $sth->finish;
2457     $query =
2458       qq|SELECT
2459            d.curr AS currencies, d.closedto, d.revtrans,
2460            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2461            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2462          FROM defaults d|;
2463     $ref = selectfirst_hashref_query($self, $dbh, $query);
2464     map { $self->{$_} = $ref->{$_} } keys %$ref;
2465
2466   } else {
2467
2468     # get date
2469     $query =
2470        qq|SELECT
2471             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2472             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2473             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2474           FROM defaults d|;
2475     $ref = selectfirst_hashref_query($self, $dbh, $query);
2476     map { $self->{$_} = $ref->{$_} } keys %$ref;
2477
2478     if ($self->{"$self->{vc}_id"}) {
2479
2480       # only setup currency
2481       ($self->{currency}) = split(/:/, $self->{currencies});
2482
2483     } else {
2484
2485       $self->lastname_used($dbh, $myconfig, $table, $module);
2486
2487       # get exchangerate for currency
2488       $self->{exchangerate} =
2489         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2490
2491     }
2492
2493   }
2494
2495   $main::lxdebug->leave_sub();
2496 }
2497
2498 sub lastname_used {
2499   $main::lxdebug->enter_sub();
2500
2501   my ($self, $dbh, $myconfig, $table, $module) = @_;
2502
2503   my $arap  = ($table eq 'customer') ? "ar" : "ap";
2504   $table = $table eq "customer" ? "customer" : "vendor";
2505   my $where = "1 = 1";
2506
2507   if ($self->{type} =~ /_order/) {
2508     $arap  = 'oe';
2509     $where = "quotation = '0'";
2510   }
2511   if ($self->{type} =~ /_quotation/) {
2512     $arap  = 'oe';
2513     $where = "quotation = '1'";
2514   }
2515
2516   my $query = qq|SELECT MAX(id) FROM $arap
2517                  WHERE $where AND ${table}_id > 0|;
2518   my ($trans_id) = selectrow_query($self, $dbh, $query);
2519
2520   $trans_id *= 1;
2521   $query =
2522     qq|SELECT
2523          a.curr, a.${table}_id, a.department_id,
2524          d.description AS department,
2525          ct.name, current_date + ct.terms AS duedate
2526        FROM $arap a
2527        LEFT JOIN $table ct ON (a.${table}_id = ct.id)
2528        LEFT JOIN department d ON (a.department_id = d.id)
2529        WHERE a.id = ?|;
2530   ($self->{currency},   $self->{"${table}_id"}, $self->{department_id},
2531    $self->{department}, $self->{$table},        $self->{duedate})
2532     = selectrow_query($self, $dbh, $query, $trans_id);
2533
2534   $main::lxdebug->leave_sub();
2535 }
2536
2537 sub current_date {
2538   $main::lxdebug->enter_sub();
2539
2540   my ($self, $myconfig, $thisdate, $days) = @_;
2541
2542   my $dbh = $self->get_standard_dbh($myconfig);
2543   my $query;
2544
2545   $days *= 1;
2546   if ($thisdate) {
2547     my $dateformat = $myconfig->{dateformat};
2548     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2549     $thisdate = $dbh->quote($thisdate);
2550     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
2551   } else {
2552     $query = qq|SELECT current_date AS thisdate|;
2553   }
2554
2555   ($thisdate) = selectrow_query($self, $dbh, $query);
2556
2557   $main::lxdebug->leave_sub();
2558
2559   return $thisdate;
2560 }
2561
2562 sub like {
2563   $main::lxdebug->enter_sub();
2564
2565   my ($self, $string) = @_;
2566
2567   if ($string !~ /%/) {
2568     $string = "%$string%";
2569   }
2570
2571   $string =~ s/\'/\'\'/g;
2572
2573   $main::lxdebug->leave_sub();
2574
2575   return $string;
2576 }
2577
2578 sub redo_rows {
2579   $main::lxdebug->enter_sub();
2580
2581   my ($self, $flds, $new, $count, $numrows) = @_;
2582
2583   my @ndx = ();
2584
2585   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
2586
2587   my $i = 0;
2588
2589   # fill rows
2590   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
2591     $i++;
2592     $j = $item->{ndx} - 1;
2593     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
2594   }
2595
2596   # delete empty rows
2597   for $i ($count + 1 .. $numrows) {
2598     map { delete $self->{"${_}_$i"} } @{$flds};
2599   }
2600
2601   $main::lxdebug->leave_sub();
2602 }
2603
2604 sub update_status {
2605   $main::lxdebug->enter_sub();
2606
2607   my ($self, $myconfig) = @_;
2608
2609   my ($i, $id);
2610
2611   my $dbh = $self->dbconnect_noauto($myconfig);
2612
2613   my $query = qq|DELETE FROM status
2614                  WHERE (formname = ?) AND (trans_id = ?)|;
2615   my $sth = prepare_query($self, $dbh, $query);
2616
2617   if ($self->{formname} =~ /(check|receipt)/) {
2618     for $i (1 .. $self->{rowcount}) {
2619       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
2620     }
2621   } else {
2622     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
2623   }
2624   $sth->finish();
2625
2626   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2627   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2628
2629   my %queued = split / /, $self->{queued};
2630   my @values;
2631
2632   if ($self->{formname} =~ /(check|receipt)/) {
2633
2634     # this is a check or receipt, add one entry for each lineitem
2635     my ($accno) = split /--/, $self->{account};
2636     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
2637                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
2638     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
2639     $sth = prepare_query($self, $dbh, $query);
2640
2641     for $i (1 .. $self->{rowcount}) {
2642       if ($self->{"checked_$i"}) {
2643         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
2644       }
2645     }
2646     $sth->finish();
2647
2648   } else {
2649     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2650                 VALUES (?, ?, ?, ?, ?)|;
2651     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
2652              $queued{$self->{formname}}, $self->{formname});
2653   }
2654
2655   $dbh->commit;
2656   $dbh->disconnect;
2657
2658   $main::lxdebug->leave_sub();
2659 }
2660
2661 sub save_status {
2662   $main::lxdebug->enter_sub();
2663
2664   my ($self, $dbh) = @_;
2665
2666   my ($query, $printed, $emailed);
2667
2668   my $formnames  = $self->{printed};
2669   my $emailforms = $self->{emailed};
2670
2671   $query = qq|DELETE FROM status
2672                  WHERE (formname = ?) AND (trans_id = ?)|;
2673   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
2674
2675   # this only applies to the forms
2676   # checks and receipts are posted when printed or queued
2677
2678   if ($self->{queued}) {
2679     my %queued = split / /, $self->{queued};
2680
2681     foreach my $formname (keys %queued) {
2682       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2683       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
2684
2685       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
2686                   VALUES (?, ?, ?, ?, ?)|;
2687       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
2688
2689       $formnames  =~ s/\Q$self->{formname}\E//;
2690       $emailforms =~ s/\Q$self->{formname}\E//;
2691
2692     }
2693   }
2694
2695   # save printed, emailed info
2696   $formnames  =~ s/^ +//g;
2697   $emailforms =~ s/^ +//g;
2698
2699   my %status = ();
2700   map { $status{$_}{printed} = 1 } split / +/, $formnames;
2701   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
2702
2703   foreach my $formname (keys %status) {
2704     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
2705     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
2706
2707     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2708                 VALUES (?, ?, ?, ?)|;
2709     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
2710   }
2711
2712   $main::lxdebug->leave_sub();
2713 }
2714
2715 #--- 4 locale ---#
2716 # $main::locale->text('SAVED')
2717 # $main::locale->text('DELETED')
2718 # $main::locale->text('ADDED')
2719 # $main::locale->text('PAYMENT POSTED')
2720 # $main::locale->text('POSTED')
2721 # $main::locale->text('POSTED AS NEW')
2722 # $main::locale->text('ELSE')
2723 # $main::locale->text('SAVED FOR DUNNING')
2724 # $main::locale->text('DUNNING STARTED')
2725 # $main::locale->text('PRINTED')
2726 # $main::locale->text('MAILED')
2727 # $main::locale->text('SCREENED')
2728 # $main::locale->text('CANCELED')
2729 # $main::locale->text('invoice')
2730 # $main::locale->text('proforma')
2731 # $main::locale->text('sales_order')
2732 # $main::locale->text('packing_list')
2733 # $main::locale->text('pick_list')
2734 # $main::locale->text('purchase_order')
2735 # $main::locale->text('bin_list')
2736 # $main::locale->text('sales_quotation')
2737 # $main::locale->text('request_quotation')
2738
2739 sub save_history {
2740   $main::lxdebug->enter_sub();
2741
2742   my $self = shift();
2743   my $dbh = shift();
2744
2745   if(!exists $self->{employee_id}) {
2746     &get_employee($self, $dbh);
2747   }
2748
2749   my $query =
2750    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
2751    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
2752   my @values = (conv_i($self->{id}), $self->{login},
2753                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
2754   do_query($self, $dbh, $query, @values);
2755
2756   $main::lxdebug->leave_sub();
2757 }
2758
2759 sub get_history {
2760   $main::lxdebug->enter_sub();
2761
2762   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
2763   my ($orderBy, $desc) = split(/\-\-/, $order);
2764   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
2765   my @tempArray;
2766   my $i = 0;
2767   if ($trans_id ne "") {
2768     my $query =
2769       qq|SELECT h.employee_id, h.itime::timestamp(0) AS itime, h.addition, h.what_done, emp.name, h.snumbers, h.trans_id AS id | .
2770       qq|FROM history_erp h | .
2771       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
2772       qq|WHERE trans_id = | . $trans_id
2773       . $restriction . qq| |
2774       . $order;
2775       
2776     my $sth = $dbh->prepare($query) || $self->dberror($query);
2777
2778     $sth->execute() || $self->dberror("$query");
2779
2780     while(my $hash_ref = $sth->fetchrow_hashref()) {
2781       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
2782       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
2783       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
2784       $tempArray[$i++] = $hash_ref;
2785     }
2786     $main::lxdebug->leave_sub() and return \@tempArray 
2787       if ($i > 0 && $tempArray[0] ne "");
2788   }
2789   $main::lxdebug->leave_sub();
2790   return 0;
2791 }
2792
2793 sub update_defaults {
2794   $main::lxdebug->enter_sub();
2795
2796   my ($self, $myconfig, $fld, $provided_dbh) = @_;
2797
2798   my $dbh;
2799   if ($provided_dbh) {
2800     $dbh = $provided_dbh;
2801   } else {
2802     $dbh = $self->dbconnect_noauto($myconfig);
2803   }
2804   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2805   my $sth   = $dbh->prepare($query);
2806
2807   $sth->execute || $self->dberror($query);
2808   my ($var) = $sth->fetchrow_array;
2809   $sth->finish;
2810
2811   if ($var =~ m/\d+$/) {
2812     my $new_var  = (substr $var, $-[0]) * 1 + 1;
2813     my $len_diff = length($var) - $-[0] - length($new_var);
2814     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
2815
2816   } else {
2817     $var = $var . '1';
2818   }
2819
2820   $query = qq|UPDATE defaults SET $fld = ?|;
2821   do_query($self, $dbh, $query, $var);
2822
2823   if (!$provided_dbh) {
2824     $dbh->commit;
2825     $dbh->disconnect;
2826   }
2827
2828   $main::lxdebug->leave_sub();
2829
2830   return $var;
2831 }
2832
2833 sub update_business {
2834   $main::lxdebug->enter_sub();
2835
2836   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
2837
2838   my $dbh;
2839   if ($provided_dbh) {
2840     $dbh = $provided_dbh;
2841   } else {
2842     $dbh = $self->dbconnect_noauto($myconfig);
2843   }
2844   my $query =
2845     qq|SELECT customernumberinit FROM business
2846        WHERE id = ? FOR UPDATE|;
2847   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
2848
2849   if ($var =~ m/\d+$/) {
2850     my $new_var  = (substr $var, $-[0]) * 1 + 1;
2851     my $len_diff = length($var) - $-[0] - length($new_var);
2852     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
2853
2854   } else {
2855     $var = $var . '1';
2856   }
2857
2858   $query = qq|UPDATE business
2859               SET customernumberinit = ?
2860               WHERE id = ?|;
2861   do_query($self, $dbh, $query, $var, $business_id);
2862
2863   if (!$provided_dbh) {
2864     $dbh->commit;
2865     $dbh->disconnect;
2866   }
2867
2868   $main::lxdebug->leave_sub();
2869
2870   return $var;
2871 }
2872
2873 sub get_partsgroup {
2874   $main::lxdebug->enter_sub();
2875
2876   my ($self, $myconfig, $p) = @_;
2877
2878   my $dbh = $self->get_standard_dbh($myconfig);
2879
2880   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2881                  FROM partsgroup pg
2882                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
2883   my @values;
2884
2885   if ($p->{searchitems} eq 'part') {
2886     $query .= qq|WHERE p.inventory_accno_id > 0|;
2887   }
2888   if ($p->{searchitems} eq 'service') {
2889     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
2890   }
2891   if ($p->{searchitems} eq 'assembly') {
2892     $query .= qq|WHERE p.assembly = '1'|;
2893   }
2894   if ($p->{searchitems} eq 'labor') {
2895     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
2896   }
2897
2898   $query .= qq|ORDER BY partsgroup|;
2899
2900   if ($p->{all}) {
2901     $query = qq|SELECT id, partsgroup FROM partsgroup
2902                 ORDER BY partsgroup|;
2903   }
2904
2905   if ($p->{language_code}) {
2906     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2907                   t.description AS translation
2908                 FROM partsgroup pg
2909                 JOIN parts p ON (p.partsgroup_id = pg.id)
2910                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
2911                 ORDER BY translation|;
2912     @values = ($p->{language_code});
2913   }
2914
2915   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
2916
2917   $main::lxdebug->leave_sub();
2918 }
2919
2920 sub get_pricegroup {
2921   $main::lxdebug->enter_sub();
2922
2923   my ($self, $myconfig, $p) = @_;
2924
2925   my $dbh = $self->get_standard_dbh($myconfig);
2926
2927   my $query = qq|SELECT p.id, p.pricegroup
2928                  FROM pricegroup p|;
2929
2930   $query .= qq| ORDER BY pricegroup|;
2931
2932   if ($p->{all}) {
2933     $query = qq|SELECT id, pricegroup FROM pricegroup
2934                 ORDER BY pricegroup|;
2935   }
2936
2937   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
2938
2939   $main::lxdebug->leave_sub();
2940 }
2941
2942 sub all_years {
2943 # usage $form->all_years($myconfig, [$dbh])
2944 # return list of all years where bookings found
2945 # (@all_years)
2946
2947   $main::lxdebug->enter_sub();
2948
2949   my ($self, $myconfig, $dbh) = @_;
2950
2951   $dbh ||= $self->get_standard_dbh($myconfig);
2952
2953   # get years
2954   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
2955                    (SELECT MAX(transdate) FROM acc_trans)|;
2956   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
2957
2958   if ($myconfig->{dateformat} =~ /^yy/) {
2959     ($startdate) = split /\W/, $startdate;
2960     ($enddate) = split /\W/, $enddate;
2961   } else {
2962     (@_) = split /\W/, $startdate;
2963     $startdate = $_[2];
2964     (@_) = split /\W/, $enddate;
2965     $enddate = $_[2];
2966   }
2967
2968   my @all_years;
2969   $startdate = substr($startdate,0,4);
2970   $enddate = substr($enddate,0,4);
2971
2972   while ($enddate >= $startdate) {
2973     push @all_years, $enddate--;
2974   }
2975
2976   return @all_years;
2977
2978   $main::lxdebug->leave_sub();
2979 }
2980
2981 1;