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);
 
  30   my ($a, $b) = gettimeofday();
 
  31   return "${a}-${b}-${$}";
 
  35   return "/tmp/kivitendo-tmp-" . unique_id();
 
  39   my ($text, %params) = @_;
 
  42   $params{at}         =  3 if 3 > $params{at};
 
  44   $params{strip}    //= '';
 
  46   $text =~ s/[\r\n]+$//g if $params{strip} =~ m/^(?: 1 | newlines? | full )$/x;
 
  47   $text =~ s/[\r\n]+/ /g if $params{strip} =~ m/^(?:     newlines? | full )$/x;
 
  49   return $text if length($text) <= $params{at};
 
  50   return substr($text, 0, $params{at} - 3) . '...';
 
  54   $main::lxdebug->enter_sub();
 
  56   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
 
  58   my $dbh = SL::DB->client->dbh;
 
  60   my (@filter_values, $filter);
 
  62   foreach (qw(partnumber description ean)) {
 
  63     next unless $form->{$_};
 
  65     $filter .= qq| AND ($_ ILIKE ?)|;
 
  66     push @filter_values, like($form->{$_});
 
  69   if ($form->{no_assemblies}) {
 
  70     $filter .= qq| AND (NOT part_type = 'assembly')|;
 
  72   if ($form->{assemblies}) {
 
  73     $filter .= qq| AND part_type = 'assembly'|;
 
  76   if ($form->{no_services}) {
 
  77     $filter .= qq| AND NOT (part_type = 'service' OR part_type = 'assembly')|;
 
  80   substr($filter, 1, 3) = "WHERE" if ($filter);
 
  82   $order_by =~ s/[^a-zA-Z_]//g;
 
  83   $order_dir = $order_dir ? "ASC" : "DESC";
 
  86     qq|SELECT id, partnumber, description, ean, | .
 
  87     qq|       warehouse_id, bin_id | .
 
  88     qq|FROM parts $filter | .
 
  89     qq|ORDER BY $order_by $order_dir|;
 
  90   my $sth = $dbh->prepare($query);
 
  91   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
 
  93   while (my $ref = $sth->fetchrow_hashref()) {
 
  94     push(@{$parts}, $ref);
 
  98   $main::lxdebug->leave_sub();
 
 103 sub retrieve_customers_or_vendors {
 
 104   $main::lxdebug->enter_sub();
 
 106   my ($self, $myconfig, $form, $order_by, $order_dir, $is_vendor, $allow_both) = @_;
 
 108   my $dbh = SL::DB->client->dbh;
 
 110   my (@filter_values, $filter);
 
 111   if ($form->{"name"}) {
 
 112     $filter .= " AND (TABLE.name ILIKE ?)";
 
 113     push(@filter_values, like($form->{"name"}));
 
 115   if (!$form->{"obsolete"}) {
 
 116     $filter .= " AND NOT TABLE.obsolete";
 
 118   substr($filter, 1, 3) = "WHERE" if ($filter);
 
 120   $order_by =~ s/[^a-zA-Z_]//g;
 
 121   $order_dir = $order_dir ? "ASC" : "DESC";
 
 123   my (@queries, @query_parameters);
 
 125   if ($allow_both || !$is_vendor) {
 
 126     my $c_filter = $filter;
 
 127     $c_filter =~ s/TABLE/c/g;
 
 128     push(@queries, qq|SELECT
 
 129                         c.id, c.name, 0 AS customer_is_vendor,
 
 130                         c.street, c.zipcode, c.city,
 
 131                         ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
 
 133                       LEFT JOIN contacts ct ON (c.id = ct.cp_cv_id)
 
 135     push(@query_parameters, @filter_values);
 
 138   if ($allow_both || $is_vendor) {
 
 139     my $v_filter = $filter;
 
 140     $v_filter =~ s/TABLE/v/g;
 
 141     push(@queries, qq|SELECT
 
 142                         v.id, v.name, 1 AS customer_is_vendor,
 
 143                         v.street, v.zipcode, v.city,
 
 144                         ct.cp_gender, ct.cp_title, ct.cp_givenname, ct.cp_name
 
 146                       LEFT JOIN contacts ct ON (v.id = ct.cp_cv_id)
 
 148     push(@query_parameters, @filter_values);
 
 151   my $query = join(" UNION ", @queries) . " ORDER BY $order_by $order_dir";
 
 152   my $sth = $dbh->prepare($query);
 
 153   $sth->execute(@query_parameters) || $form->dberror($query . " (" . join(", ", @query_parameters) . ")");
 
 155   while (my $ref = $sth->fetchrow_hashref()) {
 
 156     push(@{$customers}, $ref);
 
 160   $main::lxdebug->leave_sub();
 
 165 sub retrieve_delivery_customer {
 
 166   $main::lxdebug->enter_sub();
 
 168   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
 
 170   my $dbh = SL::DB->client->dbh;
 
 172   my (@filter_values, $filter);
 
 173   if ($form->{"name"}) {
 
 174     $filter .= qq| (name ILIKE ?) AND|;
 
 175     push(@filter_values, like($form->{"name"}));
 
 178   $order_by =~ s/[^a-zA-Z_]//g;
 
 179   $order_dir = $order_dir ? "ASC" : "DESC";
 
 182     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
 
 184     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
 
 185     qq!ORDER BY $order_by $order_dir!;
 
 186   my $sth = $dbh->prepare($query);
 
 187   $sth->execute(@filter_values) ||
 
 188     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
 
 189   my $delivery_customers = [];
 
 190   while (my $ref = $sth->fetchrow_hashref()) {
 
 191     push(@{$delivery_customers}, $ref);
 
 195   $main::lxdebug->leave_sub();
 
 197   return $delivery_customers;
 
 200 sub retrieve_vendor {
 
 201   $main::lxdebug->enter_sub();
 
 203   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
 
 205   my $dbh = SL::DB->client->dbh;
 
 207   my (@filter_values, $filter);
 
 208   if ($form->{"name"}) {
 
 209     $filter .= qq| (name ILIKE ?) AND|;
 
 210     push(@filter_values, like($form->{"name"}));
 
 213   $order_by =~ s/[^a-zA-Z_]//g;
 
 214   $order_dir = $order_dir ? "ASC" : "DESC";
 
 217     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
 
 218     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = ?') ! .
 
 219     qq!ORDER BY $order_by $order_dir!;
 
 220   push @filter_values, $::locale->{iconv_utf8}->convert('Händler');
 
 221   my $sth = $dbh->prepare($query);
 
 222   $sth->execute(@filter_values) ||
 
 223     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
 
 225   while (my $ref = $sth->fetchrow_hashref()) {
 
 226     push(@{$vendors}, $ref);
 
 230   $main::lxdebug->leave_sub();
 
 235 sub mkdir_with_parents {
 
 236   $main::lxdebug->enter_sub();
 
 238   my ($full_path) = @_;
 
 242   $full_path =~ s|/+|/|;
 
 244   foreach my $part (split(m|/|, $full_path)) {
 
 245     $path .= "/" if ($path);
 
 248     die("Could not create directory '$path' because a file exists with " .
 
 249         "the same name.\n") if (-f $path);
 
 252       mkdir($path, 0770) || die("Could not create the directory '$path'. " .
 
 257   $main::lxdebug->leave_sub();
 
 261   $main::lxdebug->enter_sub();
 
 265   return $main::lxdebug->leave_sub()
 
 266     unless ($::instance_conf->get_webdav && $form->{id});
 
 270   $form->{WEBDAV} = [];
 
 272   my ($path, $number) = get_webdav_folder($form);
 
 273   return $main::lxdebug->leave_sub() unless ($path && $number);
 
 276     mkdir_with_parents($path);
 
 279     my $base_path = $ENV{'SCRIPT_NAME'};
 
 280     $base_path =~ s|[^/]+$||;
 
 281     if (opendir my $dir, $path) {
 
 282       foreach my $file (sort { lc $a cmp lc $b } map { decode("UTF-8", $_) } readdir $dir) {
 
 283         next if (($file eq '.') || ($file eq '..'));
 
 288         my $is_directory = -d "$path/$file";
 
 290         $file  = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
 
 291         $file .=  '/' if ($is_directory);
 
 293         push @{ $form->{WEBDAV} }, {
 
 295           'link' => $base_path . $file,
 
 296           'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
 
 304   $main::lxdebug->leave_sub();
 
 308   $main::lxdebug->enter_sub();
 
 310   my ($self, $myconfig, $form, $vc, $vc_id) = @_;
 
 312   $vc = $vc eq "customer" ? "customer" : "vendor";
 
 314   my $dbh = SL::DB->client->dbh;
 
 321          pt.description AS payment_terms,
 
 322          b.description AS business,
 
 323          l.description AS language,
 
 324          dt.description AS delivery_terms
 
 326        LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
 
 327        LEFT JOIN business b ON (vc.business_id = b.id)
 
 328        LEFT JOIN language l ON (vc.language_id = l.id)
 
 329        LEFT JOIN delivery_terms dt ON (vc.delivery_term_id = dt.id)
 
 331   my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
 
 334     $main::lxdebug->leave_sub();
 
 338   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
 
 340   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
 
 342   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
 
 343   $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
 
 345   $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
 
 346   $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
 
 348   # Only show default pricegroup for customer, not vendor, which is why this is outside the main query
 
 349   ($form->{pricegroup}) = selectrow_query($form, $dbh, qq|SELECT pricegroup FROM pricegroup WHERE id = ?|, $form->{pricegroup_id});
 
 351   $main::lxdebug->leave_sub();
 
 356 sub get_shipto_by_id {
 
 357   $main::lxdebug->enter_sub();
 
 359   my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
 
 363   my $dbh = SL::DB->client->dbh;
 
 365   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
 366   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
 
 368   map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
 
 370   my $cvars = CVar->get_custom_variables(
 
 373     trans_id => $shipto_id,
 
 375   $form->{"${prefix}shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
 
 377   $main::lxdebug->leave_sub();
 
 380 sub save_email_status {
 
 381   $main::lxdebug->enter_sub();
 
 383   my ($self, $myconfig, $form) = @_;
 
 385   my ($table, $query, $dbh);
 
 387   if ($form->{script} eq 'oe.pl') {
 
 390   } elsif ($form->{script} eq 'is.pl') {
 
 393   } elsif ($form->{script} eq 'ir.pl') {
 
 396   } elsif ($form->{script} eq 'do.pl') {
 
 397     $table = 'delivery_orders';
 
 400   return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
 
 402   SL::DB->client->with_transaction(sub {
 
 403     $dbh = SL::DB->client->dbh;
 
 405     my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
 
 407     $intnotes =~ s|\r||g;
 
 408     $intnotes =~ s|\n$||;
 
 410     $intnotes .= "\n\n" if ($intnotes);
 
 412     my $cc  = $form->{cc}  ? $main::locale->text('Cc') . ": $form->{cc}\n"   : '';
 
 413     my $bcc = $form->{bcc} ? $main::locale->text('Bcc') . ": $form->{bcc}\n" : '';
 
 414     my $now = scalar localtime;
 
 416     $intnotes .= $main::locale->text('[email]') . "\n"
 
 417       . $main::locale->text('Date') . ": $now\n"
 
 418       . $main::locale->text('To (email)') . ": $form->{email}\n"
 
 420       . $main::locale->text('Subject') . ": $form->{subject}\n\n"
 
 421       . $main::locale->text('Message') . ": $form->{message}";
 
 423     $intnotes =~ s|\r||g;
 
 425     do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
 
 427     $form->save_status($dbh);
 
 429   }) or do { die SL::DB->client->error };
 
 431   $main::lxdebug->leave_sub();
 
 437   foreach my $key (@_) {
 
 438     if ((ref $key eq '') && !defined $params->{$key}) {
 
 439       my $subroutine = (caller(1))[3];
 
 440       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
 
 441       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
 
 442       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
 
 444     } elsif (ref $key eq 'ARRAY') {
 
 446       foreach my $subkey (@{ $key }) {
 
 447         if (defined $params->{$subkey}) {
 
 454         my $subroutine = (caller(1))[3];
 
 455         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
 
 456         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
 
 457         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
 
 466   foreach my $key (@_) {
 
 467     if ((ref $key eq '') && !exists $params->{$key}) {
 
 468       my $subroutine = (caller(1))[3];
 
 469       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
 
 471     } elsif (ref $key eq 'ARRAY') {
 
 473       foreach my $subkey (@{ $key }) {
 
 474         if (exists $params->{$subkey}) {
 
 481         my $subroutine = (caller(1))[3];
 
 482         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
 
 488 sub get_webdav_folder {
 
 489   $main::lxdebug->enter_sub();
 
 493   croak "No client set in \$::auth" unless $::auth->client;
 
 498   if ($form->{type} eq "sales_quotation") {
 
 499     ($path, $number) = ("angebote", $form->{quonumber});
 
 500   } elsif ($form->{type} eq "sales_order") {
 
 501     ($path, $number) = ("bestellungen", $form->{ordnumber});
 
 502   } elsif ($form->{type} eq "request_quotation") {
 
 503     ($path, $number) = ("anfragen", $form->{quonumber});
 
 504   } elsif ($form->{type} eq "purchase_order") {
 
 505     ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
 
 506   } elsif ($form->{type} eq "sales_delivery_order") {
 
 507     ($path, $number) = ("verkaufslieferscheine", $form->{donumber});
 
 508   } elsif ($form->{type} eq "purchase_delivery_order") {
 
 509     ($path, $number) = ("einkaufslieferscheine", $form->{donumber});
 
 510   } elsif ($form->{type} eq "credit_note") {
 
 511     ($path, $number) = ("gutschriften", $form->{invnumber});
 
 512   } elsif ($form->{type} eq "letter") {
 
 513     ($path, $number) = ("briefe", $form->{letternumber} );
 
 514   } elsif ($form->{vc} eq "customer") {
 
 515     ($path, $number) = ("rechnungen", $form->{invnumber});
 
 516   } elsif ($form->{vc} eq "vendor") {
 
 517     ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
 
 519     $main::lxdebug->leave_sub();
 
 523   $number =~ s|[/\\]|_|g;
 
 525   $path = "webdav/" . $::auth->client->{id} . "/${path}/${number}";
 
 527   $main::lxdebug->leave_sub();
 
 529   return ($path, $number);
 
 532 sub copy_file_to_webdav_folder {
 
 533   $::lxdebug->enter_sub();
 
 536   my ($last_mod_time, $latest_file_name, $complete_path);
 
 539   foreach my $item (qw(tmpdir tmpfile type)){
 
 540     next if $form->{$item};
 
 541     $::lxdebug->message(LXDebug::WARN(), 'Missing parameter:' . $item);
 
 542     $::lxdebug->leave_sub();
 
 543     return $::locale->text("Missing parameter for WebDAV file copy");
 
 546   my ($webdav_folder, $document_name) =  get_webdav_folder($form);
 
 548   if (! $webdav_folder){
 
 549     $::lxdebug->message(LXDebug::WARN(), 'Cannot check correct WebDAV folder');
 
 550     $::lxdebug->leave_sub();
 
 551     return $::locale->text("Cannot check correct WebDAV folder")
 
 554   $complete_path =  File::Spec->catfile($form->{cwd},  $webdav_folder);
 
 556   # maybe the path does not exist (automatic printing), see #2446
 
 557   if (!-d $complete_path) {
 
 558     # we need a chdir and restore old dir
 
 559     my $current_dir = POSIX::getcwd();
 
 560     chdir("$form->{cwd}");
 
 561     mkdir_with_parents($webdav_folder);
 
 566   if (!opendir $dh, $complete_path) {
 
 567     $::lxdebug->leave_sub();
 
 568     return "Could not open $complete_path: $!";
 
 571   my ($newest_name, $newest_time);
 
 572   while ( defined( my $file = readdir( $dh ) ) ) {
 
 573     my $path = File::Spec->catfile( $complete_path, $file );
 
 574     next if -d $path; # skip directories, or anything else you like
 
 575     ( $newest_name, $newest_time ) = ( $file, -M _ ) if( ! defined $newest_time or -M $path < $newest_time );
 
 580   $latest_file_name    = File::Spec->catfile($complete_path, $newest_name);
 
 581   my $filesize         = stat($latest_file_name)->size;
 
 583   my $current_file     = File::Spec->catfile($form->{tmpdir}, apply { s:.*/:: } $form->{tmpfile});
 
 584   my $current_filesize = -f $current_file ? stat($current_file)->size : 0;
 
 586   if ($current_filesize == $filesize) {
 
 587     $::lxdebug->leave_sub();
 
 591   my $timestamp =  get_current_formatted_time();
 
 592   my $new_file  =  File::Spec->catfile($form->{cwd}, $webdav_folder, $form->generate_attachment_filename());
 
 593   $new_file =~ s{(.*)\.}{$1$timestamp\.};
 
 595   if (!File::Copy::copy($current_file, $new_file)) {
 
 596     $::lxdebug->message(LXDebug::WARN(), "Copy file from $current_file to $new_file failed: $ERRNO");
 
 597     $::lxdebug->leave_sub();
 
 598     return $::locale->text("Copy file from #1 to #2 failed: #3", $current_file, $new_file, $ERRNO);
 
 602   $::lxdebug->leave_sub();
 
 605 sub get_current_formatted_time {
 
 606   return POSIX::strftime('_%Y%m%d_%H%M%S', localtime());
 
 618 Common - Common routines used in a lot of places.
 
 622   my $short_text = Common::truncate($long_text, at => 10);
 
 628 =item C<truncate $text, %params>
 
 630 Truncates C<$text> at a position and insert an ellipsis if the text is
 
 631 longer. The maximum number of characters to return is given with the
 
 632 paramter C<at> which defaults to 50.
 
 634 The optional parameter C<strip> can be used to remove unwanted line
 
 635 feed/carriage return characters from the text before truncation. It
 
 636 can be set to C<1> (only strip those at the end of C<$text>) or
 
 637 C<full> (replace consecutive line feed/carriage return characters in
 
 638 the middle by a single space and remove tailing line feed/carriage
 
 649 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
 
 650 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>