Bug 23473: Allow overwrite of passwords during import
[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
26 use C4::Members;
27
28 use Koha::Libraries;
29 use Koha::Patrons;
30 use Koha::Patron::Categories;
31 use Koha::Patron::Debarments;
32 use Koha::DateUtils;
33
34 =head1 NAME
35
36 Koha::Patrons::Import - Perl Module containing import_patrons method exported from import_borrowers script.
37
38 =head1 SYNOPSIS
39
40 use Koha::Patrons::Import;
41
42 =head1 DESCRIPTION
43
44 This module contains one method for importing patrons in bulk.
45
46 =head1 FUNCTIONS
47
48 =head2 import_patrons
49
50  my $return = Koha::Patrons::Import::import_patrons($params);
51
52 Applies various checks and imports patrons in bulk from a csv file.
53
54 Further pod documentation needed here.
55
56 =cut
57
58 has 'today_iso' => ( is => 'ro', lazy => 1,
59     default => sub { output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); }, );
60
61 has 'text_csv' => ( is => 'rw', lazy => 1,
62     default => sub { Text::CSV->new( { binary => 1, } ); },  );
63
64 sub import_patrons {
65     my ($self, $params) = @_;
66
67     my $handle = $params->{file};
68     unless( $handle ) { carp('No file handle passed in!'); return; }
69
70     my $matchpoint           = $params->{matchpoint};
71     my $defaults             = $params->{defaults};
72     my $ext_preserve         = $params->{preserve_extended_attributes};
73     my $overwrite_cardnumber = $params->{overwrite_cardnumber};
74     my $overwrite_passwords  = $params->{overwrite_passwords};
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 => decode_utf8($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 => decode_utf8($borrowerline) };
129                 }
130                 else {
131                     $borrower{$key} = '';
132                 }
133             }
134         }
135
136         $borrower{cardnumber} = undef if $borrower{cardnumber} eq "";
137
138         # Check if borrower category code exists and if it matches to a known category. Pushing error to missing_criticals otherwise.
139         $self->check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
140
141         # Check if branch code exists and if it matches to a branch name. Pushing error to missing_criticals otherwise.
142         $self->check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
143
144         # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
145         $self->format_dates({borrower => \%borrower, lineraw => $borrowerline, line => $line_number, missing_criticals => \@missing_criticals, });
146
147         if (@missing_criticals) {
148             foreach (@missing_criticals) {
149                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
150                 $_->{surname}        = $borrower{surname}        || 'UNDEF';
151             }
152             $invalid++;
153             ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
154
155             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
156             next LINE;
157         }
158
159         # Generate patron attributes if extended.
160         my $patron_attributes = $self->generate_patron_attributes($extended, $borrower{patron_attributes}, \@feedback);
161         if( $extended ) { delete $borrower{patron_attributes}; } # Not really a field in borrowers.
162
163         # Default date enrolled and date expiry if not already set.
164         $borrower{dateenrolled} = $self->today_iso() unless $borrower{dateenrolled};
165         $borrower{dateexpiry} = Koha::Patron::Categories->find( $borrower{categorycode} )->get_expiry_date( $borrower{dateenrolled} ) unless $borrower{dateexpiry};
166
167         my $borrowernumber;
168         my ( $member, $patron );
169         if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
170             $patron = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
171         }
172         elsif ( defined($matchpoint) && ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
173             $patron = Koha::Patrons->find( { userid => $borrower{userid} } );
174         }
175         elsif ($extended) {
176             if ( defined($matchpoint_attr_type) ) {
177                 foreach my $attr (@$patron_attributes) {
178                     if ( $attr->{code} eq $matchpoint and $attr->{attribute} ne '' ) {
179                         my @borrowernumbers = Koha::Patron::Attributes->search(
180                             {
181                                 code      => $matchpoint_attr_type->code,
182                                 attribute => $attr->{attribute}
183                             }
184                         )->get_column('borrowernumber');
185
186                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
187                         $patron = Koha::Patrons->find( $borrowernumber );
188                         last;
189                     }
190                 }
191             }
192         }
193
194         if ($patron) {
195             $member = $patron->unblessed;
196             $borrowernumber = $member->{'borrowernumber'};
197         } else {
198             $member = {};
199         }
200
201         if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
202             push @errors,
203               {
204                 invalid_cardnumber => 1,
205                 borrowernumber     => $borrowernumber,
206                 cardnumber         => $borrower{cardnumber}
207               };
208             $invalid++;
209             next;
210         }
211
212
213         # Check if the userid provided does not exist yet
214         if (    defined($matchpoint)
215             and $matchpoint ne 'userid'
216             and exists $borrower{userid}
217             and $borrower{userid}
218             and not ( $borrowernumber ? $patron->userid( $borrower{userid} )->has_valid_userid : Koha::Patron->new( { userid => $borrower{userid} } )->has_valid_userid )
219         ) {
220             push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
221             $invalid++;
222             next LINE;
223         }
224
225         my $relationship        = $borrower{relationship};
226         my $guarantor_id        = $borrower{guarantor_id};
227         delete $borrower{relationship};
228         delete $borrower{guarantor_id};
229
230         # Remove warning for int datatype that cannot be null
231         # Argument "" isn't numeric in numeric eq (==) at /usr/share/perl5/DBIx/Class/Row.pm line 1018
232         for my $field (
233             qw( privacy privacy_guarantor_fines privacy_guarantor_checkouts anonymized ))
234         {
235             delete $borrower{$field}
236               if exists $borrower{$field} and $borrower{$field} eq "";
237         }
238
239         if ($borrowernumber) {
240
241             # borrower exists
242             unless ($overwrite_cardnumber) {
243                 $alreadyindb++;
244                 push(
245                     @feedback,
246                     {
247                         already_in_db => 1,
248                         value         => $borrower{'surname'} . ' / ' . $borrowernumber
249                     }
250                 );
251                 next LINE;
252             }
253             $borrower{'borrowernumber'} = $borrowernumber;
254             for my $col ( keys %borrower ) {
255
256                 # use values from extant patron unless our csv file includes this column or we provided a default.
257                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
258
259                 # The password is always encrypted, skip it unless we are forcing overwrite!
260                 next if $col eq 'password' && !$overwrite_passwords;
261
262                 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
263                     $borrower{$col} = $member->{$col} if ( $member->{$col} );
264                 }
265             }
266
267             my $patron = Koha::Patrons->find( $borrowernumber );
268             eval { $patron->set(\%borrower)->store };
269             if ( $@ ) {
270                 $invalid++;
271
272                 push(
273                     @errors,
274                     {
275                         # TODO We can raise a better error
276                         name  => 'lastinvalid',
277                         value => $borrower{'surname'} . ' / ' . $borrowernumber
278                     }
279                 );
280                 next LINE;
281             }
282             # Don't add a new restriction if the existing 'combined' restriction matches this one
283             if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
284
285                 # Check to see if this debarment already exists
286                 my $debarrments = GetDebarments(
287                     {
288                         borrowernumber => $borrowernumber,
289                         expiration     => $borrower{debarred},
290                         comment        => $borrower{debarredcomment}
291                     }
292                 );
293
294                 # If it doesn't, then add it!
295                 unless (@$debarrments) {
296                     AddDebarment(
297                         {
298                             borrowernumber => $borrowernumber,
299                             expiration     => $borrower{debarred},
300                             comment        => $borrower{debarredcomment}
301                         }
302                     );
303                 }
304             }
305             if ($overwrite_passwords){
306                 $patron->set_password({ password => $borrower{password} });
307             }
308             if ($extended) {
309                 if ($ext_preserve) {
310                     $patron_attributes = $patron->extended_attributes->merge_with( $patron_attributes );
311                 }
312                 eval {
313                     # We do not want to filter by branch, maybe we should?
314                     Koha::Patrons->find($borrowernumber)->extended_attributes->delete;
315                     $patron->extended_attributes($patron_attributes);
316                 };
317                 if ($@) {
318                     # FIXME This is not an unknown error, we can do better here
319                     push @errors, { unknown_error => 1 };
320                 }
321             }
322             $overwritten++;
323             push(
324                 @feedback,
325                 {
326                     feedback => 1,
327                     name     => 'lastoverwritten',
328                     value    => $borrower{'surname'} . ' / ' . $borrowernumber
329                 }
330             );
331         }
332         else {
333             my $patron = eval {
334                 Koha::Patron->new(\%borrower)->store;
335             };
336             unless ( $@ ) {
337
338                 if ( $patron->is_debarred ) {
339                     AddDebarment(
340                         {
341                             borrowernumber => $patron->borrowernumber,
342                             expiration     => $patron->debarred,
343                             comment        => $patron->debarredcomment,
344                         }
345                     );
346                 }
347
348                 if ($extended) {
349                     # FIXME Hum, we did not filter earlier and now we do?
350                     $patron->extended_attributes->filter_by_branch_limitations->delete;
351                     $patron->extended_attributes($patron_attributes);
352                 }
353
354                 if ($set_messaging_prefs) {
355                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
356                         {
357                             borrowernumber => $patron->borrowernumber,
358                             categorycode   => $patron->categorycode,
359                         }
360                     );
361                 }
362
363                 $imported++;
364                 push @imported_borrowers, $patron->borrowernumber; #for patronlist
365                 push(
366                     @feedback,
367                     {
368                         feedback => 1,
369                         name     => 'lastimported',
370                         value    => $patron->surname . ' / ' . $patron->borrowernumber,
371                     }
372                 );
373             }
374             else {
375                 $invalid++;
376                 push @errors, { unknown_error => 1 };
377                 push(
378                     @errors,
379                     {
380                         name  => 'lastinvalid',
381                         value => $borrower{'surname'} . ' / Create patron',
382                     }
383                 );
384             }
385         }
386
387         # Add a guarantor if we are given a relationship
388         if ( $guarantor_id ) {
389             Koha::Patron::Relationship->new(
390                 {
391                     guarantee_id => $borrowernumber,
392                     relationship => $relationship,
393                     guarantor_id => $guarantor_id,
394                 }
395             )->store();
396         }
397     }
398
399     return {
400         feedback      => \@feedback,
401         errors        => \@errors,
402         imported      => $imported,
403         overwritten   => $overwritten,
404         already_in_db => $alreadyindb,
405         invalid       => $invalid,
406         imported_borrowers => \@imported_borrowers,
407     };
408 }
409
410 =head2 prepare_columns
411
412  my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
413
414 Returns an array of all column key and populates a hash of colunm key positions.
415
416 =cut
417
418 sub prepare_columns {
419     my ($self, $params) = @_;
420
421     my $status = $self->text_csv->parse($params->{headerrow});
422     unless( $status ) {
423         push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
424         return;
425     }
426
427     my @csvcolumns = $self->text_csv->fields();
428     my $col = 0;
429     foreach my $keycol (@csvcolumns) {
430         # columnkeys don't contain whitespace, but some stupid tools add it
431         $keycol =~ s/ +//g;
432         $keycol =~ s/^\N{BOM}//; # Strip BOM if exists, otherwise it will be part of first column key
433         $params->{keycol}->{$keycol} = $col++;
434     }
435
436     return @csvcolumns;
437 }
438
439 =head2 set_attribute_types
440
441  my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
442
443 Returns an attribute type based on matchpoint parameter.
444
445 =cut
446
447 sub set_attribute_types {
448     my ($self, $params) = @_;
449
450     my $attribute_type;
451     if( $params->{extended} ) {
452         $attribute_type = Koha::Patron::Attribute::Types->find($params->{matchpoint});
453     }
454
455     return $attribute_type;
456 }
457
458 =head2 set_column_keys
459
460  my @columnkeys = set_column_keys($extended);
461
462 Returns an array of borrowers' table columns.
463
464 =cut
465
466 sub set_column_keys {
467     my ($self, $extended) = @_;
468
469     my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
470     push( @columnkeys, 'patron_attributes' ) if $extended;
471
472     return @columnkeys;
473 }
474
475 =head2 generate_patron_attributes
476
477  my $patron_attributes = generate_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
478
479 Returns a Koha::Patron::Attributes as expected by Koha::Patron->extended_attributes
480
481 =cut
482
483 sub generate_patron_attributes {
484     my ($self, $extended, $string, $feedback) = @_;
485
486     unless( $extended ) { return; }
487     unless( defined $string ) { return; }
488
489     # Fixup double quotes in case we are passed smart quotes
490     $string =~ s/\xe2\x80\x9c/"/g;
491     $string =~ s/\xe2\x80\x9d/"/g;
492
493     push (@$feedback, { feedback => 1, name => 'attribute string', value => $string });
494     return [] unless $string; # Unit tests want the feedback, is it really needed?
495
496     my $csv = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
497     my $ok   = $csv->parse($string);  # parse field again to get subfields!
498     my @list = $csv->fields();
499     my @patron_attributes =
500       sort { $a->{code} cmp $b->{code} || $a->{value} cmp $b->{value} }
501       map {
502         my @arr = split /:/, $_, 2;
503         { code => $arr[0], attribute => $arr[1] }
504       } @list;
505     return \@patron_attributes;
506     # TODO: error handling (check $ok)
507 }
508
509 =head2 check_branch_code
510
511  check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
512
513 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
514
515 =cut
516
517 sub check_branch_code {
518     my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
519
520     # No branch code
521     unless( $branchcode ) {
522         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => decode_utf8($borrowerline), });
523         return;
524     }
525
526     # look for branch code
527     my $library = Koha::Libraries->find( $branchcode );
528     unless( $library ) {
529         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => decode_utf8($borrowerline),
530                                      value => $branchcode, branch_map => 1, });
531     }
532 }
533
534 =head2 check_borrower_category
535
536  check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
537
538 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
539
540 =cut
541
542 sub check_borrower_category {
543     my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
544
545     # No branch code
546     unless( $categorycode ) {
547         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => decode_utf8($borrowerline), });
548         return;
549     }
550
551     # Looking for borrower category
552     my $category = Koha::Patron::Categories->find($categorycode);
553     unless( $category ) {
554         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => decode_utf8($borrowerline),
555                                      value => $categorycode, category_map => 1, });
556     }
557 }
558
559 =head2 format_dates
560
561  format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
562
563 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
564 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
565
566 =cut
567
568 sub format_dates {
569     my ($self, $params) = @_;
570
571     foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry date_renewed)) {
572         my $tempdate = $params->{borrower}->{$date_type} or next();
573         my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
574
575         if ($formatted_date) {
576             $params->{borrower}->{$date_type} = $formatted_date;
577         } else {
578             $params->{borrower}->{$date_type} = '';
579             push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => decode_utf8($params->{lineraw}), bad_date => 1 });
580         }
581     }
582 }
583
584 1;
585
586 =head1 AUTHOR
587
588 Koha Team
589
590 =cut