bedb9e6d7550594774701b8e48b17df6dfa7a924
[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
33 use constant DEFAULT_CHARSET => 'ISO-8859-15';
34
35 sub unique_id {
36   my ($a, $b) = gettimeofday();
37   return "${a}-${b}-${$}";
38 }
39
40 sub tmpname {
41   return "/tmp/lx-office-tmp-" . unique_id();
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   if ($form->{"partnumber"}) {
53     $filter .= qq| AND (partnumber ILIKE ?)|;
54     push(@filter_values, '%' . $form->{"partnumber"} . '%');
55   }
56   if ($form->{"description"}) {
57     $filter .= qq| AND (description ILIKE ?)|;
58     push(@filter_values, '%' . $form->{"description"} . '%');
59   }
60   substr($filter, 1, 3) = "WHERE" if ($filter);
61
62   $order_by =~ s/[^a-zA-Z_]//g;
63   $order_dir = $order_dir ? "ASC" : "DESC";
64
65   my $query =
66     qq|SELECT id, partnumber, description | .
67     qq|FROM parts $filter | .
68     qq|ORDER BY $order_by $order_dir|;
69   my $sth = $dbh->prepare($query);
70   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
71   my $parts = [];
72   while (my $ref = $sth->fetchrow_hashref()) {
73     push(@{$parts}, $ref);
74   }
75   $sth->finish();
76   $dbh->disconnect();
77
78   $main::lxdebug->leave_sub();
79
80   return $parts;
81 }
82
83 sub retrieve_projects {
84   $main::lxdebug->enter_sub();
85
86   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
87
88   my $dbh = $form->dbconnect($myconfig);
89
90   my (@filter_values, $filter);
91   if ($form->{"projectnumber"}) {
92     $filter .= qq| AND (projectnumber ILIKE ?)|;
93     push(@filter_values, '%' . $form->{"projectnumber"} . '%');
94   }
95   if ($form->{"description"}) {
96     $filter .= qq| AND (description ILIKE ?)|;
97     push(@filter_values, '%' . $form->{"description"} . '%');
98   }
99   substr($filter, 1, 3) = "WHERE" if ($filter);
100
101   $order_by =~ s/[^a-zA-Z_]//g;
102   $order_dir = $order_dir ? "ASC" : "DESC";
103
104   my $query =
105     qq|SELECT id, projectnumber, description | .
106     qq|FROM project $filter | .
107     qq|ORDER BY $order_by $order_dir|;
108   my $sth = $dbh->prepare($query);
109   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
110   my $projects = [];
111   while (my $ref = $sth->fetchrow_hashref()) {
112     push(@{$projects}, $ref);
113   }
114   $sth->finish();
115   $dbh->disconnect();
116
117   $main::lxdebug->leave_sub();
118
119   return $projects;
120 }
121
122 sub retrieve_employees {
123   $main::lxdebug->enter_sub();
124
125   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
126
127   my $dbh = $form->dbconnect($myconfig);
128
129   my (@filter_values, $filter);
130   if ($form->{"name"}) {
131     $filter .= qq| AND (name ILIKE ?)|;
132     push(@filter_values, '%' . $form->{"name"} . '%');
133   }
134   substr($filter, 1, 3) = "WHERE" if ($filter);
135
136   $order_by =~ s/[^a-zA-Z_]//g;
137   $order_dir = $order_dir ? "ASC" : "DESC";
138
139   my $query =
140     qq|SELECT id, name | .
141     qq|FROM employee $filter | .
142     qq|ORDER BY $order_by $order_dir|;
143   my $sth = $dbh->prepare($query);
144   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
145   my $employees = [];
146   while (my $ref = $sth->fetchrow_hashref()) {
147     push(@{$employees}, $ref);
148   }
149   $sth->finish();
150   $dbh->disconnect();
151
152   $main::lxdebug->leave_sub();
153
154   return $employees;
155 }
156
157 sub retrieve_customers_or_vendors {
158   $main::lxdebug->enter_sub();
159
160   my ($self, $myconfig, $form, $order_by, $order_dir, $is_vendor, $allow_both) = @_;
161
162   my $dbh = $form->dbconnect($myconfig);
163
164   my (@filter_values, $filter);
165   if ($form->{"name"}) {
166     $filter .= " AND (TABLE.name ILIKE ?)";
167     push(@filter_values, '%' . $form->{"name"} . '%');
168   }
169   if (!$form->{"obsolete"}) {
170     $filter .= " AND NOT TABLE.obsolete";
171   }
172   substr($filter, 1, 3) = "WHERE" if ($filter);
173
174   $order_by =~ s/[^a-zA-Z_]//g;
175   $order_dir = $order_dir ? "ASC" : "DESC";
176
177   my (@queries, @query_parameters);
178
179   if ($allow_both || !$is_vendor) {
180     my $c_filter = $filter;
181     $c_filter =~ s/TABLE/c/g;
182     push(@queries, qq|SELECT
183                         c.id, c.name, 0 AS customer_is_vendor,
184                         c.street, c.zipcode, c.city,
185                         ct.cp_greeting, ct.cp_title, ct.cp_givenname, ct.cp_name
186                       FROM customer c
187                       LEFT JOIN contacts ct ON (c.id = ct.cp_cv_id)
188                       $c_filter|);
189     push(@query_parameters, @filter_values);
190   }
191
192   if ($allow_both || $is_vendor) {
193     my $v_filter = $filter;
194     $v_filter =~ s/TABLE/v/g;
195     push(@queries, qq|SELECT
196                         v.id, v.name, 1 AS customer_is_vendor,
197                         v.street, v.zipcode, v.city,
198                         ct.cp_greeting, ct.cp_title, ct.cp_givenname, ct.cp_name
199                       FROM vendor v
200                       LEFT JOIN contacts ct ON (v.id = ct.cp_cv_id)
201                       $v_filter|);
202     push(@query_parameters, @filter_values);
203   }
204
205   my $query = join(" UNION ", @queries) . " ORDER BY $order_by $order_dir";
206   my $sth = $dbh->prepare($query);
207   $sth->execute(@query_parameters) || $form->dberror($query . " (" . join(", ", @query_parameters) . ")");
208   my $customers = [];
209   while (my $ref = $sth->fetchrow_hashref()) {
210     push(@{$customers}, $ref);
211   }
212   $sth->finish();
213   $dbh->disconnect();
214
215   $main::lxdebug->leave_sub();
216
217   return $customers;
218 }
219
220 sub retrieve_delivery_customer {
221   $main::lxdebug->enter_sub();
222
223   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
224
225   my $dbh = $form->dbconnect($myconfig);
226
227   my (@filter_values, $filter);
228   if ($form->{"name"}) {
229     $filter .= qq| (name ILIKE ?) AND|;
230     push(@filter_values, '%' . $form->{"name"} . '%');
231   }
232
233   $order_by =~ s/[^a-zA-Z_]//g;
234   $order_dir = $order_dir ? "ASC" : "DESC";
235
236   my $query =
237     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
238     qq!FROM customer ! .
239     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
240     qq!ORDER BY $order_by $order_dir!;
241   my $sth = $dbh->prepare($query);
242   $sth->execute(@filter_values) ||
243     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
244   my $delivery_customers = [];
245   while (my $ref = $sth->fetchrow_hashref()) {
246     push(@{$delivery_customers}, $ref);
247   }
248   $sth->finish();
249   $dbh->disconnect();
250
251   $main::lxdebug->leave_sub();
252
253   return $delivery_customers;
254 }
255
256 sub retrieve_vendor {
257   $main::lxdebug->enter_sub();
258
259   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
260
261   my $dbh = $form->dbconnect($myconfig);
262
263   my (@filter_values, $filter);
264   if ($form->{"name"}) {
265     $filter .= qq| (name ILIKE ?) AND|;
266     push(@filter_values, '%' . $form->{"name"} . '%');
267   }
268
269   $order_by =~ s/[^a-zA-Z_]//g;
270   $order_dir = $order_dir ? "ASC" : "DESC";
271
272   my $query =
273     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
274     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Händler') ! .
275     qq!ORDER BY $order_by $order_dir!;
276   my $sth = $dbh->prepare($query);
277   $sth->execute(@filter_values) ||
278     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
279   my $vendors = [];
280   while (my $ref = $sth->fetchrow_hashref()) {
281     push(@{$vendors}, $ref);
282   }
283   $sth->finish();
284   $dbh->disconnect();
285
286   $main::lxdebug->leave_sub();
287
288   return $vendors;
289 }
290
291 sub mkdir_with_parents {
292   $main::lxdebug->enter_sub();
293
294   my ($full_path) = @_;
295
296   my $path = "";
297
298   $full_path =~ s|/+|/|;
299
300   foreach my $part (split(m|/|, $full_path)) {
301     $path .= "/" if ($path);
302     $path .= $part;
303
304     die("Could not create directory '$path' because a file exists with " .
305         "the same name.\n") if (-f $path);
306
307     if (! -d $path) {
308       mkdir($path, 0770) || die("Could not create the directory '$path'. " .
309                                 "OS error: $!\n");
310     }
311   }
312
313   $main::lxdebug->leave_sub();
314 }
315
316 sub webdav_folder {
317   $main::lxdebug->enter_sub();
318
319   my ($form) = @_;
320
321   return $main::lxdebug->leave_sub()
322     unless ($main::webdav && $form->{id});
323
324   my ($path, $number);
325
326   $form->{WEBDAV} = [];
327
328   if ($form->{type} eq "sales_quotation") {
329     ($path, $number) = ("angebote", $form->{quonumber});
330   } elsif ($form->{type} eq "sales_order") {
331     ($path, $number) = ("bestellungen", $form->{ordnumber});
332   } elsif ($form->{type} eq "request_quotation") {
333     ($path, $number) = ("anfragen", $form->{quonumber});
334   } elsif ($form->{type} eq "purchase_order") {
335     ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
336   } elsif ($form->{type} eq "credit_note") {
337     ($path, $number) = ("gutschriften", $form->{invnumber});
338   } elsif ($form->{vc} eq "customer") {
339     ($path, $number) = ("rechnungen", $form->{invnumber});
340   } else {
341     ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
342   }
343
344   return $main::lxdebug->leave_sub() unless ($path && $number);
345
346   $number =~ s|[/\\]|_|g;
347
348   $path = "webdav/${path}/${number}";
349
350   if (!-d $path) {
351     mkdir_with_parents($path);
352
353   } else {
354     my $base_path = substr($ENV{'SCRIPT_NAME'}, 1);
355     $base_path =~ s|[^/]+$||;
356     $base_path =~ s|/$||;
357
358     if (opendir $dir, $path) {
359       foreach my $file (sort { lc $a cmp lc $b } readdir $dir) {
360         next if (($file eq '.') || ($file eq '..'));
361
362         my $fname = $file;
363         $fname  =~ s|.*/||;
364
365         my $is_directory = -d "$path/$file";
366
367         $file  = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
368         $file .=  '/' if ($is_directory);
369
370         push @{ $form->{WEBDAV} }, {
371           'name' => $fname,
372           'link' => ($ENV{"HTTPS"} ? "https://" : "http://") . $ENV{'SERVER_NAME'} . "/$base_path/$file",
373           'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
374         };
375       }
376
377       closedir $dir;
378     }
379   }
380
381   $main::lxdebug->leave_sub();
382 }
383
384 sub get_vc_details {
385   $main::lxdebug->enter_sub();
386
387   my ($self, $myconfig, $form, $vc, $vc_id) = @_;
388
389   $vc = $vc eq "customer" ? "customer" : "vendor";
390
391   my $dbh = $form->dbconnect($myconfig);
392
393   my $query;
394
395   $query =
396     qq|SELECT
397          vc.*,
398          pt.description AS payment_terms,
399          b.description AS business,
400          l.description AS language
401        FROM ${vc} vc
402        LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
403        LEFT JOIN business b ON (vc.business_id = b.id)
404        LEFT JOIN language l ON (vc.language_id = l.id)
405        WHERE vc.id = ?|;
406   my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
407
408   if (!$ref) {
409     $dbh->disconnect();
410     $main::lxdebug->leave_sub();
411     return 0;
412   }
413
414   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
415
416   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
417
418   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
419   $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
420
421   $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
422   $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
423
424   $dbh->disconnect();
425
426   $main::lxdebug->leave_sub();
427
428   return 1;
429 }
430
431 sub get_shipto_by_id {
432   $main::lxdebug->enter_sub();
433
434   my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
435
436   $prefix ||= "";
437
438   my $dbh = $form->dbconnect($myconfig);
439
440   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
441   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
442
443   map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
444
445   $dbh->disconnect();
446
447   $main::lxdebug->leave_sub();
448 }
449
450 sub save_email_status {
451   $main::lxdebug->enter_sub();
452
453   my ($self, $myconfig, $form) = @_;
454
455   my ($table, $query, $dbh);
456
457   if ($form->{script} eq 'oe.pl') {
458     $table = 'oe';
459
460   } elsif ($form->{script} eq 'is.pl') {
461     $table = 'ar';
462
463   } elsif ($form->{script} eq 'ir.pl') {
464     $table = 'ap';
465
466   }
467
468   return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
469
470   $dbh = $form->get_standard_dbh($myconfig);
471
472   my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
473
474   $intnotes =~ s|\r||g;
475   $intnotes =~ s|\n$||;
476
477   $intnotes .= "\n\n" if ($intnotes);
478
479   my $cc  = $main::locale->text('Cc') . ": $form->{cc}\n"   if $form->{cc};
480   my $bcc = $main::locale->text('Bcc') . ": $form->{bcc}\n" if $form->{bcc};
481   my $now = scalar localtime;
482
483   $intnotes .= $main::locale->text('[email]') . "\n"
484     . $main::locale->text('Date') . ": $now\n"
485     . $main::locale->text('To (email)') . ": $form->{email}\n"
486     . "${cc}${bcc}"
487     . $main::locale->text('Subject') . ": $form->{subject}\n\n"
488     . $main::locale->text('Message') . ": $form->{message}";
489
490   $intnotes =~ s|\r||g;
491
492   do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
493
494   $form->save_status($dbh);
495
496   $dbh->commit();
497
498   $main::lxdebug->leave_sub();
499 }
500
501 sub check_params {
502   my $params = shift;
503
504   foreach my $key (@_) {
505     if (!defined $params->{$key}) {
506       my $subroutine = (caller(1))[3];
507       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
508     }
509   }
510 }
511
512 sub check_params_x {
513   my $params = shift;
514
515   foreach my $key (@_) {
516     if (!exists $params->{$key}) {
517       my $subroutine = (caller(1))[3];
518       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
519     }
520   }
521 }
522
523 1;