Projekt

Allgemein

Profil

Herunterladen (13,5 KB) Statistiken
| Zweig: | Markierung: | Revision:
7f1f5efe Moritz Bunkus
package SL::Controller::CsvImport;

use strict;

1abd7845 Moritz Bunkus
use SL::DB::Buchungsgruppe;
7f1f5efe Moritz Bunkus
use SL::DB::CsvImportProfile;
67643d03 Sven Schöling
use SL::DB::CsvImportReport;
31b1b2c2 Moritz Bunkus
use SL::DB::Unit;
7f1f5efe Moritz Bunkus
use SL::Helper::Flash;
29269e99 Moritz Bunkus
use SL::SessionFile;
7b9d1666 Moritz Bunkus
use SL::Controller::CsvImport::Contact;
f87763cd Moritz Bunkus
use SL::Controller::CsvImport::CustomerVendor;
81379539 Moritz Bunkus
use SL::Controller::CsvImport::Part;
9e152755 Moritz Bunkus
use SL::Controller::CsvImport::Shipto;
159dd378 Thomas Heck
use SL::Controller::CsvImport::Project;
82c3b7eb Sven Schöling
use SL::BackgroundJob::CsvImport;
use SL::System::TaskServer;
7f1f5efe Moritz Bunkus
use List::MoreUtils qw(none);

use parent qw(SL::Controller::Base);

use Rose::Object::MakeMethods::Generic
(
80e68986 Thomas Heck
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
import_status errors headers raw_data_headers info_headers data num_imported num_importable displayable_columns file) ],
d7492165 Sven Schöling
'scalar --get_set_init' => [ qw(worker) ],
'array' => [
progress_tracker => { },
add_progress_tracker => { interface => 'add', hash_key => 'progress_tracker' },
],
7f1f5efe Moritz Bunkus
);

__PACKAGE__->run_before('check_auth');
__PACKAGE__->run_before('ensure_form_structure');
67643d03 Sven Schöling
__PACKAGE__->run_before('check_type', except => [ qw(report) ]);
7f1f5efe Moritz Bunkus
__PACKAGE__->run_before('load_all_profiles');

#
# actions
#

sub action_new {
my ($self) = @_;

$self->load_default_profile unless $self->profile;
$self->render_inputs;
}

sub action_test {
my ($self) = @_;
82c3b7eb Sven Schöling
$self->test_and_import_deferred(test => 1);
7f1f5efe Moritz Bunkus
}

sub action_import {
my $self = shift;
82c3b7eb Sven Schöling
$self->test_and_import_deferred(test => 0);
7f1f5efe Moritz Bunkus
}

sub action_save {
my ($self) = @_;

4b26e243 Sven Schöling
$self->profile_from_form(SL::DB::Manager::CsvImportProfile->find_by(name => $::form->{profile}->{name}, login => $::myconfig{login}));
7f1f5efe Moritz Bunkus
$self->profile->save;

flash_later('info', $::locale->text("The profile has been saved under the name '#1'.", $self->profile->name));
$self->redirect_to(action => 'new', 'profile.type' => $self->type, 'profile.id' => $self->profile->id);
}

sub action_destroy {
my $self = shift;

4b26e243 Sven Schöling
my $profile = SL::DB::CsvImportProfile->new(id => $::form->{profile}->{id}, login => $::myconfig{login});
7f1f5efe Moritz Bunkus
$profile->delete(cascade => 1);

flash_later('info', $::locale->text('The profile \'#1\' has been deleted.', $profile->name));
$self->redirect_to(action => 'new', 'profile.type' => $self->type);
}

82c3b7eb Sven Schöling
sub action_result {
my $self = shift;

# load resultobject
$self->{background_job} = SL::DB::Manager::BackgroundJob->find_by(id => $::form->{job});

my $data = $self->{background_job}->data_as_hash;

d7492165 Sven Schöling
my $profile = SL::DB::Manager::CsvImportProfile->find_by(id => $data->{profile_id});
82c3b7eb Sven Schöling
$self->profile($profile);

98f37c10 Sven Schöling
if ($data->{errors} and my $first_error = $data->{errors}->[0]) {
flash('error', $::locale->text('There was an error parsing the csv file: #1 in line #2.', $first_error->[2], $first_error->[0]));
}

b2930e37 Sven Schöling
if ($data->{progress}{finished} || $data->{errors}) {
d7492165 Sven Schöling
$self->action_report(report_id => $data->{report_id}, no_layout => 1);
b2930e37 Sven Schöling
} else {
$self->render('csv_import/_deferred_results', { no_layout => 1 });
82c3b7eb Sven Schöling
}
}

