Debug-Code entfernt
[kivitendo-erp.git] / SL / Common.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
9 package Common;
10
11 use Time::HiRes qw(gettimeofday);
12
13 use SL::DBUtils;
14
15 use vars qw(@db_encodings %db_encoding_to_charset);
16
17 @db_encodings = (
18   { "label" => "ASCII",          "dbencoding" => "SQL_ASCII", "charset" => "ASCII" },
19   { "label" => "UTF-8 Unicode",  "dbencoding" => "UNICODE",   "charset" => "UTF-8" },
20   { "label" => "ISO 8859-1",     "dbencoding" => "LATIN1",    "charset" => "ISO-8859-1" },
21   { "label" => "ISO 8859-2",     "dbencoding" => "LATIN2",    "charset" => "ISO-8859-2" },
22   { "label" => "ISO 8859-3",     "dbencoding" => "LATIN3",    "charset" => "ISO-8859-3" },
23   { "label" => "ISO 8859-4",     "dbencoding" => "LATIN4",    "charset" => "ISO-8859-4" },
24   { "label" => "ISO 8859-5",     "dbencoding" => "LATIN5",    "charset" => "ISO-8859-5" },
25   { "label" => "ISO 8859-15",    "dbencoding" => "LATIN9",    "charset" => "ISO-8859-15" },
26   { "label" => "KOI8-R",         "dbencoding" => "KOI8",      "charset" => "KOI8-R" },
27   { "label" => "Windows CP1251", "dbencoding" => "WIN",       "charset" => "CP1251" },
28   { "label" => "Windows CP866",  "dbencoding" => "ALT",       "charset" => "CP866" },
29 );
30
31 %db_encoding_to_charset = map { $_->{dbencoding}, $_->{charset} } @db_encodings;
32 %charset_to_db_encoding = map { $_->{charset}, $_->{dbencoding} } @db_encodings;
33
34 use constant DEFAULT_CHARSET => 'ISO-8859-15';
35
36 sub unique_id {
37   my ($a, $b) = gettimeofday();
38   return "${a}-${b}-${$}";
39 }
40
41 sub tmpname {
42   return "/tmp/lx-office-tmp-" . unique_id();
43 }
44
45 sub retrieve_parts {
46   $main::lxdebug->enter_sub();
47
48   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
49
50   my $dbh = $form->dbconnect($myconfig);
51
52   my (@filter_values, $filter);
53
54   foreach (qw(partnumber description)) {
55     next unless $form->{$_};
56
57     $filter .= qq| AND ($_ ILIKE ?)|;
58     push @filter_values, '%' . $form->{$_} . '%';
59   }
60
61   if ($form->{no_assemblies}) {
62     $filter .= qq| AND (NOT COALESCE(assembly, FALSE))|;
63   }
64   if ($form->{assemblies}) {
65     $filter .= qq| AND assembly=TRUE|;          # alles was assembly ist rausgeben erweiterung für bin/mozilla/wh.pl -> transfer_assembly_update_part 
66 # eigentlich möchte ich diesen filter abbilden: 
67 # select distinct partnumber  from parts inner join assembly on (parts.id = assembly.id) where assembly='t';
68 # und so common ist die anweisung gar nicht. wie wäre es mit auslagern in WH.pm? -> get_all_working_assemblies? jb 21.2.2009
69   }
70
71   if ($form->{no_services}) {
72     $filter .= qq| AND (inventory_accno_id is not NULL or assembly=TRUE)|; # @mb hier nochmal optimieren ... nach kurzer ruecksprache alles i.o. 
73   }
74
75   substr($filter, 1, 3) = "WHERE" if ($filter);
76
77   $order_by =~ s/[^a-zA-Z_]//g;
78   $order_dir = $order_dir ? "ASC" : "DESC";
79
80   my $query =
81     qq|SELECT id, partnumber, description | .
82     qq|FROM parts $filter | .
83     qq|ORDER BY $order_by $order_dir|;
84   my $sth = $dbh->prepare($query);
85   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
86     open STDERR, ">>/usr/local/src/lxoffice/users/de.log" or die $!; print STDERR "hier:" . $query . "filter " . $filter . "filterwerte:" . $filter_values[0] .  "\n"; close STDERR;
87   my $parts = [];
88   while (my $ref = $sth->fetchrow_hashref()) {
89     push(@{$parts}, $ref);
90   }
91   $sth->finish();
92   $dbh->disconnect();
93
94   $main::lxdebug->leave_sub();
95
96   return $parts;
97 }
98
99 sub retrieve_projects {
100   $main::lxdebug->enter_sub();
101
102   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
103
104   my $dbh = $form->dbconnect($myconfig);
105
106   my (@filter_values, $filter);
107   if ($form->{"projectnumber"}) {
108     $filter .= qq| AND (projectnumber ILIKE ?)|;
109     push(@filter_values, '%' . $form->{"projectnumber"} . '%');
110   }
111   if ($form->{"description"}) {
112     $filter .= qq| AND (description ILIKE ?)|;
113     push(@filter_values, '%' . $form->{"description"} . '%');
114   }
115   substr($filter, 1, 3) = "WHERE" if ($filter);
116
117   $order_by =~ s/[^a-zA-Z_]//g;
118   $order_dir = $order_dir ? "ASC" : "DESC";
119
120   my $query =
121     qq|SELECT id, projectnumber, description | .
122     qq|FROM project $filter | .
123     qq|ORDER BY $order_by $order_dir|;
124   my $sth = $dbh->prepare($query);
125   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
126   my $projects = [];
127   while (my $ref = $sth->fetchrow_hashref()) {
128     push(@{$projects}, $ref);
129   }
130   $sth->finish();
131   $dbh->disconnect();
132
133   $main::lxdebug->leave_sub();
134
135   return $projects;
136 }
137
138 sub retrieve_employees {
139   $main::lxdebug->enter_sub();
140
141   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
142
143   my $dbh = $form->dbconnect($myconfig);
144
145   my (@filter_values, $filter);
146   if ($form->{"name"}) {
147     $filter .= qq| AND (name ILIKE ?)|;
148     push(@filter_values, '%' . $form->{"name"} . '%');
149   }
150   substr($filter, 1, 3) = "WHERE" if ($filter);
151
152   $order_by =~ s/[^a-zA-Z_]//g;
153   $order_dir = $order_dir ? "ASC" : "DESC";
154
155   my $query =
156     qq|SELECT id, name | .
157     qq|FROM employee $filter | .
158     qq|ORDER BY $order_by $order_dir|;
159   my $sth = $dbh->prepare($query);
160   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
161   my $employees = [];
162   while (my $ref = $sth->fetchrow_hashref()) {
163     push(@{$employees}, $ref);
164   }
165   $sth->finish();
166   $dbh->disconnect();
167
168   $main::lxdebug->leave_sub();
169
170   return $employees;
171 }
172
173 sub retrieve_customers_or_vendors {
174   $main::lxdebug->enter_sub();
175
176   my ($self, $myconfig, $form, $order_by, $order_dir, $is_vendor, $allow_both) = @_;
177
178   my $dbh = $form->dbconnect($myconfig);
179
180   my (@filter_values, $filter);
181   if ($form->{"name"}) {
182     $filter .= " AND (TABLE.name ILIKE ?)";
183     push(@filter_values, '%' . $form->{"name"} . '%');
184   }
185   if (!$form->{"obsolete"}) {
186     $filter .= " AND NOT TABLE.obsolete";
187   }
188   substr($filter, 1, 3) = "WHERE" if ($filter);
189
190   $order_by =~ s/[^a-zA-Z_]//g;
191   $order_dir = $order_dir ? "ASC" : "DESC";
192
193   my (@queries, @query_parameters);
194
195   if ($allow_both || !$is_vendor) {
196     my $c_filter = $filter;
197     $c_filter =~ s/TABLE/c/g;
198     push(@queries, qq|SELECT
199                         c.id, c.name, 0 AS customer_is_vendor,
200                         c.street, c.zipcode, c.city,
201                         ct.cp_greeting, ct.cp_title, ct.cp_givenname, ct.cp_name
202                       FROM customer c
203                       LEFT JOIN contacts ct ON (c.id = ct.cp_cv_id)
204                       $c_filter|);
205     push(@query_parameters, @filter_values);
206   }
207
208   if ($allow_both || $is_vendor) {
209     my $v_filter = $filter;
210     $v_filter =~ s/TABLE/v/g;
211     push(@queries, qq|SELECT
212                         v.id, v.name, 1 AS customer_is_vendor,
213                         v.street, v.zipcode, v.city,
214                         ct.cp_greeting, ct.cp_title, ct.cp_givenname, ct.cp_name
215                       FROM vendor v
216                       LEFT JOIN contacts ct ON (v.id = ct.cp_cv_id)
217                       $v_filter|);
218     push(@query_parameters, @filter_values);
219   }
220
221   my $query = join(" UNION ", @queries) . " ORDER BY $order_by $order_dir";
222   my $sth = $dbh->prepare($query);
223   $sth->execute(@query_parameters) || $form->dberror($query . " (" . join(", ", @query_parameters) . ")");
224   my $customers = [];
225   while (my $ref = $sth->fetchrow_hashref()) {
226     push(@{$customers}, $ref);
227   }
228   $sth->finish();
229   $dbh->disconnect();
230
231   $main::lxdebug->leave_sub();
232
233   return $customers;
234 }
235
236 sub retrieve_delivery_customer {
237   $main::lxdebug->enter_sub();
238
239   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
240
241   my $dbh = $form->dbconnect($myconfig);
242
243   my (@filter_values, $filter);
244   if ($form->{"name"}) {
245     $filter .= qq| (name ILIKE ?) AND|;
246     push(@filter_values, '%' . $form->{"name"} . '%');
247   }
248
249   $order_by =~ s/[^a-zA-Z_]//g;
250   $order_dir = $order_dir ? "ASC" : "DESC";
251
252   my $query =
253     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
254     qq!FROM customer ! .
255     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
256     qq!ORDER BY $order_by $order_dir!;
257   my $sth = $dbh->prepare($query);
258   $sth->execute(@filter_values) ||
259     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
260   my $delivery_customers = [];
261   while (my $ref = $sth->fetchrow_hashref()) {
262     push(@{$delivery_customers}, $ref);
263   }
264   $sth->finish();
265   $dbh->disconnect();
266
267   $main::lxdebug->leave_sub();
268
269   return $delivery_customers;
270 }
271
272 sub retrieve_vendor {
273   $main::lxdebug->enter_sub();
274
275   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
276
277   my $dbh = $form->dbconnect($myconfig);
278
279   my (@filter_values, $filter);
280   if ($form->{"name"}) {
281     $filter .= qq| (name ILIKE ?) AND|;
282     push(@filter_values, '%' . $form->{"name"} . '%');
283   }
284
285   $order_by =~ s/[^a-zA-Z_]//g;
286   $order_dir = $order_dir ? "ASC" : "DESC";
287
288   my $query =
289     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
290     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Händler') ! .
291     qq!ORDER BY $order_by $order_dir!;
292   my $sth = $dbh->prepare($query);
293   $sth->execute(@filter_values) ||
294     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
295   my $vendors = [];
296   while (my $ref = $sth->fetchrow_hashref()) {
297     push(@{$vendors}, $ref);
298   }
299   $sth->finish();
300   $dbh->disconnect();
301
302   $main::lxdebug->leave_sub();
303
304   return $vendors;
305 }
306
307 sub mkdir_with_parents {
308   $main::lxdebug->enter_sub();
309
310   my ($full_path) = @_;
311
312   my $path = "";
313
314   $full_path =~ s|/+|/|;
315
316   foreach my $part (split(m|/|, $full_path)) {
317     $path .= "/" if ($path);
318     $path .= $part;
319
320     die("Could not create directory '$path' because a file exists with " .
321         "the same name.\n") if (-f $path);
322
323     if (! -d $path) {
324       mkdir($path, 0770) || die("Could not create the directory '$path'. " .
325                                 "OS error: $!\n");
326     }
327   }
328
329   $main::lxdebug->leave_sub();
330 }
331
332 sub webdav_folder {
333   $main::lxdebug->enter_sub();
334
335   my ($form) = @_;
336
337   return $main::lxdebug->leave_sub()
338     unless ($main::webdav && $form->{id});
339
340   my ($path, $number);
341
342   $form->{WEBDAV} = [];
343
344   if ($form->{type} eq "sales_quotation") {
345     ($path, $number) = ("angebote", $form->{quonumber});
346   } elsif ($form->{type} eq "sales_order") {
347     ($path, $number) = ("bestellungen", $form->{ordnumber});
348   } elsif ($form->{type} eq "request_quotation") {
349     ($path, $number) = ("anfragen", $form->{quonumber});
350   } elsif ($form->{type} eq "purchase_order") {
351     ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
352   } elsif ($form->{type} eq "credit_note") {
353     ($path, $number) = ("gutschriften", $form->{invnumber});
354   } elsif ($form->{vc} eq "customer") {
355     ($path, $number) = ("rechnungen", $form->{invnumber});
356   } else {
357     ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
358   }
359
360   return $main::lxdebug->leave_sub() unless ($path && $number);
361
362   $number =~ s|[/\\]|_|g;
363
364   $path = "webdav/${path}/${number}";
365
366   if (!-d $path) {
367     mkdir_with_parents($path);
368
369   } else {
370     my $base_path = substr($ENV{'SCRIPT_NAME'}, 1);
371     $base_path =~ s|[^/]+$||;
372     $base_path =~ s|/$||;
373     # wo kommt der wert für dir her? es wird doch gar nichts übergeben? fix für strict my $dir jb 21.2.
374     if (opendir my $dir, $path) {
375       foreach my $file (sort { lc $a cmp lc $b } readdir $dir) {
376         next if (($file eq '.') || ($file eq '..'));
377
378         my $fname = $file;
379         $fname  =~ s|.*/||;
380
381         my $is_directory = -d "$path/$file";
382
383         $file  = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
384         $file .=  '/' if ($is_directory);
385
386         push @{ $form->{WEBDAV} }, {
387           'name' => $fname,
388           'link' => ($ENV{"HTTPS"} ? "https://" : "http://") . $ENV{'SERVER_NAME'} . "/$base_path/$file",
389           'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
390         };
391       }
392
393       closedir $dir;
394     }
395   }
396
397   $main::lxdebug->leave_sub();
398 }
399
400 sub get_vc_details {
401   $main::lxdebug->enter_sub();
402
403   my ($self, $myconfig, $form, $vc, $vc_id) = @_;
404
405   $vc = $vc eq "customer" ? "customer" : "vendor";
406
407   my $dbh = $form->dbconnect($myconfig);
408
409   my $query;
410
411   $query =
412     qq|SELECT
413          vc.*,
414          pt.description AS payment_terms,
415          b.description AS business,
416          l.description AS language
417        FROM ${vc} vc
418        LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
419        LEFT JOIN business b ON (vc.business_id = b.id)
420        LEFT JOIN language l ON (vc.language_id = l.id)
421        WHERE vc.id = ?|;
422   my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
423
424   if (!$ref) {
425     $dbh->disconnect();
426     $main::lxdebug->leave_sub();
427     return 0;
428   }
429
430   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
431
432   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
433
434   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
435   $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
436
437   $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
438   $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
439
440   $dbh->disconnect();
441
442   $main::lxdebug->leave_sub();
443
444   return 1;
445 }
446
447 sub get_shipto_by_id {
448   $main::lxdebug->enter_sub();
449
450   my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
451
452   $prefix ||= "";
453
454   my $dbh = $form->dbconnect($myconfig);
455
456   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
457   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
458
459   map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
460
461   $dbh->disconnect();
462
463   $main::lxdebug->leave_sub();
464 }
465
466 sub save_email_status {
467   $main::lxdebug->enter_sub();
468
469   my ($self, $myconfig, $form) = @_;
470
471   my ($table, $query, $dbh);
472
473   if ($form->{script} eq 'oe.pl') {
474     $table = 'oe';
475
476   } elsif ($form->{script} eq 'is.pl') {
477     $table = 'ar';
478
479   } elsif ($form->{script} eq 'ir.pl') {
480     $table = 'ap';
481
482   }
483
484   return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
485
486   $dbh = $form->get_standard_dbh($myconfig);
487
488   my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
489
490   $intnotes =~ s|\r||g;
491   $intnotes =~ s|\n$||;
492
493   $intnotes .= "\n\n" if ($intnotes);
494
495   my $cc  = $main::locale->text('Cc') . ": $form->{cc}\n"   if $form->{cc};
496   my $bcc = $main::locale->text('Bcc') . ": $form->{bcc}\n" if $form->{bcc};
497   my $now = scalar localtime;
498
499   $intnotes .= $main::locale->text('[email]') . "\n"
500     . $main::locale->text('Date') . ": $now\n"
501     . $main::locale->text('To (email)') . ": $form->{email}\n"
502     . "${cc}${bcc}"
503     . $main::locale->text('Subject') . ": $form->{subject}\n\n"
504     . $main::locale->text('Message') . ": $form->{message}";
505
506   $intnotes =~ s|\r||g;
507
508   do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
509
510   $form->save_status($dbh);
511
512   $dbh->commit();
513
514   $main::lxdebug->leave_sub();
515 }
516
517 sub check_params {
518   my $params = shift;
519
520   foreach my $key (@_) {
521     if ((ref $key eq '') && !defined $params->{$key}) {
522       my $subroutine = (caller(1))[3];
523       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
524
525     } elsif (ref $key eq 'ARRAY') {
526       my $found = 0;
527       foreach my $subkey (@{ $key }) {
528         if (defined $params->{$subkey}) {
529           $found = 1;
530           last;
531         }
532       }
533
534       if (!$found) {
535         my $subroutine = (caller(1))[3];
536         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
537       }
538     }
539   }
540 }
541
542 sub check_params_x {
543   my $params = shift;
544
545   foreach my $key (@_) {
546     if ((ref $key eq '') && !exists $params->{$key}) {
547       my $subroutine = (caller(1))[3];
548       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
549
550     } elsif (ref $key eq 'ARRAY') {
551       my $found = 0;
552       foreach my $subkey (@{ $key }) {
553         if (exists $params->{$subkey}) {
554           $found = 1;
555           last;
556         }
557       }
558
559       if (!$found) {
560         my $subroutine = (caller(1))[3];
561         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
562       }
563     }
564   }
565 }
566
567 1;