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