1 package SL::Controller::CsvImport::Base;
5 use English qw(-no_match_vars);
6 use List::MoreUtils qw(pairwise any);
10 use SL::DB::BankAccount;
13 use SL::DB::PaymentTerm;
14 use SL::DB::DeliveryTerm;
19 use parent qw(Rose::Object);
21 use Rose::Object::MakeMethods::Generic
23 scalar => [ qw(controller file csv test_run save_with_cascade) ],
24 '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) ],
28 my ($self, %params) = @_;
30 $self->test_run($params{test});
32 $self->controller->track_progress(phase => 'parsing csv', progress => 0);
34 my $profile = $self->profile;
35 $self->csv(SL::Helper::Csv->new(file => $self->file->file_name,
36 encoding => $self->controller->profile->get('charset'),
37 profile => [{ profile => $profile, class => $self->class }],
38 ignore_unknown_columns => 1,
40 case_insensitive_header => 1,
41 map { ( $_ => $self->controller->profile->get($_) ) } qw(sep_char escape_char quote_char),
44 $self->controller->track_progress(progress => 10);
46 my $old_numberformat = $::myconfig{numberformat};
47 $::myconfig{numberformat} = $self->controller->profile->get('numberformat');
51 $self->controller->track_progress(progress => 50);
53 $self->controller->errors([ $self->csv->errors ]) if $self->csv->errors;
55 return if ( !$self->csv->header || $self->csv->errors );
57 my $headers = { headers => [ grep { $profile->{$_} } @{ $self->csv->header } ] };
58 $headers->{methods} = [ map { $profile->{$_} } @{ $headers->{headers} } ];
59 $headers->{used} = { map { ($_ => 1) } @{ $headers->{headers} } };
60 $self->controller->headers($headers);
61 $self->controller->raw_data_headers({ used => { }, headers => [ ] });
62 $self->controller->info_headers({ used => { }, headers => [ ] });
64 my $objects = $self->csv->get_objects;
66 $self->controller->track_progress(progress => 70);
68 my @raw_data = @{ $self->csv->get_data };
70 $self->controller->track_progress(progress => 80);
72 $self->controller->data([ pairwise { { object => $a, raw_data => $b, errors => [], information => [], info_data => {} } } @$objects, @raw_data ]);
74 $self->controller->track_progress(progress => 90);
77 if ( $self->controller->profile->get('duplicates', 'no_check') ne 'no_check' ) {
78 $self->check_std_duplicates();
79 $self->check_duplicates();
81 $self->fix_field_lengths;
83 $self->controller->track_progress(progress => 100);
85 $::myconfig{numberformat} = $old_numberformat;
89 my ($self, @columns) = @_;
91 my $h = $self->controller->headers;
93 foreach my $column (grep { !$h->{used}->{$_} } @columns) {
94 $h->{used}->{$column} = 1;
95 push @{ $h->{methods} }, $column;
96 push @{ $h->{headers} }, $column;
100 sub add_info_columns {
101 my ($self, @columns) = @_;
103 my $h = $self->controller->info_headers;
105 foreach my $column (grep { !$h->{used}->{ $_->{method} } } map { ref $_ eq 'HASH' ? $_ : { method => $_, header => $_ } } @columns) {
106 $h->{used}->{ $column->{method} } = 1;
107 push @{ $h->{methods} }, $column->{method};
108 push @{ $h->{headers} }, $column->{header};
112 sub add_raw_data_columns {
113 my ($self, @columns) = @_;
115 my $h = $self->controller->raw_data_headers;
117 foreach my $column (grep { !$h->{used}->{$_} } @columns) {
118 $h->{used}->{$column} = 1;
119 push @{ $h->{headers} }, $column;
123 sub add_cvar_raw_data_columns {
126 map { $self->add_raw_data_columns($_) if exists $self->controller->data->[0]->{raw_data}->{$_} } @{ $self->cvar_columns };
129 sub init_all_cvar_configs {
130 # Must be overridden by derived specialized importer classes.
134 sub init_cvar_columns {
137 return [ map { "cvar_" . $_->name } (@{ $self->all_cvar_configs }) ];
140 sub init_all_languages {
143 return SL::DB::Manager::Language->get_all;
146 sub init_all_bank_accounts {
149 return SL::DB::Manager::BankAccount->get_all_sorted( query => [ obsolete => 0 ] );
152 sub init_payment_terms_by {
155 my $all_payment_terms = SL::DB::Manager::PaymentTerm->get_all;
156 return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_payment_terms } } ) } qw(id description) };
159 sub init_delivery_terms_by {
162 my $all_delivery_terms = SL::DB::Manager::DeliveryTerm->get_all;
163 return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_delivery_terms } } ) } qw(id description) };
169 return { customers => SL::DB::Manager::Customer->get_all,
170 vendors => SL::DB::Manager::Vendor->get_all };
173 sub init_clone_methods {
177 sub force_allow_columns {
184 my %by_id = map { ( $_->id => $_ ) } @{ $self->all_vc->{customers} }, @{ $self->all_vc->{vendors} };
185 my %by_number = ( customers => { map { ( $_->customernumber => $_ ) } @{ $self->all_vc->{customers} } },
186 vendors => { map { ( $_->vendornumber => $_ ) } @{ $self->all_vc->{vendors} } } );
187 my %by_name = ( customers => { map { ( $_->name => $_ ) } @{ $self->all_vc->{customers} } },
188 vendors => { map { ( $_->name => $_ ) } @{ $self->all_vc->{vendors} } } );
190 return { id => \%by_id,
191 number => \%by_number,
192 name => \%by_name, };
196 my ($self, $entry, $id_column) = @_;
198 if ($entry->{object}->$id_column) {
199 $entry->{object}->$id_column(undef) if !$self->vc_by->{id}->{ $entry->{object}->$id_column };
202 if (!$entry->{object}->$id_column) {
203 my $vc = $self->vc_by->{number}->{customers}->{ $entry->{raw_data}->{customernumber} }
204 || $self->vc_by->{number}->{vendors}->{ $entry->{raw_data}->{vendornumber} };
205 $entry->{object}->$id_column($vc->id) if $vc;
208 if (!$entry->{object}->$id_column) {
209 my $vc = $self->vc_by->{name}->{customers}->{ $entry->{raw_data}->{customer} }
210 || $self->vc_by->{name}->{vendors}->{ $entry->{raw_data}->{vendor} };
211 $entry->{object}->$id_column($vc->id) if $vc;
214 if ($entry->{object}->$id_column) {
215 $entry->{info_data}->{vc_name} = $self->vc_by->{id}->{ $entry->{object}->$id_column }->name;
217 push @{ $entry->{errors} }, $::locale->text('Error: Customer/vendor not found');
222 my ($self, $entry) = @_;
224 my %type_to_column = ( text => 'text_value',
225 textfield => 'text_value',
226 select => 'text_value',
227 date => 'timestamp_value_as_date',
228 timestamp => 'timestamp_value_as_date',
229 number => 'number_value_as_number',
230 bool => 'bool_value' );
234 foreach my $config (@{ $self->all_cvar_configs }) {
235 next unless exists $entry->{raw_data}->{ "cvar_" . $config->name };
236 my $value = $entry->{raw_data}->{ "cvar_" . $config->name };
237 my $column = $type_to_column{ $config->type } || die "Program logic error: unknown custom variable storage type";
239 my $new_cvar = SL::DB::CustomVariable->new(config_id => $config->id, $column => $value, sub_module => '');
241 push @cvars, $new_cvar;
242 $changed_cvars{$config->name} = $new_cvar;
245 # merge existing with new cvars. swap every existing with the imported one, push the rest
247 my @orig_cvars = ($entry->{object_to_save} || $entry->{object})->custom_variables;
249 $_ = $changed_cvars{ $_->config->name } if $changed_cvars{ $_->config->name };
250 delete $changed_cvars{ $_->config->name };
252 push @orig_cvars, values %changed_cvars;
254 $entry->{object}->custom_variables(\@orig_cvars);
261 eval "require " . $self->class;
263 my %unwanted = map { ( $_ => 1 ) } (qw(itime mtime), map { $_->name } @{ $self->class->meta->primary_key_columns });
264 delete $unwanted{$_} for ($self->force_allow_columns);
267 for my $col ($self->class->meta->columns) {
268 next if $unwanted{$col};
270 my $name = $col->isa('Rose::DB::Object::Metadata::Column::Numeric') ? "$col\_as_number"
271 : $col->isa('Rose::DB::Object::Metadata::Column::Date') ? "$col\_as_date"
272 : $col->isa('Rose::DB::Object::Metadata::Column::Timestamp') ? "$col\_as_date"
275 $profile{$col} = $name;
278 $profile{ 'cvar_' . $_->name } = '' for @{ $self->all_cvar_configs };
283 sub add_displayable_columns {
284 my ($self, @columns) = @_;
286 my @cols = @{ $self->controller->displayable_columns || [] };
287 my %ex_col_map = map { $_->{name} => $_ } @cols;
289 foreach my $column (@columns) {
290 if ($ex_col_map{ $column->{name} }) {
291 @{ $ex_col_map{ $column->{name} } }{ keys %{ $column } } = @{ $column }{ keys %{ $column } };
297 $self->controller->displayable_columns([ sort { $a->{name} cmp $b->{name} } @cols ]);
300 sub setup_displayable_columns {
303 $self->add_displayable_columns(map { { name => $_ } } keys %{ $self->profile });
306 sub add_cvar_columns_to_displayable_columns {
309 $self->add_displayable_columns(map { { name => 'cvar_' . $_->name,
310 description => $::locale->text('#1 (custom variable)', $_->description) } }
311 @{ $self->all_cvar_configs });
314 sub init_existing_objects {
317 eval "require " . $self->class;
318 $self->existing_objects($self->manager_class->get_all);
325 sub init_manager_class {
328 $self->class =~ m/^SL::DB::(.+)/;
329 $self->manager_class("SL::DB::Manager::" . $1);
332 sub is_multiplexed { 0 }
337 sub check_duplicates {
340 sub check_std_duplicates {
345 my $all_fields = $self->get_duplicate_check_fields();
347 foreach my $key (keys(%{ $all_fields })) {
348 if ( $self->controller->profile->get('duplicates_'. $key) && (!exists($all_fields->{$key}->{std_check}) || $all_fields->{$key}->{std_check} ) ) {
349 $duplicates->{$key} = {};
353 my @duplicates_keys = keys(%{ $duplicates });
355 if ( !scalar(@duplicates_keys) ) {
359 if ( $self->controller->profile->get('duplicates') eq 'check_db' ) {
360 foreach my $object (@{ $self->existing_objects }) {
361 foreach my $key (@duplicates_keys) {
362 my $value = exists($all_fields->{$key}->{maker}) ? $all_fields->{$key}->{maker}->($object, $self) : $object->$key;
363 $duplicates->{$key}->{$value} = 'db';
368 foreach my $entry (@{ $self->controller->data }) {
369 if ( @{ $entry->{errors} } ) {
373 my $object = $entry->{object};
375 foreach my $key (@duplicates_keys) {
376 my $value = exists($all_fields->{$key}->{maker}) ? $all_fields->{$key}->{maker}->($object, $self) : $object->$key;
378 if ( exists($duplicates->{$key}->{$value}) ) {
379 push(@{ $entry->{errors} }, $duplicates->{$key}->{$value} eq 'db' ? $::locale->text('Duplicate in database') : $::locale->text('Duplicate in CSV file'));
382 $duplicates->{$key}->{$value} = 'csv';
390 sub get_duplicate_check_fields {
395 my ($self, $entry) = @_;
397 my $object = $entry->{object};
399 # Check whether or not payment ID is valid.
400 if ($object->payment_id && !$self->payment_terms_by->{id}->{ $object->payment_id }) {
401 push @{ $entry->{errors} }, $::locale->text('Error: Invalid payment terms');
405 # Map name to ID if given.
406 if (!$object->payment_id && $entry->{raw_data}->{payment}) {
407 my $terms = $self->payment_terms_by->{description}->{ $entry->{raw_data}->{payment} };
410 push @{ $entry->{errors} }, $::locale->text('Error: Invalid payment terms');
414 $object->payment_id($terms->id);
416 # register payment_id for method copying later
417 $self->clone_methods->{payment_id} = 1;
423 sub check_delivery_term {
424 my ($self, $entry) = @_;
426 my $object = $entry->{object};
428 # Check whether or not delivery term ID is valid.
429 if ($object->delivery_term_id && !$self->delivery_terms_by->{id}->{ $object->delivery_term_id }) {
430 push @{ $entry->{errors} }, $::locale->text('Error: Invalid delivery terms');
434 # Map name to ID if given.
435 if (!$object->delivery_term_id && $entry->{raw_data}->{delivery_term}) {
436 my $terms = $self->delivery_terms_by->{description}->{ $entry->{raw_data}->{delivery_term} };
439 push @{ $entry->{errors} }, $::locale->text('Error: Invalid delivery terms');
443 $object->delivery_term_id($terms->id);
445 # register delivery_term_id for method copying later
446 $self->clone_methods->{delivery_term_id} = 1;
453 my ($self, %params) = @_;
455 my $data = $params{data} || $self->controller->data;
457 return unless $data->[0];
458 return unless $data->[0]{object};
460 $self->controller->track_progress(phase => 'saving data', progress => 0); # scale from 45..95%;
462 my $dbh = $data->[0]{object}->db;
465 foreach my $entry_index (0 .. $#$data) {
466 my $entry = $data->[$entry_index];
467 next if @{ $entry->{errors} };
469 my $object = $entry->{object_to_save} || $entry->{object};
472 if (!eval { $ret = $object->save(cascade => !!$self->save_with_cascade()); 1 }) {
473 push @{ $entry->{errors} }, $::locale->text('Error when saving: #1', $EVAL_ERROR);
475 push @{ $entry->{errors} }, $::locale->text('Error when saving: #1', $object->db->error);
477 $self->_save_history($object);
478 $self->controller->num_imported($self->controller->num_imported + 1);
481 if ($entry_index % 100 == 0) {
483 $self->controller->track_progress(progress => $entry_index/scalar(@$data) * 100); # scale from 45..95%;
493 return map { $_->name => $_->length } grep { $_->type eq 'varchar' } @{$self->class->meta->columns};
496 sub fix_field_lengths {
499 my %field_lengths = $self->field_lengths;
500 foreach my $entry (@{ $self->controller->data }) {
501 next unless @{ $entry->{errors} };
502 map { $entry->{object}->$_(substr($entry->{object}->$_, 0, $field_lengths{$_})) if $entry->{object}->$_ } keys %field_lengths;
507 my ($self, $illegal_chars, $object, @fields) = @_;
510 foreach my $field (grep { $object->can($_) } @fields) {
511 my $value = $object->$field;
513 next unless defined($value) && ($value =~ s/$illegal_chars/ /g);
515 $object->$field($value);
516 push @cleaned_fields, $field;
519 return @cleaned_fields;
523 my ($self, $object) = @_;
525 if (any { $_ eq $self->controller->{type} } qw(parts customers_vendors orders)) {
526 my $snumbers = $self->controller->{type} eq 'parts' ? 'partnumber_' . $object->partnumber
527 : $self->controller->{type} eq 'customers_vendors' ?
528 ($self->table eq 'customer' ? 'customernumber_' . $object->customernumber : 'vendornumber_' . $object->vendornumber)
529 : $self->controller->{type} eq 'orders' ? 'ordnumber_' . $object->ordnumber
532 my $what_done = $self->controller->{type} eq 'orders' ? 'sales_order'
535 SL::DB::History->new(
536 trans_id => $object->id,
537 snumbers => $snumbers,
538 employee_id => $self->controller->{employee_id},
540 what_done => $what_done,