6759902a Moritz Bunkus
sub action_download_sample {
my $self = shift;

$self->profile_from_form;
$self->setup_help;

my $file_name = 'csv_import_sample_' . $self->type . '.csv';
my $file = SL::SessionFile->new($file_name, mode => '>', encoding => $self->profile->get('charset'));
my $csv = Text::CSV_XS->new({ binary => 1, map { ( $_ => $self->profile->get($_) ) } qw(sep_char escape_char quote_char),});

$csv->print($file->fh, [ map { $_->{name} } @{ $self->displayable_columns } ]);
$file->fh->print("\r\n");
$csv->print($file->fh, [ map { $_->{description} } @{ $self->displayable_columns } ]);
$file->fh->print("\r\n");

$file->fh->close;

9dcc0d85 Moritz Bunkus
$self->send_file($file->file_name, name => $file_name);
6759902a Moritz Bunkus
}

1ad93745 Sven Schöling
sub action_report {
my ($self, %params) = @_;

$self->{report} = SL::DB::Manager::CsvImportReport->find_by(id => $params{report_id} || $::form->{id});

$self->render('csv_import/report', { no_layout => $params{no_layout} });
}


7f1f5efe Moritz Bunkus
#
# filters
#

sub check_auth {
$::auth->assert('config');
}

sub check_type {
my ($self) = @_;

159dd378 Thomas Heck
die "Invalid CSV import type" if none { $_ eq $::form->{profile}->{type} } qw(parts customers_vendors addresses contacts projects);
7f1f5efe Moritz Bunkus
$self->type($::form->{profile}->{type});
}

sub ensure_form_structure {
my ($self, %params) = @_;

$::form->{profile} = {} unless ref $::form->{profile} eq 'HASH';
$::form->{settings} = {} unless ref $::form->{settings} eq 'HASH';
}

#
# helpers
#

sub render_inputs {
my ($self, %params) = @_;

$self->all_charsets([ [ 'UTF-8', 'UTF-8' ],
[ 'ISO-8859-1', 'ISO-8859-1 (Latin 1)' ],
[ 'ISO-8859-15', 'ISO-8859-15 (Latin 9)' ],
[ 'CP850', 'CP850 (DOS/ANSI)' ],
[ 'CP1252', 'CP1252 (Windows)' ],
]);

my %char_map = $self->char_map;

foreach my $type (qw(sep quote escape)) {
my $sub = "all_${type}_chars";
$self->$sub([ sort { $a->[0] cmp $b->[0] } values %{ $char_map{$type} } ]);

my $char = $self->profile->get($type . '_char');
$sub = "${type}_char";
$self->$sub(($char_map{$type}->{$char} || [])->[0] || $char);
}

29269e99 Moritz Bunkus
$self->file(SL::SessionFile->new($self->csv_file_name));

f5594740 Moritz Bunkus
my $title = $self->type eq 'customers_vendors' ? $::locale->text('CSV import: customers and vendors')
: $self->type eq 'addresses' ? $::locale->text('CSV import: shipping addresses')
: $self->type eq 'contacts' ? $::locale->text('CSV import: contacts')
1abd7845 Moritz Bunkus
: $self->type eq 'parts' ? $::locale->text('CSV import: parts and services')
159dd378 Thomas Heck
: $self->type eq 'projects' ? $::locale->text('CSV import: projects')
f5594740 Moritz Bunkus
: die;
7f1f5efe Moritz Bunkus
d582b83d Moritz Bunkus
if ($self->{type} eq 'parts') {
$self->all_buchungsgruppen(SL::DB::Manager::Buchungsgruppe->get_all_sorted);
31b1b2c2 Moritz Bunkus
$self->all_units(SL::DB::Manager::Unit->get_all_sorted);
d582b83d Moritz Bunkus
}
1abd7845 Moritz Bunkus
7caf72ff Moritz Bunkus
$self->setup_help;

f5594740 Moritz Bunkus
$self->render('csv_import/form', title => $title);
7f1f5efe Moritz Bunkus
}

82c3b7eb Sven Schöling
sub test_and_import_deferred {
my ($self, %params) = @_;

$self->profile_from_form;

if ($::form->{file}) {
my $file = SL::SessionFile->new($self->csv_file_name, mode => '>');
$file->fh->print($::form->{file});
$file->fh->close;
}

$self->{background_job} = SL::BackgroundJob::CsvImport->create_job(
file => $self->csv_file_name,
profile => $self->profile,
type => $self->profile->type,
98f37c10 Sven Schöling
test => $params{test},
82c3b7eb Sven Schöling
)->save;

SL::System::TaskServer->start_if_not_running;
SL::System::TaskServer->wake_up;

flash('info', $::locale->text('Your import is beig processed.'));

$self->{deferred} = 1;

$self->render_inputs;
}

