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