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