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