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;
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 $extended = C4::Context->preference('ExtendedPatronAttributes');
76 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
78 my @columnkeys = $self->set_column_keys($extended);
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
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> ) {
99 my @missing_criticals;
101 my $status = $self->text_csv->parse($borrowerline);
102 my @columns = $self->text_csv->fields();
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};
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 };
131 $borrower{$key} = '';
136 # Check if borrower category code exists and if it matches to a known category. Pushing error to missing_criticals otherwise.
137 $self->check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
139 # Check if branch code exists and if it matches to a branch name. Pushing error to missing_criticals otherwise.
140 $self->check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
142 # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
143 $self->format_dates({borrower => \%borrower, lineraw => $borrowerline, line => $line_number, missing_criticals => \@missing_criticals, });
145 if (@missing_criticals) {
146 foreach (@missing_criticals) {
147 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
148 $_->{surname} = $borrower{surname} || 'UNDEF';
151 ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
153 # The first 25 errors are enough. Keeping track of 30,000+ would destroy performance.
157 # Set patron attributes if extended.
158 my $patron_attributes = $self->set_patron_attributes($extended, $borrower{patron_attributes}, \@feedback);
159 if( $extended ) { delete $borrower{patron_attributes}; } # Not really a field in borrowers.
161 # Default date enrolled and date expiry if not already set.
162 $borrower{dateenrolled} = $self->today_iso() unless $borrower{dateenrolled};
163 $borrower{dateexpiry} = Koha::Patron::Categories->find( $borrower{categorycode} )->get_expiry_date( $borrower{dateenrolled} ) unless $borrower{dateexpiry};
166 my ( $member, $patron );
167 if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
168 $patron = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
170 elsif ( defined($matchpoint) && ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
171 $patron = Koha::Patrons->find( { userid => $borrower{userid} } );
174 if ( defined($matchpoint_attr_type) ) {
175 foreach my $attr (@$patron_attributes) {
176 if ( $attr->{code} eq $matchpoint and $attr->{value} ne '' ) {
177 my @borrowernumbers = $matchpoint_attr_type->get_patrons( $attr->{value} );
178 $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
186 $member = $patron->unblessed;
187 $borrowernumber = $member->{'borrowernumber'};
192 if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
195 invalid_cardnumber => 1,
196 borrowernumber => $borrowernumber,
197 cardnumber => $borrower{cardnumber}
204 # Check if the userid provided does not exist yet
205 if ( defined($matchpoint)
206 and $matchpoint ne 'userid'
207 and exists $borrower{userid}
208 and $borrower{userid}
209 and not ( $borrowernumber ? $patron->userid( $borrower{userid} )->has_valid_userid : Koha::Patron->new( { userid => $borrower{userid} } )->has_valid_userid )
211 push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
216 if ($borrowernumber) {
219 unless ($overwrite_cardnumber) {
225 value => $borrower{'surname'} . ' / ' . $borrowernumber
230 $borrower{'borrowernumber'} = $borrowernumber;
231 for my $col ( keys %borrower ) {
233 # use values from extant patron unless our csv file includes this column or we provided a default.
234 # FIXME : You cannot update a field with a perl-evaluated false value using the defaults.
236 # The password is always encrypted, skip it!
237 next if $col eq 'password';
239 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
240 $borrower{$col} = $member->{$col} if ( $member->{$col} );
244 my $patron = Koha::Patrons->find( $borrowernumber );
245 eval { $patron->set(\%borrower)->store };
252 # TODO We can raise a better error
253 name => 'lastinvalid',
254 value => $borrower{'surname'} . ' / ' . $borrowernumber
259 # Don't add a new restriction if the existing 'combined' restriction matches this one
260 if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
262 # Check to see if this debarment already exists
263 my $debarrments = GetDebarments(
265 borrowernumber => $borrowernumber,
266 expiration => $borrower{debarred},
267 comment => $borrower{debarredcomment}
271 # If it doesn't, then add it!
272 unless (@$debarrments) {
275 borrowernumber => $borrowernumber,
276 expiration => $borrower{debarred},
277 comment => $borrower{debarredcomment}
284 my $old_attributes = GetBorrowerAttributes($borrowernumber);
285 $patron_attributes = extended_attributes_merge( $old_attributes, $patron_attributes );
287 push @errors, { unknown_error => 1 }
288 unless SetBorrowerAttributes( $borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
295 name => 'lastoverwritten',
296 value => $borrower{'surname'} . ' / ' . $borrowernumber
302 Koha::Patron->new(\%borrower)->store;
306 if ( $patron->is_debarred ) {
309 borrowernumber => $patron->borrowernumber,
310 expiration => $patron->debarred,
311 comment => $patron->debarredcomment,
317 SetBorrowerAttributes( $patron->borrowernumber, $patron_attributes );
320 if ($set_messaging_prefs) {
321 C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
323 borrowernumber => $patron->borrowernumber,
324 categorycode => $patron->categorycode,
330 push @imported_borrowers, $patron->borrowernumber; #for patronlist
335 name => 'lastimported',
336 value => $patron->surname . ' / ' . $patron->borrowernumber,
342 push @errors, { unknown_error => 1 };
346 name => 'lastinvalid',
347 value => $borrower{'surname'} . ' / Create patron',
355 feedback => \@feedback,
357 imported => $imported,
358 overwritten => $overwritten,
359 already_in_db => $alreadyindb,
361 imported_borrowers => \@imported_borrowers,
365 =head2 prepare_columns
367 my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
369 Returns an array of all column key and populates a hash of colunm key positions.
373 sub prepare_columns {
374 my ($self, $params) = @_;
376 my $status = $self->text_csv->parse($params->{headerrow});
378 push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
382 my @csvcolumns = $self->text_csv->fields();
384 foreach my $keycol (@csvcolumns) {
385 # columnkeys don't contain whitespace, but some stupid tools add it
387 $params->{keycol}->{$keycol} = $col++;
393 =head2 set_attribute_types
395 my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
397 Returns an attribute type based on matchpoint parameter.
401 sub set_attribute_types {
402 my ($self, $params) = @_;
405 if( $params->{extended} ) {
406 $attribute_types = C4::Members::AttributeTypes->fetch($params->{matchpoint});
409 return $attribute_types;
412 =head2 set_column_keys
414 my @columnkeys = set_column_keys($extended);
416 Returns an array of borrowers' table columns.
420 sub set_column_keys {
421 my ($self, $extended) = @_;
423 my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
424 push( @columnkeys, 'patron_attributes' ) if $extended;
429 =head2 set_patron_attributes
431 my $patron_attributes = set_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
433 Returns a reference to array of hashrefs data structure as expected by SetBorrowerAttributes.
437 sub set_patron_attributes {
438 my ($self, $extended, $patron_attributes, $feedback) = @_;
440 unless( $extended ) { return; }
441 unless( defined($patron_attributes) ) { return; }
443 # Fixup double quotes in case we are passed smart quotes
444 $patron_attributes =~ s/\xe2\x80\x9c/"/g;
445 $patron_attributes =~ s/\xe2\x80\x9d/"/g;
447 push (@$feedback, { feedback => 1, name => 'attribute string', value => $patron_attributes });
449 my $result = extended_attributes_code_value_arrayref($patron_attributes);
454 =head2 check_branch_code
456 check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
458 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
462 sub check_branch_code {
463 my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
466 unless( $branchcode ) {
467 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline, });
471 # look for branch code
472 my $library = Koha::Libraries->find( $branchcode );
474 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline,
475 value => $branchcode, branch_map => 1, });
479 =head2 check_borrower_category
481 check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
483 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
487 sub check_borrower_category {
488 my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
491 unless( $categorycode ) {
492 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline, });
496 # Looking for borrower category
497 my $category = Koha::Patron::Categories->find($categorycode);
498 unless( $category ) {
499 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline,
500 value => $categorycode, category_map => 1, });
506 format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
508 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
509 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
514 my ($self, $params) = @_;
516 foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry date_renewed)) {
517 my $tempdate = $params->{borrower}->{$date_type} or next();
518 my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
520 if ($formatted_date) {
521 $params->{borrower}->{$date_type} = $formatted_date;
523 $params->{borrower}->{$date_type} = '';
524 push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => $params->{lineraw}, bad_date => 1 });