epic-ts
[kivitendo-erp.git] / SL / Controller / CsvImport / Base.pm
index fa3e4f4..3090182 100644 (file)
@@ -2,35 +2,39 @@ 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 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) ],
+ '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, %params) = @_;
 
-  $self->test_run($params{test_run});
+  $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,
@@ -57,7 +61,7 @@ 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);
 
@@ -65,7 +69,7 @@ sub run {
 
   $self->controller->track_progress(progress => 80);
 
-  $self->controller->data([ pairwise { { object => $a, raw_data => $b, errors => [], information => [], info_data => {} } } @objects, @raw_data ]);
+  $self->controller->data([ pairwise { { object => $a, raw_data => $b, errors => [], information => [], info_data => {} } } @$objects, @raw_data ]);
 
   $self->controller->track_progress(progress => 90);
 
@@ -139,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) = @_;
 
@@ -146,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) = @_;
 
@@ -153,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)    = @_;
 
@@ -205,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, sub_module => '');
+    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 {
@@ -222,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};
@@ -288,6 +329,8 @@ sub init_manager_class {
   $self->manager_class("SL::DB::Manager::" . $1);
 }
 
+sub is_multiplexed { 0 }
+
 sub check_objects {
 }
 
@@ -369,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;
@@ -393,9 +468,13 @@ sub save_objects {
 
     my $object = $entry->{object_to_save} || $entry->{object};
 
-    if ( !$object->save(cascade => !!$self->save_with_cascade()) ) {
-      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 {
@@ -409,7 +488,9 @@ sub save_objects {
 }
 
 sub field_lengths {
-  return ();
+  my ($self) = @_;
+
+  return map { $_->name => $_->length } grep { $_->type eq 'varchar' } @{$self->class->meta->columns};
 }
 
 sub fix_field_lengths {
@@ -422,5 +503,43 @@ sub fix_field_lengths {
   }
 }
 
-1;
+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;