Merge branch 'master' of github.com:kivitendo/kivitendo-erp
[kivitendo-erp.git] / SL / Controller / CsvImport / Base.pm
index eda921f..e7889d7 100644 (file)
@@ -15,12 +15,16 @@ use parent qw(Rose::Object);
 
 use Rose::Object::MakeMethods::Generic
 (
- scalar                  => [ qw(controller file csv) ],
+ 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 all_vc vc_by) ],
 );
 
 sub run {
-  my ($self) = @_;
+  my ($self, %params) = @_;
+
+  $self->test_run($params{test_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,
@@ -29,17 +33,22 @@ sub run {
                                   profile                => $profile,
                                   ignore_unknown_columns => 1,
                                   strict_profile         => 1,
+                                  case_insensitive_header => 1,
                                   map { ( $_ => $self->controller->profile->get($_) ) } qw(sep_char escape_char quote_char),
                                  ));
 
+  $self->controller->track_progress(progress => 10);
+
   my $old_numberformat      = $::myconfig{numberformat};
   $::myconfig{numberformat} = $self->controller->profile->get('numberformat');
 
   $self->csv->parse;
 
+  $self->controller->track_progress(progress => 50);
+
   $self->controller->errors([ $self->csv->errors ]) if $self->csv->errors;
 
-  return unless $self->csv->header;
+  return if ( !$self->csv->header || $self->csv->errors );
 
   my $headers         = { headers => [ grep { $profile->{$_} } @{ $self->csv->header } ] };
   $headers->{methods} = [ map { $profile->{$_} } @{ $headers->{headers} } ];
@@ -49,13 +58,26 @@ sub run {
   $self->controller->info_headers({ used => { }, headers => [ ] });
 
   my @objects  = $self->csv->get_objects;
+
+  $self->controller->track_progress(progress => 70);
+
   my @raw_data = @{ $self->csv->get_data };
+
+  $self->controller->track_progress(progress => 80);
+
   $self->controller->data([ pairwise { { object => $a, raw_data => $b, errors => [], information => [], info_data => {} } } @objects, @raw_data ]);
 
+  $self->controller->track_progress(progress => 90);
+
   $self->check_objects;
-  $self->check_duplicates if $self->controller->profile->get('duplicates', 'no_check') ne 'no_check';
+  if ( $self->controller->profile->get('duplicates', 'no_check') ne 'no_check' ) {
+    $self->check_std_duplicates();
+    $self->check_duplicates();
+  }
   $self->fix_field_lengths;
 
+  $self->controller->track_progress(progress => 100);
+
   $::myconfig{numberformat} = $old_numberformat;
 }
 
@@ -100,6 +122,11 @@ sub add_cvar_raw_data_columns {
   map { $self->add_raw_data_columns($_) if exists $self->controller->data->[0]->{raw_data}->{$_} } @{ $self->cvar_columns };
 }
 
+sub init_all_cvar_configs {
+  # Must be overridden by derived specialized importer classes.
+  return [];
+}
+
 sub init_cvar_columns {
   my ($self) = @_;
 
@@ -169,8 +196,6 @@ sub check_vc {
 sub handle_cvars {
   my ($self, $entry) = @_;
 
-  return unless $self->can('all_cvar_configs');
-
   my %type_to_column = ( text      => 'text_value',
                          textfield => 'text_value',
                          select    => 'text_value',
@@ -185,7 +210,7 @@ sub handle_cvars {
     my $value  = $entry->{raw_data}->{ "cvar_" . $config->name };
     my $column = $type_to_column{ $config->type } || die "Program logic error: unknown custom variable storage type";
 
-    push @cvars, SL::DB::CustomVariable->new(config_id => $config->id, $column => $value);
+    push @cvars, SL::DB::CustomVariable->new(config_id => $config->id, $column => $value, sub_module => '');
   }
 
   $entry->{object}->custom_variables(\@cvars);
@@ -209,7 +234,9 @@ sub init_profile {
     $profile{$col} = $name;
   }
 
-  $self->profile(\%profile);
+  $profile{ 'cvar_' . $_->name } = '' for @{ $self->all_cvar_configs };
+
+  \%profile;
 }
 
 sub add_displayable_columns {
@@ -238,8 +265,6 @@ sub setup_displayable_columns {
 sub add_cvar_columns_to_displayable_columns {
   my ($self) = @_;
 
-  return unless $self->can('all_cvar_configs');
-
   $self->add_displayable_columns(map { { name        => 'cvar_' . $_->name,
                                          description => $::locale->text('#1 (custom variable)', $_->description) } }
                                      @{ $self->all_cvar_configs });
@@ -269,6 +294,60 @@ sub check_objects {
 sub check_duplicates {
 }
 
+sub check_std_duplicates {
+  my $self = shift;
+
+  my $duplicates = {};
+
+  my $all_fields = $self->get_duplicate_check_fields();
+
+  foreach my $key (keys(%{ $all_fields })) {
+    if ( $self->controller->profile->get('duplicates_'. $key) && (!exists($all_fields->{$key}->{std_check}) || $all_fields->{$key}->{std_check} )  ) {
+      $duplicates->{$key} = {};
+    }
+  }
+
+  my @duplicates_keys = keys(%{ $duplicates });
+
+  if ( !scalar(@duplicates_keys) ) {
+    return;
+  }
+
+  if ( $self->controller->profile->get('duplicates') eq 'check_db' ) {
+    foreach my $object (@{ $self->existing_objects }) {
+      foreach my $key (@duplicates_keys) {
+        my $value = exists($all_fields->{$key}->{maker}) ? $all_fields->{$key}->{maker}->($object, $self) : $object->$key;
+        $duplicates->{$key}->{$value} = 'db';
+      }
+    }
+  }
+
+  foreach my $entry (@{ $self->controller->data }) {
+    if ( @{ $entry->{errors} } ) {
+      next;
+    }
+
+    my $object = $entry->{object};
+
+    foreach my $key (@duplicates_keys) {
+      my $value = exists($all_fields->{$key}->{maker}) ? $all_fields->{$key}->{maker}->($object, $self) : $object->$key;
+
+      if ( exists($duplicates->{$key}->{$value}) ) {
+        push(@{ $entry->{errors} }, $duplicates->{$key}->{$value} eq 'db' ? $::locale->text('Duplicate in database') : $::locale->text('Duplicate in CSV file'));
+        last;
+      } else {
+        $duplicates->{$key}->{$value} = 'csv';
+      }
+
+    }
+  }
+
+}
+
+sub get_duplicate_check_fields {
+  return {};
+}
+
 sub check_payment {
   my ($self, $entry) = @_;
 
@@ -300,17 +379,33 @@ sub save_objects {
 
   my $data = $params{data} || $self->controller->data;
 
-  foreach my $entry (@{ $data }) {
+  return unless $data->[0];
+  return unless $data->[0]{object};
+
+  $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};
 
-    if (!$object->save) {
+    if ( !$object->save(cascade => !!$self->save_with_cascade()) ) {
       push @{ $entry->{errors} }, $::locale->text('Error when saving: #1', $entry->{object}->db->error);
     } else {
       $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;
+    }
   }
+  $dbh->commit;
 }
 
 sub field_lengths {
@@ -327,4 +422,20 @@ sub fix_field_lengths {
   }
 }
 
+sub clean_fields {
+  my ($self, $illegal_chars, $object, @fields) = @_;
+
+  my @cleaned_fields;
+  foreach my $field (grep { $object->can($_) } @fields) {
+    my $value = $object->$field;
+
+    next unless defined($value) && ($value =~ s/$illegal_chars/ /g);
+
+    $object->$field($value);
+    push @cleaned_fields, $field;
+  }
+
+  return @cleaned_fields;
+}
+
 1;