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);
27 my ($a, $b) = gettimeofday();
28 return "${a}-${b}-${$}";
32 return "/tmp/kivitendo-tmp-" . unique_id();
36 my ($text, %params) = @_;
39 $params{at} = 3 if 3 > $params{at};
41 $params{strip} //= '';
43 $text =~ s/[\r\n]+$//g if $params{strip} =~ m/^(?: 1 | newlines? | full )$/x;
44 $text =~ s/[\r\n]+/ /g if $params{strip} =~ m/^(?: newlines? | full )$/x;
46 return $text if length($text) <= $params{at};
47 return substr($text, 0, $params{at} - 3) . '...';
51 $main::lxdebug->enter_sub();
53 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
55 my $dbh = $form->dbconnect($myconfig);
57 my (@filter_values, $filter);
59 foreach (qw(partnumber description ean)) {
60 next unless $form->{$_};
62 $filter .= qq| AND ($_ ILIKE ?)|;
63 push @filter_values, '%' . $form->{$_} . '%';
66 if ($form->{no_assemblies}) {
67 $filter .= qq| AND (NOT COALESCE(assembly, FALSE))|;
69 if ($form->{assemblies}) {
70 $filter .= qq| AND assembly=TRUE|;
73 if ($form->{no_services}) {
74 $filter .= qq| AND (inventory_accno_id is not NULL or assembly=TRUE)|;
77 substr($filter, 1, 3) = "WHERE" if ($filter);
79 $order_by =~ s/[^a-zA-Z_]//g;
80 $order_dir = $order_dir ? "ASC" : "DESC";
83 qq|SELECT id, partnumber, description, ean, | .
84 qq| warehouse_id, bin_id | .
85 qq|FROM parts $filter | .
86 qq|ORDER BY $order_by $order_dir|;
87 my $sth = $dbh->prepare($query);
88 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
90 while (my $ref = $sth->fetchrow_hashref()) {
91 push(@{$parts}, $ref);
96 $main::lxdebug->leave_sub();
101 sub retrieve_projects {
102 $main::lxdebug->enter_sub();
104 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
106 my $dbh = $form->dbconnect($myconfig);
108 my (@filter_values, $filter);
109 if ($form->{"projectnumber"}) {
110 $filter .= qq| AND (projectnumber ILIKE ?)|;
111 push(@filter_values, '%' . $form->{"projectnumber"} . '%');
113 if ($form->{"description"}) {
114 $filter .= qq| AND (description ILIKE ?)|;
115 push(@filter_values, '%' . $form->{"description"} . '%');
117 substr($filter, 1, 3) = "WHERE" if ($filter);
119 $order_by =~ s/[^a-zA-Z_]//g;
120 $order_dir = $order_dir ? "ASC" : "DESC";
123 qq|SELECT id, projectnumber, description | .
124 qq|FROM project $filter | .
125 qq|ORDER BY $order_by $order_dir|;
126 my $sth = $dbh->prepare($query);
127 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
129 while (my $ref = $sth->fetchrow_hashref()) {
130 push(@{$projects}, $ref);
135 $main::lxdebug->leave_sub();
140 sub retrieve_employees {
141 $main::lxdebug->enter_sub();
143 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
145 my $dbh = $form->dbconnect($myconfig);
147 my (@filter_values, $filter);
148 if ($form->{"name"}) {
149 $filter .= qq| AND (name ILIKE ?)|;
150 push(@filter_values, '%' . $form->{"name"} . '%');
152 substr($filter, 1, 3) = "WHERE" if ($filter);
154 $order_by =~ s/[^a-zA-Z_]//g;
155 $order_dir = $order_dir ? "ASC" : "DESC";
158 qq|SELECT id, name | .
159 qq|FROM employee $filter | .
160 qq|ORDER BY $order_by $order_dir|;
161 my $sth = $dbh->prepare($query);
162 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
164 while (my $ref = $sth->fetchrow_hashref()) {
165 push(@{$employees}, $ref);
170 $main::lxdebug->leave_sub();
175 sub retrieve_customers_or_vendors {
176 $main::lxdebug->enter_sub();
178 my ($self, $myconfig, $form, $order_by, $order_dir, $is_vendor, $allow_both) = @_;
180 my $dbh = $form->dbconnect($myconfig);
182 my (@filter_values, $filter);
183 if ($form->{"name"}) {
184 $filter .= " AND (TABLE.name ILIKE ?)";
185 push(@filter_values, '%' . $form->{"name"} . '%');
187 if (!$form->{"obsolete"}) {
188 $filter .= " AND NOT TABLE.obsolete";
190 substr($filter, 1, 3) = "WHERE" if ($filter);
192 $order_by =~ s/[^a-zA-Z_]//g;
193 $order_dir = $order_dir ? "ASC" : "DESC";
195 my (@queries, @query_parameters);
197 if ($allow_both || !$is_vendor) {
198 my $c_filter = $filter;
199 $c_filter =~ s/TABLE/c/g;
200 push(@queries, qq|SELECT
201 c.id, c.name, 0 AS customer_is_vendor,
202 c.street, c.zipcode, c.city,
203 ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
205 LEFT JOIN contacts ct ON (c.id = ct.cp_cv_id)
207 push(@query_parameters, @filter_values);
210 if ($allow_both || $is_vendor) {
211 my $v_filter = $filter;
212 $v_filter =~ s/TABLE/v/g;
213 push(@queries, qq|SELECT
214 v.id, v.name, 1 AS customer_is_vendor,
215 v.street, v.zipcode, v.city,
216 ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
218 LEFT JOIN contacts ct ON (v.id = ct.cp_cv_id)
220 push(@query_parameters, @filter_values);
223 my $query = join(" UNION ", @queries) . " ORDER BY $order_by $order_dir";
224 my $sth = $dbh->prepare($query);
225 $sth->execute(@query_parameters) || $form->dberror($query . " (" . join(", ", @query_parameters) . ")");
227 while (my $ref = $sth->fetchrow_hashref()) {
228 push(@{$customers}, $ref);
233 $main::lxdebug->leave_sub();
238 sub retrieve_delivery_customer {
239 $main::lxdebug->enter_sub();
241 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
243 my $dbh = $form->dbconnect($myconfig);
245 my (@filter_values, $filter);
246 if ($form->{"name"}) {
247 $filter .= qq| (name ILIKE ?) AND|;
248 push(@filter_values, '%' . $form->{"name"} . '%');
251 $order_by =~ s/[^a-zA-Z_]//g;
252 $order_dir = $order_dir ? "ASC" : "DESC";
255 qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
257 qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
258 qq!ORDER BY $order_by $order_dir!;
259 my $sth = $dbh->prepare($query);
260 $sth->execute(@filter_values) ||
261 $form->dberror($query . " (" . join(", ", @filter_values) . ")");
262 my $delivery_customers = [];
263 while (my $ref = $sth->fetchrow_hashref()) {
264 push(@{$delivery_customers}, $ref);
269 $main::lxdebug->leave_sub();
271 return $delivery_customers;
274 sub retrieve_vendor {
275 $main::lxdebug->enter_sub();
277 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
279 my $dbh = $form->dbconnect($myconfig);
281 my (@filter_values, $filter);
282 if ($form->{"name"}) {
283 $filter .= qq| (name ILIKE ?) AND|;
284 push(@filter_values, '%' . $form->{"name"} . '%');
287 $order_by =~ s/[^a-zA-Z_]//g;
288 $order_dir = $order_dir ? "ASC" : "DESC";
291 qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
292 qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = ?') ! .
293 qq!ORDER BY $order_by $order_dir!;
294 push @filter_values, $::locale->{iconv_utf8}->convert('Händler');
295 my $sth = $dbh->prepare($query);
296 $sth->execute(@filter_values) ||
297 $form->dberror($query . " (" . join(", ", @filter_values) . ")");
299 while (my $ref = $sth->fetchrow_hashref()) {
300 push(@{$vendors}, $ref);
305 $main::lxdebug->leave_sub();
310 sub mkdir_with_parents {
311 $main::lxdebug->enter_sub();
313 my ($full_path) = @_;
317 $full_path =~ s|/+|/|;
319 foreach my $part (split(m|/|, $full_path)) {
320 $path .= "/" if ($path);
323 die("Could not create directory '$path' because a file exists with " .
324 "the same name.\n") if (-f $path);
327 mkdir($path, 0770) || die("Could not create the directory '$path'. " .
332 $main::lxdebug->leave_sub();
336 $main::lxdebug->enter_sub();
340 return $main::lxdebug->leave_sub()
341 unless ($::instance_conf->get_webdav && $form->{id});
345 $form->{WEBDAV} = [];
347 my ($path, $number) = get_webdav_folder($form);
348 return $main::lxdebug->leave_sub() unless ($path && $number);
351 mkdir_with_parents($path);
354 my $base_path = $ENV{'SCRIPT_NAME'};
355 $base_path =~ s|[^/]+$||;
356 if (opendir my $dir, $path) {
357 foreach my $file (sort { lc $a cmp lc $b } readdir $dir) {
358 next if (($file eq '.') || ($file eq '..'));
363 my $is_directory = -d "$path/$file";
365 $file = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
366 $file .= '/' if ($is_directory);
368 push @{ $form->{WEBDAV} }, {
370 'link' => $base_path . $file,
371 'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
379 $main::lxdebug->leave_sub();
383 $main::lxdebug->enter_sub();
385 my ($self, $myconfig, $form, $vc, $vc_id) = @_;
387 $vc = $vc eq "customer" ? "customer" : "vendor";
389 my $dbh = $form->dbconnect($myconfig);
396 pt.description AS payment_terms,
397 b.description AS business,
398 l.description AS language
400 LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
401 LEFT JOIN business b ON (vc.business_id = b.id)
402 LEFT JOIN language l ON (vc.language_id = l.id)
404 my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
408 $main::lxdebug->leave_sub();
412 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
414 map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
416 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
417 $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
419 $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
420 $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
422 # Only show default pricegroup for customer, not vendor, which is why this is outside the main query
423 ($form->{pricegroup}) = selectrow_query($form, $dbh, qq|SELECT pricegroup FROM pricegroup WHERE id = ?|, $form->{klass});
427 $main::lxdebug->leave_sub();
432 sub get_shipto_by_id {
433 $main::lxdebug->enter_sub();
435 my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
439 my $dbh = $form->dbconnect($myconfig);
441 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
442 my $ref = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
444 map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
448 $main::lxdebug->leave_sub();
451 sub save_email_status {
452 $main::lxdebug->enter_sub();
454 my ($self, $myconfig, $form) = @_;
456 my ($table, $query, $dbh);
458 if ($form->{script} eq 'oe.pl') {
461 } elsif ($form->{script} eq 'is.pl') {
464 } elsif ($form->{script} eq 'ir.pl') {
467 } elsif ($form->{script} eq 'do.pl') {
468 $table = 'delivery_orders';
471 return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
473 $dbh = $form->get_standard_dbh($myconfig);
475 my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
477 $intnotes =~ s|\r||g;
478 $intnotes =~ s|\n$||;
480 $intnotes .= "\n\n" if ($intnotes);
482 my $cc = $form->{cc} ? $main::locale->text('Cc') . ": $form->{cc}\n" : '';
483 my $bcc = $form->{bcc} ? $main::locale->text('Bcc') . ": $form->{bcc}\n" : '';
484 my $now = scalar localtime;
486 $intnotes .= $main::locale->text('[email]') . "\n"
487 . $main::locale->text('Date') . ": $now\n"
488 . $main::locale->text('To (email)') . ": $form->{email}\n"
490 . $main::locale->text('Subject') . ": $form->{subject}\n\n"
491 . $main::locale->text('Message') . ": $form->{message}";
493 $intnotes =~ s|\r||g;
495 do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
497 $form->save_status($dbh);
501 $main::lxdebug->leave_sub();
507 foreach my $key (@_) {
508 if ((ref $key eq '') && !defined $params->{$key}) {
509 my $subroutine = (caller(1))[3];
510 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
511 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
512 $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
514 } elsif (ref $key eq 'ARRAY') {
516 foreach my $subkey (@{ $key }) {
517 if (defined $params->{$subkey}) {
524 my $subroutine = (caller(1))[3];
525 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
526 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
527 $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
536 foreach my $key (@_) {
537 if ((ref $key eq '') && !exists $params->{$key}) {
538 my $subroutine = (caller(1))[3];
539 $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
541 } elsif (ref $key eq 'ARRAY') {
543 foreach my $subkey (@{ $key }) {
544 if (exists $params->{$subkey}) {
551 my $subroutine = (caller(1))[3];
552 $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
558 sub get_webdav_folder {
559 $main::lxdebug->enter_sub();
563 croak "No client set in \$::auth" unless $::auth->client;
568 if ($form->{type} eq "sales_quotation") {
569 ($path, $number) = ("angebote", $form->{quonumber});
570 } elsif ($form->{type} eq "sales_order") {
571 ($path, $number) = ("bestellungen", $form->{ordnumber});
572 } elsif ($form->{type} eq "request_quotation") {
573 ($path, $number) = ("anfragen", $form->{quonumber});
574 } elsif ($form->{type} eq "purchase_order") {
575 ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
576 } elsif ($form->{type} eq "sales_delivery_order") {
577 ($path, $number) = ("verkaufslieferscheine", $form->{donumber});
578 } elsif ($form->{type} eq "purchase_delivery_order") {
579 ($path, $number) = ("einkaufslieferscheine", $form->{donumber});
580 } elsif ($form->{type} eq "credit_note") {
581 ($path, $number) = ("gutschriften", $form->{invnumber});
582 } elsif ($form->{vc} eq "customer") {
583 ($path, $number) = ("rechnungen", $form->{invnumber});
584 } elsif ($form->{vc} eq "vendor") {
585 ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
587 $main::lxdebug->leave_sub();
591 $number =~ s|[/\\]|_|g;
593 $path = "webdav/" . $::auth->client->{id} . "/${path}/${number}";
595 $main::lxdebug->leave_sub();
597 return ($path, $number);
600 sub copy_file_to_webdav_folder {
601 $::lxdebug->enter_sub();
604 my ($last_mod_time, $latest_file_name, $complete_path);
607 foreach my $item (qw(tmpdir tmpfile type)){
608 next if $form->{$item};
609 $::lxdebug->message(LXDebug::WARN(), 'Missing parameter');
610 $::form->error($::locale->text("Missing parameter for webdav file copy"));
613 my ($webdav_folder, $document_name) = get_webdav_folder($form);
615 if (! $webdav_folder){
616 $::lxdebug->leave_sub();
617 $::form->error($::locale->text("Cannot check correct webdav folder"));
621 $complete_path = File::Spec->catfile($form->{cwd}, $webdav_folder);
622 opendir my $dh, $complete_path or die "Could not open $complete_path: $!";
624 my ($newest_name, $newest_time);
625 while ( defined( my $file = readdir( $dh ) ) ) {
626 my $path = File::Spec->catfile( $complete_path, $file );
627 next if -d $path; # skip directories, or anything else you like
628 ( $newest_name, $newest_time ) = ( $file, -M _ ) if( ! defined $newest_time or -M $path < $newest_time );
633 $latest_file_name = File::Spec->catfile($complete_path, $newest_name);
634 my $filesize = stat($latest_file_name)->size;
636 my ($ext) = $form->{tmpfile} =~ /(\.[^.]+)$/;
637 my $current_file = File::Spec->catfile($form->{tmpdir}, $form->{tmpfile});
638 my $current_filesize = -f $current_file ? stat($current_file)->size : 0;
640 if ($current_filesize == $filesize) {
641 $::lxdebug->leave_sub();
645 my $timestamp = get_current_formatted_time();
646 my $new_file = File::Spec->catfile($form->{cwd}, $webdav_folder, $form->generate_attachment_filename());
647 $new_file =~ s/\./$timestamp\./;
649 if (!File::Copy::copy($current_file, $new_file)) {
650 $::lxdebug->message(LXDebug::WARN(), "Copy file from $current_file to $new_file failed: $ERRNO");
651 $::form->error($::locale->text("Copy file from #1 to #2 failed: #3", $current_file, $new_file, $ERRNO));
654 $::lxdebug->leave_sub();
657 sub get_current_formatted_time {
658 return POSIX::strftime('_%Y%m%d_%H%M%S', localtime());
670 Common - Common routines used in a lot of places.
674 my $short_text = Common::truncate($long_text, at => 10);
680 =item C<truncate $text, %params>
682 Truncates C<$text> at a position and insert an ellipsis if the text is
683 longer. The maximum number of characters to return is given with the
684 paramter C<at> which defaults to 50.
686 The optional parameter C<strip> can be used to remove unwanted line
687 feed/carriage return characters from the text before truncation. It
688 can be set to C<1> (only strip those at the end of C<$text>) or
689 C<full> (replace consecutive line feed/carriage return characters in
690 the middle by a single space and remove tailing line feed/carriage
701 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
702 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>