Bug 23329: Only redirect tracklinks.pl to urls contained in records
[koha.git] / Koha / Patrons / Import.pm
blobcb3ba56134991f19bb503d0d91fc86d53e5d855a
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;
24 use Encode qw( decode_utf8 );
26 use C4::Members;
27 use C4::Members::Attributes qw(:all);
28 use C4::Members::AttributeTypes;
30 use Koha::Libraries;
31 use Koha::Patrons;
32 use Koha::Patron::Categories;
33 use Koha::Patron::Debarments;
34 use Koha::DateUtils;
36 =head1 NAME
38 Koha::Patrons::Import - Perl Module containing import_patrons method exported from import_borrowers script.
40 =head1 SYNOPSIS
42 use Koha::Patrons::Import;
44 =head1 DESCRIPTION
46 This module contains one method for importing patrons in bulk.
48 =head1 FUNCTIONS
50 =head2 import_patrons
52 my $return = Koha::Patrons::Import::import_patrons($params);
54 Applies various checks and imports patrons in bulk from a csv file.
56 Further pod documentation needed here.
58 =cut
60 has 'today_iso' => ( is => 'ro', lazy => 1,
61 default => sub { output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); }, );
63 has 'text_csv' => ( is => 'rw', lazy => 1,
64 default => sub { Text::CSV->new( { binary => 1, } ); }, );
66 sub import_patrons {
67 my ($self, $params) = @_;
69 my $handle = $params->{file};
70 unless( $handle ) { carp('No file handle passed in!'); return; }
72 my $matchpoint = $params->{matchpoint};
73 my $defaults = $params->{defaults};
74 my $ext_preserve = $params->{preserve_extended_attributes};
75 my $overwrite_cardnumber = $params->{overwrite_cardnumber};
76 my $extended = C4::Context->preference('ExtendedPatronAttributes');
77 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
79 my @columnkeys = $self->set_column_keys($extended);
80 my @feedback;
81 my @errors;
83 my $imported = 0;
84 my $alreadyindb = 0;
85 my $overwritten = 0;
86 my $invalid = 0;
87 my @imported_borrowers;
88 my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
90 # Use header line to construct key to column map
91 my %csvkeycol;
92 my $borrowerline = <$handle>;
93 my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
94 push(@feedback, { feedback => 1, name => 'headerrow', value => join( ', ', @csvcolumns ) });
96 my @criticals = qw( surname ); # there probably should be others - rm branchcode && categorycode
97 LINE: while ( my $borrowerline = <$handle> ) {
98 my $line_number = $.;
99 my %borrower;
100 my @missing_criticals;
102 my $status = $self->text_csv->parse($borrowerline);
103 my @columns = $self->text_csv->fields();
104 if ( !$status ) {
105 push @missing_criticals, { badparse => 1, line => $line_number, lineraw => decode_utf8($borrowerline) };
107 elsif ( @columns == @columnkeys ) {
108 @borrower{@columnkeys} = @columns;
110 # MJR: try to fill blanks gracefully by using default values
111 foreach my $key (@columnkeys) {
112 if ( $borrower{$key} !~ /\S/ ) {
113 $borrower{$key} = $defaults->{$key};
117 else {
118 # MJR: try to recover gracefully by using default values
119 foreach my $key (@columnkeys) {
120 if ( defined( $csvkeycol{$key} ) and $columns[ $csvkeycol{$key} ] =~ /\S/ ) {
121 $borrower{$key} = $columns[ $csvkeycol{$key} ];
123 elsif ( $defaults->{$key} ) {
124 $borrower{$key} = $defaults->{$key};
126 elsif ( scalar grep { $key eq $_ } @criticals ) {
128 # a critical field is undefined
129 push @missing_criticals, { key => $key, line => $., lineraw => decode_utf8($borrowerline) };
131 else {
132 $borrower{$key} = '';
137 $borrower{cardnumber} = undef if $borrower{cardnumber} eq "";
139 # Check if borrower category code exists and if it matches to a known category. Pushing error to missing_criticals otherwise.
140 $self->check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
142 # Check if branch code exists and if it matches to a branch name. Pushing error to missing_criticals otherwise.
143 $self->check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
145 # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
146 $self->format_dates({borrower => \%borrower, lineraw => $borrowerline, line => $line_number, missing_criticals => \@missing_criticals, });
148 if (@missing_criticals) {
149 foreach (@missing_criticals) {
150 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
151 $_->{surname} = $borrower{surname} || 'UNDEF';
153 $invalid++;
154 ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
156 # The first 25 errors are enough. Keeping track of 30,000+ would destroy performance.
157 next LINE;
160 # Set patron attributes if extended.
161 my $patron_attributes = $self->set_patron_attributes($extended, $borrower{patron_attributes}, \@feedback);
162 if( $extended ) { delete $borrower{patron_attributes}; } # Not really a field in borrowers.
164 # Default date enrolled and date expiry if not already set.
165 $borrower{dateenrolled} = $self->today_iso() unless $borrower{dateenrolled};
166 $borrower{dateexpiry} = Koha::Patron::Categories->find( $borrower{categorycode} )->get_expiry_date( $borrower{dateenrolled} ) unless $borrower{dateexpiry};
168 my $borrowernumber;
169 my ( $member, $patron );
170 if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
171 $patron = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
173 elsif ( defined($matchpoint) && ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
174 $patron = Koha::Patrons->find( { userid => $borrower{userid} } );
176 elsif ($extended) {
177 if ( defined($matchpoint_attr_type) ) {
178 foreach my $attr (@$patron_attributes) {
179 if ( $attr->{code} eq $matchpoint and $attr->{value} ne '' ) {
180 my @borrowernumbers = $matchpoint_attr_type->get_patrons( $attr->{value} );
181 $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
182 $patron = Koha::Patrons->find( $borrowernumber );
183 last;
189 if ($patron) {
190 $member = $patron->unblessed;
191 $borrowernumber = $member->{'borrowernumber'};
192 } else {
193 $member = {};
196 if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
197 push @errors,
199 invalid_cardnumber => 1,
200 borrowernumber => $borrowernumber,
201 cardnumber => $borrower{cardnumber}
203 $invalid++;
204 next;
208 # Check if the userid provided does not exist yet
209 if ( defined($matchpoint)
210 and $matchpoint ne 'userid'
211 and exists $borrower{userid}
212 and $borrower{userid}
213 and not ( $borrowernumber ? $patron->userid( $borrower{userid} )->has_valid_userid : Koha::Patron->new( { userid => $borrower{userid} } )->has_valid_userid )
215 push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
216 $invalid++;
217 next LINE;
220 my $relationship = $borrower{relationship};
221 my $guarantor_id = $borrower{guarantor_id};
222 delete $borrower{relationship};
223 delete $borrower{guarantor_id};
225 if ($borrowernumber) {
227 # borrower exists
228 unless ($overwrite_cardnumber) {
229 $alreadyindb++;
230 push(
231 @feedback,
233 already_in_db => 1,
234 value => $borrower{'surname'} . ' / ' . $borrowernumber
237 next LINE;
239 $borrower{'borrowernumber'} = $borrowernumber;
240 for my $col ( keys %borrower ) {
242 # use values from extant patron unless our csv file includes this column or we provided a default.
243 # FIXME : You cannot update a field with a perl-evaluated false value using the defaults.
245 # The password is always encrypted, skip it!
246 next if $col eq 'password';
248 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
249 $borrower{$col} = $member->{$col} if ( $member->{$col} );
253 my $patron = Koha::Patrons->find( $borrowernumber );
254 eval { $patron->set(\%borrower)->store };
255 if ( $@ ) {
256 $invalid++;
258 push(
259 @errors,
261 # TODO We can raise a better error
262 name => 'lastinvalid',
263 value => $borrower{'surname'} . ' / ' . $borrowernumber
266 next LINE;
268 # Don't add a new restriction if the existing 'combined' restriction matches this one
269 if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
271 # Check to see if this debarment already exists
272 my $debarrments = GetDebarments(
274 borrowernumber => $borrowernumber,
275 expiration => $borrower{debarred},
276 comment => $borrower{debarredcomment}
280 # If it doesn't, then add it!
281 unless (@$debarrments) {
282 AddDebarment(
284 borrowernumber => $borrowernumber,
285 expiration => $borrower{debarred},
286 comment => $borrower{debarredcomment}
291 if ($extended) {
292 if ($ext_preserve) {
293 my $old_attributes = GetBorrowerAttributes($borrowernumber);
294 $patron_attributes = extended_attributes_merge( $old_attributes, $patron_attributes );
296 push @errors, { unknown_error => 1 }
297 unless SetBorrowerAttributes( $borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
299 $overwritten++;
300 push(
301 @feedback,
303 feedback => 1,
304 name => 'lastoverwritten',
305 value => $borrower{'surname'} . ' / ' . $borrowernumber
309 else {
310 my $patron = eval {
311 Koha::Patron->new(\%borrower)->store;
313 unless ( $@ ) {
315 if ( $patron->is_debarred ) {
316 AddDebarment(
318 borrowernumber => $patron->borrowernumber,
319 expiration => $patron->debarred,
320 comment => $patron->debarredcomment,
325 if ($extended) {
326 SetBorrowerAttributes( $patron->borrowernumber, $patron_attributes );
329 if ($set_messaging_prefs) {
330 C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
332 borrowernumber => $patron->borrowernumber,
333 categorycode => $patron->categorycode,
338 $imported++;
339 push @imported_borrowers, $patron->borrowernumber; #for patronlist
340 push(
341 @feedback,
343 feedback => 1,
344 name => 'lastimported',
345 value => $patron->surname . ' / ' . $patron->borrowernumber,
349 else {
350 $invalid++;
351 push @errors, { unknown_error => 1 };
352 push(
353 @errors,
355 name => 'lastinvalid',
356 value => $borrower{'surname'} . ' / Create patron',
362 # Add a guarantor if we are given a relationship
363 if ( $guarantor_id ) {
364 Koha::Patron::Relationship->new(
366 guarantee_id => $borrowernumber,
367 relationship => $relationship,
368 guarantor_id => $guarantor_id,
370 )->store();
374 return {
375 feedback => \@feedback,
376 errors => \@errors,
377 imported => $imported,
378 overwritten => $overwritten,
379 already_in_db => $alreadyindb,
380 invalid => $invalid,
381 imported_borrowers => \@imported_borrowers,
385 =head2 prepare_columns
387 my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
389 Returns an array of all column key and populates a hash of colunm key positions.
391 =cut
393 sub prepare_columns {
394 my ($self, $params) = @_;
396 my $status = $self->text_csv->parse($params->{headerrow});
397 unless( $status ) {
398 push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
399 return;
402 my @csvcolumns = $self->text_csv->fields();
403 my $col = 0;
404 foreach my $keycol (@csvcolumns) {
405 # columnkeys don't contain whitespace, but some stupid tools add it
406 $keycol =~ s/ +//g;
407 $params->{keycol}->{$keycol} = $col++;
410 return @csvcolumns;
413 =head2 set_attribute_types
415 my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
417 Returns an attribute type based on matchpoint parameter.
419 =cut
421 sub set_attribute_types {
422 my ($self, $params) = @_;
424 my $attribute_types;
425 if( $params->{extended} ) {
426 $attribute_types = C4::Members::AttributeTypes->fetch($params->{matchpoint});
429 return $attribute_types;
432 =head2 set_column_keys
434 my @columnkeys = set_column_keys($extended);
436 Returns an array of borrowers' table columns.
438 =cut
440 sub set_column_keys {
441 my ($self, $extended) = @_;
443 my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
444 push( @columnkeys, 'patron_attributes' ) if $extended;
446 return @columnkeys;
449 =head2 set_patron_attributes
451 my $patron_attributes = set_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
453 Returns a reference to array of hashrefs data structure as expected by SetBorrowerAttributes.
455 =cut
457 sub set_patron_attributes {
458 my ($self, $extended, $patron_attributes, $feedback) = @_;
460 unless( $extended ) { return; }
461 unless( defined($patron_attributes) ) { return; }
463 # Fixup double quotes in case we are passed smart quotes
464 $patron_attributes =~ s/\xe2\x80\x9c/"/g;
465 $patron_attributes =~ s/\xe2\x80\x9d/"/g;
467 push (@$feedback, { feedback => 1, name => 'attribute string', value => $patron_attributes });
469 my $result = extended_attributes_code_value_arrayref($patron_attributes);
471 return $result;
474 =head2 check_branch_code
476 check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
478 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
480 =cut
482 sub check_branch_code {
483 my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
485 # No branch code
486 unless( $branchcode ) {
487 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => decode_utf8($borrowerline), });
488 return;
491 # look for branch code
492 my $library = Koha::Libraries->find( $branchcode );
493 unless( $library ) {
494 push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => decode_utf8($borrowerline),
495 value => $branchcode, branch_map => 1, });
499 =head2 check_borrower_category
501 check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
503 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
505 =cut
507 sub check_borrower_category {
508 my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
510 # No branch code
511 unless( $categorycode ) {
512 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => decode_utf8($borrowerline), });
513 return;
516 # Looking for borrower category
517 my $category = Koha::Patron::Categories->find($categorycode);
518 unless( $category ) {
519 push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => decode_utf8($borrowerline),
520 value => $categorycode, category_map => 1, });
524 =head2 format_dates
526 format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
528 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
529 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
531 =cut
533 sub format_dates {
534 my ($self, $params) = @_;
536 foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry date_renewed)) {
537 my $tempdate = $params->{borrower}->{$date_type} or next();
538 my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
540 if ($formatted_date) {
541 $params->{borrower}->{$date_type} = $formatted_date;
542 } else {
543 $params->{borrower}->{$date_type} = '';
544 push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => decode_utf8($params->{lineraw}), bad_date => 1 });
551 =head1 AUTHOR
553 Koha Team
555 =cut