1 package SL::Controller::CsvImport::Base;
7 use parent qw(Rose::Object);
9 use Rose::Object::MakeMethods::Generic
11 scalar => [ qw(controller file csv) ],
12 'scalar --get_set_init' => [ qw(profile existing_objects class manager_class) ],
18 my $profile = $self->profile;
19 $self->csv(SL::Helper::Csv->new(file => $self->file->file_name,
20 encoding => $self->controller->profile->get('charset'),
21 class => $self->class,
23 ignore_unknown_columns => 1,
24 map { ( $_ => $self->controller->profile->get($_) ) } qw(sep_char escape_char quote_char),
28 $self->controller->errors([ $self->csv->errors ]) if $self->csv->errors;
30 return unless $self->csv->header;
32 my $headers = { headers => [ grep { $profile->{$_} } @{ $self->csv->header } ] };
33 $headers->{methods} = [ map { $profile->{$_} } @{ $headers->{headers} } ];
34 $self->controller->headers($headers);
36 $self->controller->data([ map { { object => $_, errors => [] } } $self->csv->get_objects ]);
39 $self->check_duplicates if $self->controller->profile->get('duplicates', 'no_check') ne 'no_check';
40 $self->fix_field_lenghts;
46 eval "require " . $self->class;
49 for my $col ($self->class->meta->columns) {
50 my $name = $col->isa('Rose::DB::Object::Metadata::Column::Numeric') ? "$col\_as_number"
51 : $col->isa('Rose::DB::Object::Metadata::Column::Date') ? "$col\_as_date"
52 : $col->isa('Rose::DB::Object::Metadata::Column::Timestamp') ? "$col\_as_date"
55 $profile{$col} = $name;
58 $self->profile(\%profile);
61 sub init_existing_objects {
64 eval "require " . $self->class;
65 $self->existing_objects($self->manager_class->get_all);
72 sub init_manager_class {
75 $self->class =~ m/^SL::DB::(.+)/;
76 $self->manager_class("SL::DB::Manager::" . $1);
82 sub check_duplicates {
86 my ($self, %params) = @_;
88 my $data = $params{data} || $self->controller->data;
90 foreach my $entry (@{ $data }) {
91 next if @{ $entry->{errors} };
93 if (!$entry->{object}->save) {
94 push @{ $entry->{errors} }, $::locale->text('Error when saving: #1', $entry->{object}->db->error);
96 $self->controller->num_imported($self->controller->num_imported + 1);
105 sub fix_field_lenghts {
108 my %field_lengths = $self->field_lengths;
109 foreach my $entry (@{ $self->controller->data }) {
110 next unless @{ $entry->{errors} };
111 map { $entry->{object}->$_(substr($entry->{object}->$_, 0, $field_lengths{$_})) if $entry->{object}->$_ } keys %field_lengths;