Bugzilla Eintrag 856 EAN auch fuers Einlagern ... Teil II von III
[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
13 use SL::DBUtils;
14
15 use vars qw(@db_encodings %db_encoding_to_charset);
16
17 @db_encodings = (
18   { "label" => "ASCII",          "dbencoding" => "SQL_ASCII", "charset" => "ASCII" },
19   { "label" => "UTF-8 Unicode",  "dbencoding" => "UNICODE",   "charset" => "UTF-8" },
20   { "label" => "ISO 8859-1",     "dbencoding" => "LATIN1",    "charset" => "ISO-8859-1" },
21   { "label" => "ISO 8859-2",     "dbencoding" => "LATIN2",    "charset" => "ISO-8859-2" },
22   { "label" => "ISO 8859-3",     "dbencoding" => "LATIN3",    "charset" => "ISO-8859-3" },
23   { "label" => "ISO 8859-4",     "dbencoding" => "LATIN4",    "charset" => "ISO-8859-4" },
24   { "label" => "ISO 8859-5",     "dbencoding" => "LATIN5",    "charset" => "ISO-8859-5" },
25   { "label" => "ISO 8859-15",    "dbencoding" => "LATIN9",    "charset" => "ISO-8859-15" },
26   { "label" => "KOI8-R",         "dbencoding" => "KOI8",      "charset" => "KOI8-R" },
27   { "label" => "Windows CP1251", "dbencoding" => "WIN",       "charset" => "CP1251" },
28   { "label" => "Windows CP866",  "dbencoding" => "ALT",       "charset" => "CP866" },
29 );
30
31 %db_encoding_to_charset = map { $_->{dbencoding}, $_->{charset} } @db_encodings;
32 %charset_to_db_encoding = map { $_->{charset}, $_->{dbencoding} } @db_encodings;
33
34 use constant DEFAULT_CHARSET => 'ISO-8859-15';
35
36 sub unique_id {
37   my ($a, $b) = gettimeofday();
38   return "${a}-${b}-${$}";
39 }
40
41 sub tmpname {
42   return "/tmp/lx-office-tmp-" . unique_id();
43 }
44
45 sub retrieve_parts {
46   $main::lxdebug->enter_sub();
47
48   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
49
50   my $dbh = $form->dbconnect($myconfig);
51
52   my (@filter_values, $filter);
53
54   foreach (qw(partnumber description ean)) {
55     next unless $form->{$_};
56
57     $filter .= qq| AND ($_ ILIKE ?)|;
58     push @filter_values, '%' . $form->{$_} . '%';
59   }
60
61   if ($form->{no_assemblies}) {
62     $filter .= qq| AND (NOT COALESCE(assembly, FALSE))|;
63   }
64   if ($form->{assemblies}) {
65     $filter .= qq| AND assembly=TRUE|;
66   }
67
68   if ($form->{no_services}) {
69     $filter .= qq| AND (inventory_accno_id is not NULL or assembly=TRUE)|; # @mb hier nochmal optimieren ... nach kurzer ruecksprache alles i.o.
70   }
71
72   substr($filter, 1, 3) = "WHERE" if ($filter);
73
74   $order_by =~ s/[^a-zA-Z_]//g;
75   $order_dir = $order_dir ? "ASC" : "DESC";
76
77   my $query =
78     qq|SELECT id, partnumber, description, ean | .
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_greeting, 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_greeting, 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 = 'Händler') ! .
287     qq!ORDER BY $order_by $order_dir!;
288   my $sth = $dbh->prepare($query);
289   $sth->execute(@filter_values) ||
290     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
291   my $vendors = [];
292   while (my $ref = $sth->fetchrow_hashref()) {
293     push(@{$vendors}, $ref);
294   }
295   $sth->finish();
296   $dbh->disconnect();
297
298   $main::lxdebug->leave_sub();
299
300   return $vendors;
301 }
302
303 sub mkdir_with_parents {
304   $main::lxdebug->enter_sub();
305
306   my ($full_path) = @_;
307
308   my $path = "";
309
310   $full_path =~ s|/+|/|;
311
312   foreach my $part (split(m|/|, $full_path)) {
313     $path .= "/" if ($path);
314     $path .= $part;
315
316     die("Could not create directory '$path' because a file exists with " .
317         "the same name.\n") if (-f $path);
318
319     if (! -d $path) {
320       mkdir($path, 0770) || die("Could not create the directory '$path'. " .
321                                 "OS error: $!\n");
322     }
323   }
324
325   $main::lxdebug->leave_sub();
326 }
327
328 sub webdav_folder {
329   $main::lxdebug->enter_sub();
330
331   my ($form) = @_;
332
333   return $main::lxdebug->leave_sub()
334     unless ($main::webdav && $form->{id});
335
336   my ($path, $number);
337
338   $form->{WEBDAV} = [];
339
340   if ($form->{type} eq "sales_quotation") {
341     ($path, $number) = ("angebote", $form->{quonumber});
342   } elsif ($form->{type} eq "sales_order") {
343     ($path, $number) = ("bestellungen", $form->{ordnumber});
344   } elsif ($form->{type} eq "request_quotation") {
345     ($path, $number) = ("anfragen", $form->{quonumber});
346   } elsif ($form->{type} eq "purchase_order") {
347     ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
348   } elsif ($form->{type} eq "credit_note") {
349     ($path, $number) = ("gutschriften", $form->{invnumber});
350   } elsif ($form->{vc} eq "customer") {
351     ($path, $number) = ("rechnungen", $form->{invnumber});
352   } else {
353     ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
354   }
355
356   return $main::lxdebug->leave_sub() unless ($path && $number);
357
358   $number =~ s|[/\\]|_|g;
359
360   $path = "webdav/${path}/${number}";
361
362   if (!-d $path) {
363     mkdir_with_parents($path);
364
365   } else {
366     my $base_path = substr($ENV{'SCRIPT_NAME'}, 1);
367     $base_path =~ s|[^/]+$||;
368     $base_path =~ s|/$||;
369     # wo kommt der wert für dir her? es wird doch gar nichts übergeben? fix für strict my $dir jb 21.2.
370     if (opendir my $dir, $path) {
371       foreach my $file (sort { lc $a cmp lc $b } readdir $dir) {
372         next if (($file eq '.') || ($file eq '..'));
373
374         my $fname = $file;
375         $fname  =~ s|.*/||;
376
377         my $is_directory = -d "$path/$file";
378
379         $file  = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
380         $file .=  '/' if ($is_directory);
381
382         push @{ $form->{WEBDAV} }, {
383           'name' => $fname,
384           'link' => ($ENV{"HTTPS"} ? "https://" : "http://") . $ENV{'SERVER_NAME'} . "/$base_path/$file",
385           'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
386         };
387       }
388
389       closedir $dir;
390     }
391   }
392
393   $main::lxdebug->leave_sub();
394 }
395
396 sub get_vc_details {
397   $main::lxdebug->enter_sub();
398
399   my ($self, $myconfig, $form, $vc, $vc_id) = @_;
400
401   $vc = $vc eq "customer" ? "customer" : "vendor";
402
403   my $dbh = $form->dbconnect($myconfig);
404
405   my $query;
406
407   $query =
408     qq|SELECT
409          vc.*,
410          pt.description AS payment_terms,
411          b.description AS business,
412          l.description AS language
413        FROM ${vc} vc
414        LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
415        LEFT JOIN business b ON (vc.business_id = b.id)
416        LEFT JOIN language l ON (vc.language_id = l.id)
417        WHERE vc.id = ?|;
418   my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
419
420   if (!$ref) {
421     $dbh->disconnect();
422     $main::lxdebug->leave_sub();
423     return 0;
424   }
425
426   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
427
428   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
429
430   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
431   $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
432
433   $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
434   $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
435
436   $dbh->disconnect();
437
438   $main::lxdebug->leave_sub();
439
440   return 1;
441 }
442
443 sub get_shipto_by_id {
444   $main::lxdebug->enter_sub();
445
446   my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
447
448   $prefix ||= "";
449
450   my $dbh = $form->dbconnect($myconfig);
451
452   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
453   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
454
455   map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
456
457   $dbh->disconnect();
458
459   $main::lxdebug->leave_sub();
460 }
461
462 sub save_email_status {
463   $main::lxdebug->enter_sub();
464
465   my ($self, $myconfig, $form) = @_;
466
467   my ($table, $query, $dbh);
468
469   if ($form->{script} eq 'oe.pl') {
470     $table = 'oe';
471
472   } elsif ($form->{script} eq 'is.pl') {
473     $table = 'ar';
474
475   } elsif ($form->{script} eq 'ir.pl') {
476     $table = 'ap';
477
478   }
479
480   return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
481
482   $dbh = $form->get_standard_dbh($myconfig);
483
484   my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
485
486   $intnotes =~ s|\r||g;
487   $intnotes =~ s|\n$||;
488
489   $intnotes .= "\n\n" if ($intnotes);
490
491   my $cc  = $main::locale->text('Cc') . ": $form->{cc}\n"   if $form->{cc};
492   my $bcc = $main::locale->text('Bcc') . ": $form->{bcc}\n" if $form->{bcc};
493   my $now = scalar localtime;
494
495   $intnotes .= $main::locale->text('[email]') . "\n"
496     . $main::locale->text('Date') . ": $now\n"
497     . $main::locale->text('To (email)') . ": $form->{email}\n"
498     . "${cc}${bcc}"
499     . $main::locale->text('Subject') . ": $form->{subject}\n\n"
500     . $main::locale->text('Message') . ": $form->{message}";
501
502   $intnotes =~ s|\r||g;
503
504   do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
505
506   $form->save_status($dbh);
507
508   $dbh->commit();
509
510   $main::lxdebug->leave_sub();
511 }
512
513 sub check_params {
514   my $params = shift;
515
516   foreach my $key (@_) {
517     if ((ref $key eq '') && !defined $params->{$key}) {
518       my $subroutine = (caller(1))[3];
519       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
520
521     } elsif (ref $key eq 'ARRAY') {
522       my $found = 0;
523       foreach my $subkey (@{ $key }) {
524         if (defined $params->{$subkey}) {
525           $found = 1;
526           last;
527         }
528       }
529
530       if (!$found) {
531         my $subroutine = (caller(1))[3];
532         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
533       }
534     }
535   }
536 }
537
538 sub check_params_x {
539   my $params = shift;
540
541   foreach my $key (@_) {
542     if ((ref $key eq '') && !exists $params->{$key}) {
543       my $subroutine = (caller(1))[3];
544       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
545
546     } elsif (ref $key eq 'ARRAY') {
547       my $found = 0;
548       foreach my $subkey (@{ $key }) {
549         if (exists $params->{$subkey}) {
550           $found = 1;
551           last;
552         }
553       }
554
555       if (!$found) {
556         my $subroutine = (caller(1))[3];
557         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
558       }
559     }
560   }
561 }
562
563 1;