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;
21 use SL::Controller::CsvImport::BankTransaction;
22 use SL::BackgroundJob::CsvImport;
23 use SL::System::TaskServer;
25 use List::MoreUtils qw(none);
26 use List::Util qw(min);
28 use parent qw(SL::Controller::Base);
30 use Rose::Object::MakeMethods::Generic
32 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
33 import_status errors headers raw_data_headers info_headers data num_imported num_importable displayable_columns file all_taxzones) ],
34 'scalar --get_set_init' => [ qw(worker task_server) ],
36 progress_tracker => { },
37 add_progress_tracker => { interface => 'add', hash_key => 'progress_tracker' },
41 __PACKAGE__->run_before('check_auth');
42 __PACKAGE__->run_before('ensure_form_structure');
43 __PACKAGE__->run_before('check_type', except => [ qw(report) ]);
44 __PACKAGE__->run_before('load_all_profiles');
45 __PACKAGE__->run_before('check_task_server');
47 __PACKAGE__->run_after('cleanup_reports');
56 $self->load_default_profile unless $self->profile;
62 $self->test_and_import_deferred(test => 1);
67 $self->test_and_import_deferred(test => 0);
73 $self->profile_from_form(SL::DB::Manager::CsvImportProfile->find_by(name => $::form->{profile}->{name}, login => $::myconfig{login}));
76 flash_later('info', $::locale->text("The profile has been saved under the name '#1'.", $self->profile->name));
77 $self->redirect_to(action => 'new', 'profile.type' => $self->type, 'profile.id' => $self->profile->id);
83 my $profile = SL::DB::CsvImportProfile->new(id => $::form->{profile}->{id}, login => $::myconfig{login});
84 $profile->delete(cascade => 1);
86 flash_later('info', $::locale->text('The profile \'#1\' has been deleted.', $profile->name));
87 $self->redirect_to(action => 'new', 'profile.type' => $self->type);
94 $self->{background_job} = SL::DB::Manager::BackgroundJob->find_by(id => $::form->{job});
96 my $data = $self->{background_job}->data_as_hash;
98 my $profile = SL::DB::Manager::CsvImportProfile->find_by(id => $data->{profile_id});
100 $self->profile($profile);
102 if ($data->{errors} and my $first_error = $data->{errors}->[0]) {
103 flash('error', $::locale->text('There was an error parsing the csv file: #1 in line #2.', $first_error->[2], $first_error->[0]));
106 if ($data->{progress}{finished} || $data->{errors}) {
107 $self->render('csv_import/_deferred_report', { layout => 0 });
109 if (!$self->task_server->is_running) {
110 $self->task_server->start;
111 $self->{status_text} = t8('Task Server is not running, starting it now. If this does not change, please check your task server config');
112 } elsif (my $phase = $data->{progress}{phase}) {
113 $self->{status_text} = "$data->{progress}{plan}{$phase} / $data->{progress}{num_phases} " . t8($phase);
115 $self->{status_text} = t8('Import not started yet, please wait...');
118 $self->render('csv_import/_deferred_results', { layout => 0 });
122 sub action_download_sample {
125 $self->profile_from_form;
128 my $file_name = 'csv_import_sample_' . $self->type . '.csv';
129 my $file = SL::SessionFile->new($file_name, mode => '>', encoding => $self->profile->get('charset'));
130 my $csv = Text::CSV_XS->new({ binary => 1, map { ( $_ => $self->profile->get($_) ) } qw(sep_char escape_char quote_char),});
132 if ($self->worker->is_multiplexed) {
133 foreach my $p (@{ $self->worker->profile }) {
134 $csv->print($file->fh, [ map { $_->{name} } @{ $self->displayable_columns->{$p->{row_ident}} } ]);
135 $file->fh->print("\r\n");
137 foreach my $p (@{ $self->worker->profile }) {
138 $csv->print($file->fh, [ map { $_->{description} } @{ $self->displayable_columns->{$p->{row_ident}} } ]);
139 $file->fh->print("\r\n");
142 $csv->print($file->fh, [ map { $_->{name} } @{ $self->displayable_columns } ]);
143 $file->fh->print("\r\n");
144 $csv->print($file->fh, [ map { $_->{description} } @{ $self->displayable_columns } ]);
145 $file->fh->print("\r\n");
150 $self->send_file($file->file_name, name => $file_name);
154 my ($self, %params) = @_;
156 my $report_id = $params{report_id} || $::form->{id};
158 $self->{report} = SL::DB::Manager::CsvImportReport->find_by(id => $report_id);
160 if (!$self->{report}) {
161 $::form->error(t8('No report with id #1', $report_id));
163 my $num_rows = $self->{report}->numrows;
164 my $num_cols = SL::DB::Manager::CsvImportReportRow->get_all_count(query => [ csv_import_report_id => $report_id, row => 0 ]);
166 # manual paginating, yuck
167 my $page = $::form->{page} || 1;
169 $pages->{per_page} = $::form->{per_page} || 20;
170 $pages->{max} = SL::DB::Helper::Paginated::ceil($num_rows, $pages->{per_page}) || 1;
171 $pages->{page} = $page < 1 ? 1
172 : $page > $pages->{max} ? $pages->{max}
174 $pages->{common} = [ grep { $_->{visible} } @{ SL::DB::Helper::Paginated::make_common_pages($pages->{page}, $pages->{max}) } ];
176 $self->{report_numheaders} = $self->{report}->numheaders;
177 my $first_row_header = 0;
178 my $last_row_header = $self->{report_numheaders} - 1;
179 my $first_row_data = $pages->{per_page} * ($pages->{page}-1) + $self->{report_numheaders};
180 my $last_row_data = min($pages->{per_page} * $pages->{page}, $num_rows) + $self->{report_numheaders} - 1;
181 $self->{display_rows} = [
191 csv_import_report_id => $report_id,
194 row => { ge => $first_row_header },
195 row => { le => $last_row_header },
198 row => { ge => $first_row_data },
199 row => { le => $last_row_data },
204 my $rows = SL::DB::Manager::CsvImportReportRow->get_all(query => \@query);
205 my $status = SL::DB::Manager::CsvImportReportStatus->get_all(query => \@query);
207 $self->{report_rows} = $self->{report}->folded_rows(rows => $rows);
208 $self->{report_status} = $self->{report}->folded_status(status => $status);
209 $self->{pages} = $pages;
210 $self->{base_url} = $self->url_for(action => 'report', id => $report_id, no_layout => $params{no_layout} || $::form->{no_layout} );
212 $self->render('csv_import/report', { layout => !($params{no_layout} || $::form->{no_layout}) });
221 $::auth->assert('config');
227 die "Invalid CSV import type" if none { $_ eq $::form->{profile}->{type} } qw(parts inventories customers_vendors addresses contacts projects orders bank_transactions);
228 $self->type($::form->{profile}->{type});
231 sub ensure_form_structure {
232 my ($self, %params) = @_;
234 $::form->{profile} = {} unless ref $::form->{profile} eq 'HASH';
235 $::form->{settings} = {} unless ref $::form->{settings} eq 'HASH';
243 my ($self, %params) = @_;
245 $self->all_charsets([ [ 'UTF-8', 'UTF-8' ],
246 [ 'ISO-8859-1', 'ISO-8859-1 (Latin 1)' ],
247 [ 'ISO-8859-15', 'ISO-8859-15 (Latin 9)' ],
248 [ 'CP850', 'CP850 (DOS/ANSI)' ],
249 [ 'CP1252', 'CP1252 (Windows)' ],
252 my %char_map = $self->char_map;
254 foreach my $type (qw(sep quote escape)) {
255 my $sub = "all_${type}_chars";
256 $self->$sub([ sort { $a->[0] cmp $b->[0] } values %{ $char_map{$type} } ]);
258 my $char = $self->profile->get($type . '_char');
259 $sub = "${type}_char";
260 $self->$sub(($char_map{$type}->{$char} || [])->[0] || $char);
263 $self->file(SL::SessionFile->new($self->csv_file_name));
265 my $title = $self->type eq 'customers_vendors' ? $::locale->text('CSV import: customers and vendors')
266 : $self->type eq 'addresses' ? $::locale->text('CSV import: shipping addresses')
267 : $self->type eq 'contacts' ? $::locale->text('CSV import: contacts')
268 : $self->type eq 'parts' ? $::locale->text('CSV import: parts and services')
269 : $self->type eq 'inventories' ? $::locale->text('CSV import: inventories')
270 : $self->type eq 'projects' ? $::locale->text('CSV import: projects')
271 : $self->type eq 'orders' ? $::locale->text('CSV import: orders')
272 : $self->type eq 'bank_transactions' ? $::locale->text('CSV import: bank transactions')
275 if ($self->{type} eq 'customers_vendors' or $self->{type} eq 'orders' ) {
276 $self->all_taxzones(SL::DB::Manager::TaxZone->get_all_sorted(query => [ obsolete => 0 ]));
279 if ($self->{type} eq 'parts') {
280 $self->all_buchungsgruppen(SL::DB::Manager::Buchungsgruppe->get_all_sorted);
281 $self->all_units(SL::DB::Manager::Unit->get_all_sorted);
286 $self->render('csv_import/form', title => $title);
289 sub test_and_import_deferred {
290 my ($self, %params) = @_;
292 if ( $::form->{force_profile} && $::form->{profile}->{id} ) {
293 $self->load_default_profile;
295 $self->profile_from_form;
298 if ($::form->{file}) {
299 my $file = SL::SessionFile->new($self->csv_file_name, mode => '>');
300 $file->fh->print($::form->{file});
304 my $file = SL::SessionFile->new($self->csv_file_name, mode => '<', encoding => $self->profile->get('charset'));
306 flash('error', $::locale->text('No file has been uploaded yet.'));
307 return $self->action_new;
310 $self->{background_job} = SL::BackgroundJob::CsvImport->create_job(
311 file => $self->csv_file_name,
312 profile => $self->profile,
313 type => $self->profile->type,
314 test => $params{test},
315 employee_id => SL::DB::Manager::Employee->current->id,
318 if ($self->task_server->is_running) {
319 $self->task_server->wake_up;
321 $self->task_server->start;
324 flash('info', $::locale->text('Your import is being processed.'));
326 $self->{deferred} = 1;
328 if ($::request->type eq 'json') {
329 $self->render(\ SL::JSON::to_json($self->{background_job}->as_tree), { type => 'json' })
331 $self->render_inputs;
335 sub test_and_import {
336 my ($self, %params) = @_;
338 my $file = SL::SessionFile->new(
339 $self->csv_file_name,
341 encoding => $self->profile->get('charset'),
342 session_id => $params{session_id}
347 my $worker = $self->worker();
349 $worker->run(%params);
351 return if $self->errors;
353 $self->num_imported(0);
354 $worker->save_objects if !$params{test};
356 $self->num_importable(scalar grep { !$_ } map { scalar @{ $_->{errors} } } @{ $self->data || [] });
357 $self->import_status($params{test} ? 'tested' : 'imported');
359 # flash('info', $::locale->text('Objects have been imported.')) if !$params{test};
362 sub load_default_profile {
366 if ($::form->{profile}->{id}) {
367 $profile = SL::DB::Manager::CsvImportProfile->find_by(id => $::form->{profile}->{id}, login => $::myconfig{login});
369 $profile ||= SL::DB::Manager::CsvImportProfile->find_by(type => $self->{type}, is_default => 1, login => $::myconfig{login});
370 $profile ||= SL::DB::CsvImportProfile->new(type => $self->{type}, login => $::myconfig{login});
372 $self->profile($profile);
373 $self->worker->set_profile_defaults;
374 $self->profile->set_defaults;
377 sub load_all_profiles {
378 my ($self, %params) = @_;
380 $self->all_profiles(SL::DB::Manager::CsvImportProfile->get_all(
383 login => $::myconfig{login},
389 sub profile_from_form {
390 my ($self, $existing_profile) = @_;
392 delete $::form->{profile}->{id};
394 my %char_map = $self->char_map;
397 foreach my $type (qw(sep quote escape)) {
398 my %rev_chars = map { $char_map{$type}->{$_}->[0] => $_ } keys %{ $char_map{$type} };
399 my $char = $::form->{"${type}_char"} eq 'custom' ? $::form->{"custom_${type}_char"} : $rev_chars{ $::form->{"${type}_char"} };
401 push @settings, { key => "${type}_char", value => $char };
404 if ($self->type eq 'parts') {
405 $::form->{settings}->{sellprice_adjustment} = $::form->parse_amount(\%::myconfig, $::form->{settings}->{sellprice_adjustment});
408 if ($self->type eq 'orders') {
409 $::form->{settings}->{max_amount_diff} = $::form->parse_amount(\%::myconfig, $::form->{settings}->{max_amount_diff});
412 delete $::form->{profile}->{id};
413 $self->profile($existing_profile || SL::DB::CsvImportProfile->new(login => $::myconfig{login}));
414 $self->profile->assign_attributes(%{ $::form->{profile} });
415 $self->profile->settings(map({ { key => $_, value => $::form->{settings}->{$_} } } keys %{ $::form->{settings} }),
417 $self->profile->set_defaults;
421 return ( sep => { ',' => [ 'comma', $::locale->text('Comma') ],
422 ';' => [ 'semicolon', $::locale->text('Semicolon') ],
423 "\t" => [ 'tab', $::locale->text('Tab') ],
424 ' ' => [ 'space', $::locale->text('Space') ],
426 quote => { '"' => [ 'quote', $::locale->text('Quotes') ],
427 "'" => [ 'singlequote', $::locale->text('Single quotes') ],
429 escape => { '"' => [ 'quote', $::locale->text('Quotes') ],
430 "'" => [ 'singlequote', $::locale->text('Single quotes') ],
436 my ($self, %params) = @_;
438 if ($self->worker->is_multiplexed) {
439 return $self->save_report_multi(%params);
441 return $self->save_report_single(%params);
445 sub save_report_single {
446 my ($self, %params) = @_;
448 $self->track_progress(phase => 'building report', progress => 0);
450 my $clone_profile = $self->profile->clone_and_reset_deep;
451 $clone_profile->save; # weird bug. if this isn't saved before adding it to the report, it will default back to the last profile.
453 my $report = SL::DB::CsvImportReport->new(
454 session_id => $params{session_id},
455 profile => $clone_profile,
458 numrows => scalar @{ $self->data },
462 $report->save(cascade => 1) or die $report->db->error;
464 my $dbh = $::form->get_standard_dbh;
467 my $query = 'INSERT INTO csv_import_report_rows (csv_import_report_id, col, row, value) VALUES (?, ?, ?, ?)';
468 my $query2 = 'INSERT INTO csv_import_report_status (csv_import_report_id, row, type, value) VALUES (?, ?, ?, ?)';
470 my $sth = $dbh->prepare($query);
471 my $sth2 = $dbh->prepare($query2);
474 my (@headers, @info_methods, @raw_methods, @methods);
476 for my $i (0 .. $#{ $self->info_headers->{headers} }) {
477 next unless $self->info_headers->{used}->{ $self->info_headers->{methods}->[$i] };
478 push @headers, $self->info_headers->{headers}->[$i];
479 push @info_methods, $self->info_headers->{methods}->[$i];
481 for my $i (0 .. $#{ $self->headers->{headers} }) {
482 next unless $self->headers->{used}->{ $self->headers->{headers}->[$i] };
483 push @headers, $self->headers->{headers}->[$i];
484 push @methods, $self->headers->{methods}->[$i];
486 for my $i (0 .. $#{ $self->raw_data_headers->{headers} }) {
487 next unless $self->raw_data_headers->{used}->{ $self->raw_data_headers->{headers}->[$i] };
488 push @headers, $self->raw_data_headers->{headers}->[$i];
489 push @raw_methods, $self->raw_data_headers->{headers}->[$i];
492 $sth->execute($report->id, $_, 0, $headers[$_]) for 0 .. $#headers;
495 my $o1 = @info_methods;
496 my $o2 = $o1 + @methods;
498 for my $row (0 .. $#{ $self->data }) {
499 $self->track_progress(progress => $row / @{ $self->data } * 100) if $row % 1000 == 0;
500 my $data_row = $self->{data}[$row];
502 $sth->execute($report->id, $_, $row + 1, $data_row->{info_data}{ $info_methods[$_] }) for 0 .. $#info_methods;
503 $sth->execute($report->id, $o1 + $_, $row + 1, $data_row->{object}->${ \ $methods[$_] }) for 0 .. $#methods;
504 $sth->execute($report->id, $o2 + $_, $row + 1, $data_row->{raw_data}{ $raw_methods[$_] }) for 0 .. $#raw_methods;
506 $sth2->execute($report->id, $row + 1, 'information', $_) for @{ $data_row->{information} || [] };
507 $sth2->execute($report->id, $row + 1, 'errors', $_) for @{ $data_row->{errors} || [] };
515 sub save_report_multi {
516 my ($self, %params) = @_;
518 $self->track_progress(phase => 'building report', progress => 0);
520 my $clone_profile = $self->profile->clone_and_reset_deep;
521 $clone_profile->save; # weird bug. if this isn't saved before adding it to the report, it will default back to the last profile.
523 my $report = SL::DB::CsvImportReport->new(
524 session_id => $params{session_id},
525 profile => $clone_profile,
528 numrows => scalar @{ $self->data },
529 numheaders => scalar @{ $self->worker->profile },
532 $report->save(cascade => 1) or die $report->db->error;
534 my $dbh = $::form->get_standard_dbh;
537 my $query = 'INSERT INTO csv_import_report_rows (csv_import_report_id, col, row, value) VALUES (?, ?, ?, ?)';
538 my $query2 = 'INSERT INTO csv_import_report_status (csv_import_report_id, row, type, value) VALUES (?, ?, ?, ?)';
540 my $sth = $dbh->prepare($query);
541 my $sth2 = $dbh->prepare($query2);
544 my ($headers, $info_methods, $raw_methods, $methods);
546 for my $i (0 .. $#{ $self->worker->profile }) {
547 my $row_ident = $self->worker->profile->[$i]->{row_ident};
549 for my $i (0 .. $#{ $self->info_headers->{$row_ident}->{headers} }) {
550 next unless $self->info_headers->{$row_ident}->{used}->{ $self->info_headers->{$row_ident}->{methods}->[$i] };
551 push @{ $headers->{$row_ident} }, $self->info_headers->{$row_ident}->{headers}->[$i];
552 push @{ $info_methods->{$row_ident} }, $self->info_headers->{$row_ident}->{methods}->[$i];
554 for my $i (0 .. $#{ $self->headers->{$row_ident}->{headers} }) {
555 next unless $self->headers->{$row_ident}->{used}->{ $self->headers->{$row_ident}->{headers}->[$i] };
556 push @{ $headers->{$row_ident} }, $self->headers->{$row_ident}->{headers}->[$i];
557 push @{ $methods->{$row_ident} }, $self->headers->{$row_ident}->{methods}->[$i];
560 for my $i (0 .. $#{ $self->raw_data_headers->{$row_ident}->{headers} }) {
561 next unless $self->raw_data_headers->{$row_ident}->{used}->{ $self->raw_data_headers->{$row_ident}->{headers}->[$i] };
562 push @{ $headers->{$row_ident} }, $self->raw_data_headers->{$row_ident}->{headers}->[$i];
563 push @{ $raw_methods->{$row_ident} }, $self->raw_data_headers->{$row_ident}->{headers}->[$i];
568 for my $i (0 .. $#{ $self->worker->profile }) {
569 my $row_ident = $self->worker->profile->[$i]->{row_ident};
570 $sth->execute($report->id, $_, $i, $headers->{$row_ident}->[$_]) for 0 .. $#{ $headers->{$row_ident} };
575 for my $i (0 .. $#{ $self->worker->profile }) {
576 my $row_ident = $self->worker->profile->[$i]->{row_ident};
577 my $n_info_methods = $info_methods->{$row_ident} ? scalar @{ $info_methods->{$row_ident} } : 0;
578 my $n_methods = $methods->{$row_ident} ? scalar @{ $methods->{$row_ident} } : 0;
580 $off1->{$row_ident} = $n_info_methods;
581 $off2->{$row_ident} = $off1->{$row_ident} + $n_methods;
584 my $n_header_rows = scalar @{ $self->worker->profile };
586 for my $row (0 .. $#{ $self->data }) {
587 $self->track_progress(progress => $row / @{ $self->data } * 100) if $row % 1000 == 0;
588 my $data_row = $self->{data}[$row];
589 my $row_ident = $data_row->{raw_data}{datatype};
591 my $o1 = $off1->{$row_ident};
592 my $o2 = $off2->{$row_ident};
594 $sth->execute($report->id, $_, $row + $n_header_rows, $data_row->{info_data}{ $info_methods->{$row_ident}->[$_] }) for 0 .. $#{ $info_methods->{$row_ident} };
595 $sth->execute($report->id, $o1 + $_, $row + $n_header_rows, $data_row->{object}->${ \ $methods->{$row_ident}->[$_] }) for 0 .. $#{ $methods->{$row_ident} };
596 $sth->execute($report->id, $o2 + $_, $row + $n_header_rows, $data_row->{raw_data}{ $raw_methods->{$row_ident}->[$_] }) for 0 .. $#{ $raw_methods->{$row_ident} };
598 $sth2->execute($report->id, $row + $n_header_rows, 'information', $_) for @{ $data_row->{information} || [] };
599 $sth2->execute($report->id, $row + $n_header_rows, 'errors', $_) for @{ $data_row->{errors} || [] };
609 return "csv-import-" . $self->type . ".csv";
615 my @args = (controller => $self);
617 if ( $self->file() ) {
618 push(@args, file => $self->file());
621 return $self->{type} eq 'customers_vendors' ? SL::Controller::CsvImport::CustomerVendor->new(@args)
622 : $self->{type} eq 'contacts' ? SL::Controller::CsvImport::Contact->new(@args)
623 : $self->{type} eq 'addresses' ? SL::Controller::CsvImport::Shipto->new(@args)
624 : $self->{type} eq 'parts' ? SL::Controller::CsvImport::Part->new(@args)
625 : $self->{type} eq 'inventories' ? SL::Controller::CsvImport::Inventory->new(@args)
626 : $self->{type} eq 'projects' ? SL::Controller::CsvImport::Project->new(@args)
627 : $self->{type} eq 'orders' ? SL::Controller::CsvImport::Order->new(@args)
628 : $self->{type} eq 'bank_transactions' ? SL::Controller::CsvImport::BankTransaction->new(@args)
629 : die "Program logic error";
635 $self->worker->setup_displayable_columns;
639 my ($self, %params) = @_;
641 for my $tracker ($self->progress_tracker) {
642 $tracker->track_progress(%params);
646 sub init_task_server {
647 SL::System::TaskServer->new;
650 sub cleanup_reports {
651 SL::DB::Manager::CsvImportReport->cleanup;
654 sub check_task_server {
655 return 1 if $_[0]->task_server->is_running;
657 flash('info', t8('The task server is not running at the moment but needed for this module'));