Bug 25172: Adjust tests
[koha.git] / Koha / Patrons / Import.pm
blob56b18023cef43bab5337782f35edd3cb2f3d2847
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>.
18 use Modern::Perl;
19 use Moo;
20 use namespace::clean;
22 use Carp;
23 use Text::CSV;
24 use Encode qw( decode_utf8 );
25 use Try::Tiny;
27 use C4::Members;
29 use Koha::Libraries;
30 use Koha::Patrons;
31 use Koha::Patron::Categories;
32 use Koha::Patron::Debarments;
33 use Koha::DateUtils;
35 =head1 NAME
37 Koha::Patrons::Import - Perl Module containing import_patrons method exported from import_borrowers script.
39 =head1 SYNOPSIS
41 use Koha::Patrons::Import;
43 =head1 DESCRIPTION
45 This module contains one method for importing patrons in bulk.
47 =head1 FUNCTIONS
49 =head2 import_patrons
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.
57 =cut
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, } ); }, );
65 sub import_patrons {
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 $extended = C4::Context->preference('ExtendedPatronAttributes');
77 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
79 my @columnkeys = $self->set_column_keys($extended);
80 my @feedback;
81 my @errors;
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, });
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 ) });
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;
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) };
107 elsif ( @columns == @columnkeys ) {
108 @borrower{@columnkeys} = @columns;
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};
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} ];
123 elsif ( $defaults->{$key} ) {
124 $borrower{$key} = $defaults->{$key};
126 elsif ( scalar grep { $key eq $_ } @criticals ) {
128 # a critical field is undefined
129 push @missing_criticals, { key => $key, line => $., lineraw => decode_utf8($borrowerline) };
131 else {
132 $borrower{$key} = '';
137 $borrower{cardnumber} = undef if $borrower{cardnumber} eq "";
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);
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);
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, });
148 if (@missing_criticals) {
149 foreach (@missing_criticals) {
150 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
151 $_->{surname} = $borrower{surname} || 'UNDEF';
153 $invalid++;
154 ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
156 # The first 25 errors are enough. Keeping track of 30,000+ would destroy performance.
157 next LINE;
160 # Generate patron attributes if extended.
161 my $patron_attributes = $self->generate_patron_attributes($extended, $borrower{patron_attributes}, \@feedback);
162 if( $extended ) { delete $borrower{patron_attributes}; } # Not really a field in borrowers.
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};
168 my $borrowernumber;
169 my ( $member, $patron );
170 if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
171 $patron = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
173 elsif ( defined($matchpoint) && ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
174 $patron = Koha::Patrons->find( { userid => $borrower{userid} } );
176 elsif ($extended) {
177 if ( defined($matchpoint_attr_type) ) {
178 foreach my $attr (@$patron_attributes) {
179 if ( $attr->{code} eq $matchpoint and $attr->{attribute} ne '' ) {
180 my @borrowernumbers = Koha::Patron::Attributes->search(
182 code => $matchpoint_attr_type->code,
183 attribute => $attr->{attribute}
185 )->get_column('borrowernumber');
187 $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
188 $patron = Koha::Patrons->find( $borrowernumber );
189 last;
195 if ($patron) {
196 $member = $patron->unblessed;
197 $borrowernumber = $member->{'borrowernumber'};
198 } else {
199 $member = {};
202 if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
203 push @errors,
205 invalid_cardnumber => 1,
206 borrowernumber => $borrowernumber,
207 cardnumber => $borrower{cardnumber}
209 $invalid++;
210 next;
214 # Check if the userid provided does not exist yet
215 if ( defined($matchpoint)
216 and $matchpoint ne 'userid'
217 and exists $borrower{userid}
218 and $borrower{userid}
219 and not ( $borrowernumber ? $patron->userid( $borrower{userid} )->has_valid_userid : Koha::Patron->new( { userid => $borrower{userid} } )->has_valid_userid )
221 push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
222 $invalid++;
223 next LINE;
226 my $relationship = $borrower{relationship};
227 my $guarantor_id = $borrower{guarantor_id};
228 delete $borrower{relationship};
229 delete $borrower{guarantor_id};
231 # Remove warning for int datatype that cannot be null
232 # Argument "" isn't numeric in numeric eq (==) at /usr/share/perl5/DBIx/Class/Row.pm line 1018
233 for my $field (
234 qw( privacy privacy_guarantor_fines privacy_guarantor_checkouts anonymized ))
236 delete $borrower{$field}
237 if exists $borrower{$field} and $borrower{$field} eq "";
240 if ($borrowernumber) {
242 # borrower exists
243 unless ($overwrite_cardnumber) {
244 $alreadyindb++;
245 push(
246 @feedback,
248 already_in_db => 1,
249 value => $borrower{'surname'} . ' / ' . $borrowernumber
252 next LINE;
254 $borrower{'borrowernumber'} = $borrowernumber;
255 for my $col ( keys %borrower ) {
257 # use values from extant patron unless our csv file includes this column or we provided a default.
258 # FIXME : You cannot update a field with a perl-evaluated false value using the defaults.
260 # The password is always encrypted, skip it unless we are forcing overwrite!
261 next if $col eq 'password' && !$overwrite_passwords;
263 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
264 $borrower{$col} = $member->{$col} if ( $member->{$col} );
268 my $patron = Koha::Patrons->find( $borrowernumber );
269 eval { $patron->set(\%borrower)->store };
270 if ( $@ ) {
271 $invalid++;
273 push(
274 @errors,
276 # TODO We can raise a better error
277 name => 'lastinvalid',
278 value => $borrower{'surname'} . ' / ' . $borrowernumber
281 next LINE;
283 # Don't add a new restriction if the existing 'combined' restriction matches this one
284 if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
286 # Check to see if this debarment already exists
287 my $debarrments = GetDebarments(
289 borrowernumber => $borrowernumber,
290 expiration => $borrower{debarred},
291 comment => $borrower{debarredcomment}
295 # If it doesn't, then add it!
296 unless (@$debarrments) {
297 AddDebarment(
299 borrowernumber => $borrowernumber,
300 expiration => $borrower{debarred},
301 comment => $borrower{debarredcomment}
306 if ($patron->category->category_type ne 'S' && $overwrite_passwords && defined $borrower{password} && $borrower{password} ne ''){
307 try {
308 $patron->set_password({ password => $borrower{password} });
310 catch {
311 if ( $_->isa('Koha::Exceptions::Password::TooShort') ) {
312 push @errors, { passwd_too_short => 1, borrowernumber => $borrowernumber, length => $_->{length}, min_length => $_->{min_length} };
314 elsif ( $_->isa('Koha::Exceptions::Password::WhitespaceCharacters') ) {
315 push @errors, { passwd_whitespace => 1, borrowernumber => $borrowernumber } ;
317 elsif ( $_->isa('Koha::Exceptions::Password::TooWeak') ) {
318 push @errors, { passwd_too_weak => 1, borrowernumber => $borrowernumber } ;
320 elsif ( $_->isa('Koha::Exceptions::Password::Plugin') ) {
321 push @errors, { passwd_plugin_err => 1, borrowernumber => $borrowernumber } ;
323 else {
324 push @errors, { passwd_unknown_err => 1, borrowernumber => $borrowernumber } ;
328 if ($extended) {
329 if ($ext_preserve) {
330 $patron_attributes = $patron->extended_attributes->merge_with( $patron_attributes );
332 eval {
333 # We do not want to filter by branch, maybe we should?
334 Koha::Patrons->find($borrowernumber)->extended_attributes->delete;
335 $patron->extended_attributes($patron_attributes);
337 if ($@) {
338 # FIXME This is not an unknown error, we can do better here
339 push @errors, { unknown_error => 1 };
342 $overwritten++;
343 push(
344 @feedback,
346 feedback => 1,
347 name => 'lastoverwritten',
348 value => $borrower{'surname'} . ' / ' . $borrowernumber
352 else {
353 my $patron = eval {
354 Koha::Patron->new(\%borrower)->store;
356 unless ( $@ ) {
358 if ( $patron->is_debarred ) {
359 AddDebarment(
361 borrowernumber => $patron->borrowernumber,
362 expiration => $patron->debarred,
363 comment => $patron->debarredcomment,
368 if ($extended) {
369 # FIXME Hum, we did not filter earlier and now we do?
370 $patron->extended_attributes->filter_by_branch_limitations->delete;
371 $patron->extended_attributes($patron_attributes);
374 if ($set_messaging_prefs) {
375 C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
377 borrowernumber => $patron->borrowernumber,
378 categorycode => $patron->categorycode,
383 $imported++;
384 push @imported_borrowers, $patron->borrowernumber; #for patronlist
385 push(
386 @feedback,
388 feedback => 1,
389 name => 'lastimported',
390 value => $patron->surname . ' / ' . $patron->borrowernumber,
394 else {
395 $invalid++;
396 push @errors, { unknown_error => 1 };
397 push(
398 @errors,
400 name => 'lastinvalid',
401 value => $borrower{'surname'} . ' / Create patron',
407 # Add a guarantor if we are given a relationship
408 if ( $guarantor_id ) {
409 Koha::Patron::Relationship->new(
411 guarantee_id => $borrowernumber,
412 relationship => $relationship,
413 guarantor_id => $guarantor_id,
415 )->store();
419 return {
420 feedback => \@feedback,
421 errors => \@errors,
422 imported => $imported,
423 overwritten => $overwritten,
424 already_in_db => $alreadyindb,
425 invalid => $invalid,
426 imported_borrowers => \@imported_borrowers,
430 =head2 prepare_columns
432 my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
434 Returns an array of all column key and populates a hash of colunm key positions.
436 =cut
438 sub prepare_columns {
439 my ($self, $params) = @_;
441 my $status = $self->text_csv->parse($params->{headerrow});
442 unless( $status ) {
443 push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
444 return;
447 my @csvcolumns = $self->text_csv->fields();
448 my $col = 0;
449 foreach my $keycol (@csvcolumns) {
450 # columnkeys don't contain whitespace, but some stupid tools add it
451 $keycol =~ s/ +//g;
452 $keycol =~ s/^\N{BOM}//; # Strip BOM if exists, otherwise it will be part of first column key
453 $params->{keycol}->{$keycol} = $col++;
456 return @csvcolumns;
459 =head2 set_attribute_types
461 my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
463 Returns an attribute type based on matchpoint parameter.
465 =cut
467 sub set_attribute_types {
468 my ($self, $params) = @_;
470 my $attribute_type;
471 if( $params->{extended} ) {
472 $attribute_type = Koha::Patron::Attribute::Types->find($params->{matchpoint});
475 return $attribute_type;
478 =head2 set_column_keys
480 my @columnkeys = set_column_keys($extended);
482 Returns an array of borrowers' table columns.
484 =cut
486 sub set_column_keys {
487 my ($self, $extended) = @_;
489 my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
490 push( @columnkeys, 'patron_attributes' ) if $extended;
492 return @columnkeys;
495 =head2 generate_patron_attributes
497 my $patron_attributes = generate_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
499 Returns a Koha::Patron::Attributes as expected by Koha::Patron->extended_attributes
501 =cut
503 sub generate_patron_attributes {
504 my ($self, $extended, $string, $feedback) = @_;
506 unless( $extended ) { return; }
507 unless( defined $string ) { return; }
509 # Fixup double quotes in case we are passed smart quotes
510 $string =~ s/\xe2\x80\x9c/"/g;
511 $string =~ s/\xe2\x80\x9d/"/g;
513 push (@$feedback, { feedback => 1, name => 'attribute string', value => $string });
514 return [] unless $string; # Unit tests want the feedback, is it really needed?
516 my $csv = Text::CSV->new({binary => 1}); # binary needed for non-ASCII Unicode
517 my $ok = $csv->parse($string); # parse field again to get subfields!
518 my @list = $csv->fields();
519 my @patron_attributes =
520 sort { $a->{code} cmp $b->{code} || $a->{value} cmp $b->{value} }
521 map {
522 my @arr = split /:/, $_, 2;
523 { code => $arr[0], attribute => $arr[1] }
524 } @list;
525 return \@patron_attributes;
526 # TODO: error handling (check $ok)
529 =head2 check_branch_code
531 check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
533 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
535 =cut
537 sub check_branch_code {
538 my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
540 # No branch code
541 unless( $branchcode ) {
542 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => decode_utf8($borrowerline), });
543 return;
546 # look for branch code
547 my $library = Koha::Libraries->find( $branchcode );
548 unless( $library ) {
549 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => decode_utf8($borrowerline),
550 value => $branchcode, branch_map => 1, });
554 =head2 check_borrower_category
556 check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
558 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
560 =cut
562 sub check_borrower_category {
563 my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
565 # No branch code
566 unless( $categorycode ) {
567 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => decode_utf8($borrowerline), });
568 return;
571 # Looking for borrower category
572 my $category = Koha::Patron::Categories->find($categorycode);
573 unless( $category ) {
574 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => decode_utf8($borrowerline),
575 value => $categorycode, category_map => 1, });
579 =head2 format_dates
581 format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
583 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
584 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
586 =cut
588 sub format_dates {
589 my ($self, $params) = @_;
591 foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry date_renewed)) {
592 my $tempdate = $params->{borrower}->{$date_type} or next();
593 my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
595 if ($formatted_date) {
596 $params->{borrower}->{$date_type} = $formatted_date;
597 } else {
598 $params->{borrower}->{$date_type} = '';
599 push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => decode_utf8($params->{lineraw}), bad_date => 1 });
606 =head1 AUTHOR
608 Koha Team
610 =cut