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);
 
  29   my ($a, $b) = gettimeofday();
 
  30   return "${a}-${b}-${$}";
 
  34   return "/tmp/kivitendo-tmp-" . unique_id();
 
  38   my ($text, %params) = @_;
 
  41   $params{at}         =  3 if 3 > $params{at};
 
  43   $params{strip}    //= '';
 
  45   $text =~ s/[\r\n]+$//g if $params{strip} =~ m/^(?: 1 | newlines? | full )$/x;
 
  46   $text =~ s/[\r\n]+/ /g if $params{strip} =~ m/^(?:     newlines? | full )$/x;
 
  48   return $text if length($text) <= $params{at};
 
  49   return substr($text, 0, $params{at} - 3) . '...';
 
  53   $main::lxdebug->enter_sub();
 
  55   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
 
  57   my $dbh = $form->dbconnect($myconfig);
 
  59   my (@filter_values, $filter);
 
  61   foreach (qw(partnumber description ean)) {
 
  62     next unless $form->{$_};
 
  64     $filter .= qq| AND ($_ ILIKE ?)|;
 
  65     push @filter_values, like($form->{$_});
 
  68   if ($form->{no_assemblies}) {
 
  69     $filter .= qq| AND (NOT COALESCE(assembly, FALSE))|;
 
  71   if ($form->{assemblies}) {
 
  72     $filter .= qq| AND assembly=TRUE|;
 
  75   if ($form->{no_services}) {
 
  76     $filter .= qq| AND (inventory_accno_id is not NULL or assembly=TRUE)|;
 
  79   substr($filter, 1, 3) = "WHERE" if ($filter);
 
  81   $order_by =~ s/[^a-zA-Z_]//g;
 
  82   $order_dir = $order_dir ? "ASC" : "DESC";
 
  85     qq|SELECT id, partnumber, description, ean, | .
 
  86     qq|       warehouse_id, bin_id | .
 
  87     qq|FROM parts $filter | .
 
  88     qq|ORDER BY $order_by $order_dir|;
 
  89   my $sth = $dbh->prepare($query);
 
  90   $sth->execute(@filter_values) || $form->dberror($query . " (" . join(", ", @filter_values) . ")");
 
  92   while (my $ref = $sth->fetchrow_hashref()) {
 
  93     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 = $form->dbconnect($myconfig);
 
 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);
 
 161   $main::lxdebug->leave_sub();
 
 166 sub retrieve_delivery_customer {
 
 167   $main::lxdebug->enter_sub();
 
 169   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
 
 171   my $dbh = $form->dbconnect($myconfig);
 
 173   my (@filter_values, $filter);
 
 174   if ($form->{"name"}) {
 
 175     $filter .= qq| (name ILIKE ?) AND|;
 
 176     push(@filter_values, like($form->{"name"}));
 
 179   $order_by =~ s/[^a-zA-Z_]//g;
 
 180   $order_dir = $order_dir ? "ASC" : "DESC";
 
 183     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address ! .
 
 185     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = 'Endkunde') ! .
 
 186     qq!ORDER BY $order_by $order_dir!;
 
 187   my $sth = $dbh->prepare($query);
 
 188   $sth->execute(@filter_values) ||
 
 189     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
 
 190   my $delivery_customers = [];
 
 191   while (my $ref = $sth->fetchrow_hashref()) {
 
 192     push(@{$delivery_customers}, $ref);
 
 197   $main::lxdebug->leave_sub();
 
 199   return $delivery_customers;
 
 202 sub retrieve_vendor {
 
 203   $main::lxdebug->enter_sub();
 
 205   my ($self, $myconfig, $form, $order_by, $order_dir) = @_;
 
 207   my $dbh = $form->dbconnect($myconfig);
 
 209   my (@filter_values, $filter);
 
 210   if ($form->{"name"}) {
 
 211     $filter .= qq| (name ILIKE ?) AND|;
 
 212     push(@filter_values, like($form->{"name"}));
 
 215   $order_by =~ s/[^a-zA-Z_]//g;
 
 216   $order_dir = $order_dir ? "ASC" : "DESC";
 
 219     qq!SELECT id, name, customernumber, (street || ', ' || zipcode || city) AS address FROM customer ! .
 
 220     qq!WHERE $filter business_id = (SELECT id FROM business WHERE description = ?') ! .
 
 221     qq!ORDER BY $order_by $order_dir!;
 
 222   push @filter_values, $::locale->{iconv_utf8}->convert('Händler');
 
 223   my $sth = $dbh->prepare($query);
 
 224   $sth->execute(@filter_values) ||
 
 225     $form->dberror($query . " (" . join(", ", @filter_values) . ")");
 
 227   while (my $ref = $sth->fetchrow_hashref()) {
 
 228     push(@{$vendors}, $ref);
 
 233   $main::lxdebug->leave_sub();
 
 238 sub mkdir_with_parents {
 
 239   $main::lxdebug->enter_sub();
 
 241   my ($full_path) = @_;
 
 245   $full_path =~ s|/+|/|;
 
 247   foreach my $part (split(m|/|, $full_path)) {
 
 248     $path .= "/" if ($path);
 
 251     die("Could not create directory '$path' because a file exists with " .
 
 252         "the same name.\n") if (-f $path);
 
 255       mkdir($path, 0770) || die("Could not create the directory '$path'. " .
 
 260   $main::lxdebug->leave_sub();
 
 264   $main::lxdebug->enter_sub();
 
 268   return $main::lxdebug->leave_sub()
 
 269     unless ($::instance_conf->get_webdav && $form->{id});
 
 273   $form->{WEBDAV} = [];
 
 275   my ($path, $number) = get_webdav_folder($form);
 
 276   return $main::lxdebug->leave_sub() unless ($path && $number);
 
 279     mkdir_with_parents($path);
 
 282     my $base_path = $ENV{'SCRIPT_NAME'};
 
 283     $base_path =~ s|[^/]+$||;
 
 284     if (opendir my $dir, $path) {
 
 285       foreach my $file (sort { lc $a cmp lc $b } map { decode("UTF-8", $_) } readdir $dir) {
 
 286         next if (($file eq '.') || ($file eq '..'));
 
 291         my $is_directory = -d "$path/$file";
 
 293         $file  = join('/', map { $form->escape($_) } grep { $_ } split m|/+|, "$path/$file");
 
 294         $file .=  '/' if ($is_directory);
 
 296         push @{ $form->{WEBDAV} }, {
 
 298           'link' => $base_path . $file,
 
 299           'type' => $is_directory ? $main::locale->text('Directory') : $main::locale->text('File'),
 
 307   $main::lxdebug->leave_sub();
 
 311   $main::lxdebug->enter_sub();
 
 313   my ($self, $myconfig, $form, $vc, $vc_id) = @_;
 
 315   $vc = $vc eq "customer" ? "customer" : "vendor";
 
 317   my $dbh = $form->dbconnect($myconfig);
 
 324          pt.description AS payment_terms,
 
 325          b.description AS business,
 
 326          l.description AS language,
 
 327          dt.description AS delivery_terms
 
 329        LEFT JOIN payment_terms pt ON (vc.payment_id = pt.id)
 
 330        LEFT JOIN business b ON (vc.business_id = b.id)
 
 331        LEFT JOIN language l ON (vc.language_id = l.id)
 
 332        LEFT JOIN delivery_terms dt ON (vc.delivery_term_id = dt.id)
 
 334   my $ref = selectfirst_hashref_query($form, $dbh, $query, $vc_id);
 
 338     $main::lxdebug->leave_sub();
 
 342   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
 
 344   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_} * 1) } qw(discount creditlimit);
 
 346   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?)|;
 
 347   $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $vc_id);
 
 349   $query = qq|SELECT * FROM contacts WHERE (cp_cv_id = ?)|;
 
 350   $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $vc_id);
 
 352   # Only show default pricegroup for customer, not vendor, which is why this is outside the main query
 
 353   ($form->{pricegroup}) = selectrow_query($form, $dbh, qq|SELECT pricegroup FROM pricegroup WHERE id = ?|, $form->{klass});
 
 357   $main::lxdebug->leave_sub();
 
 362 sub get_shipto_by_id {
 
 363   $main::lxdebug->enter_sub();
 
 365   my ($self, $myconfig, $form, $shipto_id, $prefix) = @_;
 
 369   my $dbh = $form->dbconnect($myconfig);
 
 371   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
 
 372   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $shipto_id);
 
 374   map { $form->{"${prefix}${_}"} = $ref->{$_} } keys %{ $ref } if $ref;
 
 376   my $cvars = CVar->get_custom_variables(
 
 379     trans_id => $shipto_id,
 
 381   $form->{"${prefix}shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
 
 385   $main::lxdebug->leave_sub();
 
 388 sub save_email_status {
 
 389   $main::lxdebug->enter_sub();
 
 391   my ($self, $myconfig, $form) = @_;
 
 393   my ($table, $query, $dbh);
 
 395   if ($form->{script} eq 'oe.pl') {
 
 398   } elsif ($form->{script} eq 'is.pl') {
 
 401   } elsif ($form->{script} eq 'ir.pl') {
 
 404   } elsif ($form->{script} eq 'do.pl') {
 
 405     $table = 'delivery_orders';
 
 408   return $main::lxdebug->leave_sub() if (!$form->{id} || !$table || !$form->{formname});
 
 410   $dbh = $form->get_standard_dbh($myconfig);
 
 412   my ($intnotes) = selectrow_query($form, $dbh, qq|SELECT intnotes FROM $table WHERE id = ?|, $form->{id});
 
 414   $intnotes =~ s|\r||g;
 
 415   $intnotes =~ s|\n$||;
 
 417   $intnotes .= "\n\n" if ($intnotes);
 
 419   my $cc  = $form->{cc}  ? $main::locale->text('Cc') . ": $form->{cc}\n"   : '';
 
 420   my $bcc = $form->{bcc} ? $main::locale->text('Bcc') . ": $form->{bcc}\n" : '';
 
 421   my $now = scalar localtime;
 
 423   $intnotes .= $main::locale->text('[email]') . "\n"
 
 424     . $main::locale->text('Date') . ": $now\n"
 
 425     . $main::locale->text('To (email)') . ": $form->{email}\n"
 
 427     . $main::locale->text('Subject') . ": $form->{subject}\n\n"
 
 428     . $main::locale->text('Message') . ": $form->{message}";
 
 430   $intnotes =~ s|\r||g;
 
 432   do_query($form, $dbh, qq|UPDATE $table SET intnotes = ? WHERE id = ?|, $intnotes, $form->{id});
 
 434   $form->save_status($dbh);
 
 438   $main::lxdebug->leave_sub();
 
 444   foreach my $key (@_) {
 
 445     if ((ref $key eq '') && !defined $params->{$key}) {
 
 446       my $subroutine = (caller(1))[3];
 
 447       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
 
 448       $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
 
 449       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
 
 451     } elsif (ref $key eq 'ARRAY') {
 
 453       foreach my $subkey (@{ $key }) {
 
 454         if (defined $params->{$subkey}) {
 
 461         my $subroutine = (caller(1))[3];
 
 462         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, "[Common::check_params] failed, params object dumped below");
 
 463         $main::lxdebug->message(LXDebug->BACKTRACE_ON_ERROR, Dumper($params));
 
 464         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
 
 473   foreach my $key (@_) {
 
 474     if ((ref $key eq '') && !exists $params->{$key}) {
 
 475       my $subroutine = (caller(1))[3];
 
 476       $main::form->error($main::locale->text("Missing parameter #1 in call to sub #2.", $key, $subroutine));
 
 478     } elsif (ref $key eq 'ARRAY') {
 
 480       foreach my $subkey (@{ $key }) {
 
 481         if (exists $params->{$subkey}) {
 
 488         my $subroutine = (caller(1))[3];
 
 489         $main::form->error($main::locale->text("Missing parameter (at least one of #1) in call to sub #2.", join(', ', @{ $key }), $subroutine));
 
 495 sub get_webdav_folder {
 
 496   $main::lxdebug->enter_sub();
 
 500   croak "No client set in \$::auth" unless $::auth->client;
 
 505   if ($form->{type} eq "sales_quotation") {
 
 506     ($path, $number) = ("angebote", $form->{quonumber});
 
 507   } elsif ($form->{type} eq "sales_order") {
 
 508     ($path, $number) = ("bestellungen", $form->{ordnumber});
 
 509   } elsif ($form->{type} eq "request_quotation") {
 
 510     ($path, $number) = ("anfragen", $form->{quonumber});
 
 511   } elsif ($form->{type} eq "purchase_order") {
 
 512     ($path, $number) = ("lieferantenbestellungen", $form->{ordnumber});
 
 513   } elsif ($form->{type} eq "sales_delivery_order") {
 
 514     ($path, $number) = ("verkaufslieferscheine", $form->{donumber});
 
 515   } elsif ($form->{type} eq "purchase_delivery_order") {
 
 516     ($path, $number) = ("einkaufslieferscheine", $form->{donumber});
 
 517   } elsif ($form->{type} eq "credit_note") {
 
 518     ($path, $number) = ("gutschriften", $form->{invnumber});
 
 519   } elsif ($form->{type} eq "letter") {
 
 520     ($path, $number) = ("briefe", $form->{letternumber} );
 
 521   } elsif ($form->{vc} eq "customer") {
 
 522     ($path, $number) = ("rechnungen", $form->{invnumber});
 
 523   } elsif ($form->{vc} eq "vendor") {
 
 524     ($path, $number) = ("einkaufsrechnungen", $form->{invnumber});
 
 526     $main::lxdebug->leave_sub();
 
 530   $number =~ s|[/\\]|_|g;
 
 532   $path = "webdav/" . $::auth->client->{id} . "/${path}/${number}";
 
 534   $main::lxdebug->leave_sub();
 
 536   return ($path, $number);
 
 539 sub copy_file_to_webdav_folder {
 
 540   $::lxdebug->enter_sub();
 
 543   my ($last_mod_time, $latest_file_name, $complete_path);
 
 546   foreach my $item (qw(tmpdir tmpfile type)){
 
 547     next if $form->{$item};
 
 548     $::lxdebug->message(LXDebug::WARN(), 'Missing parameter:' . $item);
 
 549     $::form->error($::locale->text("Missing parameter for WebDAV file copy"));
 
 552   my ($webdav_folder, $document_name) =  get_webdav_folder($form);
 
 554   if (! $webdav_folder){
 
 555     $::lxdebug->leave_sub();
 
 556     $::lxdebug->message(LXDebug::WARN(), 'Cannot check correct WebDAV folder');
 
 557     $::form->error($::locale->text("Cannot check correct WebDAV folder"));
 
 561   $complete_path =  File::Spec->catfile($form->{cwd},  $webdav_folder);
 
 563   # maybe the path does not exist (automatic printing), see #2446
 
 564   if (!-d $complete_path) {
 
 565     # we need a chdir and restore old dir
 
 566     my $current_dir = POSIX::getcwd();
 
 567     chdir("$form->{cwd}");
 
 568     mkdir_with_parents($webdav_folder);
 
 572   opendir my $dh, $complete_path or die "Could not open $complete_path: $!";
 
 574   my ($newest_name, $newest_time);
 
 575   while ( defined( my $file = readdir( $dh ) ) ) {
 
 576     my $path = File::Spec->catfile( $complete_path, $file );
 
 577     next if -d $path; # skip directories, or anything else you like
 
 578     ( $newest_name, $newest_time ) = ( $file, -M _ ) if( ! defined $newest_time or -M $path < $newest_time );
 
 583   $latest_file_name    = File::Spec->catfile($complete_path, $newest_name);
 
 584   my $filesize         = stat($latest_file_name)->size;
 
 586   my $current_file     = File::Spec->catfile($form->{tmpdir}, apply { s:.*/:: } $form->{tmpfile});
 
 587   my $current_filesize = -f $current_file ? stat($current_file)->size : 0;
 
 589   if ($current_filesize == $filesize) {
 
 590     $::lxdebug->leave_sub();
 
 594   my $timestamp =  get_current_formatted_time();
 
 595   my $new_file  =  File::Spec->catfile($form->{cwd}, $webdav_folder, $form->generate_attachment_filename());
 
 596   $new_file =~ s{(.*)\.}{$1$timestamp\.};
 
 598   if (!File::Copy::copy($current_file, $new_file)) {
 
 599     $::lxdebug->message(LXDebug::WARN(), "Copy file from $current_file to $new_file failed: $ERRNO");
 
 600     $::form->error($::locale->text("Copy file from #1 to #2 failed: #3", $current_file, $new_file, $ERRNO));
 
 603   $::lxdebug->leave_sub();
 
 606 sub get_current_formatted_time {
 
 607   return POSIX::strftime('_%Y%m%d_%H%M%S', localtime());
 
 619 Common - Common routines used in a lot of places.
 
 623   my $short_text = Common::truncate($long_text, at => 10);
 
 629 =item C<truncate $text, %params>
 
 631 Truncates C<$text> at a position and insert an ellipsis if the text is
 
 632 longer. The maximum number of characters to return is given with the
 
 633 paramter C<at> which defaults to 50.
 
 635 The optional parameter C<strip> can be used to remove unwanted line
 
 636 feed/carriage return characters from the text before truncation. It
 
 637 can be set to C<1> (only strip those at the end of C<$text>) or
 
 638 C<full> (replace consecutive line feed/carriage return characters in
 
 639 the middle by a single space and remove tailing line feed/carriage
 
 650 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
 
 651 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>