1 package SL::Controller::CsvImport;
5 use SL::DB::Buchungsgruppe;
6 use SL::DB::CsvImportProfile;
7 use SL::DB::CsvImportReport;
9 use SL::DB::Helper::Paginated ();
10 use SL::Helper::Flash;
11 use SL::Locale::String;
13 use SL::Controller::CsvImport::Contact;
14 use SL::Controller::CsvImport::CustomerVendor;
15 use SL::Controller::CsvImport::Part;
16 use SL::Controller::CsvImport::Shipto;
17 use SL::Controller::CsvImport::Project;
18 use SL::BackgroundJob::CsvImport;
19 use SL::System::TaskServer;
21 use List::MoreUtils qw(none);
22 use List::Util qw(min);
24 use parent qw(SL::Controller::Base);
26 use Rose::Object::MakeMethods::Generic
28 scalar => [ qw(type profile file all_profiles all_charsets sep_char all_sep_chars quote_char all_quote_chars escape_char all_escape_chars all_buchungsgruppen all_units
29 import_status errors headers raw_data_headers info_headers data num_imported num_importable displayable_columns file) ],
30 'scalar --get_set_init' => [ qw(worker task_server) ],
32 progress_tracker => { },
33 add_progress_tracker => { interface => 'add', hash_key => 'progress_tracker' },
37 __PACKAGE__->run_before('check_auth');
38 __PACKAGE__->run_before('ensure_form_structure');
39 __PACKAGE__->run_before('check_type', except => [ qw(report) ]);
40 __PACKAGE__->run_before('load_all_profiles');
41 __PACKAGE__->run_before('check_task_server');
43 __PACKAGE__->run_after('cleanup_reports');
52 $self->load_default_profile unless $self->profile;
58 $self->test_and_import_deferred(test => 1);
63 $self->test_and_import_deferred(test => 0);
69 $self->profile_from_form(SL::DB::Manager::CsvImportProfile->find_by(name => $::form->{profile}->{name}, login => $::myconfig{login}));
72 flash_later('info', $::locale->text("The profile has been saved under the name '#1'.", $self->profile->name));
73 $self->redirect_to(action => 'new', 'profile.type' => $self->type, 'profile.id' => $self->profile->id);
79 my $profile = SL::DB::CsvImportProfile->new(id => $::form->{profile}->{id}, login => $::myconfig{login});
80 $profile->delete(cascade => 1);
82 flash_later('info', $::locale->text('The profile \'#1\' has been deleted.', $profile->name));
83 $self->redirect_to(action => 'new', 'profile.type' => $self->type);
90 $self->{background_job} = SL::DB::Manager::BackgroundJob->find_by(id => $::form->{job});
92 my $data = $self->{background_job}->data_as_hash;
94 my $profile = SL::DB::Manager::CsvImportProfile->find_by(id => $data->{profile_id});
96 $self->profile($profile);
98 if ($data->{errors} and my $first_error = $data->{errors}->[0]) {
99 flash('error', $::locale->text('There was an error parsing the csv file: #1 in line #2.', $first_error->[2], $first_error->[0]));
102 if ($data->{progress}{finished} || $data->{errors}) {
103 $self->render('csv_import/_deferred_report', { layout => 0 });
105 if (!$self->task_server->is_running) {
106 $self->task_server->start;
107 $self->{status_text} = t8('Task Server is not running, starting it now. If this does not change, please check your task server config');
108 } elsif (my $phase = $data->{progress}{phase}) {
109 $self->{status_text} = "$data->{progress}{plan}{$phase} / $data->{progress}{num_phases} " . t8($phase);
111 $self->{status_text} = t8('Import not started yet, please wait...');
114 $self->render('csv_import/_deferred_results', { layout => 0 });
118 sub action_download_sample {
121 $self->profile_from_form;
124 my $file_name = 'csv_import_sample_' . $self->type . '.csv';
125 my $file = SL::SessionFile->new($file_name, mode => '>', encoding => $self->profile->get('charset'));
126 my $csv = Text::CSV_XS->new({ binary => 1, map { ( $_ => $self->profile->get($_) ) } qw(sep_char escape_char quote_char),});
128 $csv->print($file->fh, [ map { $_->{name} } @{ $self->displayable_columns } ]);
129 $file->fh->print("\r\n");
130 $csv->print($file->fh, [ map { $_->{description} } @{ $self->displayable_columns } ]);
131 $file->fh->print("\r\n");
135 $self->send_file($file->file_name, name => $file_name);
139 my ($self, %params) = @_;
141 my $report_id = $params{report_id} || $::form->{id};
143 $self->{report} = SL::DB::Manager::CsvImportReport->find_by(id => $report_id);
145 if (!$self->{report}) {
146 $::form->error(t8('No report with id #1', $report_id));
148 my $num_rows = $self->{report}->numrows;
149 my $num_cols = SL::DB::Manager::CsvImportReportRow->get_all_count(query => [ csv_import_report_id => $report_id, row => 0 ]);
151 # manual paginating, yuck
152 my $page = $::form->{page} || 1;
154 $pages->{per_page} = $::form->{per_page} || 20;
155 $pages->{max} = SL::DB::Helper::Paginated::ceil($num_rows / ($num_cols || 1), $pages->{per_page}) || 1;
156 $pages->{cur} = $page < 1 ? 1
157 : $page > $pages->{max} ? $pages->{max}
159 $pages->{common} = [ grep { $_->{visible} } @{ SL::DB::Helper::Paginated::make_common_pages($pages->{cur}, $pages->{max}) } ];
161 $self->{display_rows} = [
163 $pages->{per_page} * ($pages->{cur}-1) + 1
165 min($pages->{per_page} * $pages->{cur}, $num_rows / ($num_cols || 1) - 1)
169 csv_import_report_id => $report_id,
173 row => { gt => $pages->{per_page} * ($pages->{cur}-1) },
174 row => { le => $pages->{per_page} * $pages->{cur} },
179 my $rows = SL::DB::Manager::CsvImportReportRow->get_all(query => \@query);
180 my $status = SL::DB::Manager::CsvImportReportStatus->get_all(query => \@query);
182 $self->{report_rows} = $self->{report}->folded_rows(rows => $rows);
183 $self->{report_status} = $self->{report}->folded_status(status => $status);
184 $self->{pages} = $pages;
185 $self->{base_url} = $self->url_for(action => 'report', id => $report_id, no_layout => $params{no_layout} || $::form->{no_layout} );
187 $self->render('csv_import/report', { layout => !($params{no_layout} || $::form->{no_layout}) });
196 $::auth->assert('config');
202 die "Invalid CSV import type" if none { $_ eq $::form->{profile}->{type} } qw(parts customers_vendors addresses contacts projects);
203 $self->type($::form->{profile}->{type});
206 sub ensure_form_structure {
207 my ($self, %params) = @_;
209 $::form->{profile} = {} unless ref $::form->{profile} eq 'HASH';
210 $::form->{settings} = {} unless ref $::form->{settings} eq 'HASH';
218 my ($self, %params) = @_;
220 $self->all_charsets([ [ 'UTF-8', 'UTF-8' ],
221 [ 'ISO-8859-1', 'ISO-8859-1 (Latin 1)' ],
222 [ 'ISO-8859-15', 'ISO-8859-15 (Latin 9)' ],
223 [ 'CP850', 'CP850 (DOS/ANSI)' ],
224 [ 'CP1252', 'CP1252 (Windows)' ],
227 my %char_map = $self->char_map;
229 foreach my $type (qw(sep quote escape)) {
230 my $sub = "all_${type}_chars";
231 $self->$sub([ sort { $a->[0] cmp $b->[0] } values %{ $char_map{$type} } ]);
233 my $char = $self->profile->get($type . '_char');
234 $sub = "${type}_char";
235 $self->$sub(($char_map{$type}->{$char} || [])->[0] || $char);
238 $self->file(SL::SessionFile->new($self->csv_file_name));
240 my $title = $self->type eq 'customers_vendors' ? $::locale->text('CSV import: customers and vendors')
241 : $self->type eq 'addresses' ? $::locale->text('CSV import: shipping addresses')
242 : $self->type eq 'contacts' ? $::locale->text('CSV import: contacts')
243 : $self->type eq 'parts' ? $::locale->text('CSV import: parts and services')
244 : $self->type eq 'projects' ? $::locale->text('CSV import: projects')
247 if ($self->{type} eq 'parts') {
248 $self->all_buchungsgruppen(SL::DB::Manager::Buchungsgruppe->get_all_sorted);
249 $self->all_units(SL::DB::Manager::Unit->get_all_sorted);
254 $self->render('csv_import/form', title => $title);
257 sub test_and_import_deferred {
258 my ($self, %params) = @_;
260 $self->profile_from_form;
262 if ($::form->{file}) {
263 my $file = SL::SessionFile->new($self->csv_file_name, mode => '>');
264 $file->fh->print($::form->{file});
268 my $file = SL::SessionFile->new($self->csv_file_name, mode => '<', encoding => $self->profile->get('charset'));
270 flash('error', $::locale->text('No file has been uploaded yet.'));
271 return $self->action_new;
274 $self->{background_job} = SL::BackgroundJob::CsvImport->create_job(
275 file => $self->csv_file_name,
276 profile => $self->profile,
277 type => $self->profile->type,
278 test => $params{test},
281 if ($self->task_server->is_running) {
282 $self->task_server->wake_up;
284 $self->task_server->start;
287 flash('info', $::locale->text('Your import is beig processed.'));
289 $self->{deferred} = 1;
291 $self->render_inputs;
294 sub test_and_import {
295 my ($self, %params) = @_;
297 my $file = SL::SessionFile->new(
298 $self->csv_file_name,
300 encoding => $self->profile->get('charset'),
301 session_id => $params{session_id}
306 my $worker = $self->worker();
308 $worker->run(%params);
310 return if $self->errors;
312 $self->num_imported(0);
313 $worker->save_objects if !$params{test};
315 $self->num_importable(scalar grep { !$_ } map { scalar @{ $_->{errors} } } @{ $self->data || [] });
316 $self->import_status($params{test} ? 'tested' : 'imported');
318 # flash('info', $::locale->text('Objects have been imported.')) if !$params{test};
321 sub load_default_profile {
325 if ($::form->{profile}->{id}) {
326 $profile = SL::DB::Manager::CsvImportProfile->find_by(id => $::form->{profile}->{id}, login => $::myconfig{login});
328 $profile ||= SL::DB::Manager::CsvImportProfile->find_by(type => $self->{type}, is_default => 1, login => $::myconfig{login});
329 $profile ||= SL::DB::CsvImportProfile->new(type => $self->{type}, login => $::myconfig{login});
331 $self->profile($profile);
332 $self->profile->set_defaults;
335 sub load_all_profiles {
336 my ($self, %params) = @_;
338 $self->all_profiles(SL::DB::Manager::CsvImportProfile->get_all(
341 login => $::myconfig{login},
346 sub profile_from_form {
347 my ($self, $existing_profile) = @_;
349 delete $::form->{profile}->{id};
351 my %char_map = $self->char_map;
354 foreach my $type (qw(sep quote escape)) {
355 my %rev_chars = map { $char_map{$type}->{$_}->[0] => $_ } keys %{ $char_map{$type} };
356 my $char = $::form->{"${type}_char"} eq 'custom' ? $::form->{"custom_${type}_char"} : $rev_chars{ $::form->{"${type}_char"} };
358 push @settings, { key => "${type}_char", value => $char };
361 if ($self->type eq 'parts') {
362 $::form->{settings}->{sellprice_adjustment} = $::form->parse_amount(\%::myconfig, $::form->{settings}->{sellprice_adjustment});
365 delete $::form->{profile}->{id};
366 $self->profile($existing_profile || SL::DB::CsvImportProfile->new(login => $::myconfig{login}));
367 $self->profile->assign_attributes(%{ $::form->{profile} });
368 $self->profile->settings(map({ { key => $_, value => $::form->{settings}->{$_} } } keys %{ $::form->{settings} }),
370 $self->profile->set_defaults;
374 return ( sep => { ',' => [ 'comma', $::locale->text('Comma') ],
375 ';' => [ 'semicolon', $::locale->text('Semicolon') ],
376 "\t" => [ 'tab', $::locale->text('Tab') ],
377 ' ' => [ 'space', $::locale->text('Space') ],
379 quote => { '"' => [ 'quote', $::locale->text('Quotes') ],
380 "'" => [ 'singlequote', $::locale->text('Single quotes') ],
382 escape => { '"' => [ 'quote', $::locale->text('Quotes') ],
383 "'" => [ 'singlequote', $::locale->text('Single quotes') ],
389 my ($self, $report_id) = @_;
391 $self->track_progress(phase => 'building report', progress => 0);
393 my $clone_profile = $self->profile->clone_and_reset_deep;
394 $clone_profile->save; # weird bug. if this isn't saved before adding it to the report, it will default back to the last profile.
396 my $report = SL::DB::CsvImportReport->new(
397 session_id => $::auth->create_or_refresh_session,
398 profile => $clone_profile,
401 numrows => scalar @{ $self->data },
404 $report->save(cascade => 1) or die $report->db->error;
406 my $dbh = $::form->get_standard_dbh;
409 my $query = 'INSERT INTO csv_import_report_rows (csv_import_report_id, col, row, value) VALUES (?, ?, ?, ?)';
410 my $query2 = 'INSERT INTO csv_import_report_status (csv_import_report_id, row, type, value) VALUES (?, ?, ?, ?)';
412 my $sth = $dbh->prepare($query);
413 my $sth2 = $dbh->prepare($query2);
416 my (@headers, @info_methods, @raw_methods, @methods);
418 for my $i (0 .. $#{ $self->info_headers->{headers} }) {
419 next unless $self->info_headers->{used}->{ $self->info_headers->{headers}->[$i] };
420 push @headers, $self->info_headers->{headers}->[$i];
421 push @info_methods, $self->info_headers->{methods}->[$i];
423 for my $i (0 .. $#{ $self->headers->{headers} }) {
424 next unless $self->headers->{used}->{ $self->headers->{headers}->[$i] };
425 push @headers, $self->headers->{headers}->[$i];
426 push @methods, $self->headers->{methods}->[$i];
428 for my $i (0 .. $#{ $self->raw_data_headers->{headers} }) {
429 next unless $self->raw_data_headers->{used}->{ $self->raw_data_headers->{headers}->[$i] };
430 push @headers, $self->raw_data_headers->{headers}->[$i];
431 push @raw_methods, $self->raw_data_headers->{headers}->[$i];
434 $sth->execute($report->id, $_, 0, $headers[$_]) for 0 .. $#headers;
437 my $o1 = @info_methods;
438 my $o2 = $o1 + @methods;
440 for my $row (0 .. $#{ $self->data }) {
441 $self->track_progress(progress => $row / @{ $self->data } * 100) if $row % 1000 == 0;
442 my $data_row = $self->{data}[$row];
444 $sth->execute($report->id, $_, $row + 1, $data_row->{info_data}{ $info_methods[$_] }) for 0 .. $#info_methods;
445 $sth->execute($report->id, $o1 + $_, $row + 1, $data_row->{object}->${ \ $methods[$_] }) for 0 .. $#methods;
446 $sth->execute($report->id, $o2 + $_, $row + 1, $data_row->{raw_data}{ $raw_methods[$_] }) for 0 .. $#raw_methods;
448 $sth2->execute($report->id, $row + 1, 'information', $_) for @{ $data_row->{information} || [] };
449 $sth2->execute($report->id, $row + 1, 'errors', $_) for @{ $data_row->{errors} || [] };
459 return "csv-import-" . $self->type . ".csv";
465 my @args = (controller => $self);
467 if ( $self->file() ) {
468 push(@args, file => $self->file());
471 return $self->{type} eq 'customers_vendors' ? SL::Controller::CsvImport::CustomerVendor->new(@args)
472 : $self->{type} eq 'contacts' ? SL::Controller::CsvImport::Contact->new(@args)
473 : $self->{type} eq 'addresses' ? SL::Controller::CsvImport::Shipto->new(@args)
474 : $self->{type} eq 'parts' ? SL::Controller::CsvImport::Part->new(@args)
475 : $self->{type} eq 'projects' ? SL::Controller::CsvImport::Project->new(@args)
476 : die "Program logic error";
482 $self->worker->setup_displayable_columns;
486 my ($self, %params) = @_;
488 for my $tracker ($self->progress_tracker) {
489 $tracker->track_progress(%params);
493 sub init_task_server {
494 SL::System::TaskServer->new;
497 sub cleanup_reports {
498 SL::DB::Manager::CsvImportReport->cleanup;
501 sub check_task_server {
502 return 1 if $_[0]->task_server->is_running;
504 flash('info', t8('The task server is not running at the moment but needed for this module'));