Lieferscheine auch im Webdav speichern.
[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);
17
18 @db_encodings = (
19   { "label" => "ASCII",          "dbencoding" => "SQL_ASCII", "charset" => "ASCII" },
20   { "label" => "UTF-8 Unicode",  "dbencoding" => "UNICODE",   "charset" => "UTF-8" },
21   { "label" => "ISO 8859-1",     "dbencoding" => "LATIN1",    "charset" => "ISO-8859-1" },
22   { "label" => "ISO 8859-2",     "dbencoding" => "LATIN2",    "charset" => "ISO-8859-2" },
23   { "label" => "ISO 8859-3",     "dbencoding" => "LATIN3",    "charset" => "ISO-8859-3" },
24   { "label" => "ISO 8859-4",     "dbencoding" => "LATIN4",    "charset" => "ISO-8859-4" },
25   { "label" => "ISO 8859-5",     "dbencoding" => "LATIN5",    "charset" => "ISO-8859-5" },
26   { "label" => "ISO 8859-15",    "dbencoding" => "LATIN9",    "charset" => "ISO-8859-15" },
27   { "label" => "KOI8-R",         "dbencoding" => "KOI8",      "charset" => "KOI8-R" },
28   { "label" => "Windows CP1251", "dbencoding" => "WIN",       "charset" => "CP1251" },
29   { "label" => "Windows CP866",  "dbencoding" => "ALT",       "charset" => "CP866" },
30 );
31
32 %db_encoding_to_charset = map { $_->{dbencoding}, $_->{charset} } @db_encodings;
33 %charset_to_db_encoding = map { $_->{charset}, $_->{dbencoding} } @db_encodings;
34
35 use constant DEFAULT_CHARSET => 'ISO-8859-15';
36
37 sub unique_id {
38   my ($a, $b) = gettimeofday();
39   return "${a}-${b}-${$}";
40 }
41
42 sub tmpname {
43   return "/tmp/lx-office-tmp-" . unique_id();
44 }
45
46 sub retrieve_parts {
47   $main::lxdebug->enter_sub();
48
49   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
50
51   my $dbh = $form->dbconnect($myconfig);
52
53   my (@filter_values, $filter);
54
55   foreach (qw(partnumber description ean)) {
56     next unless $form->{$_};
57
58     $filter .= qq| AND ($_ ILIKE ?)|;
59     push @filter_values, '%' . $form->{$_} . '%';
60   }
61
62   if ($form->{no_assemblies}) {
63     $filter .= qq| AND (NOT COALESCE(assembly, FALSE))|;
64   }
65   if ($form->{assemblies}) {
66     $filter .= qq| AND assembly=TRUE|;
67   }
68
69   if ($form->{no_services}) {
70     $filter .= qq| AND (inventory_accno_id is not NULL or assembly=TRUE)|; # @mb hier nochmal optimieren ... nach kurzer ruecksprache alles i.o.
71   }
72
73   substr($filter, 1, 3) = "WHERE" if ($filter);
74
75   $order_by =~ s/[^a-zA-Z_]//g;
76   $order_dir = $order_dir ? "ASC" : "DESC";
77
78   my $query =
79     qq|SELECT id, partnumber, description, ean | .
80     qq|FROM parts $filter | .
81     qq|ORDER BY $order_by $order_dir|;
82   my $sth = $dbh->prepare($query);
83   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
84   my $parts = [];
85   while (my $ref = $sth->fetchrow_hashref()) {
86     push(@{$parts}, $ref);
87   }
88   $sth->finish();
89   $dbh->disconnect();
90
91   $main::lxdebug->leave_sub();
92
93   return $parts;
94 }
95
96 sub retrieve_projects {
97   $main::lxdebug->enter_sub();
98
99   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
100
101   my $dbh = $form->dbconnect($myconfig);
102
103   my (@filter_values, $filter);
104   if ($form->{"projectnumber"}) {
105     $filter .= qq| AND (projectnumber ILIKE ?)|;
106     push(@filter_values, '%' . $form->{"projectnumber"} . '%');
107   }
108   if ($form->{"description"}) {
109     $filter .= qq| AND (description ILIKE ?)|;
110     push(@filter_values, '%' . $form->{"description"} . '%');
111   }
112   substr($filter, 1, 3) = "WHERE" if ($filter);
113
114   $order_by =~ s/[^a-zA-Z_]//g;
115   $order_dir = $order_dir ? "ASC" : "DESC";
116
117   my $query =
118     qq|SELECT id, projectnumber, description | .
119     qq|FROM project $filter | .
120     qq|ORDER BY $order_by $order_dir|;
121   my $sth = $dbh->prepare($query);
122   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
123   my $projects = [];
124   while (my $ref = $sth->fetchrow_hashref()) {
125     push(@{$projects}, $ref);
126   }
127   $sth->finish();
128   $dbh->disconnect();
129
130   $main::lxdebug->leave_sub();
131
132   return $projects;
133 }
134
135 sub retrieve_employees {
136   $main::lxdebug->enter_sub();
137
138   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
139
140   my $dbh = $form->dbconnect($myconfig);
141
142   my (@filter_values, $filter);
143   if ($form->{"name"}) {
144     $filter .= qq| AND (name ILIKE ?)|;
145     push(@filter_values, '%' . $form->{"name"} . '%');
146   }
147   substr($filter, 1, 3) = "WHERE" if ($filter);
148
149   $order_by =~ s/[^a-zA-Z_]//g;
150   $order_dir = $order_dir ? "ASC" : "DESC";
151
152   my $query =
153     qq|SELECT id, name | .
154     qq|FROM employee $filter | .
155     qq|ORDER BY $order_by $order_dir|;
156   my $sth = $dbh->prepare($query);
157   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
158   my $employees = [];
159   while (my $ref = $sth->fetchrow_hashref()) {
160     push(@{$employees}, $ref);
161   }
162   $sth->finish();
163   $dbh->disconnect();
164
165   $main::lxdebug->leave_sub();
166
167   return $employees;
168 }
169
170 sub retrieve_customers_or_vendors {
171   $main::lxdebug->enter_sub();
172
173   my ($self, $myconfig, $form, $order_by, $order_dir, $is_vendor, $allow_both) = @_;
174
175   my $dbh = $form->dbconnect($myconfig);
176
177   my (@filter_values, $filter);
178   if ($form->{"name"}) {
179     $filter .= " AND (TABLE.name ILIKE ?)";
180     push(@filter_values, '%' . $form->{"name"} . '%');
181   }
182   if (!$form->{"obsolete"}) {
183     $filter .= " AND NOT TABLE.obsolete";
184   }
185   substr($filter, 1, 3) = "WHERE" if ($filter);
186
187   $order_by =~ s/[^a-zA-Z_]//g;
188   $order_dir = $order_dir ? "ASC" : "DESC";
189
190   my (@queries, @query_parameters);
191
192   if ($allow_both || !$is_vendor) {
193     my $c_filter = $filter;
194     $c_filter =~ s/TABLE/c/g;
195     push(@queries, qq|SELECT
196                         c.id, c.name, 0 AS customer_is_vendor,
197                         c.street, c.zipcode, c.city,
198                         ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
199                       FROM customer c
200                       LEFT JOIN contacts ct ON (c.id = ct.cp_cv_id)
201                       $c_filter|);
202     push(@query_parameters, @filter_values);
203   }
204
205   if ($allow_both || $is_vendor) {
206     my $v_filter = $filter;
207     $v_filter =~ s/TABLE/v/g;
208     push(@queries, qq|SELECT
209                         v.id, v.name, 1 AS customer_is_vendor,
210                         v.street, v.zipcode, v.city,
211                         ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
212                       FROM vendor v
213                       LEFT JOIN contacts ct ON (v.id = ct.cp_cv_id)
214                       $v_filter|);
215     push(@query_parameters, @filter_values);
216   }
217
218   my $query = join(" UNION ", @queries) . " ORDER BY $order_by $order_dir";
219   my $sth = $dbh->prepare($query);
220   $sth->execute(@query_parameters) || $form->dberror($query . " (" . join(", ", @query_parameters) . ")");
221   my $customers = [];
222   while (my $ref = $sth->fetchrow_hashref()) {
223     push(@{$customers}, $ref);
224   }
225   $sth->finish();
226   $dbh->disconnect();
227
228   $main::lxdebug->leave_sub();
229
230   return $customers;
231 }
232
233 sub retrieve_delivery_customer {
234   $main::lxdebug->enter_sub();
235
236   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
237
238   my $dbh = $form->dbconnect($myconfig);
239
240   my (@filter_values, $filter);
241   if ($form->{"name"}) {
242     $filter .= qq| (name ILIKE ?) AND|;
243     push(@filter_values, '%' . $form->{"name"} . '%');
244   }
245
246   $order_by =~ s/[^a-zA-Z_]//g;
247   $order_dir = $order_dir ? "ASC" : "DESC";
248
249   my $query =
250     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
251     qq!FROM customer ! .
252     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
253     qq!ORDER BY $order_by $order_dir!;
254   my $sth = $dbh->prepare($query);
255   $sth->execute(@filter_values) ||
256     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
257   my $delivery_customers = [];
258   while (my $ref = $sth->fetchrow_hashref()) {
259     push(@{$delivery_customers}, $ref);
260   }
261   $sth->finish();
262   $dbh->disconnect();
263
264   $main::lxdebug->leave_sub();
265
266   return $delivery_customers;
267 }
268
269 sub retrieve_vendor {
270   $main::lxdebug->enter_sub();
271
272   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
273
274   my $dbh = $form->dbconnect($myconfig);
275
276   my (@filter_values, $filter);
277   if ($form->{"name"}) {
278     $filter .= qq| (name ILIKE ?) AND|;
279     push(@filter_values, '%' . $form->{"name"} . '%');
280   }
281
282   $order_by =~ s/[^a-zA-Z_]//g;
283   $order_dir = $order_dir ? "ASC" : "DESC";
284
285   my $query =
286     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
287     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Händler') ! .
288     qq!ORDER BY $order_by $order_dir!;
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 ($main::webdav && $form->{id});
336
337   my ($path, $number);
338
339   $form->{WEBDAV} = [];
340
341   if ($form->{type} eq "sales_quotation") {
342     ($path, $number) = ("angebote", $form->{quonumber});
343   } elsif ($form->{type} eq "sales_order") {
344     ($path, $number) = ("bestellungen", $form->{ordnumber});
345   } elsif ($form->{type} eq "request_quotation") {
346     ($path, $number) = ("anfragen", $form->{quonumber});
347   } elsif ($form->{type} eq "purchase_order") {
348     ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
349   } elsif ($form->{type} eq "sales_delivery_order") {
350     ($path, $number) = ("verkaufslieferscheine", $form->{donumber});
351   } elsif ($form->{type} eq "purchase_delivery_order") {
352     ($path, $number) = ("einkaufslieferscheine", $form->{donumber});
353   } elsif ($form->{type} eq "credit_note") {
354     ($path, $number) = ("gutschriften", $form->{invnumber});
355   } elsif ($form->{vc} eq "customer") {
356     ($path, $number) = ("rechnungen", $form->{invnumber});
357   } else {
358     ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
359   }
360
361   return $main::lxdebug->leave_sub() unless ($path && $number);
362
363   $number =~ s|[/\\]|_|g;
364
365   $path = "webdav/${path}/${number}";
366
367   if (!-d $path) {
368     mkdir_with_parents($path);
369
370   } else {
371     my $base_path = substr($ENV{'SCRIPT_NAME'}, 1);
372     $base_path =~ s|[^/]+$||;
373     $base_path =~ s|/$||;
374     # wo kommt der wert für dir her? es wird doch gar nichts übergeben? fix für strict my $dir jb 21.2.
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' => ($ENV{"HTTPS"} ? "https://" : "http://") . $ENV{'SERVER_NAME'} . "/$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   $dbh->disconnect();
442
443   $main::lxdebug->leave_sub();
444
445   return 1;
446 }
447
448 sub get_shipto_by_id {
449   $main::lxdebug->enter_sub();
450
451   my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
452
453   $prefix ||= "";
454
455   my $dbh = $form->dbconnect($myconfig);
456
457   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
458   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
459
460   map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
461
462   $dbh->disconnect();
463
464   $main::lxdebug->leave_sub();
465 }
466
467 sub save_email_status {
468   $main::lxdebug->enter_sub();
469
470   my ($self, $myconfig, $form) = @_;
471
472   my ($table, $query, $dbh);
473
474   if ($form->{script} eq 'oe.pl') {
475     $table = 'oe';
476
477   } elsif ($form->{script} eq 'is.pl') {
478     $table = 'ar';
479
480   } elsif ($form->{script} eq 'ir.pl') {
481     $table = 'ap';
482
483   }
484
485   return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
486
487   $dbh = $form->get_standard_dbh($myconfig);
488
489   my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
490
491   $intnotes =~ s|\r||g;
492   $intnotes =~ s|\n$||;
493
494   $intnotes .= "\n\n" if ($intnotes);
495
496   my $cc  = $main::locale->text('Cc') . ": $form->{cc}\n"   if $form->{cc};
497   my $bcc = $main::locale->text('Bcc') . ": $form->{bcc}\n" if $form->{bcc};
498   my $now = scalar localtime;
499
500   $intnotes .= $main::locale->text('[email]') . "\n"
501     . $main::locale->text('Date') . ": $now\n"
502     . $main::locale->text('To (email)') . ": $form->{email}\n"
503     . "${cc}${bcc}"
504     . $main::locale->text('Subject') . ": $form->{subject}\n\n"
505     . $main::locale->text('Message') . ": $form->{message}";
506
507   $intnotes =~ s|\r||g;
508
509   do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
510
511   $form->save_status($dbh);
512
513   $dbh->commit();
514
515   $main::lxdebug->leave_sub();
516 }
517
518 sub check_params {
519   my $params = shift;
520
521   foreach my $key (@_) {
522     if ((ref $key eq '') && !defined $params->{$key}) {
523       my $subroutine = (caller(1))[3];
524       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
525       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
526       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
527
528     } elsif (ref $key eq 'ARRAY') {
529       my $found = 0;
530       foreach my $subkey (@{ $key }) {
531         if (defined $params->{$subkey}) {
532           $found = 1;
533           last;
534         }
535       }
536
537       if (!$found) {
538         my $subroutine = (caller(1))[3];
539         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
540         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
541         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
542       }
543     }
544   }
545 }
546
547 sub check_params_x {
548   my $params = shift;
549
550   foreach my $key (@_) {
551     if ((ref $key eq '') && !exists $params->{$key}) {
552       my $subroutine = (caller(1))[3];
553       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
554
555     } elsif (ref $key eq 'ARRAY') {
556       my $found = 0;
557       foreach my $subkey (@{ $key }) {
558         if (exists $params->{$subkey}) {
559           $found = 1;
560           last;
561         }
562       }
563
564       if (!$found) {
565         my $subroutine = (caller(1))[3];
566         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
567       }
568     }
569   }
570 }
571
572 1;