Bug 12598: Update code to use new modules
[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} = GetExpiryDate( $borrower{categorycode}, $borrower{dateenrolled} ) unless $borrower{dateexpiry};
162
163         my $borrowernumber;
164         my $member;
165         if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
166             $member = GetMember( 'cardnumber' => $borrower{'cardnumber'} );
167             if ($member) {
168                 $borrowernumber = $member->{'borrowernumber'};
169             }
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 ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
184             push @errors,
185               {
186                 invalid_cardnumber => 1,
187                 borrowernumber     => $borrowernumber,
188                 cardnumber         => $borrower{cardnumber}
189               };
190             $invalid++;
191             next;
192         }
193
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} };
199              $invalid++;
200              next LINE;
201         }
202
203         if ($borrowernumber) {
204
205             # borrower exists
206             unless ($overwrite_cardnumber) {
207                 $alreadyindb++;
208                 push(
209                     @feedback,
210                     {
211                         already_in_db => 1,
212                         value         => $borrower{'surname'} . ' / ' . $borrowernumber
213                     }
214                 );
215                 next LINE;
216             }
217             $borrower{'borrowernumber'} = $borrowernumber;
218             for my $col ( keys %borrower ) {
219
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.
222
223                 # The password is always encrypted, skip it!
224                 next if $col eq 'password';
225
226                 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
227                     $borrower{$col} = $member->{$col} if ( $member->{$col} );
228                 }
229             }
230
231             unless ( ModMember(%borrower) ) {
232                 $invalid++;
233
234                 push(
235                     @errors,
236                     {
237                         name  => 'lastinvalid',
238                         value => $borrower{'surname'} . ' / ' . $borrowernumber
239                     }
240                 );
241                 next LINE;
242             }
243             if ( $borrower{debarred} ) {
244
245                 # Check to see if this debarment already exists
246                 my $debarrments = GetDebarments(
247                     {
248                         borrowernumber => $borrowernumber,
249                         expiration     => $borrower{debarred},
250                         comment        => $borrower{debarredcomment}
251                     }
252                 );
253
254                 # If it doesn't, then add it!
255                 unless (@$debarrments) {
256                     AddDebarment(
257                         {
258                             borrowernumber => $borrowernumber,
259                             expiration     => $borrower{debarred},
260                             comment        => $borrower{debarredcomment}
261                         }
262                     );
263                 }
264             }
265             if ($extended) {
266                 if ($ext_preserve) {
267                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
268                     $patron_attributes = extended_attributes_merge( $old_attributes, $patron_attributes );
269                 }
270                 push @errors, { unknown_error => 1 }
271                   unless SetBorrowerAttributes( $borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
272             }
273             $overwritten++;
274             push(
275                 @feedback,
276                 {
277                     feedback => 1,
278                     name     => 'lastoverwritten',
279                     value    => $borrower{'surname'} . ' / ' . $borrowernumber
280                 }
281             );
282         }
283         else {
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);
288             }
289             if ( $borrowernumber = AddMember(%borrower) ) {
290
291                 if ( $borrower{debarred} ) {
292                     AddDebarment(
293                         {
294                             borrowernumber => $borrowernumber,
295                             expiration     => $borrower{debarred},
296                             comment        => $borrower{debarredcomment}
297                         }
298                     );
299                 }
300
301                 if ($extended) {
302                     SetBorrowerAttributes( $borrowernumber, $patron_attributes );
303                 }
304
305                 if ($set_messaging_prefs) {
306                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
307                         {
308                             borrowernumber => $borrowernumber,
309                             categorycode   => $borrower{categorycode}
310                         }
311                     );
312                 }
313
314                 $imported++;
315                 push(
316                     @feedback,
317                     {
318                         feedback => 1,
319                         name     => 'lastimported',
320                         value    => $borrower{'surname'} . ' / ' . $borrowernumber
321                     }
322                 );
323             }
324             else {
325                 $invalid++;
326                 push @errors, { unknown_error => 1 };
327                 push(
328                     @errors,
329                     {
330                         name  => 'lastinvalid',
331                         value => $borrower{'surname'} . ' / AddMember',
332                     }
333                 );
334             }
335         }
336     }
337
338     return {
339         feedback      => \@feedback,
340         errors        => \@errors,
341         imported      => $imported,
342         overwritten   => $overwritten,
343         already_in_db => $alreadyindb,
344         invalid       => $invalid,
345     };
346 }
347
348 =head2 prepare_columns
349
350  my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
351
352 Returns an array of all column key and populates a hash of colunm key positions.
353
354 =cut
355
356 sub prepare_columns {
357     my ($self, $params) = @_;
358
359     my $status = $self->text_csv->parse($params->{headerrow});
360     unless( $status ) {
361         push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
362         return;
363     }
364
365     my @csvcolumns = $self->text_csv->fields();
366     my $col = 0;
367     foreach my $keycol (@csvcolumns) {
368         # columnkeys don't contain whitespace, but some stupid tools add it
369         $keycol =~ s/ +//g;
370         $params->{keycol}->{$keycol} = $col++;
371     }
372
373     return @csvcolumns;
374 }
375
376 =head2 set_attribute_types
377
378  my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
379
380 Returns an attribute type based on matchpoint parameter.
381
382 =cut
383
384 sub set_attribute_types {
385     my ($self, $params) = @_;
386
387     my $attribute_types;
388     if( $params->{extended} ) {
389         $attribute_types = C4::Members::AttributeTypes->fetch($params->{matchpoint});
390     }
391
392     return $attribute_types;
393 }
394
395 =head2 set_column_keys
396
397  my @columnkeys = set_column_keys($extended);
398
399 Returns an array of borrowers' table columns.
400
401 =cut
402
403 sub set_column_keys {
404     my ($self, $extended) = @_;
405
406     my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
407     push( @columnkeys, 'patron_attributes' ) if $extended;
408
409     return @columnkeys;
410 }
411
412 =head2 set_patron_attributes
413
414  my $patron_attributes = set_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
415
416 Returns a reference to array of hashrefs data structure as expected by SetBorrowerAttributes.
417
418 =cut
419
420 sub set_patron_attributes {
421     my ($self, $extended, $patron_attributes, $feedback) = @_;
422
423     unless( $extended ) { return; }
424     unless( defined($patron_attributes) ) { return; }
425
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;
429
430     push (@$feedback, { feedback => 1, name => 'attribute string', value => $patron_attributes });
431
432     my $result = extended_attributes_code_value_arrayref($patron_attributes);
433
434     return $result;
435 }
436
437 =head2 check_branch_code
438
439  check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
440
441 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
442
443 =cut
444
445 sub check_branch_code {
446     my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
447
448     # No branch code
449     unless( $branchcode ) {
450         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline, });
451         return;
452     }
453
454     # look for branch code
455     my $library = Koha::Libraries->find( $branchcode );
456     unless( $library ) {
457         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline,
458                                      value => $branchcode, branch_map => 1, });
459     }
460 }
461
462 =head2 check_borrower_category
463
464  check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
465
466 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
467
468 =cut
469
470 sub check_borrower_category {
471     my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
472
473     # No branch code
474     unless( $categorycode ) {
475         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline, });
476         return;
477     }
478
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, });
484     }
485 }
486
487 =head2 format_dates
488
489  format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
490
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.
493
494 =cut
495
496 sub format_dates {
497     my ($self, $params) = @_;
498
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' } ); };
502
503         if ($formatted_date) {
504             $params->{borrower}->{$date_type} = $formatted_date;
505         } else {
506             $params->{borrower}->{$date_type} = '';
507             push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => $params->{lineraw}, bad_date => 1 });
508         }
509     }
510 }
511
512 1;
513
514 =head1 AUTHOR
515
516 Koha Team
517
518 =cut