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