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
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.
26 use C4::Members::Attributes qw(:all);
27 use C4::Members::AttributeTypes;
31 use Koha::Patron::Categories;
36 Koha::Patrons::Import - Perl Module containing import_patrons method exported from import_borrowers script.
40 use Koha::Patrons::Import;
44 This module contains one method for importing patrons in bulk.
50 my $return = Koha::Patrons::Import::import_patrons($params);
52 Applies various checks and imports patrons in bulk from a csv file.
54 Further pod documentation needed here.
58 has 'today_iso' => ( is => 'ro', lazy => 1,
59 default => sub { output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); }, );
61 has 'text_csv' => ( is => 'rw', lazy => 1,
62 default => sub { Text::CSV->new( { binary => 1, } ); }, );
65 my ($self, $params) = @_;
67 my $handle = $params->{file};
68 unless( $handle ) { carp('No file handle passed in!'); return; }
70 my $matchpoint = $params->{matchpoint};
71 my $defaults = $params->{defaults};
72 my $ext_preserve = $params->{preserve_extended_attributes};
73 my $overwrite_cardnumber = $params->{overwrite_cardnumber};
74 my $extended = C4::Context->preference('ExtendedPatronAttributes');
75 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
77 my @columnkeys = $self->set_column_keys($extended);
85 my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
87 # Use header line to construct key to column map
89 my $borrowerline = <$handle>;
90 my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
91 push(@feedback, { feedback => 1, name => 'headerrow', value => join( ', ', @csvcolumns ) });
93 my @criticals = qw( surname ); # there probably should be others - rm branchcode && categorycode
94 LINE: while ( my $borrowerline = <$handle> ) {
97 my @missing_criticals;
99 my $status = $self->text_csv->parse($borrowerline);
100 my @columns = $self->text_csv->fields();
102 push @missing_criticals, { badparse => 1, line => $line_number, lineraw => $borrowerline };
104 elsif ( @columns == @columnkeys ) {
105 @borrower{@columnkeys} = @columns;
107 # MJR: try to fill blanks gracefully by using default values
108 foreach my $key (@columnkeys) {
109 if ( $borrower{$key} !~ /\S/ ) {
110 $borrower{$key} = $defaults->{$key};
115 # MJR: try to recover gracefully by using default values
116 foreach my $key (@columnkeys) {
117 if ( defined( $csvkeycol{$key} ) and $columns[ $csvkeycol{$key} ] =~ /\S/ ) {
118 $borrower{$key} = $columns[ $csvkeycol{$key} ];
120 elsif ( $defaults->{$key} ) {
121 $borrower{$key} = $defaults->{$key};
123 elsif ( scalar grep { $key eq $_ } @criticals ) {
125 # a critical field is undefined
126 push @missing_criticals, { key => $key, line => $., lineraw => $borrowerline };
129 $borrower{$key} = '';
134 # Check if borrower category code exists and if it matches to a known category. Pushing error to missing_criticals otherwise.
135 $self->check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
137 # Check if branch code exists and if it matches to a branch name. Pushing error to missing_criticals otherwise.
138 $self->check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
140 # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
141 $self->format_dates({borrower => \%borrower, lineraw => $borrowerline, line => $line_number, missing_criticals => \@missing_criticals, });
143 if (@missing_criticals) {
144 foreach (@missing_criticals) {
145 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
146 $_->{surname} = $borrower{surname} || 'UNDEF';
149 ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
151 # The first 25 errors are enough. Keeping track of 30,000+ would destroy performance.
155 # Set patron attributes if extended.
156 my $patron_attributes = $self->set_patron_attributes($extended, $borrower{patron_attributes}, \@feedback);
157 if( $extended ) { delete $borrower{patron_attributes}; } # Not really a field in borrowers.
159 # Default date enrolled and date expiry if not already set.
160 $borrower{dateenrolled} = $self->today_iso() unless $borrower{dateenrolled};
161 $borrower{dateexpiry} = Koha::Patron::Categories->find( $borrower{categorycode} )->get_expiry_date( $borrower{dateenrolled} ) unless $borrower{dateexpiry};
165 if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
166 $member = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
169 if ( defined($matchpoint_attr_type) ) {
170 foreach my $attr (@$patron_attributes) {
171 if ( $attr->{code} eq $matchpoint and $attr->{value} ne '' ) {
172 my @borrowernumbers = $matchpoint_attr_type->get_patrons( $attr->{value} );
173 $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
181 $member = $member->unblessed;
182 $borrowernumber = $member->{'borrowernumber'};
187 if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
190 invalid_cardnumber => 1,
191 borrowernumber => $borrowernumber,
192 cardnumber => $borrower{cardnumber}
198 # Check if the userid provided does not exist yet
199 if ( exists $borrower{userid}
200 and $borrower{userid}
201 and not Check_Userid( $borrower{userid}, $borrower{borrowernumber} ) ) {
202 push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
207 if ($borrowernumber) {
210 unless ($overwrite_cardnumber) {
216 value => $borrower{'surname'} . ' / ' . $borrowernumber
221 $borrower{'borrowernumber'} = $borrowernumber;
222 for my $col ( keys %borrower ) {
224 # use values from extant patron unless our csv file includes this column or we provided a default.
225 # FIXME : You cannot update a field with a perl-evaluated false value using the defaults.
227 # The password is always encrypted, skip it!
228 next if $col eq 'password';
230 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
231 $borrower{$col} = $member->{$col} if ( $member->{$col} );
235 unless ( ModMember(%borrower) ) {
241 name => 'lastinvalid',
242 value => $borrower{'surname'} . ' / ' . $borrowernumber
247 if ( $borrower{debarred} ) {
249 # Check to see if this debarment already exists
250 my $debarrments = GetDebarments(
252 borrowernumber => $borrowernumber,
253 expiration => $borrower{debarred},
254 comment => $borrower{debarredcomment}
258 # If it doesn't, then add it!
259 unless (@$debarrments) {
262 borrowernumber => $borrowernumber,
263 expiration => $borrower{debarred},
264 comment => $borrower{debarredcomment}
271 my $old_attributes = GetBorrowerAttributes($borrowernumber);
272 $patron_attributes = extended_attributes_merge( $old_attributes, $patron_attributes );
274 push @errors, { unknown_error => 1 }
275 unless SetBorrowerAttributes( $borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
282 name => 'lastoverwritten',
283 value => $borrower{'surname'} . ' / ' . $borrowernumber
288 # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
289 # At least this is closer to AddMember than in members/memberentry.pl
290 if ( !$borrower{'cardnumber'} ) {
291 $borrower{'cardnumber'} = fixup_cardnumber(undef);
293 if ( $borrowernumber = AddMember(%borrower) ) {
295 if ( $borrower{debarred} ) {
298 borrowernumber => $borrowernumber,
299 expiration => $borrower{debarred},
300 comment => $borrower{debarredcomment}
306 SetBorrowerAttributes( $borrowernumber, $patron_attributes );
309 if ($set_messaging_prefs) {
310 C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
312 borrowernumber => $borrowernumber,
313 categorycode => $borrower{categorycode}
323 name => 'lastimported',
324 value => $borrower{'surname'} . ' / ' . $borrowernumber
330 push @errors, { unknown_error => 1 };
334 name => 'lastinvalid',
335 value => $borrower{'surname'} . ' / AddMember',
343 feedback => \@feedback,
345 imported => $imported,
346 overwritten => $overwritten,
347 already_in_db => $alreadyindb,
352 =head2 prepare_columns
354 my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
356 Returns an array of all column key and populates a hash of colunm key positions.
360 sub prepare_columns {
361 my ($self, $params) = @_;
363 my $status = $self->text_csv->parse($params->{headerrow});
365 push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
369 my @csvcolumns = $self->text_csv->fields();
371 foreach my $keycol (@csvcolumns) {
372 # columnkeys don't contain whitespace, but some stupid tools add it
374 $params->{keycol}->{$keycol} = $col++;
380 =head2 set_attribute_types
382 my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
384 Returns an attribute type based on matchpoint parameter.
388 sub set_attribute_types {
389 my ($self, $params) = @_;
392 if( $params->{extended} ) {
393 $attribute_types = C4::Members::AttributeTypes->fetch($params->{matchpoint});
396 return $attribute_types;
399 =head2 set_column_keys
401 my @columnkeys = set_column_keys($extended);
403 Returns an array of borrowers' table columns.
407 sub set_column_keys {
408 my ($self, $extended) = @_;
410 my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
411 push( @columnkeys, 'patron_attributes' ) if $extended;
416 =head2 set_patron_attributes
418 my $patron_attributes = set_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
420 Returns a reference to array of hashrefs data structure as expected by SetBorrowerAttributes.
424 sub set_patron_attributes {
425 my ($self, $extended, $patron_attributes, $feedback) = @_;
427 unless( $extended ) { return; }
428 unless( defined($patron_attributes) ) { return; }
430 # Fixup double quotes in case we are passed smart quotes
431 $patron_attributes =~ s/\xe2\x80\x9c/"/g;
432 $patron_attributes =~ s/\xe2\x80\x9d/"/g;
434 push (@$feedback, { feedback => 1, name => 'attribute string', value => $patron_attributes });
436 my $result = extended_attributes_code_value_arrayref($patron_attributes);
441 =head2 check_branch_code
443 check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
445 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
449 sub check_branch_code {
450 my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
453 unless( $branchcode ) {
454 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline, });
458 # look for branch code
459 my $library = Koha::Libraries->find( $branchcode );
461 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline,
462 value => $branchcode, branch_map => 1, });
466 =head2 check_borrower_category
468 check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
470 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
474 sub check_borrower_category {
475 my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
478 unless( $categorycode ) {
479 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline, });
483 # Looking for borrower category
484 my $category = Koha::Patron::Categories->find($categorycode);
485 unless( $category ) {
486 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline,
487 value => $categorycode, category_map => 1, });
493 format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
495 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
496 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
501 my ($self, $params) = @_;
503 foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry)) {
504 my $tempdate = $params->{borrower}->{$date_type} or next();
505 my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
507 if ($formatted_date) {
508 $params->{borrower}->{$date_type} = $formatted_date;
510 $params->{borrower}->{$date_type} = '';
511 push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => $params->{lineraw}, bad_date => 1 });