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,
401 dt.description AS delivery_terms
403 LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
404 LEFT JOIN business b ON (vc.business_id = b.id)
405 LEFT JOIN language l ON (vc.language_id = l.id)
406 LEFT JOIN delivery_terms dt ON (vc.delivery_term_id = dt.id)
408 my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
412 $main::lxdebug->leave_sub();
416 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
418 map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
420 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
421 $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
423 $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
424 $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
426 # Only show default pricegroup for customer, not vendor, which is why this is outside the main query
427 ($form->{pricegroup}) = selectrow_query($form, $dbh, qq|SELECT pricegroup FROM pricegroup WHERE id = ?|, $form->{klass});
431 $main::lxdebug->leave_sub();
436 sub get_shipto_by_id {
437 $main::lxdebug->enter_sub();
439 my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
443 my $dbh = $form->dbconnect($myconfig);
445 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
446 my $ref = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
448 map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
452 $main::lxdebug->leave_sub();
455 sub save_email_status {
456 $main::lxdebug->enter_sub();
458 my ($self, $myconfig, $form) = @_;
460 my ($table, $query, $dbh);
462 if ($form->{script} eq 'oe.pl') {
465 } elsif ($form->{script} eq 'is.pl') {
468 } elsif ($form->{script} eq 'ir.pl') {
471 } elsif ($form->{script} eq 'do.pl') {
472 $table = 'delivery_orders';
475 return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
477 $dbh = $form->get_standard_dbh($myconfig);
479 my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
481 $intnotes =~ s|\r||g;
482 $intnotes =~ s|\n$||;
484 $intnotes .= "\n\n" if ($intnotes);
486 my $cc = $form->{cc} ? $main::locale->text('Cc') . ": $form->{cc}\n" : '';
487 my $bcc = $form->{bcc} ? $main::locale->text('Bcc') . ": $form->{bcc}\n" : '';
488 my $now = scalar localtime;
490 $intnotes .= $main::locale->text('[email]') . "\n"
491 . $main::locale->text('Date') . ": $now\n"
492 . $main::locale->text('To (email)') . ": $form->{email}\n"
494 . $main::locale->text('Subject') . ": $form->{subject}\n\n"
495 . $main::locale->text('Message') . ": $form->{message}";
497 $intnotes =~ s|\r||g;
499 do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
501 $form->save_status($dbh);
505 $main::lxdebug->leave_sub();
511 foreach my $key (@_) {
512 if ((ref $key eq '') && !defined $params->{$key}) {
513 my $subroutine = (caller(1))[3];
514 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
515 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
516 $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
518 } elsif (ref $key eq 'ARRAY') {
520 foreach my $subkey (@{ $key }) {
521 if (defined $params->{$subkey}) {
528 my $subroutine = (caller(1))[3];
529 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
530 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
531 $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
540 foreach my $key (@_) {
541 if ((ref $key eq '') && !exists $params->{$key}) {
542 my $subroutine = (caller(1))[3];
543 $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
545 } elsif (ref $key eq 'ARRAY') {
547 foreach my $subkey (@{ $key }) {
548 if (exists $params->{$subkey}) {
555 my $subroutine = (caller(1))[3];
556 $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
562 sub get_webdav_folder {
563 $main::lxdebug->enter_sub();
567 croak "No client set in \$::auth" unless $::auth->client;
572 if ($form->{type} eq "sales_quotation") {
573 ($path, $number) = ("angebote", $form->{quonumber});
574 } elsif ($form->{type} eq "sales_order") {
575 ($path, $number) = ("bestellungen", $form->{ordnumber});
576 } elsif ($form->{type} eq "request_quotation") {
577 ($path, $number) = ("anfragen", $form->{quonumber});
578 } elsif ($form->{type} eq "purchase_order") {
579 ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
580 } elsif ($form->{type} eq "sales_delivery_order") {
581 ($path, $number) = ("verkaufslieferscheine", $form->{donumber});
582 } elsif ($form->{type} eq "purchase_delivery_order") {
583 ($path, $number) = ("einkaufslieferscheine", $form->{donumber});
584 } elsif ($form->{type} eq "credit_note") {
585 ($path, $number) = ("gutschriften", $form->{invnumber});
586 } elsif ($form->{vc} eq "customer") {
587 ($path, $number) = ("rechnungen", $form->{invnumber});
588 } elsif ($form->{vc} eq "vendor") {
589 ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
591 $main::lxdebug->leave_sub();
595 $number =~ s|[/\\]|_|g;
597 $path = "webdav/" . $::auth->client->{id} . "/${path}/${number}";
599 $main::lxdebug->leave_sub();
601 return ($path, $number);
604 sub copy_file_to_webdav_folder {
605 $::lxdebug->enter_sub();
608 my ($last_mod_time, $latest_file_name, $complete_path);
611 foreach my $item (qw(tmpdir tmpfile type)){
612 next if $form->{$item};
613 $::lxdebug->message(LXDebug::WARN(), 'Missing parameter');
614 $::form->error($::locale->text("Missing parameter for WebDAV file copy"));
617 my ($webdav_folder, $document_name) = get_webdav_folder($form);
619 if (! $webdav_folder){
620 $::lxdebug->leave_sub();
621 $::form->error($::locale->text("Cannot check correct WebDAV folder"));
625 $complete_path = File::Spec->catfile($form->{cwd}, $webdav_folder);
627 # maybe the path does not exist (automatic printing), see #2446
628 if (!-d $complete_path) {
629 # we need a chdir and restore old dir
630 my $current_dir = POSIX::getcwd();
631 chdir("$form->{cwd}");
632 mkdir_with_parents($webdav_folder);
636 opendir my $dh, $complete_path or die "Could not open $complete_path: $!";
638 my ($newest_name, $newest_time);
639 while ( defined( my $file = readdir( $dh ) ) ) {
640 my $path = File::Spec->catfile( $complete_path, $file );
641 next if -d $path; # skip directories, or anything else you like
642 ( $newest_name, $newest_time ) = ( $file, -M _ ) if( ! defined $newest_time or -M $path < $newest_time );
647 $latest_file_name = File::Spec->catfile($complete_path, $newest_name);
648 my $filesize = stat($latest_file_name)->size;
650 my $current_file = File::Spec->catfile($form->{tmpdir}, apply { s:.*/:: } $form->{tmpfile});
651 my $current_filesize = -f $current_file ? stat($current_file)->size : 0;
653 if ($current_filesize == $filesize) {
654 $::lxdebug->leave_sub();
658 my $timestamp = get_current_formatted_time();
659 my $new_file = File::Spec->catfile($form->{cwd}, $webdav_folder, $form->generate_attachment_filename());
660 $new_file =~ s{(.*)\.}{$1$timestamp\.};
662 if (!File::Copy::copy($current_file, $new_file)) {
663 $::lxdebug->message(LXDebug::WARN(), "Copy file from $current_file to $new_file failed: $ERRNO");
664 $::form->error($::locale->text("Copy file from #1 to #2 failed: #3", $current_file, $new_file, $ERRNO));
667 $::lxdebug->leave_sub();
670 sub get_current_formatted_time {
671 return POSIX::strftime('_%Y%m%d_%H%M%S', localtime());
683 Common - Common routines used in a lot of places.
687 my $short_text = Common::truncate($long_text, at => 10);
693 =item C<truncate $text, %params>
695 Truncates C<$text> at a position and insert an ellipsis if the text is
696 longer. The maximum number of characters to return is given with the
697 paramter C<at> which defaults to 50.
699 The optional parameter C<strip> can be used to remove unwanted line
700 feed/carriage return characters from the text before truncation. It
701 can be set to C<1> (only strip those at the end of C<$text>) or
702 C<full> (replace consecutive line feed/carriage return characters in
703 the middle by a single space and remove tailing line feed/carriage
714 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
715 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>