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