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::Controller::CsvImport::Order;
19 use SL::BackgroundJob::CsvImport;
20 use SL::System::TaskServer;
22 use List::MoreUtils qw(none);
23 use List::Util qw(min);
25 use parent qw(SL::Controller::Base);
27 use Rose::Object::MakeMethods::Generic
29 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
30 import_status errors headers raw_data_headers info_headers data num_imported num_importable displayable_columns file) ],
31 'scalar --get_set_init' => [ qw(worker task_server) ],
33 progress_tracker => { },
34 add_progress_tracker => { interface => 'add', hash_key => 'progress_tracker' },
38 __PACKAGE__->run_before('check_auth');
39 __PACKAGE__->run_before('ensure_form_structure');
40 __PACKAGE__->run_before('check_type', except => [ qw(report) ]);
41 __PACKAGE__->run_before('load_all_profiles');
42 __PACKAGE__->run_before('check_task_server');
44 __PACKAGE__->run_after('cleanup_reports');
53 $self->load_default_profile unless $self->profile;
59 $self->test_and_import_deferred(test => 1);
64 $self->test_and_import_deferred(test => 0);
70 $self->profile_from_form(SL::DB::Manager::CsvImportProfile->find_by(name => $::form->{profile}->{name}, login => $::myconfig{login}));
73 flash_later('info', $::locale->text("The profile has been saved under the name '#1'.", $self->profile->name));
74 $self->redirect_to(action => 'new', 'profile.type' => $self->type, 'profile.id' => $self->profile->id);
80 my $profile = SL::DB::CsvImportProfile->new(id => $::form->{profile}->{id}, login => $::myconfig{login});
81 $profile->delete(cascade => 1);
83 flash_later('info', $::locale->text('The profile \'#1\' has been deleted.', $profile->name));
84 $self->redirect_to(action => 'new', 'profile.type' => $self->type);
91 $self->{background_job} = SL::DB::Manager::BackgroundJob->find_by(id => $::form->{job});
93 my $data = $self->{background_job}->data_as_hash;
95 my $profile = SL::DB::Manager::CsvImportProfile->find_by(id => $data->{profile_id});
97 $self->profile($profile);
99 if ($data->{errors} and my $first_error = $data->{errors}->[0]) {
100 flash('error', $::locale->text('There was an error parsing the csv file: #1 in line #2.', $first_error->[2], $first_error->[0]));
103 if ($data->{progress}{finished} || $data->{errors}) {
104 $self->render('csv_import/_deferred_report', { layout => 0 });
106 if (!$self->task_server->is_running) {
107 $self->task_server->start;
108 $self->{status_text} = t8('Task Server is not running, starting it now. If this does not change, please check your task server config');
109 } elsif (my $phase = $data->{progress}{phase}) {
110 $self->{status_text} = "$data->{progress}{plan}{$phase} / $data->{progress}{num_phases} " . t8($phase);
112 $self->{status_text} = t8('Import not started yet, please wait...');
115 $self->render('csv_import/_deferred_results', { layout => 0 });
119 sub action_download_sample {
122 $self->profile_from_form;
125 my $file_name = 'csv_import_sample_' . $self->type . '.csv';
126 my $file = SL::SessionFile->new($file_name, mode => '>', encoding => $self->profile->get('charset'));
127 my $csv = Text::CSV_XS->new({ binary => 1, map { ( $_ => $self->profile->get($_) ) } qw(sep_char escape_char quote_char),});
129 if ($self->worker->is_multiplexed) {
130 foreach my $p (@{ $self->worker->profile }) {
131 $csv->print($file->fh, [ map { $_->{name} } @{ $self->displayable_columns->{$p->{row_ident}} } ]);
132 $file->fh->print("\r\n");
134 foreach my $p (@{ $self->worker->profile }) {
135 $csv->print($file->fh, [ map { $_->{description} } @{ $self->displayable_columns->{$p->{row_ident}} } ]);
136 $file->fh->print("\r\n");
139 $csv->print($file->fh, [ map { $_->{name} } @{ $self->displayable_columns } ]);
140 $file->fh->print("\r\n");
141 $csv->print($file->fh, [ map { $_->{description} } @{ $self->displayable_columns } ]);
142 $file->fh->print("\r\n");
147 $self->send_file($file->file_name, name => $file_name);
151 my ($self, %params) = @_;
153 my $report_id = $params{report_id} || $::form->{id};
155 $self->{report} = SL::DB::Manager::CsvImportReport->find_by(id => $report_id);
157 if (!$self->{report}) {
158 $::form->error(t8('No report with id #1', $report_id));
160 my $num_rows = $self->{report}->numrows;
161 my $num_cols = SL::DB::Manager::CsvImportReportRow->get_all_count(query => [ csv_import_report_id => $report_id, row => 0 ]);
163 # manual paginating, yuck
164 my $page = $::form->{page} || 1;
166 $pages->{per_page} = $::form->{per_page} || 20;
167 $pages->{max} = SL::DB::Helper::Paginated::ceil($num_rows, $pages->{per_page}) || 1;
168 $pages->{cur} = $page < 1 ? 1
169 : $page > $pages->{max} ? $pages->{max}
171 $pages->{common} = [ grep { $_->{visible} } @{ SL::DB::Helper::Paginated::make_common_pages($pages->{cur}, $pages->{max}) } ];
173 $self->{report_numheaders} = $self->{report}->numheaders;
174 my $first_row_header = 0;
175 my $last_row_header = $self->{report_numheaders} - 1;
176 my $first_row_data = $pages->{per_page} * ($pages->{cur}-1) + $self->{report_numheaders};
177 my $last_row_data = min($pages->{per_page} * $pages->{cur}, $num_rows) + $self->{report_numheaders} - 1;
178 $self->{display_rows} = [
188 csv_import_report_id => $report_id,
191 row => { ge => $first_row_header },
192 row => { le => $last_row_header },
195 row => { ge => $first_row_data },
196 row => { le => $last_row_data },
201 my $rows = SL::DB::Manager::CsvImportReportRow->get_all(query => \@query);
202 my $status = SL::DB::Manager::CsvImportReportStatus->get_all(query => \@query);
204 $self->{report_rows} = $self->{report}->folded_rows(rows => $rows);
205 $self->{report_status} = $self->{report}->folded_status(status => $status);
206 $self->{pages} = $pages;
207 $self->{base_url} = $self->url_for(action => 'report', id => $report_id, no_layout => $params{no_layout} || $::form->{no_layout} );
209 $self->render('csv_import/report', { layout => !($params{no_layout} || $::form->{no_layout}) });
218 $::auth->assert('config');
224 die "Invalid CSV import type" if none { $_ eq $::form->{profile}->{type} } qw(parts customers_vendors addresses contacts projects orders);
225 $self->type($::form->{profile}->{type});
228 sub ensure_form_structure {
229 my ($self, %params) = @_;
231 $::form->{profile} = {} unless ref $::form->{profile} eq 'HASH';
232 $::form->{settings} = {} unless ref $::form->{settings} eq 'HASH';
240 my ($self, %params) = @_;
242 $self->all_charsets([ [ 'UTF-8', 'UTF-8' ],
243 [ 'ISO-8859-1', 'ISO-8859-1 (Latin 1)' ],
244 [ 'ISO-8859-15', 'ISO-8859-15 (Latin 9)' ],
245 [ 'CP850', 'CP850 (DOS/ANSI)' ],
246 [ 'CP1252', 'CP1252 (Windows)' ],
249 my %char_map = $self->char_map;
251 foreach my $type (qw(sep quote escape)) {
252 my $sub = "all_${type}_chars";
253 $self->$sub([ sort { $a->[0] cmp $b->[0] } values %{ $char_map{$type} } ]);
255 my $char = $self->profile->get($type . '_char');
256 $sub = "${type}_char";
257 $self->$sub(($char_map{$type}->{$char} || [])->[0] || $char);
260 $self->file(SL::SessionFile->new($self->csv_file_name));
262 my $title = $self->type eq 'customers_vendors' ? $::locale->text('CSV import: customers and vendors')
263 : $self->type eq 'addresses' ? $::locale->text('CSV import: shipping addresses')
264 : $self->type eq 'contacts' ? $::locale->text('CSV import: contacts')
265 : $self->type eq 'parts' ? $::locale->text('CSV import: parts and services')
266 : $self->type eq 'projects' ? $::locale->text('CSV import: projects')
267 : $self->type eq 'orders' ? $::locale->text('CSV import: orders')
270 if ($self->{type} eq 'parts') {
271 $self->all_buchungsgruppen(SL::DB::Manager::Buchungsgruppe->get_all_sorted);
272 $self->all_units(SL::DB::Manager::Unit->get_all_sorted);
277 $self->render('csv_import/form', title => $title);
280 sub test_and_import_deferred {
281 my ($self, %params) = @_;
283 $self->profile_from_form;
285 if ($::form->{file}) {
286 my $file = SL::SessionFile->new($self->csv_file_name, mode => '>');
287 $file->fh->print($::form->{file});
291 my $file = SL::SessionFile->new($self->csv_file_name, mode => '<', encoding => $self->profile->get('charset'));
293 flash('error', $::locale->text('No file has been uploaded yet.'));
294 return $self->action_new;
297 $self->{background_job} = SL::BackgroundJob::CsvImport->create_job(
298 file => $self->csv_file_name,
299 profile => $self->profile,
300 type => $self->profile->type,
301 test => $params{test},
302 employee_id => SL::DB::Manager::Employee->current->id,
305 if ($self->task_server->is_running) {
306 $self->task_server->wake_up;
308 $self->task_server->start;
311 flash('info', $::locale->text('Your import is beig processed.'));
313 $self->{deferred} = 1;
315 $self->render_inputs;
318 sub test_and_import {
319 my ($self, %params) = @_;
321 my $file = SL::SessionFile->new(
322 $self->csv_file_name,
324 encoding => $self->profile->get('charset'),
325 session_id => $params{session_id}
330 my $worker = $self->worker();
332 $worker->run(%params);
334 return if $self->errors;
336 $self->num_imported(0);
337 $worker->save_objects if !$params{test};
339 $self->num_importable(scalar grep { !$_ } map { scalar @{ $_->{errors} } } @{ $self->data || [] });
340 $self->import_status($params{test} ? 'tested' : 'imported');
342 # flash('info', $::locale->text('Objects have been imported.')) if !$params{test};
345 sub load_default_profile {
349 if ($::form->{profile}->{id}) {
350 $profile = SL::DB::Manager::CsvImportProfile->find_by(id => $::form->{profile}->{id}, login => $::myconfig{login});
352 $profile ||= SL::DB::Manager::CsvImportProfile->find_by(type => $self->{type}, is_default => 1, login => $::myconfig{login});
353 $profile ||= SL::DB::CsvImportProfile->new(type => $self->{type}, login => $::myconfig{login});
355 $self->profile($profile);
356 $self->profile->set_defaults;
359 sub load_all_profiles {
360 my ($self, %params) = @_;
362 $self->all_profiles(SL::DB::Manager::CsvImportProfile->get_all(
365 login => $::myconfig{login},
370 sub profile_from_form {
371 my ($self, $existing_profile) = @_;
373 delete $::form->{profile}->{id};
375 my %char_map = $self->char_map;
378 foreach my $type (qw(sep quote escape)) {
379 my %rev_chars = map { $char_map{$type}->{$_}->[0] => $_ } keys %{ $char_map{$type} };
380 my $char = $::form->{"${type}_char"} eq 'custom' ? $::form->{"custom_${type}_char"} : $rev_chars{ $::form->{"${type}_char"} };
382 push @settings, { key => "${type}_char", value => $char };
385 if ($self->type eq 'parts') {
386 $::form->{settings}->{sellprice_adjustment} = $::form->parse_amount(\%::myconfig, $::form->{settings}->{sellprice_adjustment});
389 if ($self->type eq 'orders') {
390 $::form->{settings}->{max_amount_diff} = $::form->parse_amount(\%::myconfig, $::form->{settings}->{max_amount_diff});
393 delete $::form->{profile}->{id};
394 $self->profile($existing_profile || SL::DB::CsvImportProfile->new(login => $::myconfig{login}));
395 $self->profile->assign_attributes(%{ $::form->{profile} });
396 $self->profile->settings(map({ { key => $_, value => $::form->{settings}->{$_} } } keys %{ $::form->{settings} }),
398 $self->profile->set_defaults;
402 return ( sep => { ',' => [ 'comma', $::locale->text('Comma') ],
403 ';' => [ 'semicolon', $::locale->text('Semicolon') ],
404 "\t" => [ 'tab', $::locale->text('Tab') ],
405 ' ' => [ 'space', $::locale->text('Space') ],
407 quote => { '"' => [ 'quote', $::locale->text('Quotes') ],
408 "'" => [ 'singlequote', $::locale->text('Single quotes') ],
410 escape => { '"' => [ 'quote', $::locale->text('Quotes') ],
411 "'" => [ 'singlequote', $::locale->text('Single quotes') ],
417 my ($self, $report_id) = @_;
419 if ($self->worker->is_multiplexed) {
420 return $self->save_report_multi($report_id);
422 return $self->save_report_single($report_id);
426 sub save_report_single {
427 my ($self, $report_id) = @_;
429 $self->track_progress(phase => 'building report', progress => 0);
431 my $clone_profile = $self->profile->clone_and_reset_deep;
432 $clone_profile->save; # weird bug. if this isn't saved before adding it to the report, it will default back to the last profile.
434 my $report = SL::DB::CsvImportReport->new(
435 session_id => $::auth->create_or_refresh_session,
436 profile => $clone_profile,
439 numrows => scalar @{ $self->data },
443 $report->save(cascade => 1) or die $report->db->error;
445 my $dbh = $::form->get_standard_dbh;
448 my $query = 'INSERT INTO csv_import_report_rows (csv_import_report_id, col, row, value) VALUES (?, ?, ?, ?)';
449 my $query2 = 'INSERT INTO csv_import_report_status (csv_import_report_id, row, type, value) VALUES (?, ?, ?, ?)';
451 my $sth = $dbh->prepare($query);
452 my $sth2 = $dbh->prepare($query2);
455 my (@headers, @info_methods, @raw_methods, @methods);
457 for my $i (0 .. $#{ $self->info_headers->{headers} }) {
458 next unless $self->info_headers->{used}->{ $self->info_headers->{methods}->[$i] };
459 push @headers, $self->info_headers->{headers}->[$i];
460 push @info_methods, $self->info_headers->{methods}->[$i];
462 for my $i (0 .. $#{ $self->headers->{headers} }) {
463 next unless $self->headers->{used}->{ $self->headers->{headers}->[$i] };
464 push @headers, $self->headers->{headers}->[$i];
465 push @methods, $self->headers->{methods}->[$i];
467 for my $i (0 .. $#{ $self->raw_data_headers->{headers} }) {
468 next unless $self->raw_data_headers->{used}->{ $self->raw_data_headers->{headers}->[$i] };
469 push @headers, $self->raw_data_headers->{headers}->[$i];
470 push @raw_methods, $self->raw_data_headers->{headers}->[$i];
473 $sth->execute($report->id, $_, 0, $headers[$_]) for 0 .. $#headers;
476 my $o1 = @info_methods;
477 my $o2 = $o1 + @methods;
479 for my $row (0 .. $#{ $self->data }) {
480 $self->track_progress(progress => $row / @{ $self->data } * 100) if $row % 1000 == 0;
481 my $data_row = $self->{data}[$row];
483 $sth->execute($report->id, $_, $row + 1, $data_row->{info_data}{ $info_methods[$_] }) for 0 .. $#info_methods;
484 $sth->execute($report->id, $o1 + $_, $row + 1, $data_row->{object}->${ \ $methods[$_] }) for 0 .. $#methods;
485 $sth->execute($report->id, $o2 + $_, $row + 1, $data_row->{raw_data}{ $raw_methods[$_] }) for 0 .. $#raw_methods;
487 $sth2->execute($report->id, $row + 1, 'information', $_) for @{ $data_row->{information} || [] };
488 $sth2->execute($report->id, $row + 1, 'errors', $_) for @{ $data_row->{errors} || [] };
496 sub save_report_multi {
497 my ($self, $report_id) = @_;
499 $self->track_progress(phase => 'building report', progress => 0);
501 my $clone_profile = $self->profile->clone_and_reset_deep;
502 $clone_profile->save; # weird bug. if this isn't saved before adding it to the report, it will default back to the last profile.
504 my $report = SL::DB::CsvImportReport->new(
505 session_id => $::auth->create_or_refresh_session,
506 profile => $clone_profile,
509 numrows => scalar @{ $self->data },
510 numheaders => scalar @{ $self->worker->profile },
513 $report->save(cascade => 1) or die $report->db->error;
515 my $dbh = $::form->get_standard_dbh;
518 my $query = 'INSERT INTO csv_import_report_rows (csv_import_report_id, col, row, value) VALUES (?, ?, ?, ?)';
519 my $query2 = 'INSERT INTO csv_import_report_status (csv_import_report_id, row, type, value) VALUES (?, ?, ?, ?)';
521 my $sth = $dbh->prepare($query);
522 my $sth2 = $dbh->prepare($query2);
525 my ($headers, $info_methods, $raw_methods, $methods);
527 for my $i (0 .. $#{ $self->worker->profile }) {
528 my $row_ident = $self->worker->profile->[$i]->{row_ident};
530 for my $i (0 .. $#{ $self->info_headers->{$row_ident}->{headers} }) {
531 next unless $self->info_headers->{$row_ident}->{used}->{ $self->info_headers->{$row_ident}->{methods}->[$i] };
532 push @{ $headers->{$row_ident} }, $self->info_headers->{$row_ident}->{headers}->[$i];
533 push @{ $info_methods->{$row_ident} }, $self->info_headers->{$row_ident}->{methods}->[$i];
535 for my $i (0 .. $#{ $self->headers->{$row_ident}->{headers} }) {
536 next unless $self->headers->{$row_ident}->{used}->{ $self->headers->{$row_ident}->{headers}->[$i] };
537 push @{ $headers->{$row_ident} }, $self->headers->{$row_ident}->{headers}->[$i];
538 push @{ $methods->{$row_ident} }, $self->headers->{$row_ident}->{methods}->[$i];
541 for my $i (0 .. $#{ $self->raw_data_headers->{$row_ident}->{headers} }) {
542 next unless $self->raw_data_headers->{$row_ident}->{used}->{ $self->raw_data_headers->{$row_ident}->{headers}->[$i] };
543 push @{ $headers->{$row_ident} }, $self->raw_data_headers->{$row_ident}->{headers}->[$i];
544 push @{ $raw_methods->{$row_ident} }, $self->raw_data_headers->{$row_ident}->{headers}->[$i];
549 for my $i (0 .. $#{ $self->worker->profile }) {
550 my $row_ident = $self->worker->profile->[$i]->{row_ident};
551 $sth->execute($report->id, $_, $i, $headers->{$row_ident}->[$_]) for 0 .. $#{ $headers->{$row_ident} };
556 for my $i (0 .. $#{ $self->worker->profile }) {
557 my $row_ident = $self->worker->profile->[$i]->{row_ident};
558 my $n_info_methods = $info_methods->{$row_ident} ? scalar @{ $info_methods->{$row_ident} } : 0;
559 my $n_methods = $methods->{$row_ident} ? scalar @{ $methods->{$row_ident} } : 0;
561 $off1->{$row_ident} = $n_info_methods;
562 $off2->{$row_ident} = $off1->{$row_ident} + $n_methods;
565 my $n_header_rows = scalar @{ $self->worker->profile };
567 for my $row (0 .. $#{ $self->data }) {
568 $self->track_progress(progress => $row / @{ $self->data } * 100) if $row % 1000 == 0;
569 my $data_row = $self->{data}[$row];
570 my $row_ident = $data_row->{raw_data}{datatype};
572 my $o1 = $off1->{$row_ident};
573 my $o2 = $off2->{$row_ident};
575 $sth->execute($report->id, $_, $row + $n_header_rows, $data_row->{info_data}{ $info_methods->{$row_ident}->[$_] }) for 0 .. $#{ $info_methods->{$row_ident} };
576 $sth->execute($report->id, $o1 + $_, $row + $n_header_rows, $data_row->{object}->${ \ $methods->{$row_ident}->[$_] }) for 0 .. $#{ $methods->{$row_ident} };
577 $sth->execute($report->id, $o2 + $_, $row + $n_header_rows, $data_row->{raw_data}{ $raw_methods->{$row_ident}->[$_] }) for 0 .. $#{ $raw_methods->{$row_ident} };
579 $sth2->execute($report->id, $row + $n_header_rows, 'information', $_) for @{ $data_row->{information} || [] };
580 $sth2->execute($report->id, $row + $n_header_rows, 'errors', $_) for @{ $data_row->{errors} || [] };
590 return "csv-import-" . $self->type . ".csv";
596 my @args = (controller => $self);
598 if ( $self->file() ) {
599 push(@args, file => $self->file());
602 return $self->{type} eq 'customers_vendors' ? SL::Controller::CsvImport::CustomerVendor->new(@args)
603 : $self->{type} eq 'contacts' ? SL::Controller::CsvImport::Contact->new(@args)
604 : $self->{type} eq 'addresses' ? SL::Controller::CsvImport::Shipto->new(@args)
605 : $self->{type} eq 'parts' ? SL::Controller::CsvImport::Part->new(@args)
606 : $self->{type} eq 'projects' ? SL::Controller::CsvImport::Project->new(@args)
607 : $self->{type} eq 'orders' ? SL::Controller::CsvImport::Order->new(@args)
608 : die "Program logic error";
614 $self->worker->setup_displayable_columns;
618 my ($self, %params) = @_;
620 for my $tracker ($self->progress_tracker) {
621 $tracker->track_progress(%params);
625 sub init_task_server {
626 SL::System::TaskServer->new;
629 sub cleanup_reports {
630 SL::DB::Manager::CsvImportReport->cleanup;
633 sub check_task_server {
634 return 1 if $_[0]->task_server->is_running;
636 flash('info', t8('The task server is not running at the moment but needed for this module'));