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 = GetMember( 'cardnumber' => $borrower{'cardnumber'} );
168 $borrowernumber = $member->{'borrowernumber'};
172 if ( defined($matchpoint_attr_type) ) {
173 foreach my $attr (@$patron_attributes) {
174 if ( $attr->{code} eq $matchpoint and $attr->{value} ne '' ) {
175 my @borrowernumbers = $matchpoint_attr_type->get_patrons( $attr->{value} );
176 $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
183 if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
186 invalid_cardnumber => 1,
187 borrowernumber => $borrowernumber,
188 cardnumber => $borrower{cardnumber}
194 # Check if the userid provided does not exist yet
195 if ( exists $borrower{userid}
196 and $borrower{userid}
197 and not Check_Userid( $borrower{userid}, $borrower{borrowernumber} ) ) {
198 push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
203 if ($borrowernumber) {
206 unless ($overwrite_cardnumber) {
212 value => $borrower{'surname'} . ' / ' . $borrowernumber
217 $borrower{'borrowernumber'} = $borrowernumber;
218 for my $col ( keys %borrower ) {
220 # use values from extant patron unless our csv file includes this column or we provided a default.
221 # FIXME : You cannot update a field with a perl-evaluated false value using the defaults.
223 # The password is always encrypted, skip it!
224 next if $col eq 'password';
226 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
227 $borrower{$col} = $member->{$col} if ( $member->{$col} );
231 unless ( ModMember(%borrower) ) {
237 name => 'lastinvalid',
238 value => $borrower{'surname'} . ' / ' . $borrowernumber
243 if ( $borrower{debarred} ) {
245 # Check to see if this debarment already exists
246 my $debarrments = GetDebarments(
248 borrowernumber => $borrowernumber,
249 expiration => $borrower{debarred},
250 comment => $borrower{debarredcomment}
254 # If it doesn't, then add it!
255 unless (@$debarrments) {
258 borrowernumber => $borrowernumber,
259 expiration => $borrower{debarred},
260 comment => $borrower{debarredcomment}
267 my $old_attributes = GetBorrowerAttributes($borrowernumber);
268 $patron_attributes = extended_attributes_merge( $old_attributes, $patron_attributes );
270 push @errors, { unknown_error => 1 }
271 unless SetBorrowerAttributes( $borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
278 name => 'lastoverwritten',
279 value => $borrower{'surname'} . ' / ' . $borrowernumber
284 # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
285 # At least this is closer to AddMember than in members/memberentry.pl
286 if ( !$borrower{'cardnumber'} ) {
287 $borrower{'cardnumber'} = fixup_cardnumber(undef);
289 if ( $borrowernumber = AddMember(%borrower) ) {
291 if ( $borrower{debarred} ) {
294 borrowernumber => $borrowernumber,
295 expiration => $borrower{debarred},
296 comment => $borrower{debarredcomment}
302 SetBorrowerAttributes( $borrowernumber, $patron_attributes );
305 if ($set_messaging_prefs) {
306 C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
308 borrowernumber => $borrowernumber,
309 categorycode => $borrower{categorycode}
319 name => 'lastimported',
320 value => $borrower{'surname'} . ' / ' . $borrowernumber
326 push @errors, { unknown_error => 1 };
330 name => 'lastinvalid',
331 value => $borrower{'surname'} . ' / AddMember',
339 feedback => \@feedback,
341 imported => $imported,
342 overwritten => $overwritten,
343 already_in_db => $alreadyindb,
348 =head2 prepare_columns
350 my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
352 Returns an array of all column key and populates a hash of colunm key positions.
356 sub prepare_columns {
357 my ($self, $params) = @_;
359 my $status = $self->text_csv->parse($params->{headerrow});
361 push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
365 my @csvcolumns = $self->text_csv->fields();
367 foreach my $keycol (@csvcolumns) {
368 # columnkeys don't contain whitespace, but some stupid tools add it
370 $params->{keycol}->{$keycol} = $col++;
376 =head2 set_attribute_types
378 my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
380 Returns an attribute type based on matchpoint parameter.
384 sub set_attribute_types {
385 my ($self, $params) = @_;
388 if( $params->{extended} ) {
389 $attribute_types = C4::Members::AttributeTypes->fetch($params->{matchpoint});
392 return $attribute_types;
395 =head2 set_column_keys
397 my @columnkeys = set_column_keys($extended);
399 Returns an array of borrowers' table columns.
403 sub set_column_keys {
404 my ($self, $extended) = @_;
406 my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
407 push( @columnkeys, 'patron_attributes' ) if $extended;
412 =head2 set_patron_attributes
414 my $patron_attributes = set_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
416 Returns a reference to array of hashrefs data structure as expected by SetBorrowerAttributes.
420 sub set_patron_attributes {
421 my ($self, $extended, $patron_attributes, $feedback) = @_;
423 unless( $extended ) { return; }
424 unless( defined($patron_attributes) ) { return; }
426 # Fixup double quotes in case we are passed smart quotes
427 $patron_attributes =~ s/\xe2\x80\x9c/"/g;
428 $patron_attributes =~ s/\xe2\x80\x9d/"/g;
430 push (@$feedback, { feedback => 1, name => 'attribute string', value => $patron_attributes });
432 my $result = extended_attributes_code_value_arrayref($patron_attributes);
437 =head2 check_branch_code
439 check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
441 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
445 sub check_branch_code {
446 my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
449 unless( $branchcode ) {
450 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline, });
454 # look for branch code
455 my $library = Koha::Libraries->find( $branchcode );
457 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline,
458 value => $branchcode, branch_map => 1, });
462 =head2 check_borrower_category
464 check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
466 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
470 sub check_borrower_category {
471 my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
474 unless( $categorycode ) {
475 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline, });
479 # Looking for borrower category
480 my $category = Koha::Patron::Categories->find($categorycode);
481 unless( $category ) {
482 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline,
483 value => $categorycode, category_map => 1, });
489 format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
491 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
492 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
497 my ($self, $params) = @_;
499 foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry)) {
500 my $tempdate = $params->{borrower}->{$date_type} or next();
501 my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
503 if ($formatted_date) {
504 $params->{borrower}->{$date_type} = $formatted_date;
506 $params->{borrower}->{$date_type} = '';
507 push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => $params->{lineraw}, bad_date => 1 });