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