1 package Koha::Patrons::Import;
3 # This file is part of Koha.
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.
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.
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>.
24 use Encode qw( decode_utf8 );
31 use Koha::Patron::Categories;
32 use Koha::Patron::Debarments;
37 Koha::Patrons::Import - Perl Module containing import_patrons method exported from import_borrowers script.
41 use Koha::Patrons::Import;
45 This module contains one method for importing patrons in bulk.
51 my $return = Koha::Patrons::Import::import_patrons($params);
53 Applies various checks and imports patrons in bulk from a csv file.
55 Further pod documentation needed here.
59 has 'today_iso' => ( is => 'ro', lazy => 1,
60 default => sub { output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); }, );
62 has 'text_csv' => ( is => 'rw', lazy => 1,
63 default => sub { Text::CSV->new( { binary => 1, } ); }, );
66 my ($self, $params) = @_;
68 my $handle = $params->{file};
69 unless( $handle ) { carp('No file handle passed in!'); return; }
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');
80 my $schema = Koha::Database->new->schema;
81 $schema->storage->txn_begin if $dry_run;
83 my @columnkeys = $self->set_column_keys($extended);
91 my @imported_borrowers;
92 my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
94 # Use header line to construct key to column map
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 ) });
100 my @criticals = qw( surname ); # there probably should be others - rm branchcode && categorycode
101 LINE: while ( my $borrowerline = <$handle> ) {
102 my $line_number = $.;
104 my @missing_criticals;
106 my $status = $self->text_csv->parse($borrowerline);
107 my @columns = $self->text_csv->fields();
109 push @missing_criticals, { badparse => 1, line => $line_number, lineraw => decode_utf8($borrowerline) };
111 elsif ( @columns == @columnkeys ) {
112 @borrower{@columnkeys} = @columns;
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};
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} ];
127 elsif ( $defaults->{$key} ) {
128 $borrower{$key} = $defaults->{$key};
130 elsif ( scalar grep { $key eq $_ } @criticals ) {
132 # a critical field is undefined
133 push @missing_criticals, { key => $key, line => $., lineraw => decode_utf8($borrowerline) };
136 $borrower{$key} = '';
141 $borrower{cardnumber} = undef if $borrower{cardnumber} eq "";
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);
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);
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, });
152 if (@missing_criticals) {
153 foreach (@missing_criticals) {
154 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
155 $_->{surname} = $borrower{surname} || 'UNDEF';
158 ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
160 # The first 25 errors are enough. Keeping track of 30,000+ would destroy performance.
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.
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};
173 my ( $member, $patron );
174 if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
175 $patron = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
177 elsif ( defined($matchpoint) && ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
178 $patron = Koha::Patrons->find( { userid => $borrower{userid} } );
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(
186 code => $matchpoint_attr_type->code,
187 attribute => $attr->{attribute}
189 )->get_column('borrowernumber');
191 $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
192 $patron = Koha::Patrons->find( $borrowernumber );
200 $member = $patron->unblessed;
201 $borrowernumber = $member->{'borrowernumber'};
206 if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
209 invalid_cardnumber => 1,
210 borrowernumber => $borrowernumber,
211 cardnumber => $borrower{cardnumber}
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 )
225 push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
230 my $guarantor_relationship = $borrower{guarantor_relationship};
231 delete $borrower{guarantor_relationship};
232 my $guarantor_id = $borrower{guarantor_id};
233 delete $borrower{guarantor_id};
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
238 qw( privacy privacy_guarantor_fines privacy_guarantor_checkouts anonymized login_attempts ))
240 delete $borrower{$field}
241 if exists $borrower{$field} and $borrower{$field} eq "";
245 if ($borrowernumber) {
248 unless ($overwrite_cardnumber) {
254 value => $borrower{'surname'} . ' / ' . $borrowernumber
259 $borrower{'borrowernumber'} = $borrowernumber;
260 for my $col ( keys %borrower ) {
262 # use values from extant patron unless our csv file includes this column or we provided a default.
263 # FIXME : You cannot update a field with a perl-evaluated false value using the defaults.
265 # The password is always encrypted, skip it unless we are forcing overwrite!
266 next if $col eq 'password' && !$overwrite_passwords;
268 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
269 $borrower{$col} = $member->{$col} if ( $member->{$col} );
273 my $patron = Koha::Patrons->find( $borrowernumber );
275 $schema->storage->txn_do(sub {
276 $patron->set(\%borrower)->store;
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} ) ) ) {
280 # Check to see if this debarment already exists
281 my $debarrments = GetDebarments(
283 borrowernumber => $borrowernumber,
284 expiration => $borrower{debarred},
285 comment => $borrower{debarredcomment}
289 # If it doesn't, then add it!
290 unless (@$debarrments) {
293 borrowernumber => $borrowernumber,
294 expiration => $borrower{debarred},
295 comment => $borrower{debarredcomment}
300 if ($patron->category->category_type ne 'S' && $overwrite_passwords && defined $borrower{password} && $borrower{password} ne ''){
302 $patron->set_password({ password => $borrower{password} });
305 if ( $_->isa('Koha::Exceptions::Password::TooShort') ) {
306 push @errors, { passwd_too_short => 1, borrowernumber => $borrowernumber, length => $_->{length}, min_length => $_->{min_length} };
308 elsif ( $_->isa('Koha::Exceptions::Password::WhitespaceCharacters') ) {
309 push @errors, { passwd_whitespace => 1, borrowernumber => $borrowernumber } ;
311 elsif ( $_->isa('Koha::Exceptions::Password::TooWeak') ) {
312 push @errors, { passwd_too_weak => 1, borrowernumber => $borrowernumber } ;
314 elsif ( $_->isa('Koha::Exceptions::Password::Plugin') ) {
315 push @errors, { passwd_plugin_err => 1, borrowernumber => $borrowernumber } ;
318 push @errors, { passwd_unknown_err => 1, borrowernumber => $borrowernumber } ;
324 $patron_attributes = $patron->extended_attributes->merge_and_replace_with( $patron_attributes );
326 # We do not want to filter by branch, maybe we should?
327 Koha::Patrons->find($borrowernumber)->extended_attributes->delete;
328 $patron->extended_attributes($patron_attributes);
335 name => 'lastoverwritten',
336 value => $borrower{'surname'} . ' / ' . $borrowernumber
344 my $patron_id = defined $matchpoint ? $borrower{$matchpoint} : $matchpoint_attr_type;
345 if ( $_->isa('Koha::Exceptions::Patron::Attribute::UniqueIDConstraint') ) {
346 push @errors, { patron_attribute_unique_id_constraint => 1, borrowernumber => $borrowernumber, attribute => $_->attribute };
347 } elsif ( $_->isa('Koha::Exceptions::Patron::Attribute::InvalidType') ) {
348 push @errors, { patron_attribute_invalid_type => 1, borrowernumber => $borrowernumber, attribute_type_code => $_->type };
349 } elsif ( $_->isa('Koha::Exceptions::Patron::Attribute::NonRepeatable') ) {
350 push @errors, { patron_attribute_non_repeatable => 1, borrowernumber => $borrowernumber, attribute => $_->attribute };
352 use Data::Printer colored => 1; warn p $_;
353 push @errors, { unknown_error => 1 };
359 # TODO We can raise a better error
360 name => 'lastinvalid',
361 value => $borrower{'surname'} . ' / ' . $borrowernumber
368 $schema->storage->txn_do(sub {
369 my $patron = Koha::Patron->new(\%borrower)->store;
370 $borrowernumber = $patron->id;
372 if ( $patron->is_debarred ) {
375 borrowernumber => $patron->borrowernumber,
376 expiration => $patron->debarred,
377 comment => $patron->debarredcomment,
383 # FIXME Hum, we did not filter earlier and now we do?
384 $patron->extended_attributes->filter_by_branch_limitations->delete;
385 $patron->extended_attributes($patron_attributes);
388 if ($set_messaging_prefs) {
389 C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
391 borrowernumber => $patron->borrowernumber,
392 categorycode => $patron->categorycode,
398 push @imported_borrowers, $patron->borrowernumber; #for patronlist
403 name => 'lastimported',
404 value => $patron->surname . ' / ' . $patron->borrowernumber,
411 my $patron_id = defined $matchpoint ? $borrower{$matchpoint} : $matchpoint_attr_type;
412 if ( $_->isa('Koha::Exceptions::Patron::Attribute::UniqueIDConstraint') ) {
413 push @errors, { patron_attribute_unique_id_constraint => 1, patron_id => $patron_id, attribute => $_->attribute };
414 } elsif ( $_->isa('Koha::Exceptions::Patron::Attribute::InvalidType') ) {
415 push @errors, { patron_attribute_invalid_type => 1, patron_id => $patron_id, attribute_type_code => $_->type };
416 } elsif ( $_->isa('Koha::Exceptions::Patron::Attribute::NonRepeatable') ) {
417 push @errors, { patron_attribute_non_repeatable => 1, patron_id => $patron_id, attribute => $_->attribute };
420 use Data::Printer colored => 1; warn p $_;
421 push @errors, { unknown_error => 1 };
426 name => 'lastinvalid',
427 value => $borrower{'surname'} . ' / Create patron',
433 next LINE unless $success;
435 # Add a guarantor if we are given a relationship
436 if ( $guarantor_id ) {
437 my $relationship = Koha::Patron::Relationships->find(
439 guarantee_id => $borrowernumber,
440 guarantor_id => $guarantor_id,
444 if ( $relationship ) {
445 $relationship->relationship( $guarantor_relationship );
446 $relationship->store();
449 Koha::Patron::Relationship->new(
451 guarantee_id => $borrowernumber,
452 relationship => $guarantor_relationship,
453 guarantor_id => $guarantor_id,
460 $schema->storage->txn_rollback if $dry_run;
463 feedback => \@feedback,
465 imported => $imported,
466 overwritten => $overwritten,
467 already_in_db => $alreadyindb,
469 imported_borrowers => \@imported_borrowers,
473 =head2 prepare_columns
475 my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
477 Returns an array of all column key and populates a hash of colunm key positions.
481 sub prepare_columns {
482 my ($self, $params) = @_;
484 my $status = $self->text_csv->parse($params->{headerrow});
486 push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
490 my @csvcolumns = $self->text_csv->fields();
492 foreach my $keycol (@csvcolumns) {
493 # columnkeys don't contain whitespace, but some stupid tools add it
495 $keycol =~ s/^\N{BOM}//; # Strip BOM if exists, otherwise it will be part of first column key
496 $params->{keycol}->{$keycol} = $col++;
502 =head2 set_attribute_types
504 my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
506 Returns an attribute type based on matchpoint parameter.
510 sub set_attribute_types {
511 my ($self, $params) = @_;
514 if( $params->{extended} ) {
515 $attribute_type = Koha::Patron::Attribute::Types->find($params->{matchpoint});
518 return $attribute_type;
521 =head2 set_column_keys
523 my @columnkeys = set_column_keys($extended);
525 Returns an array of borrowers' table columns.
529 sub set_column_keys {
530 my ($self, $extended) = @_;
532 my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
533 push( @columnkeys, 'patron_attributes' ) if $extended;
534 push( @columnkeys, qw( guarantor_relationship guarantor_id ) );
539 =head2 generate_patron_attributes
541 my $patron_attributes = generate_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
543 Returns a Koha::Patron::Attributes as expected by Koha::Patron->extended_attributes
547 sub generate_patron_attributes {
548 my ($self, $extended, $string, $feedback) = @_;
550 unless( $extended ) { return; }
551 unless( defined $string ) { return; }
553 # Fixup double quotes in case we are passed smart quotes
554 $string =~ s/\xe2\x80\x9c/"/g;
555 $string =~ s/\xe2\x80\x9d/"/g;
557 push (@$feedback, { feedback => 1, name => 'attribute string', value => $string });
558 return [] unless $string; # Unit tests want the feedback, is it really needed?
560 my $csv = Text::CSV->new({binary => 1}); # binary needed for non-ASCII Unicode
561 my $ok = $csv->parse($string); # parse field again to get subfields!
562 my @list = $csv->fields();
563 my @patron_attributes =
564 sort { $a->{code} cmp $b->{code} || $a->{attribute} cmp $b->{attribute} }
566 my @arr = split /:/, $_, 2;
567 { code => $arr[0], attribute => $arr[1] }
569 return \@patron_attributes;
570 # TODO: error handling (check $ok)
573 =head2 check_branch_code
575 check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
577 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
581 sub check_branch_code {
582 my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
585 unless( $branchcode ) {
586 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => decode_utf8($borrowerline), });
590 # look for branch code
591 my $library = Koha::Libraries->find( $branchcode );
593 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => decode_utf8($borrowerline),
594 value => $branchcode, branch_map => 1, });
598 =head2 check_borrower_category
600 check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
602 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
606 sub check_borrower_category {
607 my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
610 unless( $categorycode ) {
611 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => decode_utf8($borrowerline), });
615 # Looking for borrower category
616 my $category = Koha::Patron::Categories->find($categorycode);
617 unless( $category ) {
618 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => decode_utf8($borrowerline),
619 value => $categorycode, category_map => 1, });
625 format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
627 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
628 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
633 my ($self, $params) = @_;
635 foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry date_renewed)) {
636 my $tempdate = $params->{borrower}->{$date_type} or next();
637 my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
639 if ($formatted_date) {
640 $params->{borrower}->{$date_type} = $formatted_date;
642 $params->{borrower}->{$date_type} = '';
643 push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => decode_utf8($params->{lineraw}), bad_date => 1 });