Merge branch 'b-3.6.1' of ../kivitendo-erp_20220811
[kivitendo-erp.git] / SL / Controller / CsvImport / Base.pm
index 3090182..1aaec79 100644 (file)
@@ -3,10 +3,12 @@ package SL::Controller::CsvImport::Base;
 use strict;
 
 use English qw(-no_match_vars);
+use List::Util qw(min);
 use List::MoreUtils qw(pairwise any);
 
 use SL::Helper::Csv;
 
+use SL::DB;
 use SL::DB::BankAccount;
 use SL::DB::Customer;
 use SL::DB::Language;
@@ -21,7 +23,7 @@ use parent qw(Rose::Object);
 use Rose::Object::MakeMethods::Generic
 (
  scalar                  => [ qw(controller file csv test_run save_with_cascade) ],
- 'scalar --get_set_init' => [ qw(profile displayable_columns existing_objects class manager_class cvar_columns all_cvar_configs all_languages payment_terms_by delivery_terms_by all_bank_accounts all_vc vc_by clone_methods) ],
+ 'scalar --get_set_init' => [ qw(profile displayable_columns existing_objects class manager_class cvar_columns all_cvar_configs all_languages payment_terms_by delivery_terms_by all_bank_accounts all_vc vc_by vc_counts_by clone_methods) ],
 );
 
 sub run {
@@ -32,9 +34,9 @@ sub run {
   $self->controller->track_progress(phase => 'parsing csv', progress => 0);
 
   my $profile = $self->profile;
-  $self->csv(SL::Helper::Csv->new(file                   => $self->file->file_name,
+  $self->csv(SL::Helper::Csv->new(file                   => ('SCALAR' eq ref $self->file)? $self->file: $self->file->file_name,
                                   encoding               => $self->controller->profile->get('charset'),
-                                  profile                => [{ profile => $profile, class => $self->class }],
+                                  profile                => [{ profile => $profile, class => $self->class, mapping => $self->controller->mappings_for_profile }],
                                   ignore_unknown_columns => 1,
                                   strict_profile         => 1,
                                   case_insensitive_header => 1,
@@ -43,8 +45,8 @@ sub run {
 
   $self->controller->track_progress(progress => 10);
 
-  my $old_numberformat      = $::myconfig{numberformat};
-  $::myconfig{numberformat} = $self->controller->profile->get('numberformat');
+  local $::myconfig{numberformat} = $self->controller->profile->get('numberformat');
+  local $::myconfig{dateformat}   = $self->controller->profile->get('dateformat');
 
   $self->csv->parse;
 
@@ -54,9 +56,9 @@ sub run {
 
   return if ( !$self->csv->header || $self->csv->errors );
 
-  my $headers         = { headers => [ grep { $profile->{$_} } @{ $self->csv->header } ] };
-  $headers->{methods} = [ map { $profile->{$_} } @{ $headers->{headers} } ];
-  $headers->{used}    = { map { ($_ => 1) }      @{ $headers->{headers} } };
+  my $headers         = { headers => [ grep { $self->csv->dispatcher->is_known($_, 0) } @{ $self->csv->header } ] };
+  $headers->{methods} = [ map { $_->{path} } @{ $self->csv->specs->[0] } ];
+  $headers->{used}    = { map { ($_ => 1) }  @{ $headers->{headers} } };
   $self->controller->headers($headers);
   $self->controller->raw_data_headers({ used => { }, headers => [ ] });
   $self->controller->info_headers({ used => { }, headers => [ ] });
@@ -81,8 +83,6 @@ sub run {
   $self->fix_field_lengths;
 
   $self->controller->track_progress(progress => 100);
-
-  $::myconfig{numberformat} = $old_numberformat;
 }
 
 sub add_columns {
@@ -186,10 +186,28 @@ sub init_vc_by {
                     vendors   => { map { ( $_->vendornumber   => $_ ) } @{ $self->all_vc->{vendors}   } } );
   my %by_name   = ( customers => { map { ( $_->name           => $_ ) } @{ $self->all_vc->{customers} } },
                     vendors   => { map { ( $_->name           => $_ ) } @{ $self->all_vc->{vendors}   } } );
+  my %by_gln    = ( customers => { map { ( $_->gln            => $_ ) } grep $_->gln, @{ $self->all_vc->{customers} } },
+                    vendors   => { map { ( $_->gln            => $_ ) } grep $_->gln, @{ $self->all_vc->{vendors}   } } );
 
   return { id     => \%by_id,
            number => \%by_number,
-           name   => \%by_name,   };
+           name   => \%by_name,
+           gln    => \%by_gln };
+}
+
+sub init_vc_counts_by {
+  my ($self) = @_;
+
+  my $vc_counts_by = {};
+
+  $vc_counts_by->{number}->{customers}->{$_->customernumber}++ for @{ $self->all_vc->{customers} };
+  $vc_counts_by->{number}->{vendors}->  {$_->vendornumber}++   for @{ $self->all_vc->{vendors} };
+  $vc_counts_by->{name}->  {customers}->{$_->name}++           for @{ $self->all_vc->{customers} };
+  $vc_counts_by->{name}->  {vendors}->  {$_->name}++           for @{ $self->all_vc->{vendors} };
+  $vc_counts_by->{gln}->   {customers}->{$_->gln}++            for grep $_->gln, @{ $self->all_vc->{customers} };
+  $vc_counts_by->{gln}->   {vendors}->  {$_->gln}++            for grep $_->gln, @{ $self->all_vc->{vendors} };
+
+  return $vc_counts_by;
 }
 
 sub check_vc {
@@ -199,36 +217,90 @@ sub check_vc {
     $entry->{object}->$id_column(undef) if !$self->vc_by->{id}->{ $entry->{object}->$id_column };
   }
 
+  my $is_ambiguous;
   if (!$entry->{object}->$id_column) {
-    my $vc = $self->vc_by->{number}->{customers}->{ $entry->{raw_data}->{customernumber} }
-          || $self->vc_by->{number}->{vendors}->{   $entry->{raw_data}->{vendornumber}   };
+    my $vc;
+    if ($entry->{raw_data}->{customernumber}) {
+      $vc = $self->vc_by->{number}->{customers}->{ $entry->{raw_data}->{customernumber} };
+      if ($vc && $self->vc_counts_by->{number}->{customers}->{ $entry->{raw_data}->{customernumber} } > 1) {
+        $vc = undef;
+        $is_ambiguous = 1;
+      }
+    } elsif ($entry->{raw_data}->{vendornumber}) {
+      $vc = $self->vc_by->{number}->{vendors}->{ $entry->{raw_data}->{vendornumber} };
+      if ($vc && $self->vc_counts_by->{number}->{vendors}->{ $entry->{raw_data}->{vendornumber} } > 1) {
+        $vc = undef;
+        $is_ambiguous = 1;
+      }
+    }
+
     $entry->{object}->$id_column($vc->id) if $vc;
   }
 
   if (!$entry->{object}->$id_column) {
-    my $vc = $self->vc_by->{name}->{customers}->{ $entry->{raw_data}->{customer} }
-          || $self->vc_by->{name}->{vendors}->{   $entry->{raw_data}->{vendor}   };
+    my $vc;
+    if ($entry->{raw_data}->{customer}) {
+      $vc = $self->vc_by->{name}->{customers}->{ $entry->{raw_data}->{customer} };
+      if ($vc && $self->vc_counts_by->{name}->{customers}->{ $entry->{raw_data}->{customer} } > 1) {
+        $vc = undef;
+        $is_ambiguous = 1;
+      }
+    } elsif ($entry->{raw_data}->{vendor}) {
+      $vc = $self->vc_by->{name}->{vendors}->{ $entry->{raw_data}->{vendor} };
+      if ($vc && $self->vc_counts_by->{name}->{vendors}->{ $entry->{raw_data}->{vendor} } > 1) {
+        $vc = undef;
+        $is_ambiguous = 1;
+      }
+    }
+
+    $entry->{object}->$id_column($vc->id) if $vc;
+  }
+
+  if (!$entry->{object}->$id_column) {
+    my $vc;
+    if ($entry->{raw_data}->{customer_gln}) {
+      $vc = $self->vc_by->{gln}->{customers}->{ $entry->{raw_data}->{customer_gln} };
+      if ($vc && $self->vc_counts_by->{gln}->{customers}->{ $entry->{raw_data}->{customer_gln} } > 1) {
+        $vc = undef;
+        $is_ambiguous = 1;
+      }
+    } elsif ($entry->{raw_data}->{vendor_gln}) {
+      $vc = $self->vc_by->{gln}->{vendors}->{ $entry->{raw_data}->{vendor_gln} };
+      if ($vc && $self->vc_counts_by->{gln}->{vendors}->{ $entry->{raw_data}->{vendor_gln} } > 1) {
+        $vc = undef;
+        $is_ambiguous = 1;
+      }
+    }
     $entry->{object}->$id_column($vc->id) if $vc;
   }
 
   if ($entry->{object}->$id_column) {
     $entry->{info_data}->{vc_name} = $self->vc_by->{id}->{ $entry->{object}->$id_column }->name;
   } else {
-    push @{ $entry->{errors} }, $::locale->text('Error: Customer/vendor not found');
+    if ($is_ambiguous) {
+      push @{ $entry->{errors} }, $::locale->text('Error: Customer/vendor is ambiguous');
+    } else {
+      push @{ $entry->{errors} }, $::locale->text('Error: Customer/vendor not found');
+    }
   }
 }
 
 sub handle_cvars {
   my ($self, $entry) = @_;
 
+  my $object = $entry->{object_to_save} || $entry->{object};
+  return unless $object->can('cvars_by_config');
+
   my %type_to_column = ( text      => 'text_value',
                          textfield => 'text_value',
+                         htmlfield => 'text_value',
                          select    => 'text_value',
                          date      => 'timestamp_value_as_date',
                          timestamp => 'timestamp_value_as_date',
                          number    => 'number_value_as_number',
                          bool      => 'bool_value' );
 
+  # autovivify all cvars (cvars_by_config will do that for us)
   my @cvars;
   my %changed_cvars;
   foreach my $config (@{ $self->all_cvar_configs }) {
@@ -243,16 +315,13 @@ sub handle_cvars {
   }
 
   # merge existing with new cvars. swap every existing with the imported one, push the rest
-  if (@cvars) {
-    my @orig_cvars = ($entry->{object_to_save} || $entry->{object})->custom_variables;
-    for (@orig_cvars) {
-      $_ = $changed_cvars{ $_->config->name } if $changed_cvars{ $_->config->name };
-      delete $changed_cvars{ $_->config->name };
-    }
-    push @orig_cvars, values %changed_cvars;
-
-    $entry->{object}->custom_variables(\@orig_cvars);
+  my @orig_cvars = @{ $object->cvars_by_config };
+  for (@orig_cvars) {
+    $_ = $changed_cvars{ $_->config->name } if $changed_cvars{ $_->config->name };
+    delete $changed_cvars{ $_->config->name };
   }
+  push @orig_cvars, values %changed_cvars;
+  $object->custom_variables(\@orig_cvars);
 }
 
 sub init_profile {
@@ -337,6 +406,10 @@ sub check_objects {
 sub check_duplicates {
 }
 
+sub check_auth {
+  $::auth->assert('config');
+}
+
 sub check_std_duplicates {
   my $self = shift;
 
@@ -459,32 +532,35 @@ sub save_objects {
 
   $self->controller->track_progress(phase => 'saving data', progress => 0); # scale from 45..95%;
 
-  my $dbh = $data->[0]{object}->db;
-
-  $dbh->begin_work;
-  foreach my $entry_index (0 .. $#$data) {
-    my $entry = $data->[$entry_index];
-    next if @{ $entry->{errors} };
-
-    my $object = $entry->{object_to_save} || $entry->{object};
-
-    my $ret;
-    if (!eval { $ret = $object->save(cascade => !!$self->save_with_cascade()); 1 }) {
-      push @{ $entry->{errors} }, $::locale->text('Error when saving: #1', $EVAL_ERROR);
-    } elsif ( !$ret ) {
-      push @{ $entry->{errors} }, $::locale->text('Error when saving: #1', $object->db->error);
-    } else {
-      $self->_save_history($object);
-      $self->controller->num_imported($self->controller->num_imported + 1);
-    }
-  } continue {
-    if ($entry_index % 100 == 0) {
-      $dbh->commit;
-      $self->controller->track_progress(progress => $entry_index/scalar(@$data) * 100); # scale from 45..95%;
-      $dbh->begin_work;
-    }
+  my $last_index = $#$data;
+  my $chunk_size = 100;      # one transaction and progress update every 100 objects
+
+  for my $chunk (0 .. $last_index / $chunk_size) {
+    $self->controller->track_progress(progress => ($chunk_size * $chunk)/scalar(@$data) * 100); # scale from 45..95%;
+    SL::DB->client->with_transaction(sub {
+      foreach my $entry_index ($chunk_size * $chunk .. min( $last_index, $chunk_size * ($chunk + 1) - 1 )) {
+        my $entry = $data->[$entry_index];
+
+        my $object = $entry->{object_to_save} || $entry->{object};
+        $self->save_additions_always($object);
+
+        next if @{ $entry->{errors} };
+
+        my $ret;
+        if (!eval { $ret = $object->save(cascade => !!$self->save_with_cascade()); 1 }) {
+          push @{ $entry->{errors} }, $::locale->text('Error when saving: #1', $EVAL_ERROR);
+        } elsif ( !$ret ) {
+          push @{ $entry->{errors} }, $::locale->text('Error when saving: #1', $object->db->error);
+        } else {
+          $self->_save_history($object);
+          $self->save_additions($object);
+          $self->controller->num_imported($self->controller->num_imported + 1);
+        }
+      }
+      1;
+    }) or do { die SL::DB->client->error };
   }
-  $dbh->commit;
+  $self->controller->track_progress(progress => 100);
 }
 
 sub field_lengths {
@@ -519,18 +595,47 @@ sub clean_fields {
   return @cleaned_fields;
 }
 
+sub save_additions {
+  my ($self, $object) = @_;
+
+  # Can be overridden by derived specialized importer classes to save
+  # additional tables (e.g. record links).
+  # This sub is called after the object is saved successfully in an transaction.
+
+  return;
+}
+
+sub save_additions_always {
+  my ($self, $object) = @_;
+
+  # Can be overridden by derived specialized importer classes to save
+  # additional tables always.
+  # This sub is called before the object is saved. Therefore this
+  # hook will always be executed whether or not the import entry can be saved successfully.
+
+  return;
+}
+
+
 sub _save_history {
   my ($self, $object) = @_;
 
-  if (any { $_ eq $self->controller->{type} } qw(parts customers_vendors orders)) {
+  if (any { $self->controller->{type} && $_ eq $self->controller->{type} } qw(parts customers_vendors orders delivery_orders ar_transactions)) {
     my $snumbers = $self->controller->{type} eq 'parts'             ? 'partnumber_' . $object->partnumber
                  : $self->controller->{type} eq 'customers_vendors' ?
                      ($self->table eq 'customer' ? 'customernumber_' . $object->customernumber : 'vendornumber_' . $object->vendornumber)
                  : $self->controller->{type} eq 'orders'            ? 'ordnumber_' . $object->ordnumber
+                 : $self->controller->{type} eq 'delivery_orders'   ? 'donumber_'  . $object->donumber
+                 : $self->controller->{type} eq 'ar_transactions'   ? 'invnumber_' . $object->invnumber
                  : '';
 
-    my $what_done = $self->controller->{type} eq 'orders' ? 'sales_order'
-                  : '';
+    my $what_done = '';
+    if ($self->controller->{type} eq 'orders') {
+      $what_done = $object->customer_id ? 'sales_order' : 'purchase_order';
+    }
+    if ($self->controller->{type} eq 'delivery_orders') {
+      $what_done = $object->customer_id ? 'sales_delivery_order' : 'purchase_delivery_order';
+    }
 
     SL::DB::History->new(
       trans_id    => $object->id,