Bug 23077: Don't fill cardnumber with empty string
[koha.git] / Koha / Patrons / Import.pm
1 package Koha::Patrons::Import;
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18 use Modern::Perl;
19 use Moo;
20 use namespace::clean;
21
22 use Carp;
23 use Text::CSV;
24
25 use C4::Members;
26 use C4::Members::Attributes qw(:all);
27 use C4::Members::AttributeTypes;
28
29 use Koha::Libraries;
30 use Koha::Patrons;
31 use Koha::Patron::Categories;
32 use Koha::Patron::Debarments;
33 use Koha::DateUtils;
34
35 =head1 NAME
36
37 Koha::Patrons::Import - Perl Module containing import_patrons method exported from import_borrowers script.
38
39 =head1 SYNOPSIS
40
41 use Koha::Patrons::Import;
42
43 =head1 DESCRIPTION
44
45 This module contains one method for importing patrons in bulk.
46
47 =head1 FUNCTIONS
48
49 =head2 import_patrons
50
51  my $return = Koha::Patrons::Import::import_patrons($params);
52
53 Applies various checks and imports patrons in bulk from a csv file.
54
55 Further pod documentation needed here.
56
57 =cut
58
59 has 'today_iso' => ( is => 'ro', lazy => 1,
60     default => sub { output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); }, );
61
62 has 'text_csv' => ( is => 'rw', lazy => 1,
63     default => sub { Text::CSV->new( { binary => 1, } ); },  );
64
65 sub import_patrons {
66     my ($self, $params) = @_;
67
68     my $handle = $params->{file};
69     unless( $handle ) { carp('No file handle passed in!'); return; }
70
71     my $matchpoint           = $params->{matchpoint};
72     my $defaults             = $params->{defaults};
73     my $ext_preserve         = $params->{preserve_extended_attributes};
74     my $overwrite_cardnumber = $params->{overwrite_cardnumber};
75     my $extended             = C4::Context->preference('ExtendedPatronAttributes');
76     my $set_messaging_prefs  = C4::Context->preference('EnhancedMessagingPreferences');
77
78     my @columnkeys = $self->set_column_keys($extended);
79     my @feedback;
80     my @errors;
81
82     my $imported    = 0;
83     my $alreadyindb = 0;
84     my $overwritten = 0;
85     my $invalid     = 0;
86     my @imported_borrowers;
87     my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
88
89     # Use header line to construct key to column map
90     my %csvkeycol;
91     my $borrowerline = <$handle>;
92     my @csvcolumns   = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
93     push(@feedback, { feedback => 1, name => 'headerrow', value => join( ', ', @csvcolumns ) });
94
95     my @criticals = qw( surname );    # there probably should be others - rm branchcode && categorycode
96   LINE: while ( my $borrowerline = <$handle> ) {
97         my $line_number = $.;
98         my %borrower;
99         my @missing_criticals;
100
101         my $status  = $self->text_csv->parse($borrowerline);
102         my @columns = $self->text_csv->fields();
103         if ( !$status ) {
104             push @missing_criticals, { badparse => 1, line => $line_number, lineraw => $borrowerline };
105         }
106         elsif ( @columns == @columnkeys ) {
107             @borrower{@columnkeys} = @columns;
108
109             # MJR: try to fill blanks gracefully by using default values
110             foreach my $key (@columnkeys) {
111                 if ( $borrower{$key} !~ /\S/ ) {
112                     $borrower{$key} = $defaults->{$key};
113                 }
114             }
115         }
116         else {
117             # MJR: try to recover gracefully by using default values
118             foreach my $key (@columnkeys) {
119                 if ( defined( $csvkeycol{$key} ) and $columns[ $csvkeycol{$key} ] =~ /\S/ ) {
120                     $borrower{$key} = $columns[ $csvkeycol{$key} ];
121                 }
122                 elsif ( $defaults->{$key} ) {
123                     $borrower{$key} = $defaults->{$key};
124                 }
125                 elsif ( scalar grep { $key eq $_ } @criticals ) {
126
127                     # a critical field is undefined
128                     push @missing_criticals, { key => $key, line => $., lineraw => $borrowerline };
129                 }
130                 else {
131                     $borrower{$key} = '';
132                 }
133             }
134         }
135         $borrower{cardnumber} = undef unless $borrower{cardnumber};
136
137         # Check if borrower category code exists and if it matches to a known category. Pushing error to missing_criticals otherwise.
138         $self->check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
139
140         # Check if branch code exists and if it matches to a branch name. Pushing error to missing_criticals otherwise.
141         $self->check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
142
143         # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
144         $self->format_dates({borrower => \%borrower, lineraw => $borrowerline, line => $line_number, missing_criticals => \@missing_criticals, });
145
146         if (@missing_criticals) {
147             foreach (@missing_criticals) {
148                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
149                 $_->{surname}        = $borrower{surname}        || 'UNDEF';
150             }
151             $invalid++;
152             ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
153
154             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
155             next LINE;
156         }
157
158         # Set patron attributes if extended.
159         my $patron_attributes = $self->set_patron_attributes($extended, $borrower{patron_attributes}, \@feedback);
160         if( $extended ) { delete $borrower{patron_attributes}; } # Not really a field in borrowers.
161
162         # Default date enrolled and date expiry if not already set.
163         $borrower{dateenrolled} = $self->today_iso() unless $borrower{dateenrolled};
164         $borrower{dateexpiry} = Koha::Patron::Categories->find( $borrower{categorycode} )->get_expiry_date( $borrower{dateenrolled} ) unless $borrower{dateexpiry};
165
166         my $borrowernumber;
167         my ( $member, $patron );
168         if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
169             $patron = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
170         }
171         elsif ( defined($matchpoint) && ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
172             $patron = Koha::Patrons->find( { userid => $borrower{userid} } );
173         }
174         elsif ($extended) {
175             if ( defined($matchpoint_attr_type) ) {
176                 foreach my $attr (@$patron_attributes) {
177                     if ( $attr->{code} eq $matchpoint and $attr->{value} ne '' ) {
178                         my @borrowernumbers = $matchpoint_attr_type->get_patrons( $attr->{value} );
179                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
180                         $patron = Koha::Patrons->find( $borrowernumber );
181                         last;
182                     }
183                 }
184             }
185         }
186
187         if ($patron) {
188             $member = $patron->unblessed;
189             $borrowernumber = $member->{'borrowernumber'};
190         } else {
191             $member = {};
192         }
193
194         if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
195             push @errors,
196               {
197                 invalid_cardnumber => 1,
198                 borrowernumber     => $borrowernumber,
199                 cardnumber         => $borrower{cardnumber}
200               };
201             $invalid++;
202             next;
203         }
204
205
206         # Check if the userid provided does not exist yet
207         if (    defined($matchpoint)
208             and $matchpoint ne 'userid'
209             and exists $borrower{userid}
210             and $borrower{userid}
211             and not ( $borrowernumber ? $patron->userid( $borrower{userid} )->has_valid_userid : Koha::Patron->new( { userid => $borrower{userid} } )->has_valid_userid )
212         ) {
213             push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
214             $invalid++;
215             next LINE;
216         }
217
218         if ($borrowernumber) {
219
220             # borrower exists
221             unless ($overwrite_cardnumber) {
222                 $alreadyindb++;
223                 push(
224                     @feedback,
225                     {
226                         already_in_db => 1,
227                         value         => $borrower{'surname'} . ' / ' . $borrowernumber
228                     }
229                 );
230                 next LINE;
231             }
232             $borrower{'borrowernumber'} = $borrowernumber;
233             for my $col ( keys %borrower ) {
234
235                 # use values from extant patron unless our csv file includes this column or we provided a default.
236                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
237
238                 # The password is always encrypted, skip it!
239                 next if $col eq 'password';
240
241                 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
242                     $borrower{$col} = $member->{$col} if ( $member->{$col} );
243                 }
244             }
245
246             my $patron = Koha::Patrons->find( $borrowernumber );
247             eval { $patron->set(\%borrower)->store };
248             if ( $@ ) {
249                 $invalid++;
250
251                 push(
252                     @errors,
253                     {
254                         # TODO We can raise a better error
255                         name  => 'lastinvalid',
256                         value => $borrower{'surname'} . ' / ' . $borrowernumber
257                     }
258                 );
259                 next LINE;
260             }
261             # Don't add a new restriction if the existing 'combined' restriction matches this one
262             if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
263
264                 # Check to see if this debarment already exists
265                 my $debarrments = GetDebarments(
266                     {
267                         borrowernumber => $borrowernumber,
268                         expiration     => $borrower{debarred},
269                         comment        => $borrower{debarredcomment}
270                     }
271                 );
272
273                 # If it doesn't, then add it!
274                 unless (@$debarrments) {
275                     AddDebarment(
276                         {
277                             borrowernumber => $borrowernumber,
278                             expiration     => $borrower{debarred},
279                             comment        => $borrower{debarredcomment}
280                         }
281                     );
282                 }
283             }
284             if ($extended) {
285                 if ($ext_preserve) {
286                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
287                     $patron_attributes = extended_attributes_merge( $old_attributes, $patron_attributes );
288                 }
289                 push @errors, { unknown_error => 1 }
290                   unless SetBorrowerAttributes( $borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
291             }
292             $overwritten++;
293             push(
294                 @feedback,
295                 {
296                     feedback => 1,
297                     name     => 'lastoverwritten',
298                     value    => $borrower{'surname'} . ' / ' . $borrowernumber
299                 }
300             );
301         }
302         else {
303             my $patron = eval {
304                 Koha::Patron->new(\%borrower)->store;
305             };
306             unless ( $@ ) {
307
308                 if ( $patron->is_debarred ) {
309                     AddDebarment(
310                         {
311                             borrowernumber => $patron->borrowernumber,
312                             expiration     => $patron->debarred,
313                             comment        => $patron->debarredcomment,
314                         }
315                     );
316                 }
317
318                 if ($extended) {
319                     SetBorrowerAttributes( $patron->borrowernumber, $patron_attributes );
320                 }
321
322                 if ($set_messaging_prefs) {
323                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
324                         {
325                             borrowernumber => $patron->borrowernumber,
326                             categorycode   => $patron->categorycode,
327                         }
328                     );
329                 }
330
331                 $imported++;
332                 push @imported_borrowers, $patron->borrowernumber; #for patronlist
333                 push(
334                     @feedback,
335                     {
336                         feedback => 1,
337                         name     => 'lastimported',
338                         value    => $patron->surname . ' / ' . $patron->borrowernumber,
339                     }
340                 );
341             }
342             else {
343                 $invalid++;
344                 push @errors, { unknown_error => 1 };
345                 push(
346                     @errors,
347                     {
348                         name  => 'lastinvalid',
349                         value => $borrower{'surname'} . ' / Create patron',
350                     }
351                 );
352             }
353         }
354     }
355
356     return {
357         feedback      => \@feedback,
358         errors        => \@errors,
359         imported      => $imported,
360         overwritten   => $overwritten,
361         already_in_db => $alreadyindb,
362         invalid       => $invalid,
363         imported_borrowers => \@imported_borrowers,
364     };
365 }
366
367 =head2 prepare_columns
368
369  my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
370
371 Returns an array of all column key and populates a hash of colunm key positions.
372
373 =cut
374
375 sub prepare_columns {
376     my ($self, $params) = @_;
377
378     my $status = $self->text_csv->parse($params->{headerrow});
379     unless( $status ) {
380         push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
381         return;
382     }
383
384     my @csvcolumns = $self->text_csv->fields();
385     my $col = 0;
386     foreach my $keycol (@csvcolumns) {
387         # columnkeys don't contain whitespace, but some stupid tools add it
388         $keycol =~ s/ +//g;
389         $params->{keycol}->{$keycol} = $col++;
390     }
391
392     return @csvcolumns;
393 }
394
395 =head2 set_attribute_types
396
397  my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
398
399 Returns an attribute type based on matchpoint parameter.
400
401 =cut
402
403 sub set_attribute_types {
404     my ($self, $params) = @_;
405
406     my $attribute_types;
407     if( $params->{extended} ) {
408         $attribute_types = C4::Members::AttributeTypes->fetch($params->{matchpoint});
409     }
410
411     return $attribute_types;
412 }
413
414 =head2 set_column_keys
415
416  my @columnkeys = set_column_keys($extended);
417
418 Returns an array of borrowers' table columns.
419
420 =cut
421
422 sub set_column_keys {
423     my ($self, $extended) = @_;
424
425     my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
426     push( @columnkeys, 'patron_attributes' ) if $extended;
427
428     return @columnkeys;
429 }
430
431 =head2 set_patron_attributes
432
433  my $patron_attributes = set_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
434
435 Returns a reference to array of hashrefs data structure as expected by SetBorrowerAttributes.
436
437 =cut
438
439 sub set_patron_attributes {
440     my ($self, $extended, $patron_attributes, $feedback) = @_;
441
442     unless( $extended ) { return; }
443     unless( defined($patron_attributes) ) { return; }
444
445     # Fixup double quotes in case we are passed smart quotes
446     $patron_attributes =~ s/\xe2\x80\x9c/"/g;
447     $patron_attributes =~ s/\xe2\x80\x9d/"/g;
448
449     push (@$feedback, { feedback => 1, name => 'attribute string', value => $patron_attributes });
450
451     my $result = extended_attributes_code_value_arrayref($patron_attributes);
452
453     return $result;
454 }
455
456 =head2 check_branch_code
457
458  check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
459
460 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
461
462 =cut
463
464 sub check_branch_code {
465     my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
466
467     # No branch code
468     unless( $branchcode ) {
469         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline, });
470         return;
471     }
472
473     # look for branch code
474     my $library = Koha::Libraries->find( $branchcode );
475     unless( $library ) {
476         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline,
477                                      value => $branchcode, branch_map => 1, });
478     }
479 }
480
481 =head2 check_borrower_category
482
483  check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
484
485 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
486
487 =cut
488
489 sub check_borrower_category {
490     my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
491
492     # No branch code
493     unless( $categorycode ) {
494         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline, });
495         return;
496     }
497
498     # Looking for borrower category
499     my $category = Koha::Patron::Categories->find($categorycode);
500     unless( $category ) {
501         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline,
502                                      value => $categorycode, category_map => 1, });
503     }
504 }
505
506 =head2 format_dates
507
508  format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
509
510 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
511 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
512
513 =cut
514
515 sub format_dates {
516     my ($self, $params) = @_;
517
518     foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry date_renewed)) {
519         my $tempdate = $params->{borrower}->{$date_type} or next();
520         my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
521
522         if ($formatted_date) {
523             $params->{borrower}->{$date_type} = $formatted_date;
524         } else {
525             $params->{borrower}->{$date_type} = '';
526             push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => $params->{lineraw}, bad_date => 1 });
527         }
528     }
529 }
530
531 1;
532
533 =head1 AUTHOR
534
535 Koha Team
536
537 =cut