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