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);
31 my ($a, $b) = gettimeofday();
32 return "${a}-${b}-${$}";
36 return "/tmp/kivitendo-tmp-" . unique_id();
40 my ($text, %params) = @_;
43 $params{at} = 3 if 3 > $params{at};
45 $params{strip} //= '';
47 $text =~ s/[\r\n]+$//g if $params{strip} =~ m/^(?: 1 | newlines? | full )$/x;
48 $text =~ s/[\r\n]+/ /g if $params{strip} =~ m/^(?: newlines? | full )$/x;
50 return $text if length($text) <= $params{at};
51 return substr($text, 0, $params{at} - 3) . '...';
55 $main::lxdebug->enter_sub();
57 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
59 my $dbh = SL::DB->client->dbh;
61 my (@filter_values, $filter);
63 foreach (qw(partnumber description ean)) {
64 next unless $form->{$_};
66 $filter .= qq| AND ($_ ILIKE ?)|;
67 push @filter_values, like($form->{$_});
70 if ($form->{no_assemblies}) {
71 $filter .= qq| AND (NOT part_type = 'assembly')|;
73 if ($form->{assemblies}) {
74 $filter .= qq| AND part_type = 'assembly'|;
77 if ($form->{no_services}) {
78 $filter .= qq| AND NOT (part_type = 'service' OR part_type = 'assembly')|;
81 substr($filter, 1, 3) = "WHERE" if ($filter);
83 $order_by =~ s/[^a-zA-Z_]//g;
84 $order_dir = $order_dir ? "ASC" : "DESC";
87 qq|SELECT id, partnumber, description, ean, | .
88 qq| warehouse_id, bin_id | .
89 qq|FROM parts $filter | .
90 qq|ORDER BY $order_by $order_dir|;
91 my $sth = $dbh->prepare($query);
92 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
94 while (my $ref = $sth->fetchrow_hashref()) {
95 push(@{$parts}, $ref);
99 $main::lxdebug->leave_sub();
104 sub retrieve_customers_or_vendors {
105 $main::lxdebug->enter_sub();
107 my ($self, $myconfig, $form, $order_by, $order_dir, $is_vendor, $allow_both) = @_;
109 my $dbh = SL::DB->client->dbh;
111 my (@filter_values, $filter);
112 if ($form->{"name"}) {
113 $filter .= " AND (TABLE.name ILIKE ?)";
114 push(@filter_values, like($form->{"name"}));
116 if (!$form->{"obsolete"}) {
117 $filter .= " AND NOT TABLE.obsolete";
119 substr($filter, 1, 3) = "WHERE" if ($filter);
121 $order_by =~ s/[^a-zA-Z_]//g;
122 $order_dir = $order_dir ? "ASC" : "DESC";
124 my (@queries, @query_parameters);
126 if ($allow_both || !$is_vendor) {
127 my $c_filter = $filter;
128 $c_filter =~ s/TABLE/c/g;
129 push(@queries, qq|SELECT
130 c.id, c.name, 0 AS customer_is_vendor,
131 c.street, c.zipcode, c.city,
132 ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
134 LEFT JOIN contacts ct ON (c.id = ct.cp_cv_id)
136 push(@query_parameters, @filter_values);
139 if ($allow_both || $is_vendor) {
140 my $v_filter = $filter;
141 $v_filter =~ s/TABLE/v/g;
142 push(@queries, qq|SELECT
143 v.id, v.name, 1 AS customer_is_vendor,
144 v.street, v.zipcode, v.city,
145 ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
147 LEFT JOIN contacts ct ON (v.id = ct.cp_cv_id)
149 push(@query_parameters, @filter_values);
152 my $query = join(" UNION ", @queries) . " ORDER BY $order_by $order_dir";
153 my $sth = $dbh->prepare($query);
154 $sth->execute(@query_parameters) || $form->dberror($query . " (" . join(", ", @query_parameters) . ")");
156 while (my $ref = $sth->fetchrow_hashref()) {
157 push(@{$customers}, $ref);
161 $main::lxdebug->leave_sub();
166 sub retrieve_delivery_customer {
167 $main::lxdebug->enter_sub();
169 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
171 my $dbh = SL::DB->client->dbh;
173 my (@filter_values, $filter);
174 if ($form->{"name"}) {
175 $filter .= qq| (name ILIKE ?) AND|;
176 push(@filter_values, like($form->{"name"}));
179 $order_by =~ s/[^a-zA-Z_]//g;
180 $order_dir = $order_dir ? "ASC" : "DESC";
183 qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
185 qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
186 qq!ORDER BY $order_by $order_dir!;
187 my $sth = $dbh->prepare($query);
188 $sth->execute(@filter_values) ||
189 $form->dberror($query . " (" . join(", ", @filter_values) . ")");
190 my $delivery_customers = [];
191 while (my $ref = $sth->fetchrow_hashref()) {
192 push(@{$delivery_customers}, $ref);
196 $main::lxdebug->leave_sub();
198 return $delivery_customers;
201 sub retrieve_vendor {
202 $main::lxdebug->enter_sub();
204 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
206 my $dbh = SL::DB->client->dbh;
208 my (@filter_values, $filter);
209 if ($form->{"name"}) {
210 $filter .= qq| (name ILIKE ?) AND|;
211 push(@filter_values, like($form->{"name"}));
214 $order_by =~ s/[^a-zA-Z_]//g;
215 $order_dir = $order_dir ? "ASC" : "DESC";
218 qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
219 qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = ?') ! .
220 qq!ORDER BY $order_by $order_dir!;
221 push @filter_values, $::locale->{iconv_utf8}->convert('Händler');
222 my $sth = $dbh->prepare($query);
223 $sth->execute(@filter_values) ||
224 $form->dberror($query . " (" . join(", ", @filter_values) . ")");
226 while (my $ref = $sth->fetchrow_hashref()) {
227 push(@{$vendors}, $ref);
231 $main::lxdebug->leave_sub();
236 sub mkdir_with_parents {
237 $main::lxdebug->enter_sub();
239 my ($full_path) = @_;
243 $full_path =~ s|/+|/|;
245 foreach my $part (split(m|/|, $full_path)) {
246 $path .= "/" if ($path);
249 die("Could not create directory '$path' because a file exists with " .
250 "the same name.\n") if (-f $path);
253 mkdir($path, 0770) || die("Could not create the directory '$path'. " .
258 $main::lxdebug->leave_sub();
262 $main::lxdebug->enter_sub();
266 return $main::lxdebug->leave_sub()
267 unless ($::instance_conf->get_webdav && $form->{id});
271 $form->{WEBDAV} = [];
273 my ($path, $number) = get_webdav_folder($form);
274 return $main::lxdebug->leave_sub() unless ($path && $number);
277 mkdir_with_parents($path);
280 my $base_path = $ENV{'SCRIPT_NAME'};
281 $base_path =~ s|[^/]+$||;
282 if (opendir my $dir, $path) {
283 foreach my $file (sort { lc $a cmp lc $b } map { decode("UTF-8", $_) } readdir $dir) {
284 next if (($file eq '.') || ($file eq '..'));
289 my $is_directory = -d "$path/$file";
291 $file = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
292 $file .= '/' if ($is_directory);
294 push @{ $form->{WEBDAV} }, {
296 'link' => $base_path . $file,
297 'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
305 $main::lxdebug->leave_sub();
309 $main::lxdebug->enter_sub();
311 my ($self, $myconfig, $form, $vc, $vc_id) = @_;
313 $vc = $vc eq "customer" ? "customer" : "vendor";
315 my $dbh = SL::DB->client->dbh;
322 pt.description AS payment_terms,
323 b.description AS business,
324 l.description AS language,
325 dt.description AS delivery_terms
327 LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
328 LEFT JOIN business b ON (vc.business_id = b.id)
329 LEFT JOIN language l ON (vc.language_id = l.id)
330 LEFT JOIN delivery_terms dt ON (vc.delivery_term_id = dt.id)
332 my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
335 $main::lxdebug->leave_sub();
339 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
341 map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
343 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
344 $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
346 if ($vc eq 'customer') {
347 $query = qq|SELECT * FROM additional_billing_addresses WHERE (customer_id = ?)|;
348 $form->{ADDITIONAL_BILLING_ADDRESSES} = selectall_hashref_query($form, $dbh, $query, $vc_id);
351 $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
352 $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
354 # Only show default pricegroup for customer, not vendor, which is why this is outside the main query
355 ($form->{pricegroup}) = selectrow_query($form, $dbh, qq|SELECT pricegroup FROM pricegroup WHERE id = ?|, $form->{pricegroup_id});
357 $main::lxdebug->leave_sub();
362 sub get_shipto_by_id {
363 $main::lxdebug->enter_sub();
365 my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
369 my $dbh = SL::DB->client->dbh;
371 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
372 my $ref = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
374 map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
376 my $cvars = CVar->get_custom_variables(
379 trans_id => $shipto_id,
381 $form->{"${prefix}shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
383 $main::lxdebug->leave_sub();
386 sub save_email_status {
387 $main::lxdebug->enter_sub();
389 my ($self, $myconfig, $form) = @_;
391 return unless ($::instance_conf->get_email_journal);
393 my ($table, $query, $dbh);
395 if ($form->{script} eq 'oe.pl') {
398 } elsif ($form->{script} eq 'is.pl') {
401 } elsif ($form->{script} eq 'ir.pl') {
404 } elsif ($form->{script} eq 'do.pl') {
405 $table = 'delivery_orders';
408 return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
410 SL::DB->client->with_transaction(sub {
411 $dbh = SL::DB->client->dbh;
413 my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
415 $intnotes =~ s|\r||g;
416 $intnotes =~ s|\n$||;
418 $intnotes .= "\n\n" if ($intnotes);
420 my $cc = $form->{cc} ? $main::locale->text('Cc') . ": $form->{cc}\n" : '';
421 my $bcc = $form->{bcc} ? $main::locale->text('Bcc') . ": $form->{bcc}\n" : '';
422 my $now = scalar localtime;
424 $intnotes .= $main::locale->text('[email]') . "\n"
425 . $main::locale->text('Date') . ": $now\n"
426 . $main::locale->text('To (email)') . ": $form->{email}\n"
428 . $main::locale->text('Subject') . ": $form->{subject}\n\n"
429 . $main::locale->text('Message') . ": " . SL::HTML::Util->strip($form->{message});
431 $intnotes =~ s|\r||g;
433 do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
435 $form->save_status($dbh);
437 }) or do { die SL::DB->client->error };
439 $main::lxdebug->leave_sub();
445 foreach my $key (@_) {
446 if ((ref $key eq '') && !defined $params->{$key}) {
447 my $subroutine = (caller(1))[3];
448 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
449 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
450 $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
452 } elsif (ref $key eq 'ARRAY') {
454 foreach my $subkey (@{ $key }) {
455 if (defined $params->{$subkey}) {
462 my $subroutine = (caller(1))[3];
463 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
464 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
465 $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
474 foreach my $key (@_) {
475 if ((ref $key eq '') && !exists $params->{$key}) {
476 my $subroutine = (caller(1))[3];
477 $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
479 } elsif (ref $key eq 'ARRAY') {
481 foreach my $subkey (@{ $key }) {
482 if (exists $params->{$subkey}) {
489 my $subroutine = (caller(1))[3];
490 $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
496 sub get_webdav_folder {
497 $main::lxdebug->enter_sub();
501 croak "No client set in \$::auth" unless $::auth->client;
506 if ($form->{type} eq "sales_quotation") {
507 ($path, $number) = ("angebote", $form->{quonumber});
508 } elsif ($form->{type} eq "sales_order") {
509 ($path, $number) = ("bestellungen", $form->{ordnumber});
510 } elsif ($form->{type} eq "request_quotation") {
511 ($path, $number) = ("anfragen", $form->{quonumber});
512 } elsif ($form->{type} eq "purchase_order") {
513 ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
514 } elsif ($form->{type} eq "sales_delivery_order") {
515 ($path, $number) = ("verkaufslieferscheine", $form->{donumber});
516 } elsif ($form->{type} eq "purchase_delivery_order") {
517 ($path, $number) = ("einkaufslieferscheine", $form->{donumber});
518 } elsif ($form->{type} eq "credit_note") {
519 ($path, $number) = ("gutschriften", $form->{invnumber});
520 } elsif ($form->{type} eq "letter") {
521 ($path, $number) = ("briefe", $form->{letternumber} );
522 } elsif ($form->{vc} eq "customer") {
523 ($path, $number) = ("rechnungen", $form->{invnumber});
524 } elsif ($form->{vc} eq "vendor") {
525 ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
527 $main::lxdebug->leave_sub();
531 $number =~ s|[/\\]|_|g;
533 $path = "webdav/" . $::auth->client->{id} . "/${path}/${number}";
535 $main::lxdebug->leave_sub();
537 return ($path, $number);
540 sub copy_file_to_webdav_folder {
541 $::lxdebug->enter_sub();
544 my ($last_mod_time, $latest_file_name, $complete_path);
547 foreach my $item (qw(tmpdir tmpfile type)){
548 next if $form->{$item};
549 $::lxdebug->message(LXDebug::WARN(), 'Missing parameter:' . $item);
550 $::lxdebug->leave_sub();
551 return $::locale->text("Missing parameter for WebDAV file copy");
554 my ($webdav_folder, $document_name) = get_webdav_folder($form);
556 if (! $webdav_folder){
557 $::lxdebug->message(LXDebug::WARN(), 'Cannot check correct WebDAV folder');
558 $::lxdebug->leave_sub();
559 return $::locale->text("Cannot check correct WebDAV folder")
562 $complete_path = File::Spec->catfile($form->{cwd}, $webdav_folder);
564 # maybe the path does not exist (automatic printing), see #2446
565 if (!-d $complete_path) {
566 # we need a chdir and restore old dir
567 my $current_dir = POSIX::getcwd();
568 chdir("$form->{cwd}");
569 mkdir_with_parents($webdav_folder);
574 if (!opendir $dh, $complete_path) {
575 $::lxdebug->leave_sub();
576 return "Could not open $complete_path: $!";
579 my ($newest_name, $newest_time);
580 while ( defined( my $file = readdir( $dh ) ) ) {
581 my $path = File::Spec->catfile( $complete_path, $file );
582 next if -d $path; # skip directories, or anything else you like
583 ( $newest_name, $newest_time ) = ( $file, -M _ ) if( ! defined $newest_time or -M $path < $newest_time );
588 $latest_file_name = File::Spec->catfile($complete_path, $newest_name);
589 my $filesize = stat($latest_file_name)->size;
591 my $current_file = File::Spec->catfile($form->{tmpdir}, apply { s:.*/:: } $form->{tmpfile});
592 my $current_filesize = -f $current_file ? stat($current_file)->size : 0;
594 if ($current_filesize == $filesize) {
595 $::lxdebug->leave_sub();
599 $form->{attachment_filename} ||= $form->generate_attachment_filename;
601 my $timestamp = get_current_formatted_time();
602 my $new_file = File::Spec->catfile($form->{cwd}, $webdav_folder, $form->{attachment_filename});
603 $new_file =~ s{(.*)\.}{$1$timestamp\.};
605 if (!File::Copy::copy($current_file, $new_file)) {
606 $::lxdebug->message(LXDebug::WARN(), "Copy file from $current_file to $new_file failed: $ERRNO");
607 $::lxdebug->leave_sub();
608 return $::locale->text("Copy file from #1 to #2 failed: #3", $current_file, $new_file, $ERRNO);
612 $::lxdebug->leave_sub();
615 sub get_current_formatted_time {
616 return POSIX::strftime('_%Y%m%d_%H%M%S', localtime());
628 Common - Common routines used in a lot of places.
632 my $short_text = Common::truncate($long_text, at => 10);
638 =item C<truncate $text, %params>
640 Truncates C<$text> at a position and insert an ellipsis if the text is
641 longer. The maximum number of characters to return is given with the
642 paramter C<at> which defaults to 50.
644 The optional parameter C<strip> can be used to remove unwanted line
645 feed/carriage return characters from the text before truncation. It
646 can be set to C<1> (only strip those at the end of C<$text>) or
647 C<full> (replace consecutive line feed/carriage return characters in
648 the middle by a single space and remove tailing line feed/carriage
651 =item C<save_email_status>
653 Adds sending information to internal notes.
654 Does nothing if the client config email_journal is enabled.
664 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
665 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>