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