Mehr Dokumentation
[kivitendo-erp.git] / SL / Helper / Csv.pm
1 package SL::Helper::Csv;
2
3 use strict;
4 use warnings;
5
6 use Carp;
7 use IO::File;
8 use Params::Validate qw(:all);
9 use Text::CSV;
10 use Rose::Object::MakeMethods::Generic scalar => [ qw(
11   file encoding sep_char quote_char escape_char header profile class
12   numberformat dateformat ignore_unknown_columns _io _csv _objects _parsed
13   _data _errors
14 ) ];
15
16 use SL::Helper::Csv::Dispatcher;
17
18 # public interface
19
20 sub new {
21   my $class  = shift;
22   my %params = validate(@_, {
23     sep_char               => { default => ';' },
24     quote_char             => { default => '"' },
25     escape_char            => { default => '"' },
26     header                 => { type    => ARRAYREF, optional => 1 },
27     profile                => { type    => HASHREF,  optional => 1 },
28     file                   => 1,
29     encoding               => 0,
30     class                  => 0,
31     numberformat           => 0,
32     dateformat             => 0,
33     ignore_unknown_columns => 0,
34   });
35   my $self = bless {}, $class;
36
37   $self->$_($params{$_}) for keys %params;
38
39   $self->_io(IO::File->new);
40   $self->_csv(Text::CSV->new({
41     binary => 1,
42     sep_char    => $self->sep_char,
43     quote_char  => $self->quote_char,
44     escape_char => $self->escape_char,
45
46   }));
47   $self->_errors([]);
48
49   return $self;
50 }
51
52 sub parse {
53   my ($self, %params) = @_;
54
55   $self->_open_file;
56   return if ! $self->_check_header;
57   return if ! $self->dispatcher->parse_profile;
58   return if ! $self->_parse_data;
59
60   $self->_parsed(1);
61   return $self;
62 }
63
64 sub get_data {
65   $_[0]->_data;
66 }
67
68 sub get_objects {
69   my ($self, %params) = @_;
70   croak 'no class given'   unless $self->class;
71   croak 'must parse first' unless $self->_parsed;
72
73   $self->_make_objects unless $self->_objects;
74   return wantarray ? @{ $self->_objects } : $self->_objects;
75 }
76
77 sub errors {
78   @{ $_[0]->_errors }
79 }
80
81 sub check_header {
82   $_[0]->_check_header;
83 }
84
85 # private stuff
86
87 sub _open_file {
88   my ($self, %params) = @_;
89
90   $self->encoding($self->_guess_encoding) if !$self->encoding;
91
92   $self->_io->open($self->file, '<' . $self->_encode_layer)
93     or die "could not open file " . $self->file;
94
95   return $self->_io;
96 }
97
98 sub _check_header {
99   my ($self, %params) = @_;
100   return $self->header if $self->header;
101
102   my $header = $self->_csv->getline($self->_io);
103
104   $self->_push_error([
105     $self->_csv->error_input,
106     $self->_csv->error_diag,
107     0,
108   ]) unless $header;
109
110   $self->header($header);
111 }
112
113 sub _parse_data {
114   my ($self, %params) = @_;
115   my (@data, @errors);
116
117   $self->_csv->column_names(@{ $self->header });
118
119   while (1) {
120     my $row = $self->_csv->getline($self->_io);
121     last if $self->_csv->eof;
122     if ($row) {
123       my %hr;
124       @hr{@{ $self->header }} = @$row;
125       push @data, \%hr;
126     } else {
127       push @errors, [
128         $self->_csv->error_input,
129         $self->_csv->error_diag,
130         $self->_io->input_line_number,
131       ];
132     }
133   }
134
135   $self->_data(\@data);
136   $self->_push_error(@errors);
137
138   return ! @errors;
139 }
140
141 sub _encode_layer {
142   ':encoding(' . $_[0]->encoding . ')';
143 }
144
145 sub _make_objects {
146   my ($self, %params) = @_;
147   my @objs;
148
149   eval "require " . $self->class;
150   local $::myconfig{numberformat} = $self->numberformat if $self->numberformat;
151   local $::myconfig{dateformat}   = $self->dateformat   if $self->dateformat;
152
153   for my $line (@{ $self->_data }) {
154     my $tmp_obj = $self->class->new;
155     $self->dispatcher->dispatch($tmp_obj, $line);
156     push @objs, $tmp_obj;
157   }
158
159   $self->_objects(\@objs);
160 }
161
162 sub dispatcher {
163   my ($self, %params) = @_;
164
165   $self->{_dispatcher} ||= $self->_make_dispatcher;
166 }
167
168 sub _make_dispatcher {
169   my ($self, %params) = @_;
170
171   die 'need a header to make a dispatcher' unless $self->header;
172
173   return SL::Helper::Csv::Dispatcher->new($self);
174 }
175
176 sub _guess_encoding {
177   # won't fix
178   'utf-8';
179 }
180
181 sub _push_error {
182   my ($self, @errors) = @_;
183   my @new_errors = ($self->errors, @errors);
184   $self->_errors(\@new_errors);
185 }
186
187
188 1;
189
190 __END__
191
192 =encoding utf-8
193
194 =head1 NAME
195
196 SL::Helper::Csv - take care of csv file uploads
197
198 =head1 SYNOPSIS
199
200   use SL::Helper::Csv;
201
202   my $csv = SL::Helper::Csv->new(
203     file        => \$::form->{upload_file},
204     encoding    => 'utf-8', # undef means utf8
205     sep_char    => ',',     # default ';'
206     quote_char  => '\'',    # default '"'
207     escape_char => '"',     # default '"'
208     header      => [qw(id text sellprice word)], # see later
209     profile     => { sellprice => 'sellprice_as_number' },
210     class       => 'SL::DB::CsvLine',   # if present, map lines to this
211   );
212
213   my $status  = $csv->parse;
214   my $hrefs   = $csv->get_data;
215   my @objects = $csv->get_objects;
216
217   my @errors  = $csv->errors;
218
219 =head1 DESCRIPTION
220
221 See Synopsis.
222
223 Text::CSV offeres already good functions to get lines out of a csv file, but in
224 most cases you will want those line to be parsed into hashes or even objects,
225 so this model just skips ahead and gives you objects.
226
227 Its basic assumptions are:
228
229 =over 4
230
231 =item You do know what you expect to be in that csv file.
232
233 This means first and foremost you have knowledge about encoding, number and
234 date format, csv parameters such as quoting and separation characters. You also
235 know what content will be in that csv and what L<Rose::DB> is responsible for
236 it. You provide valid header columns and their mapping to the objects.
237
238 =item You do NOT know if the csv provider yields to your expectations.
239
240 Stuff that does not work with what you expect should not crash anything, but
241 give you a hint what went wrong. As a result, if you remeber to check for
242 errors after each step, you should be fine.
243
244 =item Data does not make sense. It's just data.
245
246 Almost all data imports have some type of constraints. Some data needs to be
247 unique, other data needs to be connected to existing data sets. This will not
248 happen here. You will receive a plain mapping of the data into the class tree,
249 nothing more.
250
251 =back
252
253 =head1 METHODS
254
255 =over 4
256
257 =item C<new> PARAMS
258
259 Standard constructor. You can use this to set most of the data.
260
261 =item C<parse>
262
263 Do the actual work. Will return true ($self actually) if success, undef if not.
264
265 =item C<get_objects>
266
267 Parse the data into objects and return those.
268
269 This method will return list or arrayref depending on context.
270
271 =item C<get_data>
272
273 Returns an arrayref of the raw lines as hashrefs.
274
275 =item C<errors>
276
277 Return all errors that came up during parsing. See error handling for detailed
278 information.
279
280 =back
281
282 =head1 PARAMS
283
284 =over 4
285
286 =item C<file>
287
288 The file which contents are to be read. Can be a name of a physical file or a
289 scalar ref for memory data.
290
291 =item C<encoding>
292
293 Encoding of the CSV file. Note that this module does not do any encoding
294 guessing. Know what your data is. Defaults to utf-8.
295
296 =item C<sep_char>
297
298 =item C<quote_char>
299
300 =item C<escape_char>
301
302 Same as in L<Text::CSV>
303
304 =item C<header> \@FIELDS
305
306 Can be an array of columns, in this case the first line is not used as a
307 header. Empty header fields will be ignored in objects.
308
309 =item C<profile> \%ACCESSORS
310
311 May be used to map header fields to custom accessors. Example:
312
313   { listprice => listprice_as_number }
314
315 In this case C<listprice_as_number> will be used to read in values from the
316 C<listprice> column.
317
318 In case of a One-To-One relationsship these can also be set over
319 relationsships by sparating the steps with a dot (C<.>). This will work:
320
321   { customer => 'customer.name' }
322
323 And will result in something like this:
324
325   $obj->customer($obj->meta->relationship('customer')->class->new);
326   $obj->customer->name($csv_line->{customer})
327
328 But beware, this will not try to look up anything in the database. You will
329 simply receive objects that represent what the profile defined. If some of
330 these information are unique, and should be connected to preexisting data, you
331 will have to do that for yourself. Since you provided the profile, it is
332 assumed you know what to do in this case.
333
334 =item C<class>
335
336 If present, the line will be handed to the new sub of this class,
337 and the return value used instead of the line itself.
338
339 =item C<ignore_unknown_columns>
340
341 If set, the import will ignore unkown header columns. Useful for lazy imports,
342 but deactivated by default.
343
344 =back
345
346 =head1 ERROR HANDLING
347
348 After parsing a file all errors will be accumulated into C<errors>.
349
350 Each entry is an arrayref with the following structure:
351
352  [
353  0  offending raw input,
354  1  Text::CSV error code if Text:CSV signalled an error, 0 else,
355  2  error diagnostics,
356  3  position in line,
357  4  estimated line in file,
358  ]
359
360 Note that the last entry can be off, but will give an estimate.
361
362 =head1 CAVEATS
363
364 =over 4
365
366 =item *
367
368 sep_char, quote_char, and escape_char are passed to Text::CSV on creation.
369 Changing them later has no effect currently.
370
371 =item *
372
373 Encoding errors are not dealt with properly.
374
375 =back
376
377 =head1 TODO
378
379 Dispatch to child objects, like this:
380
381  $csv = SL::Helper::Csv->new(
382    file  => ...
383    class => SL::DB::Part,
384    profile => [
385      makemodel => {
386        make_1  => make,
387        model_1 => model,
388      },
389      makemodel => {
390        make_2  => make,
391        model_2 => model,
392      },
393    ]
394  );
395
396 =head1 AUTHOR
397
398 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>
399
400 =cut