E-Mail-Versand auch für Lieferscheinen in interne Bemerkung protokollieren
[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/kivitendo-tmp-" . unique_id();
47 }
48
49 sub truncate {
50   my ($text, %params) = @_;
51
52   $params{at}       //= 50;
53   $params{at}         =  3 if 3 > $params{at};
54
55   $params{strip}    //= '';
56
57   $text =~ s/[\r\n]+$//g if $params{strip} =~ m/^(?: 1 | newlines? | full )$/x;
58   $text =~ s/[\r\n]+/ /g if $params{strip} =~ m/^(?:     newlines? | full )$/x;
59
60   return $text if length($text) <= $params{at};
61   return substr($text, 0, $params{at} - 3) . '...';
62 }
63
64 sub retrieve_parts {
65   $main::lxdebug->enter_sub();
66
67   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
68
69   my $dbh = $form->dbconnect($myconfig);
70
71   my (@filter_values, $filter);
72
73   foreach (qw(partnumber description ean)) {
74     next unless $form->{$_};
75
76     $filter .= qq| AND ($_ ILIKE ?)|;
77     push @filter_values, '%' . $form->{$_} . '%';
78   }
79
80   if ($form->{no_assemblies}) {
81     $filter .= qq| AND (NOT COALESCE(assembly, FALSE))|;
82   }
83   if ($form->{assemblies}) {
84     $filter .= qq| AND assembly=TRUE|;
85   }
86
87   if ($form->{no_services}) {
88     $filter .= qq| AND (inventory_accno_id is not NULL or assembly=TRUE)|; # @mb hier nochmal optimieren ... nach kurzer ruecksprache alles i.o.
89   }
90
91   substr($filter, 1, 3) = "WHERE" if ($filter);
92
93   $order_by =~ s/[^a-zA-Z_]//g;
94   $order_dir = $order_dir ? "ASC" : "DESC";
95
96   my $query =
97     qq|SELECT id, partnumber, description, ean | .
98     qq|FROM parts $filter | .
99     qq|ORDER BY $order_by $order_dir|;
100   my $sth = $dbh->prepare($query);
101   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
102   my $parts = [];
103   while (my $ref = $sth->fetchrow_hashref()) {
104     push(@{$parts}, $ref);
105   }
106   $sth->finish();
107   $dbh->disconnect();
108
109   $main::lxdebug->leave_sub();
110
111   return $parts;
112 }
113
114 sub retrieve_projects {
115   $main::lxdebug->enter_sub();
116
117   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
118
119   my $dbh = $form->dbconnect($myconfig);
120
121   my (@filter_values, $filter);
122   if ($form->{"projectnumber"}) {
123     $filter .= qq| AND (projectnumber ILIKE ?)|;
124     push(@filter_values, '%' . $form->{"projectnumber"} . '%');
125   }
126   if ($form->{"description"}) {
127     $filter .= qq| AND (description ILIKE ?)|;
128     push(@filter_values, '%' . $form->{"description"} . '%');
129   }
130   substr($filter, 1, 3) = "WHERE" if ($filter);
131
132   $order_by =~ s/[^a-zA-Z_]//g;
133   $order_dir = $order_dir ? "ASC" : "DESC";
134
135   my $query =
136     qq|SELECT id, projectnumber, description | .
137     qq|FROM project $filter | .
138     qq|ORDER BY $order_by $order_dir|;
139   my $sth = $dbh->prepare($query);
140   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
141   my $projects = [];
142   while (my $ref = $sth->fetchrow_hashref()) {
143     push(@{$projects}, $ref);
144   }
145   $sth->finish();
146   $dbh->disconnect();
147
148   $main::lxdebug->leave_sub();
149
150   return $projects;
151 }
152
153 sub retrieve_employees {
154   $main::lxdebug->enter_sub();
155
156   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
157
158   my $dbh = $form->dbconnect($myconfig);
159
160   my (@filter_values, $filter);
161   if ($form->{"name"}) {
162     $filter .= qq| AND (name ILIKE ?)|;
163     push(@filter_values, '%' . $form->{"name"} . '%');
164   }
165   substr($filter, 1, 3) = "WHERE" if ($filter);
166
167   $order_by =~ s/[^a-zA-Z_]//g;
168   $order_dir = $order_dir ? "ASC" : "DESC";
169
170   my $query =
171     qq|SELECT id, name | .
172     qq|FROM employee $filter | .
173     qq|ORDER BY $order_by $order_dir|;
174   my $sth = $dbh->prepare($query);
175   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
176   my $employees = [];
177   while (my $ref = $sth->fetchrow_hashref()) {
178     push(@{$employees}, $ref);
179   }
180   $sth->finish();
181   $dbh->disconnect();
182
183   $main::lxdebug->leave_sub();
184
185   return $employees;
186 }
187
188 sub retrieve_customers_or_vendors {
189   $main::lxdebug->enter_sub();
190
191   my ($self, $myconfig, $form, $order_by, $order_dir, $is_vendor, $allow_both) = @_;
192
193   my $dbh = $form->dbconnect($myconfig);
194
195   my (@filter_values, $filter);
196   if ($form->{"name"}) {
197     $filter .= " AND (TABLE.name ILIKE ?)";
198     push(@filter_values, '%' . $form->{"name"} . '%');
199   }
200   if (!$form->{"obsolete"}) {
201     $filter .= " AND NOT TABLE.obsolete";
202   }
203   substr($filter, 1, 3) = "WHERE" if ($filter);
204
205   $order_by =~ s/[^a-zA-Z_]//g;
206   $order_dir = $order_dir ? "ASC" : "DESC";
207
208   my (@queries, @query_parameters);
209
210   if ($allow_both || !$is_vendor) {
211     my $c_filter = $filter;
212     $c_filter =~ s/TABLE/c/g;
213     push(@queries, qq|SELECT
214                         c.id, c.name, 0 AS customer_is_vendor,
215                         c.street, c.zipcode, c.city,
216                         ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
217                       FROM customer c
218                       LEFT JOIN contacts ct ON (c.id = ct.cp_cv_id)
219                       $c_filter|);
220     push(@query_parameters, @filter_values);
221   }
222
223   if ($allow_both || $is_vendor) {
224     my $v_filter = $filter;
225     $v_filter =~ s/TABLE/v/g;
226     push(@queries, qq|SELECT
227                         v.id, v.name, 1 AS customer_is_vendor,
228                         v.street, v.zipcode, v.city,
229                         ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
230                       FROM vendor v
231                       LEFT JOIN contacts ct ON (v.id = ct.cp_cv_id)
232                       $v_filter|);
233     push(@query_parameters, @filter_values);
234   }
235
236   my $query = join(" UNION ", @queries) . " ORDER BY $order_by $order_dir";
237   my $sth = $dbh->prepare($query);
238   $sth->execute(@query_parameters) || $form->dberror($query . " (" . join(", ", @query_parameters) . ")");
239   my $customers = [];
240   while (my $ref = $sth->fetchrow_hashref()) {
241     push(@{$customers}, $ref);
242   }
243   $sth->finish();
244   $dbh->disconnect();
245
246   $main::lxdebug->leave_sub();
247
248   return $customers;
249 }
250
251 sub retrieve_delivery_customer {
252   $main::lxdebug->enter_sub();
253
254   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
255
256   my $dbh = $form->dbconnect($myconfig);
257
258   my (@filter_values, $filter);
259   if ($form->{"name"}) {
260     $filter .= qq| (name ILIKE ?) AND|;
261     push(@filter_values, '%' . $form->{"name"} . '%');
262   }
263
264   $order_by =~ s/[^a-zA-Z_]//g;
265   $order_dir = $order_dir ? "ASC" : "DESC";
266
267   my $query =
268     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
269     qq!FROM customer ! .
270     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
271     qq!ORDER BY $order_by $order_dir!;
272   my $sth = $dbh->prepare($query);
273   $sth->execute(@filter_values) ||
274     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
275   my $delivery_customers = [];
276   while (my $ref = $sth->fetchrow_hashref()) {
277     push(@{$delivery_customers}, $ref);
278   }
279   $sth->finish();
280   $dbh->disconnect();
281
282   $main::lxdebug->leave_sub();
283
284   return $delivery_customers;
285 }
286
287 sub retrieve_vendor {
288   $main::lxdebug->enter_sub();
289
290   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
291
292   my $dbh = $form->dbconnect($myconfig);
293
294   my (@filter_values, $filter);
295   if ($form->{"name"}) {
296     $filter .= qq| (name ILIKE ?) AND|;
297     push(@filter_values, '%' . $form->{"name"} . '%');
298   }
299
300   $order_by =~ s/[^a-zA-Z_]//g;
301   $order_dir = $order_dir ? "ASC" : "DESC";
302
303   my $query =
304     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
305     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = ?') ! .
306     qq!ORDER BY $order_by $order_dir!;
307   push @filter_values, $::locale->{iconv_utf8}->convert('Händler');
308   my $sth = $dbh->prepare($query);
309   $sth->execute(@filter_values) ||
310     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
311   my $vendors = [];
312   while (my $ref = $sth->fetchrow_hashref()) {
313     push(@{$vendors}, $ref);
314   }
315   $sth->finish();
316   $dbh->disconnect();
317
318   $main::lxdebug->leave_sub();
319
320   return $vendors;
321 }
322
323 sub mkdir_with_parents {
324   $main::lxdebug->enter_sub();
325
326   my ($full_path) = @_;
327
328   my $path = "";
329
330   $full_path =~ s|/+|/|;
331
332   foreach my $part (split(m|/|, $full_path)) {
333     $path .= "/" if ($path);
334     $path .= $part;
335
336     die("Could not create directory '$path' because a file exists with " .
337         "the same name.\n") if (-f $path);
338
339     if (! -d $path) {
340       mkdir($path, 0770) || die("Could not create the directory '$path'. " .
341                                 "OS error: $!\n");
342     }
343   }
344
345   $main::lxdebug->leave_sub();
346 }
347
348 sub webdav_folder {
349   $main::lxdebug->enter_sub();
350
351   my ($form) = @_;
352
353   return $main::lxdebug->leave_sub()
354     unless ($::lx_office_conf{features}->{webdav} && $form->{id});
355
356   my ($path, $number);
357
358   $form->{WEBDAV} = [];
359
360   if ($form->{type} eq "sales_quotation") {
361     ($path, $number) = ("angebote", $form->{quonumber});
362   } elsif ($form->{type} eq "sales_order") {
363     ($path, $number) = ("bestellungen", $form->{ordnumber});
364   } elsif ($form->{type} eq "request_quotation") {
365     ($path, $number) = ("anfragen", $form->{quonumber});
366   } elsif ($form->{type} eq "purchase_order") {
367     ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
368   } elsif ($form->{type} eq "sales_delivery_order") {
369     ($path, $number) = ("verkaufslieferscheine", $form->{donumber});
370   } elsif ($form->{type} eq "purchase_delivery_order") {
371     ($path, $number) = ("einkaufslieferscheine", $form->{donumber});
372   } elsif ($form->{type} eq "credit_note") {
373     ($path, $number) = ("gutschriften", $form->{invnumber});
374   } elsif ($form->{vc} eq "customer") {
375     ($path, $number) = ("rechnungen", $form->{invnumber});
376   } else {
377     ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
378   }
379
380   return $main::lxdebug->leave_sub() unless ($path && $number);
381
382   $number =~ s|[/\\]|_|g;
383
384   $path = "webdav/${path}/${number}";
385
386   if (!-d $path) {
387     mkdir_with_parents($path);
388
389   } else {
390     my $base_path = $ENV{'SCRIPT_NAME'};
391     $base_path =~ s|[^/]+$||;
392     # wo kommt der wert für dir her? es wird doch gar nichts übergeben? fix für strict my $dir jb 21.2.
393     if (opendir my $dir, $path) {
394       foreach my $file (sort { lc $a cmp lc $b } readdir $dir) {
395         next if (($file eq '.') || ($file eq '..'));
396
397         my $fname = $file;
398         $fname  =~ s|.*/||;
399
400         my $is_directory = -d "$path/$file";
401
402         $file  = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
403         $file .=  '/' if ($is_directory);
404
405         push @{ $form->{WEBDAV} }, {
406           'name' => $fname,
407           'link' => $base_path . $file,
408           'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
409         };
410       }
411
412       closedir $dir;
413     }
414   }
415
416   $main::lxdebug->leave_sub();
417 }
418
419 sub get_vc_details {
420   $main::lxdebug->enter_sub();
421
422   my ($self, $myconfig, $form, $vc, $vc_id) = @_;
423
424   $vc = $vc eq "customer" ? "customer" : "vendor";
425
426   my $dbh = $form->dbconnect($myconfig);
427
428   my $query;
429
430   $query =
431     qq|SELECT
432          vc.*,
433          pt.description AS payment_terms,
434          b.description AS business,
435          l.description AS language
436        FROM ${vc} vc
437        LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
438        LEFT JOIN business b ON (vc.business_id = b.id)
439        LEFT JOIN language l ON (vc.language_id = l.id)
440        WHERE vc.id = ?|;
441   my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
442
443   if (!$ref) {
444     $dbh->disconnect();
445     $main::lxdebug->leave_sub();
446     return 0;
447   }
448
449   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
450
451   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
452
453   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
454   $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
455
456   $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
457   $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
458
459   # Only show default pricegroup for customer, not vendor, which is why this is outside the main query
460   ($form->{pricegroup}) = selectrow_query($form, $dbh, qq|SELECT pricegroup FROM pricegroup WHERE id = ?|, $form->{klass});
461
462   $dbh->disconnect();
463
464   $main::lxdebug->leave_sub();
465
466   return 1;
467 }
468
469 sub get_shipto_by_id {
470   $main::lxdebug->enter_sub();
471
472   my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
473
474   $prefix ||= "";
475
476   my $dbh = $form->dbconnect($myconfig);
477
478   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
479   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
480
481   map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
482
483   $dbh->disconnect();
484
485   $main::lxdebug->leave_sub();
486 }
487
488 sub save_email_status {
489   $main::lxdebug->enter_sub();
490
491   my ($self, $myconfig, $form) = @_;
492
493   my ($table, $query, $dbh);
494
495   if ($form->{script} eq 'oe.pl') {
496     $table = 'oe';
497
498   } elsif ($form->{script} eq 'is.pl') {
499     $table = 'ar';
500
501   } elsif ($form->{script} eq 'ir.pl') {
502     $table = 'ap';
503
504   } elsif ($form->{script} eq 'do.pl') {
505     $table = 'delivery_orders';
506   }
507
508   return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
509
510   $dbh = $form->get_standard_dbh($myconfig);
511
512   my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
513
514   $intnotes =~ s|\r||g;
515   $intnotes =~ s|\n$||;
516
517   $intnotes .= "\n\n" if ($intnotes);
518
519   my $cc  = $form->{cc}  ? $main::locale->text('Cc') . ": $form->{cc}\n"   : '';
520   my $bcc = $form->{bcc} ? $main::locale->text('Bcc') . ": $form->{bcc}\n" : '';
521   my $now = scalar localtime;
522
523   $intnotes .= $main::locale->text('[email]') . "\n"
524     . $main::locale->text('Date') . ": $now\n"
525     . $main::locale->text('To (email)') . ": $form->{email}\n"
526     . "${cc}${bcc}"
527     . $main::locale->text('Subject') . ": $form->{subject}\n\n"
528     . $main::locale->text('Message') . ": $form->{message}";
529
530   $intnotes =~ s|\r||g;
531
532   do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
533
534   $form->save_status($dbh);
535
536   $dbh->commit();
537
538   $main::lxdebug->leave_sub();
539 }
540
541 sub check_params {
542   my $params = shift;
543
544   foreach my $key (@_) {
545     if ((ref $key eq '') && !defined $params->{$key}) {
546       my $subroutine = (caller(1))[3];
547       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
548       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
549       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
550
551     } elsif (ref $key eq 'ARRAY') {
552       my $found = 0;
553       foreach my $subkey (@{ $key }) {
554         if (defined $params->{$subkey}) {
555           $found = 1;
556           last;
557         }
558       }
559
560       if (!$found) {
561         my $subroutine = (caller(1))[3];
562         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
563         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
564         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
565       }
566     }
567   }
568 }
569
570 sub check_params_x {
571   my $params = shift;
572
573   foreach my $key (@_) {
574     if ((ref $key eq '') && !exists $params->{$key}) {
575       my $subroutine = (caller(1))[3];
576       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
577
578     } elsif (ref $key eq 'ARRAY') {
579       my $found = 0;
580       foreach my $subkey (@{ $key }) {
581         if (exists $params->{$subkey}) {
582           $found = 1;
583           last;
584         }
585       }
586
587       if (!$found) {
588         my $subroutine = (caller(1))[3];
589         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
590       }
591     }
592   }
593 }
594
595 1;
596 __END__
597
598 =pod
599
600 =encoding utf8
601
602 =head1 NAME
603
604 Common - Common routines used in a lot of places.
605
606 =head1 SYNOPSIS
607
608   my $short_text = Common::truncate($long_text, at => 10);
609
610 =head1 FUNCTIONS
611
612 =over 4
613
614 =item C<truncate $text, %params>
615
616 Truncates C<$text> at a position and insert an ellipsis if the text is
617 longer. The maximum number of characters to return is given with the
618 paramter C<at> which defaults to 50.
619
620 The optional parameter C<strip> can be used to remove unwanted line
621 feed/carriage return characters from the text before truncation. It
622 can be set to C<1> (only strip those at the end of C<$text>) or
623 C<full> (replace consecutive line feed/carriage return characters in
624 the middle by a single space and remove tailing line feed/carriage
625 return characters).
626
627 =back
628
629 =head1 BUGS
630
631 Nothing here yet.
632
633 =head1 AUTHOR
634
635 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
636 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>
637
638 =cut