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