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