Zusätzliche Rechnungsadressen: in Verkaufsbelegmasken auswählbar
[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   if ($vc eq 'customer') {
346     $query = qq|SELECT * FROM additional_billing_addresses WHERE (customer_id = ?)|;
347     $form->{ADDITIONAL_BILLING_ADDRESSES} = selectall_hashref_query($form, $dbh, $query, $vc_id);
348   }
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   $main::lxdebug->leave_sub();
357
358   return 1;
359 }
360
361 sub get_shipto_by_id {
362   $main::lxdebug->enter_sub();
363
364   my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
365
366   $prefix ||= "";
367
368   my $dbh = SL::DB->client->dbh;
369
370   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
371   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
372
373   map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
374
375   my $cvars = CVar->get_custom_variables(
376     dbh      => $dbh,
377     module   => 'ShipTo',
378     trans_id => $shipto_id,
379   );
380   $form->{"${prefix}shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
381
382   $main::lxdebug->leave_sub();
383 }
384
385 sub save_email_status {
386   $main::lxdebug->enter_sub();
387
388   my ($self, $myconfig, $form) = @_;
389
390   my ($table, $query, $dbh);
391
392   if ($form->{script} eq 'oe.pl') {
393     $table = 'oe';
394
395   } elsif ($form->{script} eq 'is.pl') {
396     $table = 'ar';
397
398   } elsif ($form->{script} eq 'ir.pl') {
399     $table = 'ap';
400
401   } elsif ($form->{script} eq 'do.pl') {
402     $table = 'delivery_orders';
403   }
404
405   return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
406
407   SL::DB->client->with_transaction(sub {
408     $dbh = SL::DB->client->dbh;
409
410     my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
411
412     $intnotes =~ s|\r||g;
413     $intnotes =~ s|\n$||;
414
415     $intnotes .= "\n\n" if ($intnotes);
416
417     my $cc  = $form->{cc}  ? $main::locale->text('Cc') . ": $form->{cc}\n"   : '';
418     my $bcc = $form->{bcc} ? $main::locale->text('Bcc') . ": $form->{bcc}\n" : '';
419     my $now = scalar localtime;
420
421     $intnotes .= $main::locale->text('[email]') . "\n"
422       . $main::locale->text('Date') . ": $now\n"
423       . $main::locale->text('To (email)') . ": $form->{email}\n"
424       . "${cc}${bcc}"
425       . $main::locale->text('Subject') . ": $form->{subject}\n\n"
426       . $main::locale->text('Message') . ": $form->{message}";
427
428     $intnotes =~ s|\r||g;
429
430     do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
431
432     $form->save_status($dbh);
433     1;
434   }) or do { die SL::DB->client->error };
435
436   $main::lxdebug->leave_sub();
437 }
438
439 sub check_params {
440   my $params = shift;
441
442   foreach my $key (@_) {
443     if ((ref $key eq '') && !defined $params->{$key}) {
444       my $subroutine = (caller(1))[3];
445       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
446       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
447       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
448
449     } elsif (ref $key eq 'ARRAY') {
450       my $found = 0;
451       foreach my $subkey (@{ $key }) {
452         if (defined $params->{$subkey}) {
453           $found = 1;
454           last;
455         }
456       }
457
458       if (!$found) {
459         my $subroutine = (caller(1))[3];
460         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
461         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
462         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
463       }
464     }
465   }
466 }
467
468 sub check_params_x {
469   my $params = shift;
470
471   foreach my $key (@_) {
472     if ((ref $key eq '') && !exists $params->{$key}) {
473       my $subroutine = (caller(1))[3];
474       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
475
476     } elsif (ref $key eq 'ARRAY') {
477       my $found = 0;
478       foreach my $subkey (@{ $key }) {
479         if (exists $params->{$subkey}) {
480           $found = 1;
481           last;
482         }
483       }
484
485       if (!$found) {
486         my $subroutine = (caller(1))[3];
487         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
488       }
489     }
490   }
491 }
492
493 sub get_webdav_folder {
494   $main::lxdebug->enter_sub();
495
496   my ($form) = @_;
497
498   croak "No client set in \$::auth" unless $::auth->client;
499
500   my ($path, $number);
501
502   # dispatch table
503   if ($form->{type} eq "sales_quotation") {
504     ($path, $number) = ("angebote", $form->{quonumber});
505   } elsif ($form->{type} eq "sales_order") {
506     ($path, $number) = ("bestellungen", $form->{ordnumber});
507   } elsif ($form->{type} eq "request_quotation") {
508     ($path, $number) = ("anfragen", $form->{quonumber});
509   } elsif ($form->{type} eq "purchase_order") {
510     ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
511   } elsif ($form->{type} eq "sales_delivery_order") {
512     ($path, $number) = ("verkaufslieferscheine", $form->{donumber});
513   } elsif ($form->{type} eq "purchase_delivery_order") {
514     ($path, $number) = ("einkaufslieferscheine", $form->{donumber});
515   } elsif ($form->{type} eq "credit_note") {
516     ($path, $number) = ("gutschriften", $form->{invnumber});
517   } elsif ($form->{type} eq "letter") {
518     ($path, $number) = ("briefe", $form->{letternumber} );
519   } elsif ($form->{vc} eq "customer") {
520     ($path, $number) = ("rechnungen", $form->{invnumber});
521   } elsif ($form->{vc} eq "vendor") {
522     ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
523   } else {
524     $main::lxdebug->leave_sub();
525     return undef;
526   }
527
528   $number =~ s|[/\\]|_|g;
529
530   $path = "webdav/" . $::auth->client->{id} . "/${path}/${number}";
531
532   $main::lxdebug->leave_sub();
533
534   return ($path, $number);
535 }
536
537 sub copy_file_to_webdav_folder {
538   $::lxdebug->enter_sub();
539
540   my ($form) = @_;
541   my ($last_mod_time, $latest_file_name, $complete_path);
542
543   # checks
544   foreach my $item (qw(tmpdir tmpfile type)){
545     next if $form->{$item};
546     $::lxdebug->message(LXDebug::WARN(), 'Missing parameter:' . $item);
547     $::lxdebug->leave_sub();
548     return $::locale->text("Missing parameter for WebDAV file copy");
549   }
550
551   my ($webdav_folder, $document_name) =  get_webdav_folder($form);
552
553   if (! $webdav_folder){
554     $::lxdebug->message(LXDebug::WARN(), 'Cannot check correct WebDAV folder');
555     $::lxdebug->leave_sub();
556     return $::locale->text("Cannot check correct WebDAV folder")
557   }
558
559   $complete_path =  File::Spec->catfile($form->{cwd},  $webdav_folder);
560
561   # maybe the path does not exist (automatic printing), see #2446
562   if (!-d $complete_path) {
563     # we need a chdir and restore old dir
564     my $current_dir = POSIX::getcwd();
565     chdir("$form->{cwd}");
566     mkdir_with_parents($webdav_folder);
567     chdir($current_dir);
568   }
569
570   my $dh;
571   if (!opendir $dh, $complete_path) {
572     $::lxdebug->leave_sub();
573     return "Could not open $complete_path: $!";
574   }
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     $::lxdebug->leave_sub();
603     return $::locale->text("Copy file from #1 to #2 failed: #3", $current_file, $new_file, $ERRNO);
604   }
605
606   return;
607   $::lxdebug->leave_sub();
608 }
609
610 sub get_current_formatted_time {
611   return POSIX::strftime('_%Y%m%d_%H%M%S', localtime());
612 }
613
614 1;
615 __END__
616
617 =pod
618
619 =encoding utf8
620
621 =head1 NAME
622
623 Common - Common routines used in a lot of places.
624
625 =head1 SYNOPSIS
626
627   my $short_text = Common::truncate($long_text, at => 10);
628
629 =head1 FUNCTIONS
630
631 =over 4
632
633 =item C<truncate $text, %params>
634
635 Truncates C<$text> at a position and insert an ellipsis if the text is
636 longer. The maximum number of characters to return is given with the
637 paramter C<at> which defaults to 50.
638
639 The optional parameter C<strip> can be used to remove unwanted line
640 feed/carriage return characters from the text before truncation. It
641 can be set to C<1> (only strip those at the end of C<$text>) or
642 C<full> (replace consecutive line feed/carriage return characters in
643 the middle by a single space and remove tailing line feed/carriage
644 return characters).
645
646 =back
647
648 =head1 BUGS
649
650 Nothing here yet.
651
652 =head1 AUTHOR
653
654 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
655 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>
656
657 =cut