Bug 23473: (follow-up) Catch and show password exceptions
[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
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 use Moo;
20 use namespace::clean;
21
22 use Carp;
23 use Text::CSV;
24 use Encode qw( decode_utf8 );
25 use Try::Tiny;
26
27 use C4::Members;
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 $overwrite_passwords  = $params->{overwrite_passwords};
76     my $extended             = C4::Context->preference('ExtendedPatronAttributes');
77     my $set_messaging_prefs  = C4::Context->preference('EnhancedMessagingPreferences');
78
79     my @columnkeys = $self->set_column_keys($extended);
80     my @feedback;
81     my @errors;
82
83     my $imported    = 0;
84     my $alreadyindb = 0;
85     my $overwritten = 0;
86     my $invalid     = 0;
87     my @imported_borrowers;
88     my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
89
90     # Use header line to construct key to column map
91     my %csvkeycol;
92     my $borrowerline = <$handle>;
93     my @csvcolumns   = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
94     push(@feedback, { feedback => 1, name => 'headerrow', value => join( ', ', @csvcolumns ) });
95
96     my @criticals = qw( surname );    # there probably should be others - rm branchcode && categorycode
97   LINE: while ( my $borrowerline = <$handle> ) {
98         my $line_number = $.;
99         my %borrower;
100         my @missing_criticals;
101
102         my $status  = $self->text_csv->parse($borrowerline);
103         my @columns = $self->text_csv->fields();
104         if ( !$status ) {
105             push @missing_criticals, { badparse => 1, line => $line_number, lineraw => decode_utf8($borrowerline) };
106         }
107         elsif ( @columns == @columnkeys ) {
108             @borrower{@columnkeys} = @columns;
109
110             # MJR: try to fill blanks gracefully by using default values
111             foreach my $key (@columnkeys) {
112                 if ( $borrower{$key} !~ /\S/ ) {
113                     $borrower{$key} = $defaults->{$key};
114                 }
115             }
116         }
117         else {
118             # MJR: try to recover gracefully by using default values
119             foreach my $key (@columnkeys) {
120                 if ( defined( $csvkeycol{$key} ) and $columns[ $csvkeycol{$key} ] =~ /\S/ ) {
121                     $borrower{$key} = $columns[ $csvkeycol{$key} ];
122                 }
123                 elsif ( $defaults->{$key} ) {
124                     $borrower{$key} = $defaults->{$key};
125                 }
126                 elsif ( scalar grep { $key eq $_ } @criticals ) {
127
128                     # a critical field is undefined
129                     push @missing_criticals, { key => $key, line => $., lineraw => decode_utf8($borrowerline) };
130                 }
131                 else {
132                     $borrower{$key} = '';
133                 }
134             }
135         }
136
137         $borrower{cardnumber} = undef if $borrower{cardnumber} eq "";
138
139         # Check if borrower category code exists and if it matches to a known category. Pushing error to missing_criticals otherwise.
140         $self->check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
141
142         # Check if branch code exists and if it matches to a branch name. Pushing error to missing_criticals otherwise.
143         $self->check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
144
145         # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
146         $self->format_dates({borrower => \%borrower, lineraw => $borrowerline, line => $line_number, missing_criticals => \@missing_criticals, });
147
148         if (@missing_criticals) {
149             foreach (@missing_criticals) {
150                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
151                 $_->{surname}        = $borrower{surname}        || 'UNDEF';
152             }
153             $invalid++;
154             ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
155
156             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
157             next LINE;
158         }
159
160         # Generate patron attributes if extended.
161         my $patron_attributes = $self->generate_patron_attributes($extended, $borrower{patron_attributes}, \@feedback);
162         if( $extended ) { delete $borrower{patron_attributes}; } # Not really a field in borrowers.
163
164         # Default date enrolled and date expiry if not already set.
165         $borrower{dateenrolled} = $self->today_iso() unless $borrower{dateenrolled};
166         $borrower{dateexpiry} = Koha::Patron::Categories->find( $borrower{categorycode} )->get_expiry_date( $borrower{dateenrolled} ) unless $borrower{dateexpiry};
167
168         my $borrowernumber;
169         my ( $member, $patron );
170         if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
171             $patron = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
172         }
173         elsif ( defined($matchpoint) && ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
174             $patron = Koha::Patrons->find( { userid => $borrower{userid} } );
175         }
176         elsif ($extended) {
177             if ( defined($matchpoint_attr_type) ) {
178                 foreach my $attr (@$patron_attributes) {
179                     if ( $attr->{code} eq $matchpoint and $attr->{attribute} ne '' ) {
180                         my @borrowernumbers = Koha::Patron::Attributes->search(
181                             {
182                                 code      => $matchpoint_attr_type->code,
183                                 attribute => $attr->{attribute}
184                             }
185                         )->get_column('borrowernumber');
186
187                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
188                         $patron = Koha::Patrons->find( $borrowernumber );
189                         last;
190                     }
191                 }
192             }
193         }
194
195         if ($patron) {
196             $member = $patron->unblessed;
197             $borrowernumber = $member->{'borrowernumber'};
198         } else {
199             $member = {};
200         }
201
202         if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
203             push @errors,
204               {
205                 invalid_cardnumber => 1,
206                 borrowernumber     => $borrowernumber,
207                 cardnumber         => $borrower{cardnumber}
208               };
209             $invalid++;
210             next;
211         }
212
213
214         # Check if the userid provided does not exist yet
215         if (    defined($matchpoint)
216             and $matchpoint ne 'userid'
217             and exists $borrower{userid}
218             and $borrower{userid}
219             and not ( $borrowernumber ? $patron->userid( $borrower{userid} )->has_valid_userid : Koha::Patron->new( { userid => $borrower{userid} } )->has_valid_userid )
220         ) {
221             push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
222             $invalid++;
223             next LINE;
224         }
225
226         my $relationship        = $borrower{relationship};
227         my $guarantor_id        = $borrower{guarantor_id};
228         delete $borrower{relationship};
229         delete $borrower{guarantor_id};
230
231         # Remove warning for int datatype that cannot be null
232         # Argument "" isn't numeric in numeric eq (==) at /usr/share/perl5/DBIx/Class/Row.pm line 1018
233         for my $field (
234             qw( privacy privacy_guarantor_fines privacy_guarantor_checkouts anonymized ))
235         {
236             delete $borrower{$field}
237               if exists $borrower{$field} and $borrower{$field} eq "";
238         }
239
240         if ($borrowernumber) {
241
242             # borrower exists
243             unless ($overwrite_cardnumber) {
244                 $alreadyindb++;
245                 push(
246                     @feedback,
247                     {
248                         already_in_db => 1,
249                         value         => $borrower{'surname'} . ' / ' . $borrowernumber
250                     }
251                 );
252                 next LINE;
253             }
254             $borrower{'borrowernumber'} = $borrowernumber;
255             for my $col ( keys %borrower ) {
256
257                 # use values from extant patron unless our csv file includes this column or we provided a default.
258                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
259
260                 # The password is always encrypted, skip it unless we are forcing overwrite!
261                 next if $col eq 'password' && !$overwrite_passwords;
262
263                 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
264                     $borrower{$col} = $member->{$col} if ( $member->{$col} );
265                 }
266             }
267
268             my $patron = Koha::Patrons->find( $borrowernumber );
269             eval { $patron->set(\%borrower)->store };
270             if ( $@ ) {
271                 $invalid++;
272
273                 push(
274                     @errors,
275                     {
276                         # TODO We can raise a better error
277                         name  => 'lastinvalid',
278                         value => $borrower{'surname'} . ' / ' . $borrowernumber
279                     }
280                 );
281                 next LINE;
282             }
283             # Don't add a new restriction if the existing 'combined' restriction matches this one
284             if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
285
286                 # Check to see if this debarment already exists
287                 my $debarrments = GetDebarments(
288                     {
289                         borrowernumber => $borrowernumber,
290                         expiration     => $borrower{debarred},
291                         comment        => $borrower{debarredcomment}
292                     }
293                 );
294
295                 # If it doesn't, then add it!
296                 unless (@$debarrments) {
297                     AddDebarment(
298                         {
299                             borrowernumber => $borrowernumber,
300                             expiration     => $borrower{debarred},
301                             comment        => $borrower{debarredcomment}
302                         }
303                     );
304                 }
305             }
306             if ($overwrite_passwords){
307                 try {
308                     $patron->set_password({ password => $borrower{password} });
309                 }
310                 catch {
311                     if ( $_->isa('Koha::Exceptions::Password::TooShort') ) {
312                         push @errors, { passwd_too_short => 1, borrowernumber => $borrowernumber, length => $_->{length}, min_length => $_->{min_length} };
313                     }
314                     elsif ( $_->isa('Koha::Exceptions::Password::WhitespaceCharacters') ) {
315                         push @errors, { passwd_whitespace => 1, borrowernumber => $borrowernumber } ;
316                     }
317                     elsif ( $_->isa('Koha::Exceptions::Password::TooWeak') ) {
318                         push @errors, { passwd_too_weak => 1, borrowernumber => $borrowernumber } ;
319                     }
320                     elsif ( $_->isa('Koha::Exceptions::Password::Plugin') ) {
321                         push @errors, { passwd_plugin_err => 1, borrowernumber => $borrowernumber } ;
322                     }
323                     else {
324                         push @errors, { passwd_unknown_err => 1, borrowernumber => $borrowernumber } ;
325                     }
326                 }
327             }
328             if ($extended) {
329                 if ($ext_preserve) {
330                     $patron_attributes = $patron->extended_attributes->merge_with( $patron_attributes );
331                 }
332                 eval {
333                     # We do not want to filter by branch, maybe we should?
334                     Koha::Patrons->find($borrowernumber)->extended_attributes->delete;
335                     $patron->extended_attributes($patron_attributes);
336                 };
337                 if ($@) {
338                     # FIXME This is not an unknown error, we can do better here
339                     push @errors, { unknown_error => 1 };
340                 }
341             }
342             $overwritten++;
343             push(
344                 @feedback,
345                 {
346                     feedback => 1,
347                     name     => 'lastoverwritten',
348                     value    => $borrower{'surname'} . ' / ' . $borrowernumber
349                 }
350             );
351         }
352         else {
353             my $patron = eval {
354                 Koha::Patron->new(\%borrower)->store;
355             };
356             unless ( $@ ) {
357
358                 if ( $patron->is_debarred ) {
359                     AddDebarment(
360                         {
361                             borrowernumber => $patron->borrowernumber,
362                             expiration     => $patron->debarred,
363                             comment        => $patron->debarredcomment,
364                         }
365                     );
366                 }
367
368                 if ($extended) {
369                     # FIXME Hum, we did not filter earlier and now we do?
370                     $patron->extended_attributes->filter_by_branch_limitations->delete;
371                     $patron->extended_attributes($patron_attributes);
372                 }
373
374                 if ($set_messaging_prefs) {
375                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
376                         {
377                             borrowernumber => $patron->borrowernumber,
378                             categorycode   => $patron->categorycode,
379                         }
380                     );
381                 }
382
383                 $imported++;
384                 push @imported_borrowers, $patron->borrowernumber; #for patronlist
385                 push(
386                     @feedback,
387                     {
388                         feedback => 1,
389                         name     => 'lastimported',
390                         value    => $patron->surname . ' / ' . $patron->borrowernumber,
391                     }
392                 );
393             }
394             else {
395                 $invalid++;
396                 push @errors, { unknown_error => 1 };
397                 push(
398                     @errors,
399                     {
400                         name  => 'lastinvalid',
401                         value => $borrower{'surname'} . ' / Create patron',
402                     }
403                 );
404             }
405         }
406
407         # Add a guarantor if we are given a relationship
408         if ( $guarantor_id ) {
409             Koha::Patron::Relationship->new(
410                 {
411                     guarantee_id => $borrowernumber,
412                     relationship => $relationship,
413                     guarantor_id => $guarantor_id,
414                 }
415             )->store();
416         }
417     }
418
419     return {
420         feedback      => \@feedback,
421         errors        => \@errors,
422         imported      => $imported,
423         overwritten   => $overwritten,
424         already_in_db => $alreadyindb,
425         invalid       => $invalid,
426         imported_borrowers => \@imported_borrowers,
427     };
428 }
429
430 =head2 prepare_columns
431
432  my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
433
434 Returns an array of all column key and populates a hash of colunm key positions.
435
436 =cut
437
438 sub prepare_columns {
439     my ($self, $params) = @_;
440
441     my $status = $self->text_csv->parse($params->{headerrow});
442     unless( $status ) {
443         push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
444         return;
445     }
446
447     my @csvcolumns = $self->text_csv->fields();
448     my $col = 0;
449     foreach my $keycol (@csvcolumns) {
450         # columnkeys don't contain whitespace, but some stupid tools add it
451         $keycol =~ s/ +//g;
452         $keycol =~ s/^\N{BOM}//; # Strip BOM if exists, otherwise it will be part of first column key
453         $params->{keycol}->{$keycol} = $col++;
454     }
455
456     return @csvcolumns;
457 }
458
459 =head2 set_attribute_types
460
461  my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
462
463 Returns an attribute type based on matchpoint parameter.
464
465 =cut
466
467 sub set_attribute_types {
468     my ($self, $params) = @_;
469
470     my $attribute_type;
471     if( $params->{extended} ) {
472         $attribute_type = Koha::Patron::Attribute::Types->find($params->{matchpoint});
473     }
474
475     return $attribute_type;
476 }
477
478 =head2 set_column_keys
479
480  my @columnkeys = set_column_keys($extended);
481
482 Returns an array of borrowers' table columns.
483
484 =cut
485
486 sub set_column_keys {
487     my ($self, $extended) = @_;
488
489     my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
490     push( @columnkeys, 'patron_attributes' ) if $extended;
491
492     return @columnkeys;
493 }
494
495 =head2 generate_patron_attributes
496
497  my $patron_attributes = generate_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
498
499 Returns a Koha::Patron::Attributes as expected by Koha::Patron->extended_attributes
500
501 =cut
502
503 sub generate_patron_attributes {
504     my ($self, $extended, $string, $feedback) = @_;
505
506     unless( $extended ) { return; }
507     unless( defined $string ) { return; }
508
509     # Fixup double quotes in case we are passed smart quotes
510     $string =~ s/\xe2\x80\x9c/"/g;
511     $string =~ s/\xe2\x80\x9d/"/g;
512
513     push (@$feedback, { feedback => 1, name => 'attribute string', value => $string });
514     return [] unless $string; # Unit tests want the feedback, is it really needed?
515
516     my $csv = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
517     my $ok   = $csv->parse($string);  # parse field again to get subfields!
518     my @list = $csv->fields();
519     my @patron_attributes =
520       sort { $a->{code} cmp $b->{code} || $a->{value} cmp $b->{value} }
521       map {
522         my @arr = split /:/, $_, 2;
523         { code => $arr[0], attribute => $arr[1] }
524       } @list;
525     return \@patron_attributes;
526     # TODO: error handling (check $ok)
527 }
528
529 =head2 check_branch_code
530
531  check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
532
533 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
534
535 =cut
536
537 sub check_branch_code {
538     my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
539
540     # No branch code
541     unless( $branchcode ) {
542         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => decode_utf8($borrowerline), });
543         return;
544     }
545
546     # look for branch code
547     my $library = Koha::Libraries->find( $branchcode );
548     unless( $library ) {
549         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => decode_utf8($borrowerline),
550                                      value => $branchcode, branch_map => 1, });
551     }
552 }
553
554 =head2 check_borrower_category
555
556  check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
557
558 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
559
560 =cut
561
562 sub check_borrower_category {
563     my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
564
565     # No branch code
566     unless( $categorycode ) {
567         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => decode_utf8($borrowerline), });
568         return;
569     }
570
571     # Looking for borrower category
572     my $category = Koha::Patron::Categories->find($categorycode);
573     unless( $category ) {
574         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => decode_utf8($borrowerline),
575                                      value => $categorycode, category_map => 1, });
576     }
577 }
578
579 =head2 format_dates
580
581  format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
582
583 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
584 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
585
586 =cut
587
588 sub format_dates {
589     my ($self, $params) = @_;
590
591     foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry date_renewed)) {
592         my $tempdate = $params->{borrower}->{$date_type} or next();
593         my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
594
595         if ($formatted_date) {
596             $params->{borrower}->{$date_type} = $formatted_date;
597         } else {
598             $params->{borrower}->{$date_type} = '';
599             push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => decode_utf8($params->{lineraw}), bad_date => 1 });
600         }
601     }
602 }
603
604 1;
605
606 =head1 AUTHOR
607
608 Koha Team
609
610 =cut