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::Inventory;
17 use SL::Controller::CsvImport::Shipto;
18 use SL::Controller::CsvImport::Project;
19 use SL::Controller::CsvImport::Order;
20 use SL::BackgroundJob::CsvImport;
21 use SL::System::TaskServer;
23 use List::MoreUtils qw(none);
24 use List::Util qw(min);
26 use parent qw(SL::Controller::Base);
28 use Rose::Object::MakeMethods::Generic
30 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
31 import_status errors headers raw_data_headers info_headers data num_imported num_importable displayable_columns file all_taxzones) ],
32 'scalar --get_set_init' => [ qw(worker task_server) ],
34 progress_tracker => { },
35 add_progress_tracker => { interface => 'add', hash_key => 'progress_tracker' },
39 __PACKAGE__->run_before('check_auth');
40 __PACKAGE__->run_before('ensure_form_structure');
41 __PACKAGE__->run_before('check_type', except => [ qw(report) ]);
42 __PACKAGE__->run_before('load_all_profiles');
43 __PACKAGE__->run_before('check_task_server');
45 __PACKAGE__->run_after('cleanup_reports');
54 $self->load_default_profile unless $self->profile;
60 $self->test_and_import_deferred(test => 1);
65 $self->test_and_import_deferred(test => 0);
71 $self->profile_from_form(SL::DB::Manager::CsvImportProfile->find_by(name => $::form->{profile}->{name}, login => $::myconfig{login}));
74 flash_later('info', $::locale->text("The profile has been saved under the name '#1'.", $self->profile->name));
75 $self->redirect_to(action => 'new', 'profile.type' => $self->type, 'profile.id' => $self->profile->id);
81 my $profile = SL::DB::CsvImportProfile->new(id => $::form->{profile}->{id}, login => $::myconfig{login});
82 $profile->delete(cascade => 1);
84 flash_later('info', $::locale->text('The profile \'#1\' has been deleted.', $profile->name));
85 $self->redirect_to(action => 'new', 'profile.type' => $self->type);
92 $self->{background_job} = SL::DB::Manager::BackgroundJob->find_by(id => $::form->{job});
94 my $data = $self->{background_job}->data_as_hash;
96 my $profile = SL::DB::Manager::CsvImportProfile->find_by(id => $data->{profile_id});
98 $self->profile($profile);
100 if ($data->{errors} and my $first_error = $data->{errors}->[0]) {
101 flash('error', $::locale->text('There was an error parsing the csv file: #1 in line #2.', $first_error->[2], $first_error->[0]));
104 if ($data->{progress}{finished} || $data->{errors}) {
105 $self->render('csv_import/_deferred_report', { layout => 0 });
107 if (!$self->task_server->is_running) {
108 $self->task_server->start;
109 $self->{status_text} = t8('Task Server is not running, starting it now. If this does not change, please check your task server config');
110 } elsif (my $phase = $data->{progress}{phase}) {
111 $self->{status_text} = "$data->{progress}{plan}{$phase} / $data->{progress}{num_phases} " . t8($phase);
113 $self->{status_text} = t8('Import not started yet, please wait...');
116 $self->render('csv_import/_deferred_results', { layout => 0 });
120 sub action_download_sample {
123 $self->profile_from_form;
126 my $file_name = 'csv_import_sample_' . $self->type . '.csv';
127 my $file = SL::SessionFile->new($file_name, mode => '>', encoding => $self->profile->get('charset'));
128 my $csv = Text::CSV_XS->new({ binary => 1, map { ( $_ => $self->profile->get($_) ) } qw(sep_char escape_char quote_char),});
130 if ($self->worker->is_multiplexed) {
131 foreach my $p (@{ $self->worker->profile }) {
132 $csv->print($file->fh, [ map { $_->{name} } @{ $self->displayable_columns->{$p->{row_ident}} } ]);
133 $file->fh->print("\r\n");
135 foreach my $p (@{ $self->worker->profile }) {
136 $csv->print($file->fh, [ map { $_->{description} } @{ $self->displayable_columns->{$p->{row_ident}} } ]);
137 $file->fh->print("\r\n");
140 $csv->print($file->fh, [ map { $_->{name} } @{ $self->displayable_columns } ]);
141 $file->fh->print("\r\n");
142 $csv->print($file->fh, [ map { $_->{description} } @{ $self->displayable_columns } ]);
143 $file->fh->print("\r\n");
148 $self->send_file($file->file_name, name => $file_name);
152 my ($self, %params) = @_;
154 my $report_id = $params{report_id} || $::form->{id};
156 $self->{report} = SL::DB::Manager::CsvImportReport->find_by(id => $report_id);
158 if (!$self->{report}) {
159 $::form->error(t8('No report with id #1', $report_id));
161 my $num_rows = $self->{report}->numrows;
162 my $num_cols = SL::DB::Manager::CsvImportReportRow->get_all_count(query => [ csv_import_report_id => $report_id, row => 0 ]);
164 # manual paginating, yuck
165 my $page = $::form->{page} || 1;
167 $pages->{per_page} = $::form->{per_page} || 20;
168 $pages->{max} = SL::DB::Helper::Paginated::ceil($num_rows, $pages->{per_page}) || 1;
169 $pages->{page} = $page < 1 ? 1
170 : $page > $pages->{max} ? $pages->{max}
172 $pages->{common} = [ grep { $_->{visible} } @{ SL::DB::Helper::Paginated::make_common_pages($pages->{page}, $pages->{max}) } ];
174 $self->{report_numheaders} = $self->{report}->numheaders;
175 my $first_row_header = 0;
176 my $last_row_header = $self->{report_numheaders} - 1;
177 my $first_row_data = $pages->{per_page} * ($pages->{page}-1) + $self->{report_numheaders};
178 my $last_row_data = min($pages->{per_page} * $pages->{page}, $num_rows) + $self->{report_numheaders} - 1;
179 $self->{display_rows} = [
189 csv_import_report_id => $report_id,
192 row => { ge => $first_row_header },
193 row => { le => $last_row_header },
196 row => { ge => $first_row_data },
197 row => { le => $last_row_data },
202 my $rows = SL::DB::Manager::CsvImportReportRow->get_all(query => \@query);
203 my $status = SL::DB::Manager::CsvImportReportStatus->get_all(query => \@query);
205 $self->{report_rows} = $self->{report}->folded_rows(rows => $rows);
206 $self->{report_status} = $self->{report}->folded_status(status => $status);
207 $self->{pages} = $pages;
208 $self->{base_url} = $self->url_for(action => 'report', id => $report_id, no_layout => $params{no_layout} || $::form->{no_layout} );
210 $self->render('csv_import/report', { layout => !($params{no_layout} || $::form->{no_layout}) });
219 $::auth->assert('config');
225 die "Invalid CSV import type" if none { $_ eq $::form->{profile}->{type} } qw(parts inventories customers_vendors addresses contacts projects orders);
226 $self->type($::form->{profile}->{type});
229 sub ensure_form_structure {
230 my ($self, %params) = @_;
232 $::form->{profile} = {} unless ref $::form->{profile} eq 'HASH';
233 $::form->{settings} = {} unless ref $::form->{settings} eq 'HASH';
241 my ($self, %params) = @_;
243 $self->all_charsets([ [ 'UTF-8', 'UTF-8' ],
244 [ 'ISO-8859-1', 'ISO-8859-1 (Latin 1)' ],
245 [ 'ISO-8859-15', 'ISO-8859-15 (Latin 9)' ],
246 [ 'CP850', 'CP850 (DOS/ANSI)' ],
247 [ 'CP1252', 'CP1252 (Windows)' ],
250 my %char_map = $self->char_map;
252 foreach my $type (qw(sep quote escape)) {
253 my $sub = "all_${type}_chars";
254 $self->$sub([ sort { $a->[0] cmp $b->[0] } values %{ $char_map{$type} } ]);
256 my $char = $self->profile->get($type . '_char');
257 $sub = "${type}_char";
258 $self->$sub(($char_map{$type}->{$char} || [])->[0] || $char);
261 $self->file(SL::SessionFile->new($self->csv_file_name));
263 my $title = $self->type eq 'customers_vendors' ? $::locale->text('CSV import: customers and vendors')
264 : $self->type eq 'addresses' ? $::locale->text('CSV import: shipping addresses')
265 : $self->type eq 'contacts' ? $::locale->text('CSV import: contacts')
266 : $self->type eq 'parts' ? $::locale->text('CSV import: parts and services')
267 : $self->type eq 'inventories' ? $::locale->text('CSV import: inventories')
268 : $self->type eq 'projects' ? $::locale->text('CSV import: projects')
269 : $self->type eq 'orders' ? $::locale->text('CSV import: orders')
272 if ($self->{type} eq 'customers_vendors' or $self->{type} eq 'orders' ) {
273 $self->all_taxzones(SL::DB::Manager::TaxZone->get_all_sorted(query => [ obsolete => 0 ]));
276 if ($self->{type} eq 'parts') {
277 $self->all_buchungsgruppen(SL::DB::Manager::Buchungsgruppe->get_all_sorted);
278 $self->all_units(SL::DB::Manager::Unit->get_all_sorted);
283 $self->render('csv_import/form', title => $title);
286 sub test_and_import_deferred {
287 my ($self, %params) = @_;
289 $self->profile_from_form;
291 if ($::form->{file}) {
292 my $file = SL::SessionFile->new($self->csv_file_name, mode => '>');
293 $file->fh->print($::form->{file});
297 my $file = SL::SessionFile->new($self->csv_file_name, mode => '<', encoding => $self->profile->get('charset'));
299 flash('error', $::locale->text('No file has been uploaded yet.'));
300 return $self->action_new;
303 $self->{background_job} = SL::BackgroundJob::CsvImport->create_job(
304 file => $self->csv_file_name,
305 profile => $self->profile,
306 type => $self->profile->type,
307 test => $params{test},
308 employee_id => SL::DB::Manager::Employee->current->id,
311 if ($self->task_server->is_running) {
312 $self->task_server->wake_up;
314 $self->task_server->start;
317 flash('info', $::locale->text('Your import is being processed.'));
319 $self->{deferred} = 1;
321 $self->render_inputs;
324 sub test_and_import {
325 my ($self, %params) = @_;
327 my $file = SL::SessionFile->new(
328 $self->csv_file_name,
330 encoding => $self->profile->get('charset'),
331 session_id => $params{session_id}
336 my $worker = $self->worker();
338 $worker->run(%params);
340 return if $self->errors;
342 $self->num_imported(0);
343 $worker->save_objects if !$params{test};
345 $self->num_importable(scalar grep { !$_ } map { scalar @{ $_->{errors} } } @{ $self->data || [] });
346 $self->import_status($params{test} ? 'tested' : 'imported');
348 # flash('info', $::locale->text('Objects have been imported.')) if !$params{test};
351 sub load_default_profile {
355 if ($::form->{profile}->{id}) {
356 $profile = SL::DB::Manager::CsvImportProfile->find_by(id => $::form->{profile}->{id}, login => $::myconfig{login});
358 $profile ||= SL::DB::Manager::CsvImportProfile->find_by(type => $self->{type}, is_default => 1, login => $::myconfig{login});
359 $profile ||= SL::DB::CsvImportProfile->new(type => $self->{type}, login => $::myconfig{login});
361 $self->profile($profile);
362 $self->profile->set_defaults;
365 sub load_all_profiles {
366 my ($self, %params) = @_;
368 $self->all_profiles(SL::DB::Manager::CsvImportProfile->get_all(
371 login => $::myconfig{login},
377 sub profile_from_form {
378 my ($self, $existing_profile) = @_;
380 delete $::form->{profile}->{id};
382 my %char_map = $self->char_map;
385 foreach my $type (qw(sep quote escape)) {
386 my %rev_chars = map { $char_map{$type}->{$_}->[0] => $_ } keys %{ $char_map{$type} };
387 my $char = $::form->{"${type}_char"} eq 'custom' ? $::form->{"custom_${type}_char"} : $rev_chars{ $::form->{"${type}_char"} };
389 push @settings, { key => "${type}_char", value => $char };
392 if ($self->type eq 'parts') {
393 $::form->{settings}->{sellprice_adjustment} = $::form->parse_amount(\%::myconfig, $::form->{settings}->{sellprice_adjustment});
396 if ($self->type eq 'orders') {
397 $::form->{settings}->{max_amount_diff} = $::form->parse_amount(\%::myconfig, $::form->{settings}->{max_amount_diff});
400 delete $::form->{profile}->{id};
401 $self->profile($existing_profile || SL::DB::CsvImportProfile->new(login => $::myconfig{login}));
402 $self->profile->assign_attributes(%{ $::form->{profile} });
403 $self->profile->settings(map({ { key => $_, value => $::form->{settings}->{$_} } } keys %{ $::form->{settings} }),
405 $self->profile->set_defaults;
409 return ( sep => { ',' => [ 'comma', $::locale->text('Comma') ],
410 ';' => [ 'semicolon', $::locale->text('Semicolon') ],
411 "\t" => [ 'tab', $::locale->text('Tab') ],
412 ' ' => [ 'space', $::locale->text('Space') ],
414 quote => { '"' => [ 'quote', $::locale->text('Quotes') ],
415 "'" => [ 'singlequote', $::locale->text('Single quotes') ],
417 escape => { '"' => [ 'quote', $::locale->text('Quotes') ],
418 "'" => [ 'singlequote', $::locale->text('Single quotes') ],
424 my ($self, %params) = @_;
426 if ($self->worker->is_multiplexed) {
427 return $self->save_report_multi(%params);
429 return $self->save_report_single(%params);
433 sub save_report_single {
434 my ($self, %params) = @_;
436 $self->track_progress(phase => 'building report', progress => 0);
438 my $clone_profile = $self->profile->clone_and_reset_deep;
439 $clone_profile->save; # weird bug. if this isn't saved before adding it to the report, it will default back to the last profile.
441 my $report = SL::DB::CsvImportReport->new(
442 session_id => $params{session_id},
443 profile => $clone_profile,
446 numrows => scalar @{ $self->data },
450 $report->save(cascade => 1) or die $report->db->error;
452 my $dbh = $::form->get_standard_dbh;
455 my $query = 'INSERT INTO csv_import_report_rows (csv_import_report_id, col, row, value) VALUES (?, ?, ?, ?)';
456 my $query2 = 'INSERT INTO csv_import_report_status (csv_import_report_id, row, type, value) VALUES (?, ?, ?, ?)';
458 my $sth = $dbh->prepare($query);
459 my $sth2 = $dbh->prepare($query2);
462 my (@headers, @info_methods, @raw_methods, @methods);
464 for my $i (0 .. $#{ $self->info_headers->{headers} }) {
465 next unless $self->info_headers->{used}->{ $self->info_headers->{methods}->[$i] };
466 push @headers, $self->info_headers->{headers}->[$i];
467 push @info_methods, $self->info_headers->{methods}->[$i];
469 for my $i (0 .. $#{ $self->headers->{headers} }) {
470 next unless $self->headers->{used}->{ $self->headers->{headers}->[$i] };
471 push @headers, $self->headers->{headers}->[$i];
472 push @methods, $self->headers->{methods}->[$i];
474 for my $i (0 .. $#{ $self->raw_data_headers->{headers} }) {
475 next unless $self->raw_data_headers->{used}->{ $self->raw_data_headers->{headers}->[$i] };
476 push @headers, $self->raw_data_headers->{headers}->[$i];
477 push @raw_methods, $self->raw_data_headers->{headers}->[$i];
480 $sth->execute($report->id, $_, 0, $headers[$_]) for 0 .. $#headers;
483 my $o1 = @info_methods;
484 my $o2 = $o1 + @methods;
486 for my $row (0 .. $#{ $self->data }) {
487 $self->track_progress(progress => $row / @{ $self->data } * 100) if $row % 1000 == 0;
488 my $data_row = $self->{data}[$row];
490 $sth->execute($report->id, $_, $row + 1, $data_row->{info_data}{ $info_methods[$_] }) for 0 .. $#info_methods;
491 $sth->execute($report->id, $o1 + $_, $row + 1, $data_row->{object}->${ \ $methods[$_] }) for 0 .. $#methods;
492 $sth->execute($report->id, $o2 + $_, $row + 1, $data_row->{raw_data}{ $raw_methods[$_] }) for 0 .. $#raw_methods;
494 $sth2->execute($report->id, $row + 1, 'information', $_) for @{ $data_row->{information} || [] };
495 $sth2->execute($report->id, $row + 1, 'errors', $_) for @{ $data_row->{errors} || [] };
503 sub save_report_multi {
504 my ($self, %params) = @_;
506 $self->track_progress(phase => 'building report', progress => 0);
508 my $clone_profile = $self->profile->clone_and_reset_deep;
509 $clone_profile->save; # weird bug. if this isn't saved before adding it to the report, it will default back to the last profile.
511 my $report = SL::DB::CsvImportReport->new(
512 session_id => $params{session_id},
513 profile => $clone_profile,
516 numrows => scalar @{ $self->data },
517 numheaders => scalar @{ $self->worker->profile },
520 $report->save(cascade => 1) or die $report->db->error;
522 my $dbh = $::form->get_standard_dbh;
525 my $query = 'INSERT INTO csv_import_report_rows (csv_import_report_id, col, row, value) VALUES (?, ?, ?, ?)';
526 my $query2 = 'INSERT INTO csv_import_report_status (csv_import_report_id, row, type, value) VALUES (?, ?, ?, ?)';
528 my $sth = $dbh->prepare($query);
529 my $sth2 = $dbh->prepare($query2);
532 my ($headers, $info_methods, $raw_methods, $methods);
534 for my $i (0 .. $#{ $self->worker->profile }) {
535 my $row_ident = $self->worker->profile->[$i]->{row_ident};
537 for my $i (0 .. $#{ $self->info_headers->{$row_ident}->{headers} }) {
538 next unless $self->info_headers->{$row_ident}->{used}->{ $self->info_headers->{$row_ident}->{methods}->[$i] };
539 push @{ $headers->{$row_ident} }, $self->info_headers->{$row_ident}->{headers}->[$i];
540 push @{ $info_methods->{$row_ident} }, $self->info_headers->{$row_ident}->{methods}->[$i];
542 for my $i (0 .. $#{ $self->headers->{$row_ident}->{headers} }) {
543 next unless $self->headers->{$row_ident}->{used}->{ $self->headers->{$row_ident}->{headers}->[$i] };
544 push @{ $headers->{$row_ident} }, $self->headers->{$row_ident}->{headers}->[$i];
545 push @{ $methods->{$row_ident} }, $self->headers->{$row_ident}->{methods}->[$i];
548 for my $i (0 .. $#{ $self->raw_data_headers->{$row_ident}->{headers} }) {
549 next unless $self->raw_data_headers->{$row_ident}->{used}->{ $self->raw_data_headers->{$row_ident}->{headers}->[$i] };
550 push @{ $headers->{$row_ident} }, $self->raw_data_headers->{$row_ident}->{headers}->[$i];
551 push @{ $raw_methods->{$row_ident} }, $self->raw_data_headers->{$row_ident}->{headers}->[$i];
556 for my $i (0 .. $#{ $self->worker->profile }) {
557 my $row_ident = $self->worker->profile->[$i]->{row_ident};
558 $sth->execute($report->id, $_, $i, $headers->{$row_ident}->[$_]) for 0 .. $#{ $headers->{$row_ident} };
563 for my $i (0 .. $#{ $self->worker->profile }) {
564 my $row_ident = $self->worker->profile->[$i]->{row_ident};
565 my $n_info_methods = $info_methods->{$row_ident} ? scalar @{ $info_methods->{$row_ident} } : 0;
566 my $n_methods = $methods->{$row_ident} ? scalar @{ $methods->{$row_ident} } : 0;
568 $off1->{$row_ident} = $n_info_methods;
569 $off2->{$row_ident} = $off1->{$row_ident} + $n_methods;
572 my $n_header_rows = scalar @{ $self->worker->profile };
574 for my $row (0 .. $#{ $self->data }) {
575 $self->track_progress(progress => $row / @{ $self->data } * 100) if $row % 1000 == 0;
576 my $data_row = $self->{data}[$row];
577 my $row_ident = $data_row->{raw_data}{datatype};
579 my $o1 = $off1->{$row_ident};
580 my $o2 = $off2->{$row_ident};
582 $sth->execute($report->id, $_, $row + $n_header_rows, $data_row->{info_data}{ $info_methods->{$row_ident}->[$_] }) for 0 .. $#{ $info_methods->{$row_ident} };
583 $sth->execute($report->id, $o1 + $_, $row + $n_header_rows, $data_row->{object}->${ \ $methods->{$row_ident}->[$_] }) for 0 .. $#{ $methods->{$row_ident} };
584 $sth->execute($report->id, $o2 + $_, $row + $n_header_rows, $data_row->{raw_data}{ $raw_methods->{$row_ident}->[$_] }) for 0 .. $#{ $raw_methods->{$row_ident} };
586 $sth2->execute($report->id, $row + $n_header_rows, 'information', $_) for @{ $data_row->{information} || [] };
587 $sth2->execute($report->id, $row + $n_header_rows, 'errors', $_) for @{ $data_row->{errors} || [] };
597 return "csv-import-" . $self->type . ".csv";
603 my @args = (controller => $self);
605 if ( $self->file() ) {
606 push(@args, file => $self->file());
609 return $self->{type} eq 'customers_vendors' ? SL::Controller::CsvImport::CustomerVendor->new(@args)
610 : $self->{type} eq 'contacts' ? SL::Controller::CsvImport::Contact->new(@args)
611 : $self->{type} eq 'addresses' ? SL::Controller::CsvImport::Shipto->new(@args)
612 : $self->{type} eq 'parts' ? SL::Controller::CsvImport::Part->new(@args)
613 : $self->{type} eq 'inventories' ? SL::Controller::CsvImport::Inventory->new(@args)
614 : $self->{type} eq 'projects' ? SL::Controller::CsvImport::Project->new(@args)
615 : $self->{type} eq 'orders' ? SL::Controller::CsvImport::Order->new(@args)
616 : die "Program logic error";
622 $self->worker->setup_displayable_columns;
626 my ($self, %params) = @_;
628 for my $tracker ($self->progress_tracker) {
629 $tracker->track_progress(%params);
633 sub init_task_server {
634 SL::System::TaskServer->new;
637 sub cleanup_reports {
638 SL::DB::Manager::CsvImportReport->cleanup;
641 sub check_task_server {
642 return 1 if $_[0]->task_server->is_running;
644 flash('info', t8('The task server is not running at the moment but needed for this module'));