7f1f5efe Moritz Bunkus
sub test_and_import {
my ($self, %params) = @_;

d7492165 Sven Schöling
my $file = SL::SessionFile->new(
$self->csv_file_name,
mode => '<',
encoding => $self->profile->get('charset'),
session_id => $params{session_id}
);
29269e99 Moritz Bunkus
80e68986 Thomas Heck
$self->file($file);

my $worker = $self->worker();

f87763cd Moritz Bunkus
$worker->run;
b88b33d1 Moritz Bunkus
98f37c10 Sven Schöling
return if $self->errors;

b88b33d1 Moritz Bunkus
$self->num_imported(0);
f87763cd Moritz Bunkus
$worker->save_objects if !$params{test};

b9e6845d Moritz Bunkus
$self->num_importable(scalar grep { !$_ } map { scalar @{ $_->{errors} } } @{ $self->data || [] });
f87763cd Moritz Bunkus
$self->import_status($params{test} ? 'tested' : 'imported');

d7492165 Sven Schöling
# flash('info', $::locale->text('Objects have been imported.')) if !$params{test};
7f1f5efe Moritz Bunkus
}

sub load_default_profile {
my ($self) = @_;

4b26e243 Sven Schöling
my $profile;
7f1f5efe Moritz Bunkus
if ($::form->{profile}->{id}) {
4b26e243 Sven Schöling
$profile = SL::DB::Manager::CsvImportProfile->find_by(id => $::form->{profile}->{id}, login => $::myconfig{login});
7f1f5efe Moritz Bunkus
}
4b26e243 Sven Schöling
$profile ||= SL::DB::Manager::CsvImportProfile->find_by(type => $self->{type}, is_default => 1, login => $::myconfig{login});
$profile ||= SL::DB::CsvImportProfile->new(type => $self->{type}, login => $::myconfig{login});
7f1f5efe Moritz Bunkus
4b26e243 Sven Schöling
$self->profile($profile);
7f1f5efe Moritz Bunkus
$self->profile->set_defaults;
}

sub load_all_profiles {
my ($self, %params) = @_;

4b26e243 Sven Schöling
$self->all_profiles(SL::DB::Manager::CsvImportProfile->get_all(
where => [
type => $self->type,
login => $::myconfig{login},
],
sort_by => 'name'));
7f1f5efe Moritz Bunkus
}

sub profile_from_form {
my ($self, $existing_profile) = @_;

delete $::form->{profile}->{id};

my %char_map = $self->char_map;
my @settings;

foreach my $type (qw(sep quote escape)) {
my %rev_chars = map { $char_map{$type}->{$_}->[0] => $_ } keys %{ $char_map{$type} };
my $char = $::form->{"${type}_char"} eq 'custom' ? $::form->{"custom_${type}_char"} : $rev_chars{ $::form->{"${type}_char"} };

push @settings, { key => "${type}_char", value => $char };
}

81379539 Moritz Bunkus
if ($self->type eq 'parts') {
$::form->{settings}->{sellprice_adjustment} = $::form->parse_amount(\%::myconfig, $::form->{settings}->{sellprice_adjustment});
}

7f1f5efe Moritz Bunkus
delete $::form->{profile}->{id};
4b26e243 Sven Schöling
$self->profile($existing_profile || SL::DB::CsvImportProfile->new(login => $::myconfig{login}));
7f1f5efe Moritz Bunkus
$self->profile->assign_attributes(%{ $::form->{profile} });
$self->profile->settings(map({ { key => $_, value => $::form->{settings}->{$_} } } keys %{ $::form->{settings} }),
@settings);
$self->profile->set_defaults;
}

sub char_map {
return ( sep => { ',' => [ 'comma', $::locale->text('Comma') ],
';' => [ 'semicolon', $::locale->text('Semicolon') ],
"\t" => [ 'tab', $::locale->text('Tab') ],
' ' => [ 'space', $::locale->text('Space') ],
},
quote => { '"' => [ 'quote', $::locale->text('Quotes') ],
"'" => [ 'singlequote', $::locale->text('Single quotes') ],
},
escape => { '"' => [ 'quote', $::locale->text('Quotes') ],
"'" => [ 'singlequote', $::locale->text('Single quotes') ],
},
);
}

