Bug 20434: Update UNIMARC framework - auth (TM)
[koha.git] / Koha / Patrons / Import.pm
blob3575b8a4e24b7932f5137f0b08433b6c88a5f685
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 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.
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.
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.
18 use Modern::Perl;
19 use Moo;
20 use namespace::clean;
22 use Carp;
23 use Text::CSV;
25 use C4::Members;
26 use C4::Members::Attributes qw(:all);
27 use C4::Members::AttributeTypes;
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 $extended = C4::Context->preference('ExtendedPatronAttributes');
76 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
78 my @columnkeys = $self->set_column_keys($extended);
79 my @feedback;
80 my @errors;
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, });
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 ) });
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;
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 };
106 elsif ( @columns == @columnkeys ) {
107 @borrower{@columnkeys} = @columns;
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};
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} ];
122 elsif ( $defaults->{$key} ) {
123 $borrower{$key} = $defaults->{$key};
125 elsif ( scalar grep { $key eq $_ } @criticals ) {
127 # a critical field is undefined
128 push @missing_criticals, { key => $key, line => $., lineraw => $borrowerline };
130 else {
131 $borrower{$key} = '';
136 $borrower{cardnumber} = undef if $borrower{cardnumber} eq "";
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);
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);
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, });
147 if (@missing_criticals) {
148 foreach (@missing_criticals) {
149 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
150 $_->{surname} = $borrower{surname} || 'UNDEF';
152 $invalid++;
153 ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
155 # The first 25 errors are enough. Keeping track of 30,000+ would destroy performance.
156 next LINE;
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.
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};
167 my $borrowernumber;
168 my ( $member, $patron );
169 if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
170 $patron = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
172 elsif ( defined($matchpoint) && ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
173 $patron = Koha::Patrons->find( { userid => $borrower{userid} } );
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;
188 if ($patron) {
189 $member = $patron->unblessed;
190 $borrowernumber = $member->{'borrowernumber'};
191 } else {
192 $member = {};
195 if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
196 push @errors,
198 invalid_cardnumber => 1,
199 borrowernumber => $borrowernumber,
200 cardnumber => $borrower{cardnumber}
202 $invalid++;
203 next;
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 )
214 push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
215 $invalid++;
216 next LINE;
219 my $relationship = $borrower{relationship};
220 my $guarantor_id = $borrower{guarantor_id};
221 delete $borrower{relationship};
222 delete $borrower{guarantor_id};
224 if ($borrowernumber) {
226 # borrower exists
227 unless ($overwrite_cardnumber) {
228 $alreadyindb++;
229 push(
230 @feedback,
232 already_in_db => 1,
233 value => $borrower{'surname'} . ' / ' . $borrowernumber
236 next LINE;
238 $borrower{'borrowernumber'} = $borrowernumber;
239 for my $col ( keys %borrower ) {
241 # use values from extant patron unless our csv file includes this column or we provided a default.
242 # FIXME : You cannot update a field with a perl-evaluated false value using the defaults.
244 # The password is always encrypted, skip it!
245 next if $col eq 'password';
247 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
248 $borrower{$col} = $member->{$col} if ( $member->{$col} );
252 my $patron = Koha::Patrons->find( $borrowernumber );
253 eval { $patron->set(\%borrower)->store };
254 if ( $@ ) {
255 $invalid++;
257 push(
258 @errors,
260 # TODO We can raise a better error
261 name => 'lastinvalid',
262 value => $borrower{'surname'} . ' / ' . $borrowernumber
265 next LINE;
267 # Don't add a new restriction if the existing 'combined' restriction matches this one
268 if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
270 # Check to see if this debarment already exists
271 my $debarrments = GetDebarments(
273 borrowernumber => $borrowernumber,
274 expiration => $borrower{debarred},
275 comment => $borrower{debarredcomment}
279 # If it doesn't, then add it!
280 unless (@$debarrments) {
281 AddDebarment(
283 borrowernumber => $borrowernumber,
284 expiration => $borrower{debarred},
285 comment => $borrower{debarredcomment}
290 if ($extended) {
291 if ($ext_preserve) {
292 my $old_attributes = GetBorrowerAttributes($borrowernumber);
293 $patron_attributes = extended_attributes_merge( $old_attributes, $patron_attributes );
295 push @errors, { unknown_error => 1 }
296 unless SetBorrowerAttributes( $borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
298 $overwritten++;
299 push(
300 @feedback,
302 feedback => 1,
303 name => 'lastoverwritten',
304 value => $borrower{'surname'} . ' / ' . $borrowernumber
308 else {
309 my $patron = eval {
310 Koha::Patron->new(\%borrower)->store;
312 unless ( $@ ) {
314 if ( $patron->is_debarred ) {
315 AddDebarment(
317 borrowernumber => $patron->borrowernumber,
318 expiration => $patron->debarred,
319 comment => $patron->debarredcomment,
324 if ($extended) {
325 SetBorrowerAttributes( $patron->borrowernumber, $patron_attributes );
328 if ($set_messaging_prefs) {
329 C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
331 borrowernumber => $patron->borrowernumber,
332 categorycode => $patron->categorycode,
337 $imported++;
338 push @imported_borrowers, $patron->borrowernumber; #for patronlist
339 push(
340 @feedback,
342 feedback => 1,
343 name => 'lastimported',
344 value => $patron->surname . ' / ' . $patron->borrowernumber,
348 else {
349 $invalid++;
350 push @errors, { unknown_error => 1 };
351 push(
352 @errors,
354 name => 'lastinvalid',
355 value => $borrower{'surname'} . ' / Create patron',
361 # Add a guarantor if we are given a relationship
362 if ( $guarantor_id ) {
363 Koha::Patron::Relationship->new(
365 guarantee_id => $borrowernumber,
366 relationship => $relationship,
367 guarantor_id => $guarantor_id,
369 )->store();
373 return {
374 feedback => \@feedback,
375 errors => \@errors,
376 imported => $imported,
377 overwritten => $overwritten,
378 already_in_db => $alreadyindb,
379 invalid => $invalid,
380 imported_borrowers => \@imported_borrowers,
384 =head2 prepare_columns
386 my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
388 Returns an array of all column key and populates a hash of colunm key positions.
390 =cut
392 sub prepare_columns {
393 my ($self, $params) = @_;
395 my $status = $self->text_csv->parse($params->{headerrow});
396 unless( $status ) {
397 push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
398 return;
401 my @csvcolumns = $self->text_csv->fields();
402 my $col = 0;
403 foreach my $keycol (@csvcolumns) {
404 # columnkeys don't contain whitespace, but some stupid tools add it
405 $keycol =~ s/ +//g;
406 $params->{keycol}->{$keycol} = $col++;
409 return @csvcolumns;
412 =head2 set_attribute_types
414 my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
416 Returns an attribute type based on matchpoint parameter.
418 =cut
420 sub set_attribute_types {
421 my ($self, $params) = @_;
423 my $attribute_types;
424 if( $params->{extended} ) {
425 $attribute_types = C4::Members::AttributeTypes->fetch($params->{matchpoint});
428 return $attribute_types;
431 =head2 set_column_keys
433 my @columnkeys = set_column_keys($extended);
435 Returns an array of borrowers' table columns.
437 =cut
439 sub set_column_keys {
440 my ($self, $extended) = @_;
442 my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
443 push( @columnkeys, 'patron_attributes' ) if $extended;
445 return @columnkeys;
448 =head2 set_patron_attributes
450 my $patron_attributes = set_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
452 Returns a reference to array of hashrefs data structure as expected by SetBorrowerAttributes.
454 =cut
456 sub set_patron_attributes {
457 my ($self, $extended, $patron_attributes, $feedback) = @_;
459 unless( $extended ) { return; }
460 unless( defined($patron_attributes) ) { return; }
462 # Fixup double quotes in case we are passed smart quotes
463 $patron_attributes =~ s/\xe2\x80\x9c/"/g;
464 $patron_attributes =~ s/\xe2\x80\x9d/"/g;
466 push (@$feedback, { feedback => 1, name => 'attribute string', value => $patron_attributes });
468 my $result = extended_attributes_code_value_arrayref($patron_attributes);
470 return $result;
473 =head2 check_branch_code
475 check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
477 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
479 =cut
481 sub check_branch_code {
482 my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
484 # No branch code
485 unless( $branchcode ) {
486 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline, });
487 return;
490 # look for branch code
491 my $library = Koha::Libraries->find( $branchcode );
492 unless( $library ) {
493 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline,
494 value => $branchcode, branch_map => 1, });
498 =head2 check_borrower_category
500 check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
502 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
504 =cut
506 sub check_borrower_category {
507 my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
509 # No branch code
510 unless( $categorycode ) {
511 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline, });
512 return;
515 # Looking for borrower category
516 my $category = Koha::Patron::Categories->find($categorycode);
517 unless( $category ) {
518 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline,
519 value => $categorycode, category_map => 1, });
523 =head2 format_dates
525 format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
527 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
528 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
530 =cut
532 sub format_dates {
533 my ($self, $params) = @_;
535 foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry date_renewed)) {
536 my $tempdate = $params->{borrower}->{$date_type} or next();
537 my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
539 if ($formatted_date) {
540 $params->{borrower}->{$date_type} = $formatted_date;
541 } else {
542 $params->{borrower}->{$date_type} = '';
543 push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => $params->{lineraw}, bad_date => 1 });
550 =head1 AUTHOR
552 Koha Team
554 =cut