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