epic-ts
[kivitendo-erp.git] / SL / Controller / CsvImport / Base.pm
index eda921f..3090182 100644 (file)
@@ -2,44 +2,57 @@ package SL::Controller::CsvImport::Base;
 
 use strict;
 
-use List::MoreUtils qw(pairwise);
+use English qw(-no_match_vars);
+use List::MoreUtils qw(pairwise any);
 
 use SL::Helper::Csv;
+
+use SL::DB::BankAccount;
 use SL::DB::Customer;
 use SL::DB::Language;
 use SL::DB::PaymentTerm;
+use SL::DB::DeliveryTerm;
 use SL::DB::Vendor;
 use SL::DB::Contact;
+use SL::DB::History;
 
 use parent qw(Rose::Object);
 
 use Rose::Object::MakeMethods::Generic
 (
- scalar                  => [ qw(controller file csv) ],
- '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) ],
+ 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) ],
 );
 
 sub run {
-  my ($self) = @_;
+  my ($self, %params) = @_;
+
+  $self->test_run($params{test});
+
+  $self->controller->track_progress(phase => 'parsing csv', progress => 0);
 
   my $profile = $self->profile;
   $self->csv(SL::Helper::Csv->new(file                   => $self->file->file_name,
                                   encoding               => $self->controller->profile->get('charset'),
-                                  class                  => $self->class,
-                                  profile                => $profile,
+                                  profile                => [{ profile => $profile, class => $self->class }],
                                   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} } ];
@@ -48,14 +61,27 @@ sub run {
   $self->controller->raw_data_headers({ used => { }, headers => [ ] });
   $self->controller->info_headers({ used => { }, headers => [ ] });
 
-  my @objects  = $self->csv->get_objects;
+  my $objects  = $self->csv->get_objects;
+
+  $self->controller->track_progress(progress => 70);
+
   my @raw_data = @{ $self->csv->get_data };
-  $self->controller->data([ pairwise { { object => $a, raw_data => $b, errors => [], information => [], info_data => {} } } @objects, @raw_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 +126,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) = @_;
 
@@ -112,6 +143,12 @@ sub init_all_languages {
   return SL::DB::Manager::Language->get_all;
 }
 
+sub init_all_bank_accounts {
+  my ($self) = @_;
+
+  return SL::DB::Manager::BankAccount->get_all_sorted( query => [ obsolete => 0 ] );
+}
+
 sub init_payment_terms_by {
   my ($self) = @_;
 
@@ -119,6 +156,13 @@ sub init_payment_terms_by {
   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_payment_terms } } ) } qw(id description) };
 }
 
+sub init_delivery_terms_by {
+  my ($self) = @_;
+
+  my $all_delivery_terms = SL::DB::Manager::DeliveryTerm->get_all;
+  return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_delivery_terms } } ) } qw(id description) };
+}
+
 sub init_all_vc {
   my ($self) = @_;
 
@@ -126,6 +170,14 @@ sub init_all_vc {
            vendors   => SL::DB::Manager::Vendor->get_all };
 }
 
+sub init_clone_methods {
+  {}
+}
+
+sub force_allow_columns {
+  return ();
+}
+
 sub init_vc_by {
   my ($self)    = @_;
 
@@ -169,8 +221,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',
@@ -180,15 +230,29 @@ sub handle_cvars {
                          bool      => 'bool_value' );
 
   my @cvars;
+  my %changed_cvars;
   foreach my $config (@{ $self->all_cvar_configs }) {
     next unless exists $entry->{raw_data}->{ "cvar_" . $config->name };
     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);
+    my $new_cvar = SL::DB::CustomVariable->new(config_id => $config->id, $column => $value, sub_module => '');
+
+    push @cvars, $new_cvar;
+    $changed_cvars{$config->name} = $new_cvar;
   }
 
-  $entry->{object}->custom_variables(\@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);
+  }
 }
 
 sub init_profile {
@@ -197,6 +261,8 @@ sub init_profile {
   eval "require " . $self->class;
 
   my %unwanted = map { ( $_ => 1 ) } (qw(itime mtime), map { $_->name } @{ $self->class->meta->primary_key_columns });
+  delete $unwanted{$_} for ($self->force_allow_columns);
+
   my %profile;
   for my $col ($self->class->meta->columns) {
     next if $unwanted{$col};
@@ -209,7 +275,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 +306,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 });
@@ -263,12 +329,68 @@ sub init_manager_class {
   $self->manager_class("SL::DB::Manager::" . $1);
 }
 
+sub is_multiplexed { 0 }
+
 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) = @_;
 
@@ -290,6 +412,38 @@ sub check_payment {
     }
 
     $object->payment_id($terms->id);
+
+    # register payment_id for method copying later
+    $self->clone_methods->{payment_id} = 1;
+  }
+
+  return 1;
+}
+
+sub check_delivery_term {
+  my ($self, $entry) = @_;
+
+  my $object = $entry->{object};
+
+  # Check whether or not delivery term ID is valid.
+  if ($object->delivery_term_id && !$self->delivery_terms_by->{id}->{ $object->delivery_term_id }) {
+    push @{ $entry->{errors} }, $::locale->text('Error: Invalid delivery terms');
+    return 0;
+  }
+
+  # Map name to ID if given.
+  if (!$object->delivery_term_id && $entry->{raw_data}->{delivery_term}) {
+    my $terms = $self->delivery_terms_by->{description}->{ $entry->{raw_data}->{delivery_term} };
+
+    if (!$terms) {
+      push @{ $entry->{errors} }, $::locale->text('Error: Invalid delivery terms');
+      return 0;
+    }
+
+    $object->delivery_term_id($terms->id);
+
+    # register delivery_term_id for method copying later
+    $self->clone_methods->{delivery_term_id} = 1;
   }
 
   return 1;
@@ -300,21 +454,43 @@ 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) {
-      push @{ $entry->{errors} }, $::locale->text('Error when saving: #1', $entry->{object}->db->error);
+    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;
+    }
   }
+  $dbh->commit;
 }
 
 sub field_lengths {
-  return ();
+  my ($self) = @_;
+
+  return map { $_->name => $_->length } grep { $_->type eq 'varchar' } @{$self->class->meta->columns};
 }
 
 sub fix_field_lengths {
@@ -327,4 +503,43 @@ 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;
+}
+
+sub _save_history {
+  my ($self, $object) = @_;
+
+  if (any { $_ eq $self->controller->{type} } qw(parts customers_vendors orders)) {
+    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
+                 : '';
+
+    my $what_done = $self->controller->{type} eq 'orders' ? 'sales_order'
+                  : '';
+
+    SL::DB::History->new(
+      trans_id    => $object->id,
+      snumbers    => $snumbers,
+      employee_id => $self->controller->{employee_id},
+      addition    => 'SAVED',
+      what_done   => $what_done,
+    )->save();
+  }
+}
+
 1;