34b794fdbe1fcbb98455e490d0a58742b0ef463e
[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::DB::Unit;
8 use SL::Helper::Flash;
9 use SL::SessionFile;
10 use SL::Controller::CsvImport::Contact;
11 use SL::Controller::CsvImport::CustomerVendor;
12 use SL::Controller::CsvImport::Part;
13 use SL::Controller::CsvImport::Shipto;
14 use SL::Controller::CsvImport::Project;
15
16 use List::MoreUtils qw(none);
17
18 use parent qw(SL::Controller::Base);
19
20 use Rose::Object::MakeMethods::Generic
21 (
22  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
23                                  import_status errors headers raw_data_headers info_headers data num_imported num_importable displayable_columns file) ],
24  'scalar --get_set_init' => [ qw(worker) ]
25 );
26
27 __PACKAGE__->run_before('check_auth');
28 __PACKAGE__->run_before('ensure_form_structure');
29 __PACKAGE__->run_before('check_type');
30 __PACKAGE__->run_before('load_all_profiles');
31
32 #
33 # actions
34 #
35
36 sub action_new {
37   my ($self) = @_;
38
39   $self->load_default_profile unless $self->profile;
40   $self->render_inputs;
41 }
42
43 sub action_test {
44   my ($self) = @_;
45   $self->test_and_import(test => 1);
46 }
47
48 sub action_import {
49   my $self = shift;
50   $self->test_and_import(test => 0);
51 }
52
53 sub action_save {
54   my ($self) = @_;
55
56   $self->profile_from_form(SL::DB::Manager::CsvImportProfile->find_by(name => $::form->{profile}->{name}, login => $::myconfig{login}));
57   $self->profile->save;
58
59   flash_later('info', $::locale->text("The profile has been saved under the name '#1'.", $self->profile->name));
60   $self->redirect_to(action => 'new', 'profile.type' => $self->type, 'profile.id' => $self->profile->id);
61 }
62
63 sub action_destroy {
64   my $self = shift;
65
66   my $profile = SL::DB::CsvImportProfile->new(id => $::form->{profile}->{id}, login => $::myconfig{login});
67   $profile->delete(cascade => 1);
68
69   flash_later('info', $::locale->text('The profile \'#1\' has been deleted.', $profile->name));
70   $self->redirect_to(action => 'new', 'profile.type' => $self->type);
71 }
72
73 sub action_download_sample {
74   my $self = shift;
75
76   $self->profile_from_form;
77   $self->setup_help;
78
79   my $file_name = 'csv_import_sample_' . $self->type . '.csv';
80   my $file      = SL::SessionFile->new($file_name, mode => '>', encoding => $self->profile->get('charset'));
81   my $csv       = Text::CSV_XS->new({ binary => 1, map { ( $_ => $self->profile->get($_) ) } qw(sep_char escape_char quote_char),});
82
83   $csv->print($file->fh, [ map { $_->{name}        } @{ $self->displayable_columns } ]);
84   $file->fh->print("\r\n");
85   $csv->print($file->fh, [ map { $_->{description} } @{ $self->displayable_columns } ]);
86   $file->fh->print("\r\n");
87
88   $file->fh->close;
89
90   $self->send_file($file->file_name, name => $file_name);
91 }
92
93 #
94 # filters
95 #
96
97 sub check_auth {
98   $::auth->assert('config');
99 }
100
101 sub check_type {
102   my ($self) = @_;
103
104   die "Invalid CSV import type" if none { $_ eq $::form->{profile}->{type} } qw(parts customers_vendors addresses contacts projects);
105   $self->type($::form->{profile}->{type});
106 }
107
108 sub ensure_form_structure {
109   my ($self, %params) = @_;
110
111   $::form->{profile}  = {} unless ref $::form->{profile}  eq 'HASH';
112   $::form->{settings} = {} unless ref $::form->{settings} eq 'HASH';
113 }
114
115 #
116 # helpers
117 #
118
119 sub render_inputs {
120   my ($self, %params) = @_;
121
122   $self->all_charsets([ [ 'UTF-8',       'UTF-8'                 ],
123                         [ 'ISO-8859-1',  'ISO-8859-1 (Latin 1)'  ],
124                         [ 'ISO-8859-15', 'ISO-8859-15 (Latin 9)' ],
125                         [ 'CP850',       'CP850 (DOS/ANSI)'      ],
126                         [ 'CP1252',      'CP1252 (Windows)'      ],
127                       ]);
128
129   my %char_map = $self->char_map;
130
131   foreach my $type (qw(sep quote escape)) {
132     my $sub = "all_${type}_chars";
133     $self->$sub([ sort { $a->[0] cmp $b->[0] } values %{ $char_map{$type} } ]);
134
135     my $char = $self->profile->get($type . '_char');
136     $sub     = "${type}_char";
137     $self->$sub(($char_map{$type}->{$char} || [])->[0] || $char);
138   }
139
140   $self->file(SL::SessionFile->new($self->csv_file_name));
141
142   my $title = $self->type eq 'customers_vendors' ? $::locale->text('CSV import: customers and vendors')
143             : $self->type eq 'addresses'         ? $::locale->text('CSV import: shipping addresses')
144             : $self->type eq 'contacts'          ? $::locale->text('CSV import: contacts')
145             : $self->type eq 'parts'             ? $::locale->text('CSV import: parts and services')
146             : $self->type eq 'projects'          ? $::locale->text('CSV import: projects')
147             : die;
148
149   if ($self->{type} eq 'parts') {
150     $self->all_buchungsgruppen(SL::DB::Manager::Buchungsgruppe->get_all_sorted);
151     $self->all_units(SL::DB::Manager::Unit->get_all_sorted);
152   }
153
154   $self->setup_help;
155
156   $self->render('csv_import/form', title => $title);
157 }
158
159 sub test_and_import {
160   my ($self, %params) = @_;
161
162   $self->profile_from_form;
163
164   if ($::form->{file}) {
165     my $file = SL::SessionFile->new($self->csv_file_name, mode => '>');
166     $file->fh->print($::form->{file});
167     $file->fh->close;
168   }
169
170   my $file = SL::SessionFile->new($self->csv_file_name, mode => '<', encoding => $self->profile->get('charset'));
171   if (!$file->fh) {
172     flash('error', $::locale->text('No file has been uploaded yet.'));
173     return $self->action_new;
174   }
175
176   $self->file($file);
177
178   my $worker = $self->worker();
179
180   $worker->run;
181
182   $self->num_imported(0);
183   $worker->save_objects if !$params{test};
184
185   $self->num_importable(scalar grep { !$_ } map { scalar @{ $_->{errors} } } @{ $self->data || [] });
186   $self->import_status($params{test} ? 'tested' : 'imported');
187
188   flash('info', $::locale->text('Objects have been imported.')) if !$params{test};
189
190   $self->action_new;
191 }
192
193 sub load_default_profile {
194   my ($self) = @_;
195
196   my $profile;
197   if ($::form->{profile}->{id}) {
198     $profile = SL::DB::Manager::CsvImportProfile->find_by(id => $::form->{profile}->{id}, login => $::myconfig{login});
199   }
200   $profile ||= SL::DB::Manager::CsvImportProfile->find_by(type => $self->{type}, is_default => 1, login => $::myconfig{login});
201   $profile ||= SL::DB::CsvImportProfile->new(type => $self->{type}, login => $::myconfig{login});
202
203   $self->profile($profile);
204   $self->profile->set_defaults;
205 }
206
207 sub load_all_profiles {
208   my ($self, %params) = @_;
209
210   $self->all_profiles(SL::DB::Manager::CsvImportProfile->get_all(
211     where => [
212       type  => $self->type,
213       login => $::myconfig{login},
214     ],
215   sort_by => 'name'));
216 }
217
218 sub profile_from_form {
219   my ($self, $existing_profile) = @_;
220
221   delete $::form->{profile}->{id};
222
223   my %char_map = $self->char_map;
224   my @settings;
225
226   foreach my $type (qw(sep quote escape)) {
227     my %rev_chars = map { $char_map{$type}->{$_}->[0] => $_ } keys %{ $char_map{$type} };
228     my $char      = $::form->{"${type}_char"} eq 'custom' ? $::form->{"custom_${type}_char"} : $rev_chars{ $::form->{"${type}_char"} };
229
230     push @settings, { key => "${type}_char", value => $char };
231   }
232
233   if ($self->type eq 'parts') {
234     $::form->{settings}->{sellprice_adjustment} = $::form->parse_amount(\%::myconfig, $::form->{settings}->{sellprice_adjustment});
235   }
236
237   delete $::form->{profile}->{id};
238   $self->profile($existing_profile || SL::DB::CsvImportProfile->new(login => $::myconfig{login}));
239   $self->profile->assign_attributes(%{ $::form->{profile} });
240   $self->profile->settings(map({ { key => $_, value => $::form->{settings}->{$_} } } keys %{ $::form->{settings} }),
241                            @settings);
242   $self->profile->set_defaults;
243 }
244
245 sub char_map {
246   return ( sep    => { ','  => [ 'comma',     $::locale->text('Comma')     ],
247                        ';'  => [ 'semicolon', $::locale->text('Semicolon') ],
248                        "\t" => [ 'tab',       $::locale->text('Tab')       ],
249                        ' '  => [ 'space',     $::locale->text('Space')     ],
250                      },
251            quote  => { '"' => [ 'quote', $::locale->text('Quotes') ],
252                        "'" => [ 'singlequote', $::locale->text('Single quotes') ],
253                      },
254            escape => { '"' => [ 'quote', $::locale->text('Quotes') ],
255                        "'" => [ 'singlequote', $::locale->text('Single quotes') ],
256                      },
257          );
258 }
259
260 sub csv_file_name {
261   my ($self) = @_;
262   return "csv-import-" . $self->type . ".csv";
263 }
264
265 sub init_worker {
266   my $self = shift;
267
268   my @args = (controller => $self);
269
270   if ( $self->file() ) {
271     push(@args, file => $self->file());
272   }
273
274   return $self->{type} eq 'customers_vendors' ? SL::Controller::CsvImport::CustomerVendor->new(@args)
275        : $self->{type} eq 'contacts'          ? SL::Controller::CsvImport::Contact->new(@args)
276        : $self->{type} eq 'addresses'         ? SL::Controller::CsvImport::Shipto->new(@args)
277        : $self->{type} eq 'parts'             ? SL::Controller::CsvImport::Part->new(@args)
278        : $self->{type} eq 'projects'          ? SL::Controller::CsvImport::Project->new(@args)
279        :                                        die "Program logic error";
280 }
281
282 sub setup_help {
283   my ($self) = @_;
284
285   $self->worker->setup_displayable_columns;
286 }
287
288
289 1;