67643d03 Sven Schöling
sub save_report {
my ($self, $report_id) = @_;

98f37c10 Sven Schöling
$self->track_progress(phase => 'building report', progress => 0);

67643d03 Sven Schöling
my $clone_profile = $self->profile->clone_and_reset_deep;
$clone_profile->save; # weird bug. if this isn't saved before adding it to the report, it will default back to the last profile.

my $report = SL::DB::CsvImportReport->new(
session_id => $::auth->create_or_refresh_session,
profile => $clone_profile,
type => $self->type,
file => '',
)->save(cascade => 1);

my $dbh = $::form->get_standard_dbh;
$dbh->begin_work;

a5a42ed1 Sven Schöling
my $query = 'INSERT INTO csv_import_report_rows (csv_import_report_id, col, row, value) VALUES (?, ?, ?, ?)';
my $query2 = 'INSERT INTO csv_import_report_status (csv_import_report_id, row, type, value) VALUES (?, ?, ?, ?)';
67643d03 Sven Schöling
my $sth = $dbh->prepare($query);
a5a42ed1 Sven Schöling
my $sth2 = $dbh->prepare($query2);
67643d03 Sven Schöling
# save headers
670ca35b Sven Schöling
my (@headers, @info_methods, @raw_methods, @methods);

for my $i (0 .. $#{ $self->info_headers->{headers} }) {
next unless $self->info_headers->{used}->{ $self->info_headers->{headers}->[$i] };
push @headers, $self->info_headers->{headers}->[$i];
push @info_methods, $self->info_headers->{methods}->[$i];
}
for my $i (0 .. $#{ $self->headers->{headers} }) {
next unless $self->headers->{used}->{ $self->headers->{headers}->[$i] };
push @headers, $self->headers->{headers}->[$i];
push @methods, $self->headers->{methods}->[$i];
}
for my $i (0 .. $#{ $self->raw_data_headers->{headers} }) {
next unless $self->raw_data_headers->{used}->{ $self->raw_data_headers->{headers}->[$i] };
push @headers, $self->raw_data_headers->{headers}->[$i];
push @raw_methods, $self->raw_data_headers->{headers}->[$i];
}

$::lxdebug->dump(0, "methods",
[ \@info_methods,
\@methods,
\@raw_methods ]
67643d03 Sven Schöling
);

$sth->execute($report->id, $_, 0, $headers[$_]) for 0 .. $#headers;

# col offsets
my $o1 = @info_methods;
my $o2 = $o1 + @methods;

for my $row (0 .. $#{ $self->data }) {
98f37c10 Sven Schöling
$self->track_progress(progress => $row / @{ $self->data } * 100) if $row % 100 == 0;
67643d03 Sven Schöling
my $data_row = $self->{data}[$row];

$sth->execute($report->id, $_, $row + 1, $data_row->{info_data}{ $info_methods[$_] }) for 0 .. $#info_methods;
$sth->execute($report->id, $o1 + $_, $row + 1, $data_row->{object}->${ \ $methods[$_] }) for 0 .. $#methods;
$sth->execute($report->id, $o2 + $_, $row + 1, $data_row->{raw_data}{ $raw_methods[$_] }) for 0 .. $#raw_methods;
a5a42ed1 Sven Schöling
$sth2->execute($report->id, $row + 1, 'information', $_) for @{ $data_row->{information} || [] };
$sth2->execute($report->id, $row + 1, 'errors', $_) for @{ $data_row->{errors} || [] };
67643d03 Sven Schöling
}

$dbh->commit;

1ad93745 Sven Schöling
return $report->id;
67643d03 Sven Schöling
}

29269e99 Moritz Bunkus
sub csv_file_name {
my ($self) = @_;
return "csv-import-" . $self->type . ".csv";
}

80e68986 Thomas Heck
sub init_worker {
my $self = shift;

my @args = (controller => $self);

if ( $self->file() ) {
push(@args, file => $self->file());
}
81379539 Moritz Bunkus
80e68986 Thomas Heck
return $self->{type} eq 'customers_vendors' ? SL::Controller::CsvImport::CustomerVendor->new(@args)
: $self->{type} eq 'contacts' ? SL::Controller::CsvImport::Contact->new(@args)
: $self->{type} eq 'addresses' ? SL::Controller::CsvImport::Shipto->new(@args)
: $self->{type} eq 'parts' ? SL::Controller::CsvImport::Part->new(@args)
: $self->{type} eq 'projects' ? SL::Controller::CsvImport::Project->new(@args)
81379539 Moritz Bunkus
: die "Program logic error";
}

7caf72ff Moritz Bunkus
sub setup_help {
my ($self) = @_;

80e68986 Thomas Heck
$self->worker->setup_displayable_columns;
7caf72ff Moritz Bunkus
}

d7492165 Sven Schöling
sub track_progress {
98f37c10 Sven Schöling
my ($self, %params) = @_;
d7492165 Sven Schöling
for my $tracker ($self->progress_tracker) {
98f37c10 Sven Schöling
$tracker->track_progress(%params);
d7492165 Sven Schöling
}
}

7caf72ff Moritz Bunkus
7f1f5efe Moritz Bunkus
1;