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);
28 my ($a, $b) = gettimeofday();
29 return "${a}-${b}-${$}";
33 return "/tmp/kivitendo-tmp-" . unique_id();
37 my ($text, %params) = @_;
40 $params{at} = 3 if 3 > $params{at};
42 $params{strip} //= '';
44 $text =~ s/[\r\n]+$//g if $params{strip} =~ m/^(?: 1 | newlines? | full )$/x;
45 $text =~ s/[\r\n]+/ /g if $params{strip} =~ m/^(?: newlines? | full )$/x;
47 return $text if length($text) <= $params{at};
48 return substr($text, 0, $params{at} - 3) . '...';
52 $main::lxdebug->enter_sub();
54 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
56 my $dbh = $form->dbconnect($myconfig);
58 my (@filter_values, $filter);
60 foreach (qw(partnumber description ean)) {
61 next unless $form->{$_};
63 $filter .= qq| AND ($_ ILIKE ?)|;
64 push @filter_values, '%' . $form->{$_} . '%';
67 if ($form->{no_assemblies}) {
68 $filter .= qq| AND (NOT COALESCE(assembly, FALSE))|;
70 if ($form->{assemblies}) {
71 $filter .= qq| AND assembly=TRUE|;
74 if ($form->{no_services}) {
75 $filter .= qq| AND (inventory_accno_id is not NULL or assembly=TRUE)|;
78 substr($filter, 1, 3) = "WHERE" if ($filter);
80 $order_by =~ s/[^a-zA-Z_]//g;
81 $order_dir = $order_dir ? "ASC" : "DESC";
84 qq|SELECT id, partnumber, description, ean, | .
85 qq| warehouse_id, bin_id | .
86 qq|FROM parts $filter | .
87 qq|ORDER BY $order_by $order_dir|;
88 my $sth = $dbh->prepare($query);
89 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
91 while (my $ref = $sth->fetchrow_hashref()) {
92 push(@{$parts}, $ref);
97 $main::lxdebug->leave_sub();
102 sub retrieve_projects {
103 $main::lxdebug->enter_sub();
105 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
107 my $dbh = $form->dbconnect($myconfig);
109 my (@filter_values, $filter);
110 if ($form->{"projectnumber"}) {
111 $filter .= qq| AND (projectnumber ILIKE ?)|;
112 push(@filter_values, '%' . $form->{"projectnumber"} . '%');
114 if ($form->{"description"}) {
115 $filter .= qq| AND (description ILIKE ?)|;
116 push(@filter_values, '%' . $form->{"description"} . '%');
118 substr($filter, 1, 3) = "WHERE" if ($filter);
120 $order_by =~ s/[^a-zA-Z_]//g;
121 $order_dir = $order_dir ? "ASC" : "DESC";
124 qq|SELECT id, projectnumber, description | .
125 qq|FROM project $filter | .
126 qq|ORDER BY $order_by $order_dir|;
127 my $sth = $dbh->prepare($query);
128 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
130 while (my $ref = $sth->fetchrow_hashref()) {
131 push(@{$projects}, $ref);
136 $main::lxdebug->leave_sub();
141 sub retrieve_employees {
142 $main::lxdebug->enter_sub();
144 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
146 my $dbh = $form->dbconnect($myconfig);
148 my (@filter_values, $filter);
149 if ($form->{"name"}) {
150 $filter .= qq| AND (name ILIKE ?)|;
151 push(@filter_values, '%' . $form->{"name"} . '%');
153 substr($filter, 1, 3) = "WHERE" if ($filter);
155 $order_by =~ s/[^a-zA-Z_]//g;
156 $order_dir = $order_dir ? "ASC" : "DESC";
159 qq|SELECT id, name | .
160 qq|FROM employee $filter | .
161 qq|ORDER BY $order_by $order_dir|;
162 my $sth = $dbh->prepare($query);
163 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
165 while (my $ref = $sth->fetchrow_hashref()) {
166 push(@{$employees}, $ref);
171 $main::lxdebug->leave_sub();
176 sub retrieve_customers_or_vendors {
177 $main::lxdebug->enter_sub();
179 my ($self, $myconfig, $form, $order_by, $order_dir, $is_vendor, $allow_both) = @_;
181 my $dbh = $form->dbconnect($myconfig);
183 my (@filter_values, $filter);
184 if ($form->{"name"}) {
185 $filter .= " AND (TABLE.name ILIKE ?)";
186 push(@filter_values, '%' . $form->{"name"} . '%');
188 if (!$form->{"obsolete"}) {
189 $filter .= " AND NOT TABLE.obsolete";
191 substr($filter, 1, 3) = "WHERE" if ($filter);
193 $order_by =~ s/[^a-zA-Z_]//g;
194 $order_dir = $order_dir ? "ASC" : "DESC";
196 my (@queries, @query_parameters);
198 if ($allow_both || !$is_vendor) {
199 my $c_filter = $filter;
200 $c_filter =~ s/TABLE/c/g;
201 push(@queries, qq|SELECT
202 c.id, c.name, 0 AS customer_is_vendor,
203 c.street, c.zipcode, c.city,
204 ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
206 LEFT JOIN contacts ct ON (c.id = ct.cp_cv_id)
208 push(@query_parameters, @filter_values);
211 if ($allow_both || $is_vendor) {
212 my $v_filter = $filter;
213 $v_filter =~ s/TABLE/v/g;
214 push(@queries, qq|SELECT
215 v.id, v.name, 1 AS customer_is_vendor,
216 v.street, v.zipcode, v.city,
217 ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
219 LEFT JOIN contacts ct ON (v.id = ct.cp_cv_id)
221 push(@query_parameters, @filter_values);
224 my $query = join(" UNION ", @queries) . " ORDER BY $order_by $order_dir";
225 my $sth = $dbh->prepare($query);
226 $sth->execute(@query_parameters) || $form->dberror($query . " (" . join(", ", @query_parameters) . ")");
228 while (my $ref = $sth->fetchrow_hashref()) {
229 push(@{$customers}, $ref);
234 $main::lxdebug->leave_sub();
239 sub retrieve_delivery_customer {
240 $main::lxdebug->enter_sub();
242 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
244 my $dbh = $form->dbconnect($myconfig);
246 my (@filter_values, $filter);
247 if ($form->{"name"}) {
248 $filter .= qq| (name ILIKE ?) AND|;
249 push(@filter_values, '%' . $form->{"name"} . '%');
252 $order_by =~ s/[^a-zA-Z_]//g;
253 $order_dir = $order_dir ? "ASC" : "DESC";
256 qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
258 qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
259 qq!ORDER BY $order_by $order_dir!;
260 my $sth = $dbh->prepare($query);
261 $sth->execute(@filter_values) ||
262 $form->dberror($query . " (" . join(", ", @filter_values) . ")");
263 my $delivery_customers = [];
264 while (my $ref = $sth->fetchrow_hashref()) {
265 push(@{$delivery_customers}, $ref);
270 $main::lxdebug->leave_sub();
272 return $delivery_customers;
275 sub retrieve_vendor {
276 $main::lxdebug->enter_sub();
278 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
280 my $dbh = $form->dbconnect($myconfig);
282 my (@filter_values, $filter);
283 if ($form->{"name"}) {
284 $filter .= qq| (name ILIKE ?) AND|;
285 push(@filter_values, '%' . $form->{"name"} . '%');
288 $order_by =~ s/[^a-zA-Z_]//g;
289 $order_dir = $order_dir ? "ASC" : "DESC";
292 qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
293 qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = ?') ! .
294 qq!ORDER BY $order_by $order_dir!;
295 push @filter_values, $::locale->{iconv_utf8}->convert('Händler');
296 my $sth = $dbh->prepare($query);
297 $sth->execute(@filter_values) ||
298 $form->dberror($query . " (" . join(", ", @filter_values) . ")");
300 while (my $ref = $sth->fetchrow_hashref()) {
301 push(@{$vendors}, $ref);
306 $main::lxdebug->leave_sub();
311 sub mkdir_with_parents {
312 $main::lxdebug->enter_sub();
314 my ($full_path) = @_;
318 $full_path =~ s|/+|/|;
320 foreach my $part (split(m|/|, $full_path)) {
321 $path .= "/" if ($path);
324 die("Could not create directory '$path' because a file exists with " .
325 "the same name.\n") if (-f $path);
328 mkdir($path, 0770) || die("Could not create the directory '$path'. " .
333 $main::lxdebug->leave_sub();
337 $main::lxdebug->enter_sub();
341 return $main::lxdebug->leave_sub()
342 unless ($::instance_conf->get_webdav && $form->{id});
346 $form->{WEBDAV} = [];
348 my ($path, $number) = get_webdav_folder($form);
349 return $main::lxdebug->leave_sub() unless ($path && $number);
352 mkdir_with_parents($path);
355 my $base_path = $ENV{'SCRIPT_NAME'};
356 $base_path =~ s|[^/]+$||;
357 if (opendir my $dir, $path) {
358 foreach my $file (sort { lc $a cmp lc $b } readdir $dir) {
359 next if (($file eq '.') || ($file eq '..'));
364 my $is_directory = -d "$path/$file";
366 $file = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
367 $file .= '/' if ($is_directory);
369 push @{ $form->{WEBDAV} }, {
371 'link' => $base_path . $file,
372 'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
380 $main::lxdebug->leave_sub();
384 $main::lxdebug->enter_sub();
386 my ($self, $myconfig, $form, $vc, $vc_id) = @_;
388 $vc = $vc eq "customer" ? "customer" : "vendor";
390 my $dbh = $form->dbconnect($myconfig);
397 pt.description AS payment_terms,
398 b.description AS business,
399 l.description AS language
401 LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
402 LEFT JOIN business b ON (vc.business_id = b.id)
403 LEFT JOIN language l ON (vc.language_id = l.id)
405 my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
409 $main::lxdebug->leave_sub();
413 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
415 map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
417 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
418 $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
420 $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
421 $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
423 # Only show default pricegroup for customer, not vendor, which is why this is outside the main query
424 ($form->{pricegroup}) = selectrow_query($form, $dbh, qq|SELECT pricegroup FROM pricegroup WHERE id = ?|, $form->{klass});
428 $main::lxdebug->leave_sub();
433 sub get_shipto_by_id {
434 $main::lxdebug->enter_sub();
436 my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
440 my $dbh = $form->dbconnect($myconfig);
442 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
443 my $ref = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
445 map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
449 $main::lxdebug->leave_sub();
452 sub save_email_status {
453 $main::lxdebug->enter_sub();
455 my ($self, $myconfig, $form) = @_;
457 my ($table, $query, $dbh);
459 if ($form->{script} eq 'oe.pl') {
462 } elsif ($form->{script} eq 'is.pl') {
465 } elsif ($form->{script} eq 'ir.pl') {
468 } elsif ($form->{script} eq 'do.pl') {
469 $table = 'delivery_orders';
472 return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
474 $dbh = $form->get_standard_dbh($myconfig);
476 my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
478 $intnotes =~ s|\r||g;
479 $intnotes =~ s|\n$||;
481 $intnotes .= "\n\n" if ($intnotes);
483 my $cc = $form->{cc} ? $main::locale->text('Cc') . ": $form->{cc}\n" : '';
484 my $bcc = $form->{bcc} ? $main::locale->text('Bcc') . ": $form->{bcc}\n" : '';
485 my $now = scalar localtime;
487 $intnotes .= $main::locale->text('[email]') . "\n"
488 . $main::locale->text('Date') . ": $now\n"
489 . $main::locale->text('To (email)') . ": $form->{email}\n"
491 . $main::locale->text('Subject') . ": $form->{subject}\n\n"
492 . $main::locale->text('Message') . ": $form->{message}";
494 $intnotes =~ s|\r||g;
496 do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
498 $form->save_status($dbh);
502 $main::lxdebug->leave_sub();
508 foreach my $key (@_) {
509 if ((ref $key eq '') && !defined $params->{$key}) {
510 my $subroutine = (caller(1))[3];
511 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
512 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
513 $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
515 } elsif (ref $key eq 'ARRAY') {
517 foreach my $subkey (@{ $key }) {
518 if (defined $params->{$subkey}) {
525 my $subroutine = (caller(1))[3];
526 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
527 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
528 $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
537 foreach my $key (@_) {
538 if ((ref $key eq '') && !exists $params->{$key}) {
539 my $subroutine = (caller(1))[3];
540 $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
542 } elsif (ref $key eq 'ARRAY') {
544 foreach my $subkey (@{ $key }) {
545 if (exists $params->{$subkey}) {
552 my $subroutine = (caller(1))[3];
553 $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
559 sub get_webdav_folder {
560 $main::lxdebug->enter_sub();
564 croak "No client set in \$::auth" unless $::auth->client;
569 if ($form->{type} eq "sales_quotation") {
570 ($path, $number) = ("angebote", $form->{quonumber});
571 } elsif ($form->{type} eq "sales_order") {
572 ($path, $number) = ("bestellungen", $form->{ordnumber});
573 } elsif ($form->{type} eq "request_quotation") {
574 ($path, $number) = ("anfragen", $form->{quonumber});
575 } elsif ($form->{type} eq "purchase_order") {
576 ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
577 } elsif ($form->{type} eq "sales_delivery_order") {
578 ($path, $number) = ("verkaufslieferscheine", $form->{donumber});
579 } elsif ($form->{type} eq "purchase_delivery_order") {
580 ($path, $number) = ("einkaufslieferscheine", $form->{donumber});
581 } elsif ($form->{type} eq "credit_note") {
582 ($path, $number) = ("gutschriften", $form->{invnumber});
583 } elsif ($form->{vc} eq "customer") {
584 ($path, $number) = ("rechnungen", $form->{invnumber});
585 } elsif ($form->{vc} eq "vendor") {
586 ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
588 $main::lxdebug->leave_sub();
592 $number =~ s|[/\\]|_|g;
594 $path = "webdav/" . $::auth->client->{id} . "/${path}/${number}";
596 $main::lxdebug->leave_sub();
598 return ($path, $number);
601 sub copy_file_to_webdav_folder {
602 $::lxdebug->enter_sub();
605 my ($last_mod_time, $latest_file_name, $complete_path);
608 foreach my $item (qw(tmpdir tmpfile type)){
609 next if $form->{$item};
610 $::lxdebug->message(LXDebug::WARN(), 'Missing parameter');
611 $::form->error($::locale->text("Missing parameter for WebDAV file copy"));
614 my ($webdav_folder, $document_name) = get_webdav_folder($form);
616 if (! $webdav_folder){
617 $::lxdebug->leave_sub();
618 $::form->error($::locale->text("Cannot check correct WebDAV folder"));
622 $complete_path = File::Spec->catfile($form->{cwd}, $webdav_folder);
623 opendir my $dh, $complete_path or die "Could not open $complete_path: $!";
625 my ($newest_name, $newest_time);
626 while ( defined( my $file = readdir( $dh ) ) ) {
627 my $path = File::Spec->catfile( $complete_path, $file );
628 next if -d $path; # skip directories, or anything else you like
629 ( $newest_name, $newest_time ) = ( $file, -M _ ) if( ! defined $newest_time or -M $path < $newest_time );
634 $latest_file_name = File::Spec->catfile($complete_path, $newest_name);
635 my $filesize = stat($latest_file_name)->size;
637 my $current_file = File::Spec->catfile($form->{tmpdir}, apply { s:.*/:: } $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>