Bug 12598: Re-add some missing stuffs
[koha.git] / Koha / Patrons / Import.pm
1 package Koha::Patrons::Import;
2
3 # This file is part of Koha.
4 #
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.
9 #
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.
13 #
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.
17
18 use Modern::Perl;
19 use Moo;
20 use namespace::clean;
21
22 use Carp;
23 use Text::CSV;
24
25 use C4::Members;
26 use C4::Members::Attributes qw(:all);
27 use C4::Members::AttributeTypes;
28
29 use Koha::Libraries;
30 use Koha::Patrons;
31 use Koha::Patron::Categories;
32 use Koha::DateUtils;
33
34 =head1 NAME
35
36 Koha::Patrons::Import - Perl Module containing import_patrons method exported from import_borrowers script.
37
38 =head1 SYNOPSIS
39
40 use Koha::Patrons::Import;
41
42 =head1 DESCRIPTION
43
44 This module contains one method for importing patrons in bulk.
45
46 =head1 FUNCTIONS
47
48 =head2 import_patrons
49
50  my $return = Koha::Patrons::Import::import_patrons($params);
51
52 Applies various checks and imports patrons in bulk from a csv file.
53
54 Further pod documentation needed here.
55
56 =cut
57
58 has 'today_iso' => ( is => 'ro', lazy => 1,
59     default => sub { output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); }, );
60
61 has 'text_csv' => ( is => 'rw', lazy => 1,
62     default => sub { Text::CSV->new( { binary => 1, } ); },  );
63
64 sub import_patrons {
65     my ($self, $params) = @_;
66
67     my $handle = $params->{file};
68     unless( $handle ) { carp('No file handle passed in!'); return; }
69
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');
76
77     my @columnkeys = $self->set_column_keys($extended);
78     my @feedback;
79     my @errors;
80
81     my $imported    = 0;
82     my $alreadyindb = 0;
83     my $overwritten = 0;
84     my $invalid     = 0;
85     my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
86
87     # Use header line to construct key to column map
88     my %csvkeycol;
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 ) });
92
93     my @criticals = qw( surname );    # there probably should be others - rm branchcode && categorycode
94   LINE: while ( my $borrowerline = <$handle> ) {
95         my $line_number = $.;
96         my %borrower;
97         my @missing_criticals;
98
99         my $status  = $self->text_csv->parse($borrowerline);
100         my @columns = $self->text_csv->fields();
101         if ( !$status ) {
102             push @missing_criticals, { badparse => 1, line => $line_number, lineraw => $borrowerline };
103         }
104         elsif ( @columns == @columnkeys ) {
105             @borrower{@columnkeys} = @columns;
106
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};
111                 }
112             }
113         }
114         else {
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} ];
119                 }
120                 elsif ( $defaults->{$key} ) {
121                     $borrower{$key} = $defaults->{$key};
122                 }
123                 elsif ( scalar grep { $key eq $_ } @criticals ) {
124
125                     # a critical field is undefined
126                     push @missing_criticals, { key => $key, line => $., lineraw => $borrowerline };
127                 }
128                 else {
129                     $borrower{$key} = '';
130                 }
131             }
132         }
133
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);
136
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);
139
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, });
142
143         if (@missing_criticals) {
144             foreach (@missing_criticals) {
145                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
146                 $_->{surname}        = $borrower{surname}        || 'UNDEF';
147             }
148             $invalid++;
149             ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
150
151             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
152             next LINE;
153         }
154
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.
158
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};
162
163         my $borrowernumber;
164         my $member;
165         if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
166             $member = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
167         }
168         elsif ( ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
169             $member = Koha::Patrons->find( { userid => $borrower{userid} } );
170         }
171         elsif ($extended) {
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;
177                         last;
178                     }
179                 }
180             }
181         }
182
183         if ($member) {
184             $member = $member->unblessed;
185             $borrowernumber = $member->{'borrowernumber'};
186         } else {
187             $member = {};
188         }
189
190         if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
191             push @errors,
192               {
193                 invalid_cardnumber => 1,
194                 borrowernumber     => $borrowernumber,
195                 cardnumber         => $borrower{cardnumber}
196               };
197             $invalid++;
198             next;
199         }
200
201         # Check if the userid provided does not exist yet
202         if (  exists $borrower{userid}
203                  and $borrower{userid}
204              and not Check_Userid( $borrower{userid}, $borrower{borrowernumber} ) ) {
205              push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
206              $invalid++;
207              next LINE;
208         }
209
210         if ($borrowernumber) {
211
212             # borrower exists
213             unless ($overwrite_cardnumber) {
214                 $alreadyindb++;
215                 push(
216                     @feedback,
217                     {
218                         already_in_db => 1,
219                         value         => $borrower{'surname'} . ' / ' . $borrowernumber
220                     }
221                 );
222                 next LINE;
223             }
224             $borrower{'borrowernumber'} = $borrowernumber;
225             for my $col ( keys %borrower ) {
226
227                 # use values from extant patron unless our csv file includes this column or we provided a default.
228                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
229
230                 # The password is always encrypted, skip it!
231                 next if $col eq 'password';
232
233                 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
234                     $borrower{$col} = $member->{$col} if ( $member->{$col} );
235                 }
236             }
237
238             unless ( ModMember(%borrower) ) {
239                 $invalid++;
240
241                 push(
242                     @errors,
243                     {
244                         name  => 'lastinvalid',
245                         value => $borrower{'surname'} . ' / ' . $borrowernumber
246                     }
247                 );
248                 next LINE;
249             }
250             # Don't add a new restriction if the existing 'combined' restriction matches this one
251             if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
252
253                 # Check to see if this debarment already exists
254                 my $debarrments = GetDebarments(
255                     {
256                         borrowernumber => $borrowernumber,
257                         expiration     => $borrower{debarred},
258                         comment        => $borrower{debarredcomment}
259                     }
260                 );
261
262                 # If it doesn't, then add it!
263                 unless (@$debarrments) {
264                     AddDebarment(
265                         {
266                             borrowernumber => $borrowernumber,
267                             expiration     => $borrower{debarred},
268                             comment        => $borrower{debarredcomment}
269                         }
270                     );
271                 }
272             }
273             if ($extended) {
274                 if ($ext_preserve) {
275                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
276                     $patron_attributes = extended_attributes_merge( $old_attributes, $patron_attributes );
277                 }
278                 push @errors, { unknown_error => 1 }
279                   unless SetBorrowerAttributes( $borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
280             }
281             $overwritten++;
282             push(
283                 @feedback,
284                 {
285                     feedback => 1,
286                     name     => 'lastoverwritten',
287                     value    => $borrower{'surname'} . ' / ' . $borrowernumber
288                 }
289             );
290         }
291         else {
292             # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
293             # At least this is closer to AddMember than in members/memberentry.pl
294             if ( !$borrower{'cardnumber'} ) {
295                 $borrower{'cardnumber'} = fixup_cardnumber(undef);
296             }
297             if ( $borrowernumber = AddMember(%borrower) ) {
298
299                 if ( $borrower{debarred} ) {
300                     AddDebarment(
301                         {
302                             borrowernumber => $borrowernumber,
303                             expiration     => $borrower{debarred},
304                             comment        => $borrower{debarredcomment}
305                         }
306                     );
307                 }
308
309                 if ($extended) {
310                     SetBorrowerAttributes( $borrowernumber, $patron_attributes );
311                 }
312
313                 if ($set_messaging_prefs) {
314                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
315                         {
316                             borrowernumber => $borrowernumber,
317                             categorycode   => $borrower{categorycode}
318                         }
319                     );
320                 }
321
322                 $imported++;
323                 push(
324                     @feedback,
325                     {
326                         feedback => 1,
327                         name     => 'lastimported',
328                         value    => $borrower{'surname'} . ' / ' . $borrowernumber
329                     }
330                 );
331             }
332             else {
333                 $invalid++;
334                 push @errors, { unknown_error => 1 };
335                 push(
336                     @errors,
337                     {
338                         name  => 'lastinvalid',
339                         value => $borrower{'surname'} . ' / AddMember',
340                     }
341                 );
342             }
343         }
344     }
345
346     return {
347         feedback      => \@feedback,
348         errors        => \@errors,
349         imported      => $imported,
350         overwritten   => $overwritten,
351         already_in_db => $alreadyindb,
352         invalid       => $invalid,
353     };
354 }
355
356 =head2 prepare_columns
357
358  my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
359
360 Returns an array of all column key and populates a hash of colunm key positions.
361
362 =cut
363
364 sub prepare_columns {
365     my ($self, $params) = @_;
366
367     my $status = $self->text_csv->parse($params->{headerrow});
368     unless( $status ) {
369         push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
370         return;
371     }
372
373     my @csvcolumns = $self->text_csv->fields();
374     my $col = 0;
375     foreach my $keycol (@csvcolumns) {
376         # columnkeys don't contain whitespace, but some stupid tools add it
377         $keycol =~ s/ +//g;
378         $params->{keycol}->{$keycol} = $col++;
379     }
380
381     return @csvcolumns;
382 }
383
384 =head2 set_attribute_types
385
386  my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
387
388 Returns an attribute type based on matchpoint parameter.
389
390 =cut
391
392 sub set_attribute_types {
393     my ($self, $params) = @_;
394
395     my $attribute_types;
396     if( $params->{extended} ) {
397         $attribute_types = C4::Members::AttributeTypes->fetch($params->{matchpoint});
398     }
399
400     return $attribute_types;
401 }
402
403 =head2 set_column_keys
404
405  my @columnkeys = set_column_keys($extended);
406
407 Returns an array of borrowers' table columns.
408
409 =cut
410
411 sub set_column_keys {
412     my ($self, $extended) = @_;
413
414     my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
415     push( @columnkeys, 'patron_attributes' ) if $extended;
416
417     return @columnkeys;
418 }
419
420 =head2 set_patron_attributes
421
422  my $patron_attributes = set_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
423
424 Returns a reference to array of hashrefs data structure as expected by SetBorrowerAttributes.
425
426 =cut
427
428 sub set_patron_attributes {
429     my ($self, $extended, $patron_attributes, $feedback) = @_;
430
431     unless( $extended ) { return; }
432     unless( defined($patron_attributes) ) { return; }
433
434     # Fixup double quotes in case we are passed smart quotes
435     $patron_attributes =~ s/\xe2\x80\x9c/"/g;
436     $patron_attributes =~ s/\xe2\x80\x9d/"/g;
437
438     push (@$feedback, { feedback => 1, name => 'attribute string', value => $patron_attributes });
439
440     my $result = extended_attributes_code_value_arrayref($patron_attributes);
441
442     return $result;
443 }
444
445 =head2 check_branch_code
446
447  check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
448
449 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
450
451 =cut
452
453 sub check_branch_code {
454     my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
455
456     # No branch code
457     unless( $branchcode ) {
458         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline, });
459         return;
460     }
461
462     # look for branch code
463     my $library = Koha::Libraries->find( $branchcode );
464     unless( $library ) {
465         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline,
466                                      value => $branchcode, branch_map => 1, });
467     }
468 }
469
470 =head2 check_borrower_category
471
472  check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
473
474 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
475
476 =cut
477
478 sub check_borrower_category {
479     my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
480
481     # No branch code
482     unless( $categorycode ) {
483         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline, });
484         return;
485     }
486
487     # Looking for borrower category
488     my $category = Koha::Patron::Categories->find($categorycode);
489     unless( $category ) {
490         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline,
491                                      value => $categorycode, category_map => 1, });
492     }
493 }
494
495 =head2 format_dates
496
497  format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
498
499 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
500 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
501
502 =cut
503
504 sub format_dates {
505     my ($self, $params) = @_;
506
507     foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry)) {
508         my $tempdate = $params->{borrower}->{$date_type} or next();
509         my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
510
511         if ($formatted_date) {
512             $params->{borrower}->{$date_type} = $formatted_date;
513         } else {
514             $params->{borrower}->{$date_type} = '';
515             push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => $params->{lineraw}, bad_date => 1 });
516         }
517     }
518 }
519
520 1;
521
522 =head1 AUTHOR
523
524 Koha Team
525
526 =cut