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.
27 use C4::Members::Attributes qw(:all);
28 use C4::Members::AttributeTypes;
34 Koha::Patrons::Import - Perl Module containing import_patrons method exported from import_borrowers script.
38 use Koha::Patrons::Import;
42 This module contains one method for importing patrons in bulk.
48 my $return = Koha::Patrons::Import::import_patrons($params);
50 Applies various checks and imports patrons in bulk from a csv file.
52 Further pod documentation needed here.
56 has 'today_iso' => ( is => 'ro', lazy => 1,
57 default => sub { output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); }, );
59 has 'text_csv' => ( is => 'rw', lazy => 1,
60 default => sub { Text::CSV->new( { binary => 1, } ); }, );
63 my ($self, $params) = @_;
65 my $handle = $params->{file};
66 unless( $handle ) { carp('No file handle passed in!'); return; }
68 my $matchpoint = $params->{matchpoint};
69 my $defaults = $params->{defaults};
70 my $ext_preserve = $params->{preserve_extended_attributes};
71 my $overwrite_cardnumber = $params->{overwrite_cardnumber};
72 my $extended = C4::Context->preference('ExtendedPatronAttributes');
73 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
75 my @columnkeys = $self->set_column_keys($extended);
83 my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
85 # Use header line to construct key to column map
87 my $borrowerline = <$handle>;
88 my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
89 push(@feedback, { feedback => 1, name => 'headerrow', value => join( ', ', @csvcolumns ) });
91 my @criticals = qw( surname ); # there probably should be others - rm branchcode && categorycode
92 LINE: while ( my $borrowerline = <$handle> ) {
95 my @missing_criticals;
97 my $status = $self->text_csv->parse($borrowerline);
98 my @columns = $self->text_csv->fields();
100 push @missing_criticals, { badparse => 1, line => $line_number, lineraw => $borrowerline };
102 elsif ( @columns == @columnkeys ) {
103 @borrower{@columnkeys} = @columns;
105 # MJR: try to fill blanks gracefully by using default values
106 foreach my $key (@columnkeys) {
107 if ( $borrower{$key} !~ /\S/ ) {
108 $borrower{$key} = $defaults->{$key};
113 # MJR: try to recover gracefully by using default values
114 foreach my $key (@columnkeys) {
115 if ( defined( $csvkeycol{$key} ) and $columns[ $csvkeycol{$key} ] =~ /\S/ ) {
116 $borrower{$key} = $columns[ $csvkeycol{$key} ];
118 elsif ( $defaults->{$key} ) {
119 $borrower{$key} = $defaults->{$key};
121 elsif ( scalar grep { $key eq $_ } @criticals ) {
123 # a critical field is undefined
124 push @missing_criticals, { key => $key, line => $., lineraw => $borrowerline };
127 $borrower{$key} = '';
132 # Check if borrower category code exists and if it matches to a known category. Pushing error to missing_criticals otherwise.
133 $self->check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
135 # Check if branch code exists and if it matches to a branch name. Pushing error to missing_criticals otherwise.
136 $self->check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
138 # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
139 $self->format_dates({borrower => \%borrower, lineraw => $borrowerline, line => $line_number, missing_criticals => \@missing_criticals, });
141 if (@missing_criticals) {
142 foreach (@missing_criticals) {
143 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
144 $_->{surname} = $borrower{surname} || 'UNDEF';
147 ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
149 # The first 25 errors are enough. Keeping track of 30,000+ would destroy performance.
153 # Set patron attributes if extended.
154 my $patron_attributes = $self->set_patron_attributes($extended, $borrower{patron_attributes}, \@feedback);
155 if( $extended ) { delete $borrower{patron_attributes}; } # Not really a field in borrowers.
157 # Default date enrolled and date expiry if not already set.
158 $borrower{dateenrolled} = $self->today_iso() unless $borrower{dateenrolled};
159 $borrower{dateexpiry} = GetExpiryDate( $borrower{categorycode}, $borrower{dateenrolled} ) unless $borrower{dateexpiry};
163 if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
164 $member = GetMember( 'cardnumber' => $borrower{'cardnumber'} );
166 $borrowernumber = $member->{'borrowernumber'};
170 if ( defined($matchpoint_attr_type) ) {
171 foreach my $attr (@$patron_attributes) {
172 if ( $attr->{code} eq $matchpoint and $attr->{value} ne '' ) {
173 my @borrowernumbers = $matchpoint_attr_type->get_patrons( $attr->{value} );
174 $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
181 if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
184 invalid_cardnumber => 1,
185 borrowernumber => $borrowernumber,
186 cardnumber => $borrower{cardnumber}
192 # Check if the userid provided does not exist yet
193 if ( exists $borrower{userid}
194 and $borrower{userid}
195 and not Check_Userid( $borrower{userid}, $borrower{borrowernumber} ) ) {
196 push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
201 if ($borrowernumber) {
204 unless ($overwrite_cardnumber) {
210 value => $borrower{'surname'} . ' / ' . $borrowernumber
215 $borrower{'borrowernumber'} = $borrowernumber;
216 for my $col ( keys %borrower ) {
218 # use values from extant patron unless our csv file includes this column or we provided a default.
219 # FIXME : You cannot update a field with a perl-evaluated false value using the defaults.
221 # The password is always encrypted, skip it!
222 next if $col eq 'password';
224 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
225 $borrower{$col} = $member->{$col} if ( $member->{$col} );
229 unless ( ModMember(%borrower) ) {
235 name => 'lastinvalid',
236 value => $borrower{'surname'} . ' / ' . $borrowernumber
241 if ( $borrower{debarred} ) {
243 # Check to see if this debarment already exists
244 my $debarrments = GetDebarments(
246 borrowernumber => $borrowernumber,
247 expiration => $borrower{debarred},
248 comment => $borrower{debarredcomment}
252 # If it doesn't, then add it!
253 unless (@$debarrments) {
256 borrowernumber => $borrowernumber,
257 expiration => $borrower{debarred},
258 comment => $borrower{debarredcomment}
265 my $old_attributes = GetBorrowerAttributes($borrowernumber);
266 $patron_attributes = extended_attributes_merge( $old_attributes, $patron_attributes );
268 push @errors, { unknown_error => 1 }
269 unless SetBorrowerAttributes( $borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
276 name => 'lastoverwritten',
277 value => $borrower{'surname'} . ' / ' . $borrowernumber
282 # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
283 # At least this is closer to AddMember than in members/memberentry.pl
284 if ( !$borrower{'cardnumber'} ) {
285 $borrower{'cardnumber'} = fixup_cardnumber(undef);
287 if ( $borrowernumber = AddMember(%borrower) ) {
289 if ( $borrower{debarred} ) {
292 borrowernumber => $borrowernumber,
293 expiration => $borrower{debarred},
294 comment => $borrower{debarredcomment}
300 SetBorrowerAttributes( $borrowernumber, $patron_attributes );
303 if ($set_messaging_prefs) {
304 C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
306 borrowernumber => $borrowernumber,
307 categorycode => $borrower{categorycode}
317 name => 'lastimported',
318 value => $borrower{'surname'} . ' / ' . $borrowernumber
324 push @errors, { unknown_error => 1 };
328 name => 'lastinvalid',
329 value => $borrower{'surname'} . ' / AddMember',
337 feedback => \@feedback,
339 imported => $imported,
340 overwritten => $overwritten,
341 already_in_db => $alreadyindb,
346 =head2 prepare_columns
348 my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
350 Returns an array of all column key and populates a hash of colunm key positions.
354 sub prepare_columns {
355 my ($self, $params) = @_;
357 my $status = $self->text_csv->parse($params->{headerrow});
359 push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
363 my @csvcolumns = $self->text_csv->fields();
365 foreach my $keycol (@csvcolumns) {
366 # columnkeys don't contain whitespace, but some stupid tools add it
368 $params->{keycol}->{$keycol} = $col++;
374 =head2 set_attribute_types
376 my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
378 Returns an attribute type based on matchpoint parameter.
382 sub set_attribute_types {
383 my ($self, $params) = @_;
386 if( $params->{extended} ) {
387 $attribute_types = C4::Members::AttributeTypes->fetch($params->{matchpoint});
390 return $attribute_types;
393 =head2 set_column_keys
395 my @columnkeys = set_column_keys($extended);
397 Returns an array of borrowers' table columns.
401 sub set_column_keys {
402 my ($self, $extended) = @_;
404 my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } C4::Members::columns();
405 push( @columnkeys, 'patron_attributes' ) if $extended;
410 =head2 set_patron_attributes
412 my $patron_attributes = set_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
414 Returns a reference to array of hashrefs data structure as expected by SetBorrowerAttributes.
418 sub set_patron_attributes {
419 my ($self, $extended, $patron_attributes, $feedback) = @_;
421 unless( $extended ) { return; }
422 unless( defined($patron_attributes) ) { return; }
424 # Fixup double quotes in case we are passed smart quotes
425 $patron_attributes =~ s/\xe2\x80\x9c/"/g;
426 $patron_attributes =~ s/\xe2\x80\x9d/"/g;
428 push (@$feedback, { feedback => 1, name => 'attribute string', value => $patron_attributes });
430 my $result = extended_attributes_code_value_arrayref($patron_attributes);
435 =head2 check_branch_code
437 check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
439 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
443 sub check_branch_code {
444 my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
447 unless( $branchcode ) {
448 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline, });
452 # look for branch code
453 my $branch_name = GetBranchName( $branchcode );
454 unless( $branch_name ) {
455 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline,
456 value => $branchcode, branch_map => 1, });
460 =head2 check_borrower_category
462 check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
464 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
468 sub check_borrower_category {
469 my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
472 unless( $categorycode ) {
473 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline, });
477 # Looking for borrower category
478 my $category = GetBorrowercategory( $categorycode );
479 unless( $category ) {
480 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline,
481 value => $categorycode, category_map => 1, });
487 format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
489 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
490 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
495 my ($self, $params) = @_;
497 foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry)) {
498 my $tempdate = $params->{borrower}->{$date_type} or next();
499 my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
501 if ($formatted_date) {
502 $params->{borrower}->{$date_type} = $formatted_date;
504 $params->{borrower}->{$date_type} = '';
505 push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => $params->{lineraw}, bad_date => 1 });