1 #====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #====================================================================
15 use English qw(-no_match_vars);
16 use Time::HiRes qw(gettimeofday);
22 use List::MoreUtils qw(apply);
24 use Encode qw(decode);
29 my ($a, $b) = gettimeofday();
30 return "${a}-${b}-${$}";
34 return "/tmp/kivitendo-tmp-" . unique_id();
38 my ($text, %params) = @_;
41 $params{at} = 3 if 3 > $params{at};
43 $params{strip} //= '';
45 $text =~ s/[\r\n]+$//g if $params{strip} =~ m/^(?: 1 | newlines? | full )$/x;
46 $text =~ s/[\r\n]+/ /g if $params{strip} =~ m/^(?: newlines? | full )$/x;
48 return $text if length($text) <= $params{at};
49 return substr($text, 0, $params{at} - 3) . '...';
53 $main::lxdebug->enter_sub();
55 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
57 my $dbh = $form->dbconnect($myconfig);
59 my (@filter_values, $filter);
61 foreach (qw(partnumber description ean)) {
62 next unless $form->{$_};
64 $filter .= qq| AND ($_ ILIKE ?)|;
65 push @filter_values, '%' . $form->{$_} . '%';
68 if ($form->{no_assemblies}) {
69 $filter .= qq| AND (NOT COALESCE(assembly, FALSE))|;
71 if ($form->{assemblies}) {
72 $filter .= qq| AND assembly=TRUE|;
75 if ($form->{no_services}) {
76 $filter .= qq| AND (inventory_accno_id is not NULL or assembly=TRUE)|;
79 substr($filter, 1, 3) = "WHERE" if ($filter);
81 $order_by =~ s/[^a-zA-Z_]//g;
82 $order_dir = $order_dir ? "ASC" : "DESC";
85 qq|SELECT id, partnumber, description, ean, | .
86 qq| warehouse_id, bin_id | .
87 qq|FROM parts $filter | .
88 qq|ORDER BY $order_by $order_dir|;
89 my $sth = $dbh->prepare($query);
90 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
92 while (my $ref = $sth->fetchrow_hashref()) {
93 push(@{$parts}, $ref);
98 $main::lxdebug->leave_sub();
103 sub retrieve_projects {
104 $main::lxdebug->enter_sub();
106 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
108 my $dbh = $form->dbconnect($myconfig);
110 my (@filter_values, $filter);
111 if ($form->{"projectnumber"}) {
112 $filter .= qq| AND (projectnumber ILIKE ?)|;
113 push(@filter_values, '%' . $form->{"projectnumber"} . '%');
115 if ($form->{"description"}) {
116 $filter .= qq| AND (description ILIKE ?)|;
117 push(@filter_values, '%' . $form->{"description"} . '%');
119 substr($filter, 1, 3) = "WHERE" if ($filter);
121 $order_by =~ s/[^a-zA-Z_]//g;
122 $order_dir = $order_dir ? "ASC" : "DESC";
125 qq|SELECT id, projectnumber, description | .
126 qq|FROM project $filter | .
127 qq|ORDER BY $order_by $order_dir|;
128 my $sth = $dbh->prepare($query);
129 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
131 while (my $ref = $sth->fetchrow_hashref()) {
132 push(@{$projects}, $ref);
137 $main::lxdebug->leave_sub();
142 sub retrieve_employees {
143 $main::lxdebug->enter_sub();
145 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
147 my $dbh = $form->dbconnect($myconfig);
149 my (@filter_values, $filter);
150 if ($form->{"name"}) {
151 $filter .= qq| AND (name ILIKE ?)|;
152 push(@filter_values, '%' . $form->{"name"} . '%');
154 substr($filter, 1, 3) = "WHERE" if ($filter);
156 $order_by =~ s/[^a-zA-Z_]//g;
157 $order_dir = $order_dir ? "ASC" : "DESC";
160 qq|SELECT id, name | .
161 qq|FROM employee $filter | .
162 qq|ORDER BY $order_by $order_dir|;
163 my $sth = $dbh->prepare($query);
164 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
166 while (my $ref = $sth->fetchrow_hashref()) {
167 push(@{$employees}, $ref);
172 $main::lxdebug->leave_sub();
177 sub retrieve_customers_or_vendors {
178 $main::lxdebug->enter_sub();
180 my ($self, $myconfig, $form, $order_by, $order_dir, $is_vendor, $allow_both) = @_;
182 my $dbh = $form->dbconnect($myconfig);
184 my (@filter_values, $filter);
185 if ($form->{"name"}) {
186 $filter .= " AND (TABLE.name ILIKE ?)";
187 push(@filter_values, '%' . $form->{"name"} . '%');
189 if (!$form->{"obsolete"}) {
190 $filter .= " AND NOT TABLE.obsolete";
192 substr($filter, 1, 3) = "WHERE" if ($filter);
194 $order_by =~ s/[^a-zA-Z_]//g;
195 $order_dir = $order_dir ? "ASC" : "DESC";
197 my (@queries, @query_parameters);
199 if ($allow_both || !$is_vendor) {
200 my $c_filter = $filter;
201 $c_filter =~ s/TABLE/c/g;
202 push(@queries, qq|SELECT
203 c.id, c.name, 0 AS customer_is_vendor,
204 c.street, c.zipcode, c.city,
205 ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
207 LEFT JOIN contacts ct ON (c.id = ct.cp_cv_id)
209 push(@query_parameters, @filter_values);
212 if ($allow_both || $is_vendor) {
213 my $v_filter = $filter;
214 $v_filter =~ s/TABLE/v/g;
215 push(@queries, qq|SELECT
216 v.id, v.name, 1 AS customer_is_vendor,
217 v.street, v.zipcode, v.city,
218 ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
220 LEFT JOIN contacts ct ON (v.id = ct.cp_cv_id)
222 push(@query_parameters, @filter_values);
225 my $query = join(" UNION ", @queries) . " ORDER BY $order_by $order_dir";
226 my $sth = $dbh->prepare($query);
227 $sth->execute(@query_parameters) || $form->dberror($query . " (" . join(", ", @query_parameters) . ")");
229 while (my $ref = $sth->fetchrow_hashref()) {
230 push(@{$customers}, $ref);
235 $main::lxdebug->leave_sub();
240 sub retrieve_delivery_customer {
241 $main::lxdebug->enter_sub();
243 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
245 my $dbh = $form->dbconnect($myconfig);
247 my (@filter_values, $filter);
248 if ($form->{"name"}) {
249 $filter .= qq| (name ILIKE ?) AND|;
250 push(@filter_values, '%' . $form->{"name"} . '%');
253 $order_by =~ s/[^a-zA-Z_]//g;
254 $order_dir = $order_dir ? "ASC" : "DESC";
257 qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
259 qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
260 qq!ORDER BY $order_by $order_dir!;
261 my $sth = $dbh->prepare($query);
262 $sth->execute(@filter_values) ||
263 $form->dberror($query . " (" . join(", ", @filter_values) . ")");
264 my $delivery_customers = [];
265 while (my $ref = $sth->fetchrow_hashref()) {
266 push(@{$delivery_customers}, $ref);
271 $main::lxdebug->leave_sub();
273 return $delivery_customers;
276 sub retrieve_vendor {
277 $main::lxdebug->enter_sub();
279 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
281 my $dbh = $form->dbconnect($myconfig);
283 my (@filter_values, $filter);
284 if ($form->{"name"}) {
285 $filter .= qq| (name ILIKE ?) AND|;
286 push(@filter_values, '%' . $form->{"name"} . '%');
289 $order_by =~ s/[^a-zA-Z_]//g;
290 $order_dir = $order_dir ? "ASC" : "DESC";
293 qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
294 qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = ?') ! .
295 qq!ORDER BY $order_by $order_dir!;
296 push @filter_values, $::locale->{iconv_utf8}->convert('Händler');
297 my $sth = $dbh->prepare($query);
298 $sth->execute(@filter_values) ||
299 $form->dberror($query . " (" . join(", ", @filter_values) . ")");
301 while (my $ref = $sth->fetchrow_hashref()) {
302 push(@{$vendors}, $ref);
307 $main::lxdebug->leave_sub();
312 sub mkdir_with_parents {
313 $main::lxdebug->enter_sub();
315 my ($full_path) = @_;
319 $full_path =~ s|/+|/|;
321 foreach my $part (split(m|/|, $full_path)) {
322 $path .= "/" if ($path);
325 die("Could not create directory '$path' because a file exists with " .
326 "the same name.\n") if (-f $path);
329 mkdir($path, 0770) || die("Could not create the directory '$path'. " .
334 $main::lxdebug->leave_sub();
338 $main::lxdebug->enter_sub();
342 return $main::lxdebug->leave_sub()
343 unless ($::instance_conf->get_webdav && $form->{id});
347 $form->{WEBDAV} = [];
349 my ($path, $number) = get_webdav_folder($form);
350 return $main::lxdebug->leave_sub() unless ($path && $number);
353 mkdir_with_parents($path);
356 my $base_path = $ENV{'SCRIPT_NAME'};
357 $base_path =~ s|[^/]+$||;
358 if (opendir my $dir, $path) {
359 foreach my $file (sort { lc $a cmp lc $b } map { decode("UTF-8", $_) } readdir $dir) {
360 next if (($file eq '.') || ($file eq '..'));
365 my $is_directory = -d "$path/$file";
367 $file = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
368 $file .= '/' if ($is_directory);
370 push @{ $form->{WEBDAV} }, {
372 'link' => $base_path . $file,
373 'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
381 $main::lxdebug->leave_sub();
385 $main::lxdebug->enter_sub();
387 my ($self, $myconfig, $form, $vc, $vc_id) = @_;
389 $vc = $vc eq "customer" ? "customer" : "vendor";
391 my $dbh = $form->dbconnect($myconfig);
398 pt.description AS payment_terms,
399 b.description AS business,
400 l.description AS language
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)
406 my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
410 $main::lxdebug->leave_sub();
414 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
416 map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
418 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
419 $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
421 $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
422 $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
424 # Only show default pricegroup for customer, not vendor, which is why this is outside the main query
425 ($form->{pricegroup}) = selectrow_query($form, $dbh, qq|SELECT pricegroup FROM pricegroup WHERE id = ?|, $form->{klass});
429 $main::lxdebug->leave_sub();
434 sub get_shipto_by_id {
435 $main::lxdebug->enter_sub();
437 my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
441 my $dbh = $form->dbconnect($myconfig);
443 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
444 my $ref = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
446 map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
450 $main::lxdebug->leave_sub();
453 sub save_email_status {
454 $main::lxdebug->enter_sub();
456 my ($self, $myconfig, $form) = @_;
458 my ($table, $query, $dbh);
460 if ($form->{script} eq 'oe.pl') {
463 } elsif ($form->{script} eq 'is.pl') {
466 } elsif ($form->{script} eq 'ir.pl') {
469 } elsif ($form->{script} eq 'do.pl') {
470 $table = 'delivery_orders';
473 return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
475 $dbh = $form->get_standard_dbh($myconfig);
477 my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
479 $intnotes =~ s|\r||g;
480 $intnotes =~ s|\n$||;
482 $intnotes .= "\n\n" if ($intnotes);
484 my $cc = $form->{cc} ? $main::locale->text('Cc') . ": $form->{cc}\n" : '';
485 my $bcc = $form->{bcc} ? $main::locale->text('Bcc') . ": $form->{bcc}\n" : '';
486 my $now = scalar localtime;
488 $intnotes .= $main::locale->text('[email]') . "\n"
489 . $main::locale->text('Date') . ": $now\n"
490 . $main::locale->text('To (email)') . ": $form->{email}\n"
492 . $main::locale->text('Subject') . ": $form->{subject}\n\n"
493 . $main::locale->text('Message') . ": $form->{message}";
495 $intnotes =~ s|\r||g;
497 do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
499 $form->save_status($dbh);
503 $main::lxdebug->leave_sub();
509 foreach my $key (@_) {
510 if ((ref $key eq '') && !defined $params->{$key}) {
511 my $subroutine = (caller(1))[3];
512 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
513 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
514 $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
516 } elsif (ref $key eq 'ARRAY') {
518 foreach my $subkey (@{ $key }) {
519 if (defined $params->{$subkey}) {
526 my $subroutine = (caller(1))[3];
527 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
528 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
529 $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
538 foreach my $key (@_) {
539 if ((ref $key eq '') && !exists $params->{$key}) {
540 my $subroutine = (caller(1))[3];
541 $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
543 } elsif (ref $key eq 'ARRAY') {
545 foreach my $subkey (@{ $key }) {
546 if (exists $params->{$subkey}) {
553 my $subroutine = (caller(1))[3];
554 $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
560 sub get_webdav_folder {
561 $main::lxdebug->enter_sub();
565 croak "No client set in \$::auth" unless $::auth->client;
570 if ($form->{type} eq "sales_quotation") {
571 ($path, $number) = ("angebote", $form->{quonumber});
572 } elsif ($form->{type} eq "sales_order") {
573 ($path, $number) = ("bestellungen", $form->{ordnumber});
574 } elsif ($form->{type} eq "request_quotation") {
575 ($path, $number) = ("anfragen", $form->{quonumber});
576 } elsif ($form->{type} eq "purchase_order") {
577 ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
578 } elsif ($form->{type} eq "sales_delivery_order") {
579 ($path, $number) = ("verkaufslieferscheine", $form->{donumber});
580 } elsif ($form->{type} eq "purchase_delivery_order") {
581 ($path, $number) = ("einkaufslieferscheine", $form->{donumber});
582 } elsif ($form->{type} eq "credit_note") {
583 ($path, $number) = ("gutschriften", $form->{invnumber});
584 } elsif ($form->{vc} eq "customer") {
585 ($path, $number) = ("rechnungen", $form->{invnumber});
586 } elsif ($form->{vc} eq "vendor") {
587 ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
589 $main::lxdebug->leave_sub();
593 $number =~ s|[/\\]|_|g;
595 $path = "webdav/" . $::auth->client->{id} . "/${path}/${number}";
597 $main::lxdebug->leave_sub();
599 return ($path, $number);
602 sub copy_file_to_webdav_folder {
603 $::lxdebug->enter_sub();
606 my ($last_mod_time, $latest_file_name, $complete_path);
609 foreach my $item (qw(tmpdir tmpfile type)){
610 next if $form->{$item};
611 $::lxdebug->message(LXDebug::WARN(), 'Missing parameter');
612 $::form->error($::locale->text("Missing parameter for WebDAV file copy"));
615 my ($webdav_folder, $document_name) = get_webdav_folder($form);
617 if (! $webdav_folder){
618 $::lxdebug->leave_sub();
619 $::form->error($::locale->text("Cannot check correct WebDAV folder"));
623 $complete_path = File::Spec->catfile($form->{cwd}, $webdav_folder);
624 opendir my $dh, $complete_path or die "Could not open $complete_path: $!";
626 my ($newest_name, $newest_time);
627 while ( defined( my $file = readdir( $dh ) ) ) {
628 my $path = File::Spec->catfile( $complete_path, $file );
629 next if -d $path; # skip directories, or anything else you like
630 ( $newest_name, $newest_time ) = ( $file, -M _ ) if( ! defined $newest_time or -M $path < $newest_time );
635 $latest_file_name = File::Spec->catfile($complete_path, $newest_name);
636 my $filesize = stat($latest_file_name)->size;
638 my $current_file = File::Spec->catfile($form->{tmpdir}, apply { s:.*/:: } $form->{tmpfile});
639 my $current_filesize = -f $current_file ? stat($current_file)->size : 0;
641 if ($current_filesize == $filesize) {
642 $::lxdebug->leave_sub();
646 my $timestamp = get_current_formatted_time();
647 my $new_file = File::Spec->catfile($form->{cwd}, $webdav_folder, $form->generate_attachment_filename());
648 $new_file =~ s/\./$timestamp\./;
650 if (!File::Copy::copy($current_file, $new_file)) {
651 $::lxdebug->message(LXDebug::WARN(), "Copy file from $current_file to $new_file failed: $ERRNO");
652 $::form->error($::locale->text("Copy file from #1 to #2 failed: #3", $current_file, $new_file, $ERRNO));
655 $::lxdebug->leave_sub();
658 sub get_current_formatted_time {
659 return POSIX::strftime('_%Y%m%d_%H%M%S', localtime());
671 Common - Common routines used in a lot of places.
675 my $short_text = Common::truncate($long_text, at => 10);
681 =item C<truncate $text, %params>
683 Truncates C<$text> at a position and insert an ellipsis if the text is
684 longer. The maximum number of characters to return is given with the
685 paramter C<at> which defaults to 50.
687 The optional parameter C<strip> can be used to remove unwanted line
688 feed/carriage return characters from the text before truncation. It
689 can be set to C<1> (only strip those at the end of C<$text>) or
690 C<full> (replace consecutive line feed/carriage return characters in
691 the middle by a single space and remove tailing line feed/carriage
702 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
703 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>