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