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