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 = $form->dbconnect($myconfig);
 
  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 COALESCE(assembly, FALSE))|;
 
  72   if ($form->{assemblies}) {
 
  73     $filter .= qq| AND assembly=TRUE|;
 
  76   if ($form->{no_services}) {
 
  77     $filter .= qq| AND (inventory_accno_id is not NULL or assembly=TRUE)|;
 
  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);
 
  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 = $form->dbconnect($myconfig);
 
 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);
 
 162   $main::lxdebug->leave_sub();
 
 167 sub retrieve_delivery_customer {
 
 168   $main::lxdebug->enter_sub();
 
 170   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
 
 172   my $dbh = $form->dbconnect($myconfig);
 
 174   my (@filter_values, $filter);
 
 175   if ($form->{"name"}) {
 
 176     $filter .= qq| (name ILIKE ?) AND|;
 
 177     push(@filter_values, like($form->{"name"}));
 
 180   $order_by =~ s/[^a-zA-Z_]//g;
 
 181   $order_dir = $order_dir ? "ASC" : "DESC";
 
 184     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
 
 186     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
 
 187     qq!ORDER BY $order_by $order_dir!;
 
 188   my $sth = $dbh->prepare($query);
 
 189   $sth->execute(@filter_values) ||
 
 190     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
 
 191   my $delivery_customers = [];
 
 192   while (my $ref = $sth->fetchrow_hashref()) {
 
 193     push(@{$delivery_customers}, $ref);
 
 198   $main::lxdebug->leave_sub();
 
 200   return $delivery_customers;
 
 203 sub retrieve_vendor {
 
 204   $main::lxdebug->enter_sub();
 
 206   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
 
 208   my $dbh = $form->dbconnect($myconfig);
 
 210   my (@filter_values, $filter);
 
 211   if ($form->{"name"}) {
 
 212     $filter .= qq| (name ILIKE ?) AND|;
 
 213     push(@filter_values, like($form->{"name"}));
 
 216   $order_by =~ s/[^a-zA-Z_]//g;
 
 217   $order_dir = $order_dir ? "ASC" : "DESC";
 
 220     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
 
 221     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = ?') ! .
 
 222     qq!ORDER BY $order_by $order_dir!;
 
 223   push @filter_values, $::locale->{iconv_utf8}->convert('Händler');
 
 224   my $sth = $dbh->prepare($query);
 
 225   $sth->execute(@filter_values) ||
 
 226     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
 
 228   while (my $ref = $sth->fetchrow_hashref()) {
 
 229     push(@{$vendors}, $ref);
 
 234   $main::lxdebug->leave_sub();
 
 239 sub mkdir_with_parents {
 
 240   $main::lxdebug->enter_sub();
 
 242   my ($full_path) = @_;
 
 246   $full_path =~ s|/+|/|;
 
 248   foreach my $part (split(m|/|, $full_path)) {
 
 249     $path .= "/" if ($path);
 
 252     die("Could not create directory '$path' because a file exists with " .
 
 253         "the same name.\n") if (-f $path);
 
 256       mkdir($path, 0770) || die("Could not create the directory '$path'. " .
 
 261   $main::lxdebug->leave_sub();
 
 265   $main::lxdebug->enter_sub();
 
 269   return $main::lxdebug->leave_sub()
 
 270     unless ($::instance_conf->get_webdav && $form->{id});
 
 274   $form->{WEBDAV} = [];
 
 276   my ($path, $number) = get_webdav_folder($form);
 
 277   return $main::lxdebug->leave_sub() unless ($path && $number);
 
 280     mkdir_with_parents($path);
 
 283     my $base_path = $ENV{'SCRIPT_NAME'};
 
 284     $base_path =~ s|[^/]+$||;
 
 285     if (opendir my $dir, $path) {
 
 286       foreach my $file (sort { lc $a cmp lc $b } map { decode("UTF-8", $_) } readdir $dir) {
 
 287         next if (($file eq '.') || ($file eq '..'));
 
 292         my $is_directory = -d "$path/$file";
 
 294         $file  = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
 
 295         $file .=  '/' if ($is_directory);
 
 297         push @{ $form->{WEBDAV} }, {
 
 299           'link' => $base_path . $file,
 
 300           'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
 
 308   $main::lxdebug->leave_sub();
 
 312   $main::lxdebug->enter_sub();
 
 314   my ($self, $myconfig, $form, $vc, $vc_id) = @_;
 
 316   $vc = $vc eq "customer" ? "customer" : "vendor";
 
 318   my $dbh = $form->dbconnect($myconfig);
 
 325          pt.description AS payment_terms,
 
 326          b.description AS business,
 
 327          l.description AS language,
 
 328          dt.description AS delivery_terms
 
 330        LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
 
 331        LEFT JOIN business b ON (vc.business_id = b.id)
 
 332        LEFT JOIN language l ON (vc.language_id = l.id)
 
 333        LEFT JOIN delivery_terms dt ON (vc.delivery_term_id = dt.id)
 
 335   my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
 
 339     $main::lxdebug->leave_sub();
 
 343   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
 
 345   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
 
 347   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
 
 348   $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
 
 350   $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
 
 351   $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
 
 353   # Only show default pricegroup for customer, not vendor, which is why this is outside the main query
 
 354   ($form->{pricegroup}) = selectrow_query($form, $dbh, qq|SELECT pricegroup FROM pricegroup WHERE id = ?|, $form->{pricegroup_id});
 
 358   $main::lxdebug->leave_sub();
 
 363 sub get_shipto_by_id {
 
 364   $main::lxdebug->enter_sub();
 
 366   my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
 
 370   my $dbh = $form->dbconnect($myconfig);
 
 372   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
 373   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
 
 375   map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
 
 377   my $cvars = CVar->get_custom_variables(
 
 380     trans_id => $shipto_id,
 
 382   $form->{"${prefix}shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
 
 386   $main::lxdebug->leave_sub();
 
 389 sub save_email_status {
 
 390   $main::lxdebug->enter_sub();
 
 392   my ($self, $myconfig, $form) = @_;
 
 394   my ($table, $query, $dbh);
 
 396   if ($form->{script} eq 'oe.pl') {
 
 399   } elsif ($form->{script} eq 'is.pl') {
 
 402   } elsif ($form->{script} eq 'ir.pl') {
 
 405   } elsif ($form->{script} eq 'do.pl') {
 
 406     $table = 'delivery_orders';
 
 409   return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
 
 411   SL::DB->client->with_transaction(sub {
 
 412     $dbh = SL::DB->client->dbh;
 
 414     my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
 
 416     $intnotes =~ s|\r||g;
 
 417     $intnotes =~ s|\n$||;
 
 419     $intnotes .= "\n\n" if ($intnotes);
 
 421     my $cc  = $form->{cc}  ? $main::locale->text('Cc') . ": $form->{cc}\n"   : '';
 
 422     my $bcc = $form->{bcc} ? $main::locale->text('Bcc') . ": $form->{bcc}\n" : '';
 
 423     my $now = scalar localtime;
 
 425     $intnotes .= $main::locale->text('[email]') . "\n"
 
 426       . $main::locale->text('Date') . ": $now\n"
 
 427       . $main::locale->text('To (email)') . ": $form->{email}\n"
 
 429       . $main::locale->text('Subject') . ": $form->{subject}\n\n"
 
 430       . $main::locale->text('Message') . ": $form->{message}";
 
 432     $intnotes =~ s|\r||g;
 
 434     do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
 
 436     $form->save_status($dbh);
 
 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     $::form->error($::locale->text("Missing parameter for WebDAV file copy"));
 
 553   my ($webdav_folder, $document_name) =  get_webdav_folder($form);
 
 555   if (! $webdav_folder){
 
 556     $::lxdebug->leave_sub();
 
 557     $::lxdebug->message(LXDebug::WARN(), 'Cannot check correct WebDAV folder');
 
 558     $::form->error($::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);
 
 573   opendir my $dh, $complete_path or die "Could not open $complete_path: $!";
 
 575   my ($newest_name, $newest_time);
 
 576   while ( defined( my $file = readdir( $dh ) ) ) {
 
 577     my $path = File::Spec->catfile( $complete_path, $file );
 
 578     next if -d $path; # skip directories, or anything else you like
 
 579     ( $newest_name, $newest_time ) = ( $file, -M _ ) if( ! defined $newest_time or -M $path < $newest_time );
 
 584   $latest_file_name    = File::Spec->catfile($complete_path, $newest_name);
 
 585   my $filesize         = stat($latest_file_name)->size;
 
 587   my $current_file     = File::Spec->catfile($form->{tmpdir}, apply { s:.*/:: } $form->{tmpfile});
 
 588   my $current_filesize = -f $current_file ? stat($current_file)->size : 0;
 
 590   if ($current_filesize == $filesize) {
 
 591     $::lxdebug->leave_sub();
 
 595   my $timestamp =  get_current_formatted_time();
 
 596   my $new_file  =  File::Spec->catfile($form->{cwd}, $webdav_folder, $form->generate_attachment_filename());
 
 597   $new_file =~ s{(.*)\.}{$1$timestamp\.};
 
 599   if (!File::Copy::copy($current_file, $new_file)) {
 
 600     $::lxdebug->message(LXDebug::WARN(), "Copy file from $current_file to $new_file failed: $ERRNO");
 
 601     $::form->error($::locale->text("Copy file from #1 to #2 failed: #3", $current_file, $new_file, $ERRNO));
 
 604   $::lxdebug->leave_sub();
 
 607 sub get_current_formatted_time {
 
 608   return POSIX::strftime('_%Y%m%d_%H%M%S', localtime());
 
 620 Common - Common routines used in a lot of places.
 
 624   my $short_text = Common::truncate($long_text, at => 10);
 
 630 =item C<truncate $text, %params>
 
 632 Truncates C<$text> at a position and insert an ellipsis if the text is
 
 633 longer. The maximum number of characters to return is given with the
 
 634 paramter C<at> which defaults to 50.
 
 636 The optional parameter C<strip> can be used to remove unwanted line
 
 637 feed/carriage return characters from the text before truncation. It
 
 638 can be set to C<1> (only strip those at the end of C<$text>) or
 
 639 C<full> (replace consecutive line feed/carriage return characters in
 
 640 the middle by a single space and remove tailing line feed/carriage
 
 651 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
 
 652 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>