Merge branch 'master' of ssh://git-jbueren@lx-office.linet-services.de/~/lx-office-erp
[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 Time::HiRes qw(gettimeofday);
12 use Data::Dumper;
13
14 use SL::DBUtils;
15
16 use vars qw(@db_encodings %db_encoding_to_charset %charset_to_db_encoding);
17
18 use strict;
19
20 @db_encodings = (
21   { "label" => "ASCII",          "dbencoding" => "SQL_ASCII", "charset" => "ASCII" },
22   { "label" => "UTF-8 Unicode",  "dbencoding" => "UNICODE",   "charset" => "UTF-8" },
23   { "label" => "ISO 8859-1",     "dbencoding" => "LATIN1",    "charset" => "ISO-8859-1" },
24   { "label" => "ISO 8859-2",     "dbencoding" => "LATIN2",    "charset" => "ISO-8859-2" },
25   { "label" => "ISO 8859-3",     "dbencoding" => "LATIN3",    "charset" => "ISO-8859-3" },
26   { "label" => "ISO 8859-4",     "dbencoding" => "LATIN4",    "charset" => "ISO-8859-4" },
27   { "label" => "ISO 8859-5",     "dbencoding" => "LATIN5",    "charset" => "ISO-8859-5" },
28   { "label" => "ISO 8859-15",    "dbencoding" => "LATIN9",    "charset" => "ISO-8859-15" },
29   { "label" => "KOI8-R",         "dbencoding" => "KOI8",      "charset" => "KOI8-R" },
30   { "label" => "Windows CP1251", "dbencoding" => "WIN",       "charset" => "CP1251" },
31   { "label" => "Windows CP866",  "dbencoding" => "ALT",       "charset" => "CP866" },
32 );
33
34 %db_encoding_to_charset = map { $_->{dbencoding}, $_->{charset} } @db_encodings;
35 %charset_to_db_encoding = map { $_->{charset}, $_->{dbencoding} } @db_encodings;
36
37 use constant DEFAULT_CHARSET => 'ISO-8859-15';
38
39 sub unique_id {
40   my ($a, $b) = gettimeofday();
41   return "${a}-${b}-${$}";
42 }
43
44 sub tmpname {
45   return "/tmp/lx-office-tmp-" . unique_id();
46 }
47
48 sub retrieve_parts {
49   $main::lxdebug->enter_sub();
50
51   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
52
53   my $dbh = $form->dbconnect($myconfig);
54
55   my (@filter_values, $filter);
56
57   foreach (qw(partnumber description ean)) {
58     next unless $form->{$_};
59
60     $filter .= qq| AND ($_ ILIKE ?)|;
61     push @filter_values, '%' . $form->{$_} . '%';
62   }
63
64   if ($form->{no_assemblies}) {
65     $filter .= qq| AND (NOT COALESCE(assembly, FALSE))|;
66   }
67   if ($form->{assemblies}) {
68     $filter .= qq| AND assembly=TRUE|;
69   }
70
71   if ($form->{no_services}) {
72     $filter .= qq| AND (inventory_accno_id is not NULL or assembly=TRUE)|; # @mb hier nochmal optimieren ... nach kurzer ruecksprache alles i.o.
73   }
74
75   substr($filter, 1, 3) = "WHERE" if ($filter);
76
77   $order_by =~ s/[^a-zA-Z_]//g;
78   $order_dir = $order_dir ? "ASC" : "DESC";
79
80   my $query =
81     qq|SELECT id, partnumber, description, ean | .
82     qq|FROM parts $filter | .
83     qq|ORDER BY $order_by $order_dir|;
84   my $sth = $dbh->prepare($query);
85   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
86   my $parts = [];
87   while (my $ref = $sth->fetchrow_hashref()) {
88     push(@{$parts}, $ref);
89   }
90   $sth->finish();
91   $dbh->disconnect();
92
93   $main::lxdebug->leave_sub();
94
95   return $parts;
96 }
97
98 sub retrieve_projects {
99   $main::lxdebug->enter_sub();
100
101   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
102
103   my $dbh = $form->dbconnect($myconfig);
104
105   my (@filter_values, $filter);
106   if ($form->{"projectnumber"}) {
107     $filter .= qq| AND (projectnumber ILIKE ?)|;
108     push(@filter_values, '%' . $form->{"projectnumber"} . '%');
109   }
110   if ($form->{"description"}) {
111     $filter .= qq| AND (description ILIKE ?)|;
112     push(@filter_values, '%' . $form->{"description"} . '%');
113   }
114   substr($filter, 1, 3) = "WHERE" if ($filter);
115
116   $order_by =~ s/[^a-zA-Z_]//g;
117   $order_dir = $order_dir ? "ASC" : "DESC";
118
119   my $query =
120     qq|SELECT id, projectnumber, description | .
121     qq|FROM project $filter | .
122     qq|ORDER BY $order_by $order_dir|;
123   my $sth = $dbh->prepare($query);
124   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
125   my $projects = [];
126   while (my $ref = $sth->fetchrow_hashref()) {
127     push(@{$projects}, $ref);
128   }
129   $sth->finish();
130   $dbh->disconnect();
131
132   $main::lxdebug->leave_sub();
133
134   return $projects;
135 }
136
137 sub retrieve_employees {
138   $main::lxdebug->enter_sub();
139
140   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
141
142   my $dbh = $form->dbconnect($myconfig);
143
144   my (@filter_values, $filter);
145   if ($form->{"name"}) {
146     $filter .= qq| AND (name ILIKE ?)|;
147     push(@filter_values, '%' . $form->{"name"} . '%');
148   }
149   substr($filter, 1, 3) = "WHERE" if ($filter);
150
151   $order_by =~ s/[^a-zA-Z_]//g;
152   $order_dir = $order_dir ? "ASC" : "DESC";
153
154   my $query =
155     qq|SELECT id, name | .
156     qq|FROM employee $filter | .
157     qq|ORDER BY $order_by $order_dir|;
158   my $sth = $dbh->prepare($query);
159   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
160   my $employees = [];
161   while (my $ref = $sth->fetchrow_hashref()) {
162     push(@{$employees}, $ref);
163   }
164   $sth->finish();
165   $dbh->disconnect();
166
167   $main::lxdebug->leave_sub();
168
169   return $employees;
170 }
171
172 sub retrieve_customers_or_vendors {
173   $main::lxdebug->enter_sub();
174
175   my ($self, $myconfig, $form, $order_by, $order_dir, $is_vendor, $allow_both) = @_;
176
177   my $dbh = $form->dbconnect($myconfig);
178
179   my (@filter_values, $filter);
180   if ($form->{"name"}) {
181     $filter .= " AND (TABLE.name ILIKE ?)";
182     push(@filter_values, '%' . $form->{"name"} . '%');
183   }
184   if (!$form->{"obsolete"}) {
185     $filter .= " AND NOT TABLE.obsolete";
186   }
187   substr($filter, 1, 3) = "WHERE" if ($filter);
188
189   $order_by =~ s/[^a-zA-Z_]//g;
190   $order_dir = $order_dir ? "ASC" : "DESC";
191
192   my (@queries, @query_parameters);
193
194   if ($allow_both || !$is_vendor) {
195     my $c_filter = $filter;
196     $c_filter =~ s/TABLE/c/g;
197     push(@queries, qq|SELECT
198                         c.id, c.name, 0 AS customer_is_vendor,
199                         c.street, c.zipcode, c.city,
200                         ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
201                       FROM customer c
202                       LEFT JOIN contacts ct ON (c.id = ct.cp_cv_id)
203                       $c_filter|);
204     push(@query_parameters, @filter_values);
205   }
206
207   if ($allow_both || $is_vendor) {
208     my $v_filter = $filter;
209     $v_filter =~ s/TABLE/v/g;
210     push(@queries, qq|SELECT
211                         v.id, v.name, 1 AS customer_is_vendor,
212                         v.street, v.zipcode, v.city,
213                         ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
214                       FROM vendor v
215                       LEFT JOIN contacts ct ON (v.id = ct.cp_cv_id)
216                       $v_filter|);
217     push(@query_parameters, @filter_values);
218   }
219
220   my $query = join(" UNION ", @queries) . " ORDER BY $order_by $order_dir";
221   my $sth = $dbh->prepare($query);
222   $sth->execute(@query_parameters) || $form->dberror($query . " (" . join(", ", @query_parameters) . ")");
223   my $customers = [];
224   while (my $ref = $sth->fetchrow_hashref()) {
225     push(@{$customers}, $ref);
226   }
227   $sth->finish();
228   $dbh->disconnect();
229
230   $main::lxdebug->leave_sub();
231
232   return $customers;
233 }
234
235 sub retrieve_delivery_customer {
236   $main::lxdebug->enter_sub();
237
238   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
239
240   my $dbh = $form->dbconnect($myconfig);
241
242   my (@filter_values, $filter);
243   if ($form->{"name"}) {
244     $filter .= qq| (name ILIKE ?) AND|;
245     push(@filter_values, '%' . $form->{"name"} . '%');
246   }
247
248   $order_by =~ s/[^a-zA-Z_]//g;
249   $order_dir = $order_dir ? "ASC" : "DESC";
250
251   my $query =
252     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
253     qq!FROM customer ! .
254     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
255     qq!ORDER BY $order_by $order_dir!;
256   my $sth = $dbh->prepare($query);
257   $sth->execute(@filter_values) ||
258     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
259   my $delivery_customers = [];
260   while (my $ref = $sth->fetchrow_hashref()) {
261     push(@{$delivery_customers}, $ref);
262   }
263   $sth->finish();
264   $dbh->disconnect();
265
266   $main::lxdebug->leave_sub();
267
268   return $delivery_customers;
269 }
270
271 sub retrieve_vendor {
272   $main::lxdebug->enter_sub();
273
274   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
275
276   my $dbh = $form->dbconnect($myconfig);
277
278   my (@filter_values, $filter);
279   if ($form->{"name"}) {
280     $filter .= qq| (name ILIKE ?) AND|;
281     push(@filter_values, '%' . $form->{"name"} . '%');
282   }
283
284   $order_by =~ s/[^a-zA-Z_]//g;
285   $order_dir = $order_dir ? "ASC" : "DESC";
286
287   my $query =
288     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
289     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Händler') ! .
290     qq!ORDER BY $order_by $order_dir!;
291   my $sth = $dbh->prepare($query);
292   $sth->execute(@filter_values) ||
293     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
294   my $vendors = [];
295   while (my $ref = $sth->fetchrow_hashref()) {
296     push(@{$vendors}, $ref);
297   }
298   $sth->finish();
299   $dbh->disconnect();
300
301   $main::lxdebug->leave_sub();
302
303   return $vendors;
304 }
305
306 sub mkdir_with_parents {
307   $main::lxdebug->enter_sub();
308
309   my ($full_path) = @_;
310
311   my $path = "";
312
313   $full_path =~ s|/+|/|;
314
315   foreach my $part (split(m|/|, $full_path)) {
316     $path .= "/" if ($path);
317     $path .= $part;
318
319     die("Could not create directory '$path' because a file exists with " .
320         "the same name.\n") if (-f $path);
321
322     if (! -d $path) {
323       mkdir($path, 0770) || die("Could not create the directory '$path'. " .
324                                 "OS error: $!\n");
325     }
326   }
327
328   $main::lxdebug->leave_sub();
329 }
330
331 sub webdav_folder {
332   $main::lxdebug->enter_sub();
333
334   my ($form) = @_;
335
336   return $main::lxdebug->leave_sub()
337     unless ($main::webdav && $form->{id});
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/${path}/${number}";
368
369   if (!-d $path) {
370     mkdir_with_parents($path);
371
372   } else {
373     my $base_path = substr($ENV{'SCRIPT_NAME'}, 1);
374     $base_path =~ s|[^/]+$||;
375     $base_path =~ s|/$||;
376     # wo kommt der wert für dir her? es wird doch gar nichts übergeben? fix für strict my $dir jb 21.2.
377     if (opendir my $dir, $path) {
378       foreach my $file (sort { lc $a cmp lc $b } readdir $dir) {
379         next if (($file eq '.') || ($file eq '..'));
380
381         my $fname = $file;
382         $fname  =~ s|.*/||;
383
384         my $is_directory = -d "$path/$file";
385
386         $file  = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
387         $file .=  '/' if ($is_directory);
388
389         push @{ $form->{WEBDAV} }, {
390           'name' => $fname,
391           'link' => "/$base_path/$file",
392           'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
393         };
394       }
395
396       closedir $dir;
397     }
398   }
399
400   $main::lxdebug->leave_sub();
401 }
402
403 sub get_vc_details {
404   $main::lxdebug->enter_sub();
405
406   my ($self, $myconfig, $form, $vc, $vc_id) = @_;
407
408   $vc = $vc eq "customer" ? "customer" : "vendor";
409
410   my $dbh = $form->dbconnect($myconfig);
411
412   my $query;
413
414   $query =
415     qq|SELECT
416          vc.*,
417          pt.description AS payment_terms,
418          b.description AS business,
419          l.description AS language
420        FROM ${vc} vc
421        LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
422        LEFT JOIN business b ON (vc.business_id = b.id)
423        LEFT JOIN language l ON (vc.language_id = l.id)
424        WHERE vc.id = ?|;
425   my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
426
427   if (!$ref) {
428     $dbh->disconnect();
429     $main::lxdebug->leave_sub();
430     return 0;
431   }
432
433   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
434
435   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
436
437   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
438   $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
439
440   $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
441   $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
442
443   $dbh->disconnect();
444
445   $main::lxdebug->leave_sub();
446
447   return 1;
448 }
449
450 sub get_shipto_by_id {
451   $main::lxdebug->enter_sub();
452
453   my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
454
455   $prefix ||= "";
456
457   my $dbh = $form->dbconnect($myconfig);
458
459   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
460   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
461
462   map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
463
464   $dbh->disconnect();
465
466   $main::lxdebug->leave_sub();
467 }
468
469 sub save_email_status {
470   $main::lxdebug->enter_sub();
471
472   my ($self, $myconfig, $form) = @_;
473
474   my ($table, $query, $dbh);
475
476   if ($form->{script} eq 'oe.pl') {
477     $table = 'oe';
478
479   } elsif ($form->{script} eq 'is.pl') {
480     $table = 'ar';
481
482   } elsif ($form->{script} eq 'ir.pl') {
483     $table = 'ap';
484
485   }
486
487   return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
488
489   $dbh = $form->get_standard_dbh($myconfig);
490
491   my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
492
493   $intnotes =~ s|\r||g;
494   $intnotes =~ s|\n$||;
495
496   $intnotes .= "\n\n" if ($intnotes);
497
498   my $cc  = $main::locale->text('Cc') . ": $form->{cc}\n"   if $form->{cc};
499   my $bcc = $main::locale->text('Bcc') . ": $form->{bcc}\n" if $form->{bcc};
500   my $now = scalar localtime;
501
502   $intnotes .= $main::locale->text('[email]') . "\n"
503     . $main::locale->text('Date') . ": $now\n"
504     . $main::locale->text('To (email)') . ": $form->{email}\n"
505     . "${cc}${bcc}"
506     . $main::locale->text('Subject') . ": $form->{subject}\n\n"
507     . $main::locale->text('Message') . ": $form->{message}";
508
509   $intnotes =~ s|\r||g;
510
511   do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
512
513   $form->save_status($dbh);
514
515   $dbh->commit();
516
517   $main::lxdebug->leave_sub();
518 }
519
520 sub check_params {
521   my $params = shift;
522
523   foreach my $key (@_) {
524     if ((ref $key eq '') && !defined $params->{$key}) {
525       my $subroutine = (caller(1))[3];
526       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
527       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
528       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
529
530     } elsif (ref $key eq 'ARRAY') {
531       my $found = 0;
532       foreach my $subkey (@{ $key }) {
533         if (defined $params->{$subkey}) {
534           $found = 1;
535           last;
536         }
537       }
538
539       if (!$found) {
540         my $subroutine = (caller(1))[3];
541         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
542         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
543         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
544       }
545     }
546   }
547 }
548
549 sub check_params_x {
550   my $params = shift;
551
552   foreach my $key (@_) {
553     if ((ref $key eq '') && !exists $params->{$key}) {
554       my $subroutine = (caller(1))[3];
555       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
556
557     } elsif (ref $key eq 'ARRAY') {
558       my $found = 0;
559       foreach my $subkey (@{ $key }) {
560         if (exists $params->{$subkey}) {
561           $found = 1;
562           last;
563         }
564       }
565
566       if (!$found) {
567         my $subroutine = (caller(1))[3];
568         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
569       }
570     }
571   }
572 }
573
574 1;