Konfigurationsort für viele Flags ist Abschnitt 'features', nicht 'system'
[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 utf8;
12 use strict;
13
14 use Time::HiRes qw(gettimeofday);
15 use Data::Dumper;
16
17 use SL::DBUtils;
18
19 use vars qw(@db_encodings %db_encoding_to_charset %charset_to_db_encoding);
20
21 @db_encodings = (
22   { "label" => "ASCII",          "dbencoding" => "SQL_ASCII", "charset" => "ASCII" },
23   { "label" => "UTF-8 Unicode",  "dbencoding" => "UNICODE",   "charset" => "UTF-8" },
24   { "label" => "ISO 8859-1",     "dbencoding" => "LATIN1",    "charset" => "ISO-8859-1" },
25   { "label" => "ISO 8859-2",     "dbencoding" => "LATIN2",    "charset" => "ISO-8859-2" },
26   { "label" => "ISO 8859-3",     "dbencoding" => "LATIN3",    "charset" => "ISO-8859-3" },
27   { "label" => "ISO 8859-4",     "dbencoding" => "LATIN4",    "charset" => "ISO-8859-4" },
28   { "label" => "ISO 8859-5",     "dbencoding" => "LATIN5",    "charset" => "ISO-8859-5" },
29   { "label" => "ISO 8859-15",    "dbencoding" => "LATIN9",    "charset" => "ISO-8859-15" },
30   { "label" => "KOI8-R",         "dbencoding" => "KOI8",      "charset" => "KOI8-R" },
31   { "label" => "Windows CP1251", "dbencoding" => "WIN",       "charset" => "CP1251" },
32   { "label" => "Windows CP866",  "dbencoding" => "ALT",       "charset" => "CP866" },
33 );
34
35 %db_encoding_to_charset = map { $_->{dbencoding}, $_->{charset} } @db_encodings;
36 %charset_to_db_encoding = map { $_->{charset}, $_->{dbencoding} } @db_encodings;
37
38 use constant DEFAULT_CHARSET => 'ISO-8859-15';
39
40 sub unique_id {
41   my ($a, $b) = gettimeofday();
42   return "${a}-${b}-${$}";
43 }
44
45 sub tmpname {
46   return "/tmp/lx-office-tmp-" . unique_id();
47 }
48
49 sub retrieve_parts {
50   $main::lxdebug->enter_sub();
51
52   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
53
54   my $dbh = $form->dbconnect($myconfig);
55
56   my (@filter_values, $filter);
57
58   foreach (qw(partnumber description ean)) {
59     next unless $form->{$_};
60
61     $filter .= qq| AND ($_ ILIKE ?)|;
62     push @filter_values, '%' . $form->{$_} . '%';
63   }
64
65   if ($form->{no_assemblies}) {
66     $filter .= qq| AND (NOT COALESCE(assembly, FALSE))|;
67   }
68   if ($form->{assemblies}) {
69     $filter .= qq| AND assembly=TRUE|;
70   }
71
72   if ($form->{no_services}) {
73     $filter .= qq| AND (inventory_accno_id is not NULL or assembly=TRUE)|; # @mb hier nochmal optimieren ... nach kurzer ruecksprache alles i.o.
74   }
75
76   substr($filter, 1, 3) = "WHERE" if ($filter);
77
78   $order_by =~ s/[^a-zA-Z_]//g;
79   $order_dir = $order_dir ? "ASC" : "DESC";
80
81   my $query =
82     qq|SELECT id, partnumber, description, ean | .
83     qq|FROM parts $filter | .
84     qq|ORDER BY $order_by $order_dir|;
85   my $sth = $dbh->prepare($query);
86   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
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_gender, 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_gender, 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 = ?') ! .
291     qq!ORDER BY $order_by $order_dir!;
292   push @filter_values, $::locale->{iconv_utf8}->convert('Händler');
293   my $sth = $dbh->prepare($query);
294   $sth->execute(@filter_values) ||
295     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
296   my $vendors = [];
297   while (my $ref = $sth->fetchrow_hashref()) {
298     push(@{$vendors}, $ref);
299   }
300   $sth->finish();
301   $dbh->disconnect();
302
303   $main::lxdebug->leave_sub();
304
305   return $vendors;
306 }
307
308 sub mkdir_with_parents {
309   $main::lxdebug->enter_sub();
310
311   my ($full_path) = @_;
312
313   my $path = "";
314
315   $full_path =~ s|/+|/|;
316
317   foreach my $part (split(m|/|, $full_path)) {
318     $path .= "/" if ($path);
319     $path .= $part;
320
321     die("Could not create directory '$path' because a file exists with " .
322         "the same name.\n") if (-f $path);
323
324     if (! -d $path) {
325       mkdir($path, 0770) || die("Could not create the directory '$path'. " .
326                                 "OS error: $!\n");
327     }
328   }
329
330   $main::lxdebug->leave_sub();
331 }
332
333 sub webdav_folder {
334   $main::lxdebug->enter_sub();
335
336   my ($form) = @_;
337
338   return $main::lxdebug->leave_sub()
339     unless ($::lx_office_conf{features}->{webdav} && $form->{id});
340
341   my ($path, $number);
342
343   $form->{WEBDAV} = [];
344
345   if ($form->{type} eq "sales_quotation") {
346     ($path, $number) = ("angebote", $form->{quonumber});
347   } elsif ($form->{type} eq "sales_order") {
348     ($path, $number) = ("bestellungen", $form->{ordnumber});
349   } elsif ($form->{type} eq "request_quotation") {
350     ($path, $number) = ("anfragen", $form->{quonumber});
351   } elsif ($form->{type} eq "purchase_order") {
352     ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
353   } elsif ($form->{type} eq "sales_delivery_order") {
354     ($path, $number) = ("verkaufslieferscheine", $form->{donumber});
355   } elsif ($form->{type} eq "purchase_delivery_order") {
356     ($path, $number) = ("einkaufslieferscheine", $form->{donumber});
357   } elsif ($form->{type} eq "credit_note") {
358     ($path, $number) = ("gutschriften", $form->{invnumber});
359   } elsif ($form->{vc} eq "customer") {
360     ($path, $number) = ("rechnungen", $form->{invnumber});
361   } else {
362     ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
363   }
364
365   return $main::lxdebug->leave_sub() unless ($path && $number);
366
367   $number =~ s|[/\\]|_|g;
368
369   $path = "webdav/${path}/${number}";
370
371   if (!-d $path) {
372     mkdir_with_parents($path);
373
374   } else {
375     my $base_path = substr($ENV{'SCRIPT_NAME'}, 1);
376     $base_path =~ s|[^/]+$||;
377     $base_path =~ s|/$||;
378     # wo kommt der wert für dir her? es wird doch gar nichts übergeben? fix für strict my $dir jb 21.2.
379     if (opendir my $dir, $path) {
380       foreach my $file (sort { lc $a cmp lc $b } readdir $dir) {
381         next if (($file eq '.') || ($file eq '..'));
382
383         my $fname = $file;
384         $fname  =~ s|.*/||;
385
386         my $is_directory = -d "$path/$file";
387
388         $file  = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
389         $file .=  '/' if ($is_directory);
390
391         push @{ $form->{WEBDAV} }, {
392           'name' => $fname,
393           'link' => "$base_path/$file",
394           'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
395         };
396       }
397
398       closedir $dir;
399     }
400   }
401
402   $main::lxdebug->leave_sub();
403 }
404
405 sub get_vc_details {
406   $main::lxdebug->enter_sub();
407
408   my ($self, $myconfig, $form, $vc, $vc_id) = @_;
409
410   $vc = $vc eq "customer" ? "customer" : "vendor";
411
412   my $dbh = $form->dbconnect($myconfig);
413
414   my $query;
415
416   $query =
417     qq|SELECT
418          vc.*,
419          pt.description AS payment_terms,
420          b.description AS business,
421          l.description AS language
422        FROM ${vc} vc
423        LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
424        LEFT JOIN business b ON (vc.business_id = b.id)
425        LEFT JOIN language l ON (vc.language_id = l.id)
426        WHERE vc.id = ?|;
427   my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
428
429   if (!$ref) {
430     $dbh->disconnect();
431     $main::lxdebug->leave_sub();
432     return 0;
433   }
434
435   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
436
437   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
438
439   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
440   $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
441
442   $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
443   $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
444
445   $dbh->disconnect();
446
447   $main::lxdebug->leave_sub();
448
449   return 1;
450 }
451
452 sub get_shipto_by_id {
453   $main::lxdebug->enter_sub();
454
455   my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
456
457   $prefix ||= "";
458
459   my $dbh = $form->dbconnect($myconfig);
460
461   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
462   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
463
464   map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
465
466   $dbh->disconnect();
467
468   $main::lxdebug->leave_sub();
469 }
470
471 sub save_email_status {
472   $main::lxdebug->enter_sub();
473
474   my ($self, $myconfig, $form) = @_;
475
476   my ($table, $query, $dbh);
477
478   if ($form->{script} eq 'oe.pl') {
479     $table = 'oe';
480
481   } elsif ($form->{script} eq 'is.pl') {
482     $table = 'ar';
483
484   } elsif ($form->{script} eq 'ir.pl') {
485     $table = 'ap';
486
487   }
488
489   return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
490
491   $dbh = $form->get_standard_dbh($myconfig);
492
493   my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
494
495   $intnotes =~ s|\r||g;
496   $intnotes =~ s|\n$||;
497
498   $intnotes .= "\n\n" if ($intnotes);
499
500   my $cc  = $main::locale->text('Cc') . ": $form->{cc}\n"   if $form->{cc};
501   my $bcc = $main::locale->text('Bcc') . ": $form->{bcc}\n" if $form->{bcc};
502   my $now = scalar localtime;
503
504   $intnotes .= $main::locale->text('[email]') . "\n"
505     . $main::locale->text('Date') . ": $now\n"
506     . $main::locale->text('To (email)') . ": $form->{email}\n"
507     . "${cc}${bcc}"
508     . $main::locale->text('Subject') . ": $form->{subject}\n\n"
509     . $main::locale->text('Message') . ": $form->{message}";
510
511   $intnotes =~ s|\r||g;
512
513   do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
514
515   $form->save_status($dbh);
516
517   $dbh->commit();
518
519   $main::lxdebug->leave_sub();
520 }
521
522 sub check_params {
523   my $params = shift;
524
525   foreach my $key (@_) {
526     if ((ref $key eq '') && !defined $params->{$key}) {
527       my $subroutine = (caller(1))[3];
528       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
529       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
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::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
544         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
545         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
546       }
547     }
548   }
549 }
550
551 sub check_params_x {
552   my $params = shift;
553
554   foreach my $key (@_) {
555     if ((ref $key eq '') && !exists $params->{$key}) {
556       my $subroutine = (caller(1))[3];
557       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
558
559     } elsif (ref $key eq 'ARRAY') {
560       my $found = 0;
561       foreach my $subkey (@{ $key }) {
562         if (exists $params->{$subkey}) {
563           $found = 1;
564           last;
565         }
566       }
567
568       if (!$found) {
569         my $subroutine = (caller(1))[3];
570         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
571       }
572     }
573   }
574 }
575
576 1;