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