1 #====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #====================================================================
15 use Time::HiRes qw(gettimeofday);
24 my ($a, $b) = gettimeofday();
25 return "${a}-${b}-${$}";
29 return "/tmp/kivitendo-tmp-" . unique_id();
33 my ($text, %params) = @_;
36 $params{at} = 3 if 3 > $params{at};
38 $params{strip} //= '';
40 $text =~ s/[\r\n]+$//g if $params{strip} =~ m/^(?: 1 | newlines? | full )$/x;
41 $text =~ s/[\r\n]+/ /g if $params{strip} =~ m/^(?: newlines? | full )$/x;
43 return $text if length($text) <= $params{at};
44 return substr($text, 0, $params{at} - 3) . '...';
48 $main::lxdebug->enter_sub();
50 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
52 my $dbh = $form->dbconnect($myconfig);
54 my (@filter_values, $filter);
56 foreach (qw(partnumber description ean)) {
57 next unless $form->{$_};
59 $filter .= qq| AND ($_ ILIKE ?)|;
60 push @filter_values, '%' . $form->{$_} . '%';
63 if ($form->{no_assemblies}) {
64 $filter .= qq| AND (NOT COALESCE(assembly, FALSE))|;
66 if ($form->{assemblies}) {
67 $filter .= qq| AND assembly=TRUE|;
70 if ($form->{no_services}) {
71 $filter .= qq| AND (inventory_accno_id is not NULL or assembly=TRUE)|;
74 substr($filter, 1, 3) = "WHERE" if ($filter);
76 $order_by =~ s/[^a-zA-Z_]//g;
77 $order_dir = $order_dir ? "ASC" : "DESC";
80 qq|SELECT id, partnumber, description, ean, | .
81 qq| warehouse_id, bin_id | .
82 qq|FROM parts $filter | .
83 qq|ORDER BY $order_by $order_dir|;
84 my $sth = $dbh->prepare($query);
85 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
87 while (my $ref = $sth->fetchrow_hashref()) {
88 push(@{$parts}, $ref);
93 $main::lxdebug->leave_sub();
98 sub retrieve_projects {
99 $main::lxdebug->enter_sub();
101 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
103 my $dbh = $form->dbconnect($myconfig);
105 my (@filter_values, $filter);
106 if ($form->{"projectnumber"}) {
107 $filter .= qq| AND (projectnumber ILIKE ?)|;
108 push(@filter_values, '%' . $form->{"projectnumber"} . '%');
110 if ($form->{"description"}) {
111 $filter .= qq| AND (description ILIKE ?)|;
112 push(@filter_values, '%' . $form->{"description"} . '%');
114 substr($filter, 1, 3) = "WHERE" if ($filter);
116 $order_by =~ s/[^a-zA-Z_]//g;
117 $order_dir = $order_dir ? "ASC" : "DESC";
120 qq|SELECT id, projectnumber, description | .
121 qq|FROM project $filter | .
122 qq|ORDER BY $order_by $order_dir|;
123 my $sth = $dbh->prepare($query);
124 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
126 while (my $ref = $sth->fetchrow_hashref()) {
127 push(@{$projects}, $ref);
132 $main::lxdebug->leave_sub();
137 sub retrieve_employees {
138 $main::lxdebug->enter_sub();
140 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
142 my $dbh = $form->dbconnect($myconfig);
144 my (@filter_values, $filter);
145 if ($form->{"name"}) {
146 $filter .= qq| AND (name ILIKE ?)|;
147 push(@filter_values, '%' . $form->{"name"} . '%');
149 substr($filter, 1, 3) = "WHERE" if ($filter);
151 $order_by =~ s/[^a-zA-Z_]//g;
152 $order_dir = $order_dir ? "ASC" : "DESC";
155 qq|SELECT id, name | .
156 qq|FROM employee $filter | .
157 qq|ORDER BY $order_by $order_dir|;
158 my $sth = $dbh->prepare($query);
159 $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
161 while (my $ref = $sth->fetchrow_hashref()) {
162 push(@{$employees}, $ref);
167 $main::lxdebug->leave_sub();
172 sub retrieve_customers_or_vendors {
173 $main::lxdebug->enter_sub();
175 my ($self, $myconfig, $form, $order_by, $order_dir, $is_vendor, $allow_both) = @_;
177 my $dbh = $form->dbconnect($myconfig);
179 my (@filter_values, $filter);
180 if ($form->{"name"}) {
181 $filter .= " AND (TABLE.name ILIKE ?)";
182 push(@filter_values, '%' . $form->{"name"} . '%');
184 if (!$form->{"obsolete"}) {
185 $filter .= " AND NOT TABLE.obsolete";
187 substr($filter, 1, 3) = "WHERE" if ($filter);
189 $order_by =~ s/[^a-zA-Z_]//g;
190 $order_dir = $order_dir ? "ASC" : "DESC";
192 my (@queries, @query_parameters);
194 if ($allow_both || !$is_vendor) {
195 my $c_filter = $filter;
196 $c_filter =~ s/TABLE/c/g;
197 push(@queries, qq|SELECT
198 c.id, c.name, 0 AS customer_is_vendor,
199 c.street, c.zipcode, c.city,
200 ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
202 LEFT JOIN contacts ct ON (c.id = ct.cp_cv_id)
204 push(@query_parameters, @filter_values);
207 if ($allow_both || $is_vendor) {
208 my $v_filter = $filter;
209 $v_filter =~ s/TABLE/v/g;
210 push(@queries, qq|SELECT
211 v.id, v.name, 1 AS customer_is_vendor,
212 v.street, v.zipcode, v.city,
213 ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
215 LEFT JOIN contacts ct ON (v.id = ct.cp_cv_id)
217 push(@query_parameters, @filter_values);
220 my $query = join(" UNION ", @queries) . " ORDER BY $order_by $order_dir";
221 my $sth = $dbh->prepare($query);
222 $sth->execute(@query_parameters) || $form->dberror($query . " (" . join(", ", @query_parameters) . ")");
224 while (my $ref = $sth->fetchrow_hashref()) {
225 push(@{$customers}, $ref);
230 $main::lxdebug->leave_sub();
235 sub retrieve_delivery_customer {
236 $main::lxdebug->enter_sub();
238 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
240 my $dbh = $form->dbconnect($myconfig);
242 my (@filter_values, $filter);
243 if ($form->{"name"}) {
244 $filter .= qq| (name ILIKE ?) AND|;
245 push(@filter_values, '%' . $form->{"name"} . '%');
248 $order_by =~ s/[^a-zA-Z_]//g;
249 $order_dir = $order_dir ? "ASC" : "DESC";
252 qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
254 qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
255 qq!ORDER BY $order_by $order_dir!;
256 my $sth = $dbh->prepare($query);
257 $sth->execute(@filter_values) ||
258 $form->dberror($query . " (" . join(", ", @filter_values) . ")");
259 my $delivery_customers = [];
260 while (my $ref = $sth->fetchrow_hashref()) {
261 push(@{$delivery_customers}, $ref);
266 $main::lxdebug->leave_sub();
268 return $delivery_customers;
271 sub retrieve_vendor {
272 $main::lxdebug->enter_sub();
274 my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
276 my $dbh = $form->dbconnect($myconfig);
278 my (@filter_values, $filter);
279 if ($form->{"name"}) {
280 $filter .= qq| (name ILIKE ?) AND|;
281 push(@filter_values, '%' . $form->{"name"} . '%');
284 $order_by =~ s/[^a-zA-Z_]//g;
285 $order_dir = $order_dir ? "ASC" : "DESC";
288 qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
289 qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = ?') ! .
290 qq!ORDER BY $order_by $order_dir!;
291 push @filter_values, $::locale->{iconv_utf8}->convert('Händler');
292 my $sth = $dbh->prepare($query);
293 $sth->execute(@filter_values) ||
294 $form->dberror($query . " (" . join(", ", @filter_values) . ")");
296 while (my $ref = $sth->fetchrow_hashref()) {
297 push(@{$vendors}, $ref);
302 $main::lxdebug->leave_sub();
307 sub mkdir_with_parents {
308 $main::lxdebug->enter_sub();
310 my ($full_path) = @_;
314 $full_path =~ s|/+|/|;
316 foreach my $part (split(m|/|, $full_path)) {
317 $path .= "/" if ($path);
320 die("Could not create directory '$path' because a file exists with " .
321 "the same name.\n") if (-f $path);
324 mkdir($path, 0770) || die("Could not create the directory '$path'. " .
329 $main::lxdebug->leave_sub();
333 $main::lxdebug->enter_sub();
337 return $main::lxdebug->leave_sub()
338 unless ($::instance_conf->get_webdav && $form->{id});
342 $form->{WEBDAV} = [];
344 my ($path, $number) = get_webdav_folder($form);
345 return $main::lxdebug->leave_sub() unless ($path && $number);
348 mkdir_with_parents($path);
351 my $base_path = $ENV{'SCRIPT_NAME'};
352 $base_path =~ s|[^/]+$||;
353 if (opendir my $dir, $path) {
354 foreach my $file (sort { lc $a cmp lc $b } readdir $dir) {
355 next if (($file eq '.') || ($file eq '..'));
360 my $is_directory = -d "$path/$file";
362 $file = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
363 $file .= '/' if ($is_directory);
365 push @{ $form->{WEBDAV} }, {
367 'link' => $base_path . $file,
368 'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
376 $main::lxdebug->leave_sub();
380 $main::lxdebug->enter_sub();
382 my ($self, $myconfig, $form, $vc, $vc_id) = @_;
384 $vc = $vc eq "customer" ? "customer" : "vendor";
386 my $dbh = $form->dbconnect($myconfig);
393 pt.description AS payment_terms,
394 b.description AS business,
395 l.description AS language
397 LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
398 LEFT JOIN business b ON (vc.business_id = b.id)
399 LEFT JOIN language l ON (vc.language_id = l.id)
401 my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
405 $main::lxdebug->leave_sub();
409 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
411 map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
413 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
414 $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
416 $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
417 $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
419 # Only show default pricegroup for customer, not vendor, which is why this is outside the main query
420 ($form->{pricegroup}) = selectrow_query($form, $dbh, qq|SELECT pricegroup FROM pricegroup WHERE id = ?|, $form->{klass});
424 $main::lxdebug->leave_sub();
429 sub get_shipto_by_id {
430 $main::lxdebug->enter_sub();
432 my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
436 my $dbh = $form->dbconnect($myconfig);
438 my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
439 my $ref = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
441 map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
445 $main::lxdebug->leave_sub();
448 sub save_email_status {
449 $main::lxdebug->enter_sub();
451 my ($self, $myconfig, $form) = @_;
453 my ($table, $query, $dbh);
455 if ($form->{script} eq 'oe.pl') {
458 } elsif ($form->{script} eq 'is.pl') {
461 } elsif ($form->{script} eq 'ir.pl') {
464 } elsif ($form->{script} eq 'do.pl') {
465 $table = 'delivery_orders';
468 return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
470 $dbh = $form->get_standard_dbh($myconfig);
472 my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
474 $intnotes =~ s|\r||g;
475 $intnotes =~ s|\n$||;
477 $intnotes .= "\n\n" if ($intnotes);
479 my $cc = $form->{cc} ? $main::locale->text('Cc') . ": $form->{cc}\n" : '';
480 my $bcc = $form->{bcc} ? $main::locale->text('Bcc') . ": $form->{bcc}\n" : '';
481 my $now = scalar localtime;
483 $intnotes .= $main::locale->text('[email]') . "\n"
484 . $main::locale->text('Date') . ": $now\n"
485 . $main::locale->text('To (email)') . ": $form->{email}\n"
487 . $main::locale->text('Subject') . ": $form->{subject}\n\n"
488 . $main::locale->text('Message') . ": $form->{message}";
490 $intnotes =~ s|\r||g;
492 do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
494 $form->save_status($dbh);
498 $main::lxdebug->leave_sub();
504 foreach my $key (@_) {
505 if ((ref $key eq '') && !defined $params->{$key}) {
506 my $subroutine = (caller(1))[3];
507 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
508 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
509 $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
511 } elsif (ref $key eq 'ARRAY') {
513 foreach my $subkey (@{ $key }) {
514 if (defined $params->{$subkey}) {
521 my $subroutine = (caller(1))[3];
522 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
523 $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
524 $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
533 foreach my $key (@_) {
534 if ((ref $key eq '') && !exists $params->{$key}) {
535 my $subroutine = (caller(1))[3];
536 $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
538 } elsif (ref $key eq 'ARRAY') {
540 foreach my $subkey (@{ $key }) {
541 if (exists $params->{$subkey}) {
548 my $subroutine = (caller(1))[3];
549 $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
555 sub get_webdav_folder {
556 $main::lxdebug->enter_sub();
560 croak "No client set in \$::auth" unless $::auth->client;
565 if ($form->{type} eq "sales_quotation") {
566 ($path, $number) = ("angebote", $form->{quonumber});
567 } elsif ($form->{type} eq "sales_order") {
568 ($path, $number) = ("bestellungen", $form->{ordnumber});
569 } elsif ($form->{type} eq "request_quotation") {
570 ($path, $number) = ("anfragen", $form->{quonumber});
571 } elsif ($form->{type} eq "purchase_order") {
572 ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
573 } elsif ($form->{type} eq "sales_delivery_order") {
574 ($path, $number) = ("verkaufslieferscheine", $form->{donumber});
575 } elsif ($form->{type} eq "purchase_delivery_order") {
576 ($path, $number) = ("einkaufslieferscheine", $form->{donumber});
577 } elsif ($form->{type} eq "credit_note") {
578 ($path, $number) = ("gutschriften", $form->{invnumber});
579 } elsif ($form->{vc} eq "customer") {
580 ($path, $number) = ("rechnungen", $form->{invnumber});
581 } elsif ($form->{vc} eq "vendor") {
582 ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
584 $main::lxdebug->leave_sub();
588 $number =~ s|[/\\]|_|g;
590 $path = "webdav/" . $::auth->client->{id} . "/${path}/${number}";
592 $main::lxdebug->leave_sub();
594 return ($path, $number);
597 sub copy_file_to_webdav_folder {
598 $main::lxdebug->enter_sub();
601 my ($last_mod_time, $latest_file_name, $complete_path);
604 foreach my $item (qw(tmpdir tmpfile type)){
605 if (!$form->{$item}){
606 $main::lxdebug->message(0, 'Missing parameter');
607 $main::form->error($main::locale->text("Missing parameter for webdav file copy"));
611 my ($webdav_folder, $document_name) = get_webdav_folder($form);
613 if (! $webdav_folder){
614 $main::lxdebug->leave_sub();
615 $main::form->error($main::locale->text("Cannot check correct webdav folder"));
619 $complete_path = join('/', $form->{cwd}, $webdav_folder);
620 opendir my $dh, $complete_path or die "Could not open $complete_path: $!";
622 my ($newest_name, $newest_time);
623 while ( defined( my $file = readdir( $dh ) ) ) {
624 my $path = File::Spec->catfile( $complete_path, $file );
625 next if -d $path; # skip directories, or anything else you like
626 ( $newest_name, $newest_time ) = ( $file, -M _ )
627 if( ! defined $newest_time or -M $path < $newest_time );
629 $latest_file_name = $complete_path .'/' . $newest_name;
630 my $filesize = stat($latest_file_name)->size;
632 my ($ext) = $form->{tmpfile} =~ /(\.[^.]+)$/;
633 my $current_file = join('/', $form->{tmpdir}, $form->{tmpfile});
634 my $current_filesize = stat($current_file)->size;
635 if ($current_filesize == $filesize) {
636 $main::lxdebug->leave_sub();
640 my $timestamp = get_current_formatted_time();
641 my $myfilename = $form->generate_attachment_filename();
642 $myfilename =~ s/\./$timestamp\./;
644 if (!copy(join('/', $form->{tmpdir}, $form->{tmpfile}), join('/', $form->{cwd}, $webdav_folder, $myfilename))) {
645 my $j = join('/', $form->{tmpdir}, $form->{tmpfile});
646 my $k = join('/', $form->{cwd}, $webdav_folder);
647 $main::lxdebug->message(0, "Copy file from $j to $k failed");
648 $main::form->error($main::locale->text("Copy file from #1 to #2 failed", $j, $k));
651 $main::lxdebug->leave_sub();
653 sub get_current_formatted_time {
654 $main::lxdebug->enter_sub();
656 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
657 my $formatted_current_time = sprintf ( "_%04d%02d%02d_%02d%02d%02d",
658 $year+1900,$mon+1,$mday,$hour,$min,$sec);
660 $main::lxdebug->leave_sub();
661 return $formatted_current_time;
673 Common - Common routines used in a lot of places.
677 my $short_text = Common::truncate($long_text, at => 10);
683 =item C<truncate $text, %params>
685 Truncates C<$text> at a position and insert an ellipsis if the text is
686 longer. The maximum number of characters to return is given with the
687 paramter C<at> which defaults to 50.
689 The optional parameter C<strip> can be used to remove unwanted line
690 feed/carriage return characters from the text before truncation. It
691 can be set to C<1> (only strip those at the end of C<$text>) or
692 C<full> (replace consecutive line feed/carriage return characters in
693 the middle by a single space and remove tailing line feed/carriage
704 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
705 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>