]> wagnertech.de Git - kivitendo-erp.git/blob - SL/Controller/CsvImport.pm
Keine undefinierten Werte als Referenzen nutzen (passiert im Fehlerfall)
[kivitendo-erp.git] / SL / Controller / CsvImport.pm
1 package SL::Controller::CsvImport;
2
3 use strict;
4
5 use SL::DB::Buchungsgruppe;
6 use SL::DB::CsvImportProfile;
7 use SL::Helper::Flash;
8 use SL::SessionFile;
9 use SL::Controller::CsvImport::Contact;
10 use SL::Controller::CsvImport::CustomerVendor;
11 use SL::Controller::CsvImport::Shipto;
12
13 use List::MoreUtils qw(none);
14
15 use parent qw(SL::Controller::Base);
16
17 use Rose::Object::MakeMethods::Generic
18 (
19  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
20                 import_status errors headers data num_imported num_importable) ],
21 );
22
23 __PACKAGE__->run_before('check_auth');
24 __PACKAGE__->run_before('ensure_form_structure');
25 __PACKAGE__->run_before('check_type');
26 __PACKAGE__->run_before('load_all_profiles');
27
28 #
29 # actions
30 #
31
32 sub action_new {
33   my ($self) = @_;
34
35   $self->load_default_profile unless $self->profile;
36   $self->render_inputs;
37 }
38
39 sub action_test {
40   my ($self) = @_;
41   $self->test_and_import(test => 1);
42 }
43
44 sub action_import {
45   my $self = shift;
46   $self->test_and_import(test => 0);
47 }
48
49 sub action_save {
50   my ($self) = @_;
51
52   $self->profile_from_form(SL::DB::Manager::CsvImportProfile->find_by(name => $::form->{profile}->{name}));
53   $self->profile->save;
54
55   flash_later('info', $::locale->text("The profile has been saved under the name '#1'.", $self->profile->name));
56   $self->redirect_to(action => 'new', 'profile.type' => $self->type, 'profile.id' => $self->profile->id);
57 }
58
59 sub action_destroy {
60   my $self = shift;
61
62   my $profile = SL::DB::CsvImportProfile->new(id => $::form->{profile}->{id});
63   $profile->delete(cascade => 1);
64
65   flash_later('info', $::locale->text('The profile \'#1\' has been deleted.', $profile->name));
66   $self->redirect_to(action => 'new', 'profile.type' => $self->type);
67 }
68
69 #
70 # filters
71 #
72
73 sub check_auth {
74   $::auth->assert('config');
75 }
76
77 sub check_type {
78   my ($self) = @_;
79
80   die "Invalid CSV import type" if none { $_ eq $::form->{profile}->{type} } qw(parts customers_vendors addresses contacts);
81   $self->type($::form->{profile}->{type});
82 }
83
84 sub ensure_form_structure {
85   my ($self, %params) = @_;
86
87   $::form->{profile}  = {} unless ref $::form->{profile}  eq 'HASH';
88   $::form->{settings} = {} unless ref $::form->{settings} eq 'HASH';
89 }
90
91 #
92 # helpers
93 #
94
95 sub render_inputs {
96   my ($self, %params) = @_;
97
98   $self->all_charsets([ [ 'UTF-8',       'UTF-8'                 ],
99                         [ 'ISO-8859-1',  'ISO-8859-1 (Latin 1)'  ],
100                         [ 'ISO-8859-15', 'ISO-8859-15 (Latin 9)' ],
101                         [ 'CP850',       'CP850 (DOS/ANSI)'      ],
102                         [ 'CP1252',      'CP1252 (Windows)'      ],
103                       ]);
104
105   my %char_map = $self->char_map;
106
107   foreach my $type (qw(sep quote escape)) {
108     my $sub = "all_${type}_chars";
109     $self->$sub([ sort { $a->[0] cmp $b->[0] } values %{ $char_map{$type} } ]);
110
111     my $char = $self->profile->get($type . '_char');
112     $sub     = "${type}_char";
113     $self->$sub(($char_map{$type}->{$char} || [])->[0] || $char);
114   }
115
116   $self->file(SL::SessionFile->new($self->csv_file_name));
117
118   my $title = $self->type eq 'customers_vendors' ? $::locale->text('CSV import: customers and vendors')
119             : $self->type eq 'addresses'         ? $::locale->text('CSV import: shipping addresses')
120             : $self->type eq 'contacts'          ? $::locale->text('CSV import: contacts')
121             : $self->type eq 'parts'             ? $::locale->text('CSV import: parts and services')
122             : die;
123
124   $self->all_buchungsgruppen(SL::DB::Manager::Buchungsgruppe->get_all_sorted);
125
126   $self->render('csv_import/form', title => $title);
127 }
128
129 sub test_and_import {
130   my ($self, %params) = @_;
131
132   $self->profile_from_form;
133
134   if ($::form->{file}) {
135     my $file = SL::SessionFile->new($self->csv_file_name, mode => '>');
136     $file->fh->print($::form->{file});
137     $file->fh->close;
138   }
139
140   my $file = SL::SessionFile->new($self->csv_file_name, mode => '<', encoding => $self->profile->get('charset'));
141   if (!$file->fh) {
142     flash('error', $::locale->text('No file has been uploaded yet.'));
143     return $self->action_new;
144   }
145
146   my $worker = $self->{type} eq 'customers_vendors' ? SL::Controller::CsvImport::CustomerVendor->new(controller => $self, file => $file)
147              : $self->{type} eq 'contacts'          ? SL::Controller::CsvImport::Contact->new(       controller => $self, file => $file)
148              : $self->{type} eq 'addresses'         ? SL::Controller::CsvImport::Shipto->new(        controller => $self, file => $file)
149              :                                        die "Program logic error";
150
151   $worker->run;
152   $worker->save_objects if !$params{test};
153
154   $self->num_importable(scalar grep { !$_ } map { scalar @{ $_->{errors} } } @{ $self->data || [] });
155   $self->import_status($params{test} ? 'tested' : 'imported');
156
157   flash('info', $::locale->text('Objects have been imported.')) if !$params{test};
158
159   $self->action_new;
160 }
161
162 sub load_default_profile {
163   my ($self) = @_;
164
165   if ($::form->{profile}->{id}) {
166     $self->profile(SL::DB::CsvImportProfile->new(id => $::form->{profile}->{id})->load);
167
168   } else {
169     $self->profile(SL::DB::Manager::CsvImportProfile->find_by(type => $self->{type}, is_default => 1));
170     $self->profile(SL::DB::CsvImportProfile->new(type => $self->{type})) unless $self->profile;
171   }
172
173   $self->profile->set_defaults;
174 }
175
176 sub load_all_profiles {
177   my ($self, %params) = @_;
178
179   $self->all_profiles(SL::DB::Manager::CsvImportProfile->get_all(where => [ type => $self->type ], sort_by => 'name'));
180 }
181
182 sub profile_from_form {
183   my ($self, $existing_profile) = @_;
184
185   delete $::form->{profile}->{id};
186
187   my %char_map = $self->char_map;
188   my @settings;
189
190   foreach my $type (qw(sep quote escape)) {
191     my %rev_chars = map { $char_map{$type}->{$_}->[0] => $_ } keys %{ $char_map{$type} };
192     my $char      = $::form->{"${type}_char"} eq 'custom' ? $::form->{"custom_${type}_char"} : $rev_chars{ $::form->{"${type}_char"} };
193
194     push @settings, { key => "${type}_char", value => $char };
195   }
196
197   delete $::form->{profile}->{id};
198   $self->profile($existing_profile || SL::DB::CsvImportProfile->new);
199   $self->profile->assign_attributes(%{ $::form->{profile} });
200   $self->profile->settings(map({ { key => $_, value => $::form->{settings}->{$_} } } keys %{ $::form->{settings} }),
201                            @settings);
202   $self->profile->set_defaults;
203 }
204
205 sub char_map {
206   return ( sep    => { ','  => [ 'comma',     $::locale->text('Comma')     ],
207                        ';'  => [ 'semicolon', $::locale->text('Semicolon') ],
208                        "\t" => [ 'tab',       $::locale->text('Tab')       ],
209                        ' '  => [ 'space',     $::locale->text('Space')     ],
210                      },
211            quote  => { '"' => [ 'quote', $::locale->text('Quotes') ],
212                        "'" => [ 'singlequote', $::locale->text('Single quotes') ],
213                      },
214            escape => { '"' => [ 'quote', $::locale->text('Quotes') ],
215                        "'" => [ 'singlequote', $::locale->text('Single quotes') ],
216                      },
217          );
218 }
219
220 sub csv_file_name {
221   my ($self) = @_;
222   return "csv-import-" . $self->type . ".csv";
223 }
224
225 1;