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