Bug 12598: New misc/import_borrowers.pl command line tool
[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::Branch;
27 use C4::Members::Attributes qw(:all);
28 use C4::Members::AttributeTypes;
29
30 use Koha::DateUtils;
31
32 =head1 NAME
33
34 Koha::Patrons::Import - Perl Module containing import_patrons method exported from import_borrowers script.
35
36 =head1 SYNOPSIS
37
38 use Koha::Patrons::Import;
39
40 =head1 DESCRIPTION
41
42 This module contains one method for importing patrons in bulk.
43
44 =head1 FUNCTIONS
45
46 =head2 import_patrons
47
48  my $return = Koha::Patrons::Import::import_patrons($params);
49
50 Applies various checks and imports patrons in bulk from a csv file.
51
52 Further pod documentation needed here.
53
54 =cut
55
56 has 'today_iso' => ( is => 'ro', lazy => 1,
57     default => sub { output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); }, );
58
59 has 'text_csv' => ( is => 'rw', lazy => 1,
60     default => sub { Text::CSV->new( { binary => 1, } ); },  );
61
62 sub import_patrons {
63     my ($self, $params) = @_;
64
65     my $handle = $params->{file};
66     unless( $handle ) { carp('No file handle passed in!'); return; }
67
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');
74
75     my @columnkeys = $self->set_column_keys($extended);
76     my @feedback;
77     my @errors;
78
79     my $imported    = 0;
80     my $alreadyindb = 0;
81     my $overwritten = 0;
82     my $invalid     = 0;
83     my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
84
85     # Use header line to construct key to column map
86     my %csvkeycol;
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 ) });
90
91     my @criticals = qw( surname );    # there probably should be others - rm branchcode && categorycode
92   LINE: while ( my $borrowerline = <$handle> ) {
93         my $line_number = $.;
94         my %borrower;
95         my @missing_criticals;
96
97         my $status  = $self->text_csv->parse($borrowerline);
98         my @columns = $self->text_csv->fields();
99         if ( !$status ) {
100             push @missing_criticals, { badparse => 1, line => $line_number, lineraw => $borrowerline };
101         }
102         elsif ( @columns == @columnkeys ) {
103             @borrower{@columnkeys} = @columns;
104
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};
109                 }
110             }
111         }
112         else {
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} ];
117                 }
118                 elsif ( $defaults->{$key} ) {
119                     $borrower{$key} = $defaults->{$key};
120                 }
121                 elsif ( scalar grep { $key eq $_ } @criticals ) {
122
123                     # a critical field is undefined
124                     push @missing_criticals, { key => $key, line => $., lineraw => $borrowerline };
125                 }
126                 else {
127                     $borrower{$key} = '';
128                 }
129             }
130         }
131
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);
134
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);
137
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, });
140
141         if (@missing_criticals) {
142             foreach (@missing_criticals) {
143                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
144                 $_->{surname}        = $borrower{surname}        || 'UNDEF';
145             }
146             $invalid++;
147             ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
148
149             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
150             next LINE;
151         }
152
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.
156
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};
160
161         my $borrowernumber;
162         my $member;
163         if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
164             $member = GetMember( 'cardnumber' => $borrower{'cardnumber'} );
165             if ($member) {
166                 $borrowernumber = $member->{'borrowernumber'};
167             }
168         }
169         elsif ($extended) {
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;
175                         last;
176                     }
177                 }
178             }
179         }
180
181         if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
182             push @errors,
183               {
184                 invalid_cardnumber => 1,
185                 borrowernumber     => $borrowernumber,
186                 cardnumber         => $borrower{cardnumber}
187               };
188             $invalid++;
189             next;
190         }
191
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} };
197              $invalid++;
198              next LINE;
199         }
200
201         if ($borrowernumber) {
202
203             # borrower exists
204             unless ($overwrite_cardnumber) {
205                 $alreadyindb++;
206                 push(
207                     @feedback,
208                     {
209                         already_in_db => 1,
210                         value         => $borrower{'surname'} . ' / ' . $borrowernumber
211                     }
212                 );
213                 next LINE;
214             }
215             $borrower{'borrowernumber'} = $borrowernumber;
216             for my $col ( keys %borrower ) {
217
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.
220
221                 # The password is always encrypted, skip it!
222                 next if $col eq 'password';
223
224                 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
225                     $borrower{$col} = $member->{$col} if ( $member->{$col} );
226                 }
227             }
228
229             unless ( ModMember(%borrower) ) {
230                 $invalid++;
231
232                 push(
233                     @errors,
234                     {
235                         name  => 'lastinvalid',
236                         value => $borrower{'surname'} . ' / ' . $borrowernumber
237                     }
238                 );
239                 next LINE;
240             }
241             if ( $borrower{debarred} ) {
242
243                 # Check to see if this debarment already exists
244                 my $debarrments = GetDebarments(
245                     {
246                         borrowernumber => $borrowernumber,
247                         expiration     => $borrower{debarred},
248                         comment        => $borrower{debarredcomment}
249                     }
250                 );
251
252                 # If it doesn't, then add it!
253                 unless (@$debarrments) {
254                     AddDebarment(
255                         {
256                             borrowernumber => $borrowernumber,
257                             expiration     => $borrower{debarred},
258                             comment        => $borrower{debarredcomment}
259                         }
260                     );
261                 }
262             }
263             if ($extended) {
264                 if ($ext_preserve) {
265                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
266                     $patron_attributes = extended_attributes_merge( $old_attributes, $patron_attributes );
267                 }
268                 push @errors, { unknown_error => 1 }
269                   unless SetBorrowerAttributes( $borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
270             }
271             $overwritten++;
272             push(
273                 @feedback,
274                 {
275                     feedback => 1,
276                     name     => 'lastoverwritten',
277                     value    => $borrower{'surname'} . ' / ' . $borrowernumber
278                 }
279             );
280         }
281         else {
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);
286             }
287             if ( $borrowernumber = AddMember(%borrower) ) {
288
289                 if ( $borrower{debarred} ) {
290                     AddDebarment(
291                         {
292                             borrowernumber => $borrowernumber,
293                             expiration     => $borrower{debarred},
294                             comment        => $borrower{debarredcomment}
295                         }
296                     );
297                 }
298
299                 if ($extended) {
300                     SetBorrowerAttributes( $borrowernumber, $patron_attributes );
301                 }
302
303                 if ($set_messaging_prefs) {
304                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
305                         {
306                             borrowernumber => $borrowernumber,
307                             categorycode   => $borrower{categorycode}
308                         }
309                     );
310                 }
311
312                 $imported++;
313                 push(
314                     @feedback,
315                     {
316                         feedback => 1,
317                         name     => 'lastimported',
318                         value    => $borrower{'surname'} . ' / ' . $borrowernumber
319                     }
320                 );
321             }
322             else {
323                 $invalid++;
324                 push @errors, { unknown_error => 1 };
325                 push(
326                     @errors,
327                     {
328                         name  => 'lastinvalid',
329                         value => $borrower{'surname'} . ' / AddMember',
330                     }
331                 );
332             }
333         }
334     }
335
336     return {
337         feedback      => \@feedback,
338         errors        => \@errors,
339         imported      => $imported,
340         overwritten   => $overwritten,
341         already_in_db => $alreadyindb,
342         invalid       => $invalid,
343     };
344 }
345
346 =head2 prepare_columns
347
348  my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
349
350 Returns an array of all column key and populates a hash of colunm key positions.
351
352 =cut
353
354 sub prepare_columns {
355     my ($self, $params) = @_;
356
357     my $status = $self->text_csv->parse($params->{headerrow});
358     unless( $status ) {
359         push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
360         return;
361     }
362
363     my @csvcolumns = $self->text_csv->fields();
364     my $col = 0;
365     foreach my $keycol (@csvcolumns) {
366         # columnkeys don't contain whitespace, but some stupid tools add it
367         $keycol =~ s/ +//g;
368         $params->{keycol}->{$keycol} = $col++;
369     }
370
371     return @csvcolumns;
372 }
373
374 =head2 set_attribute_types
375
376  my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
377
378 Returns an attribute type based on matchpoint parameter.
379
380 =cut
381
382 sub set_attribute_types {
383     my ($self, $params) = @_;
384
385     my $attribute_types;
386     if( $params->{extended} ) {
387         $attribute_types = C4::Members::AttributeTypes->fetch($params->{matchpoint});
388     }
389
390     return $attribute_types;
391 }
392
393 =head2 set_column_keys
394
395  my @columnkeys = set_column_keys($extended);
396
397 Returns an array of borrowers' table columns.
398
399 =cut
400
401 sub set_column_keys {
402     my ($self, $extended) = @_;
403
404     my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } C4::Members::columns();
405     push( @columnkeys, 'patron_attributes' ) if $extended;
406
407     return @columnkeys;
408 }
409
410 =head2 set_patron_attributes
411
412  my $patron_attributes = set_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
413
414 Returns a reference to array of hashrefs data structure as expected by SetBorrowerAttributes.
415
416 =cut
417
418 sub set_patron_attributes {
419     my ($self, $extended, $patron_attributes, $feedback) = @_;
420
421     unless( $extended ) { return; }
422     unless( defined($patron_attributes) ) { return; }
423
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;
427
428     push (@$feedback, { feedback => 1, name => 'attribute string', value => $patron_attributes });
429
430     my $result = extended_attributes_code_value_arrayref($patron_attributes);
431
432     return $result;
433 }
434
435 =head2 check_branch_code
436
437  check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
438
439 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
440
441 =cut
442
443 sub check_branch_code {
444     my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
445
446     # No branch code
447     unless( $branchcode ) {
448         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline, });
449         return;
450     }
451
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, });
457     }
458 }
459
460 =head2 check_borrower_category
461
462  check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
463
464 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
465
466 =cut
467
468 sub check_borrower_category {
469     my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
470
471     # No branch code
472     unless( $categorycode ) {
473         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline, });
474         return;
475     }
476
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, });
482     }
483 }
484
485 =head2 format_dates
486
487  format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
488
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.
491
492 =cut
493
494 sub format_dates {
495     my ($self, $params) = @_;
496
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' } ); };
500
501         if ($formatted_date) {
502             $params->{borrower}->{$date_type} = $formatted_date;
503         } else {
504             $params->{borrower}->{$date_type} = '';
505             push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => $params->{lineraw}, bad_date => 1 });
506         }
507     }
508 }
509
510 1;
511
512 =head1 AUTHOR
513
514 Koha Team
515
516 =cut