Bug 12598: Fix conflict with 17829 - GetMember
[koha-ffzg.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 ($extended) {
169             if ( defined($matchpoint_attr_type) ) {
170                 foreach my $attr (@$patron_attributes) {
171                     if ( $attr->{code} eq $matchpoint and $attr->{value} ne '' ) {
172                         my @borrowernumbers = $matchpoint_attr_type->get_patrons( $attr->{value} );
173                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
174                         last;
175                     }
176                 }
177             }
178         }
179
180         if ($member) {
181             $member = $member->unblessed;
182             $borrowernumber = $member->{'borrowernumber'};
183         } else {
184             $member = {};
185         }
186
187         if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
188             push @errors,
189               {
190                 invalid_cardnumber => 1,
191                 borrowernumber     => $borrowernumber,
192                 cardnumber         => $borrower{cardnumber}
193               };
194             $invalid++;
195             next;
196         }
197
198         # Check if the userid provided does not exist yet
199         if (  exists $borrower{userid}
200                  and $borrower{userid}
201              and not Check_Userid( $borrower{userid}, $borrower{borrowernumber} ) ) {
202              push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
203              $invalid++;
204              next LINE;
205         }
206
207         if ($borrowernumber) {
208
209             # borrower exists
210             unless ($overwrite_cardnumber) {
211                 $alreadyindb++;
212                 push(
213                     @feedback,
214                     {
215                         already_in_db => 1,
216                         value         => $borrower{'surname'} . ' / ' . $borrowernumber
217                     }
218                 );
219                 next LINE;
220             }
221             $borrower{'borrowernumber'} = $borrowernumber;
222             for my $col ( keys %borrower ) {
223
224                 # use values from extant patron unless our csv file includes this column or we provided a default.
225                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
226
227                 # The password is always encrypted, skip it!
228                 next if $col eq 'password';
229
230                 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
231                     $borrower{$col} = $member->{$col} if ( $member->{$col} );
232                 }
233             }
234
235             unless ( ModMember(%borrower) ) {
236                 $invalid++;
237
238                 push(
239                     @errors,
240                     {
241                         name  => 'lastinvalid',
242                         value => $borrower{'surname'} . ' / ' . $borrowernumber
243                     }
244                 );
245                 next LINE;
246             }
247             if ( $borrower{debarred} ) {
248
249                 # Check to see if this debarment already exists
250                 my $debarrments = GetDebarments(
251                     {
252                         borrowernumber => $borrowernumber,
253                         expiration     => $borrower{debarred},
254                         comment        => $borrower{debarredcomment}
255                     }
256                 );
257
258                 # If it doesn't, then add it!
259                 unless (@$debarrments) {
260                     AddDebarment(
261                         {
262                             borrowernumber => $borrowernumber,
263                             expiration     => $borrower{debarred},
264                             comment        => $borrower{debarredcomment}
265                         }
266                     );
267                 }
268             }
269             if ($extended) {
270                 if ($ext_preserve) {
271                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
272                     $patron_attributes = extended_attributes_merge( $old_attributes, $patron_attributes );
273                 }
274                 push @errors, { unknown_error => 1 }
275                   unless SetBorrowerAttributes( $borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
276             }
277             $overwritten++;
278             push(
279                 @feedback,
280                 {
281                     feedback => 1,
282                     name     => 'lastoverwritten',
283                     value    => $borrower{'surname'} . ' / ' . $borrowernumber
284                 }
285             );
286         }
287         else {
288             # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
289             # At least this is closer to AddMember than in members/memberentry.pl
290             if ( !$borrower{'cardnumber'} ) {
291                 $borrower{'cardnumber'} = fixup_cardnumber(undef);
292             }
293             if ( $borrowernumber = AddMember(%borrower) ) {
294
295                 if ( $borrower{debarred} ) {
296                     AddDebarment(
297                         {
298                             borrowernumber => $borrowernumber,
299                             expiration     => $borrower{debarred},
300                             comment        => $borrower{debarredcomment}
301                         }
302                     );
303                 }
304
305                 if ($extended) {
306                     SetBorrowerAttributes( $borrowernumber, $patron_attributes );
307                 }
308
309                 if ($set_messaging_prefs) {
310                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
311                         {
312                             borrowernumber => $borrowernumber,
313                             categorycode   => $borrower{categorycode}
314                         }
315                     );
316                 }
317
318                 $imported++;
319                 push(
320                     @feedback,
321                     {
322                         feedback => 1,
323                         name     => 'lastimported',
324                         value    => $borrower{'surname'} . ' / ' . $borrowernumber
325                     }
326                 );
327             }
328             else {
329                 $invalid++;
330                 push @errors, { unknown_error => 1 };
331                 push(
332                     @errors,
333                     {
334                         name  => 'lastinvalid',
335                         value => $borrower{'surname'} . ' / AddMember',
336                     }
337                 );
338             }
339         }
340     }
341
342     return {
343         feedback      => \@feedback,
344         errors        => \@errors,
345         imported      => $imported,
346         overwritten   => $overwritten,
347         already_in_db => $alreadyindb,
348         invalid       => $invalid,
349     };
350 }
351
352 =head2 prepare_columns
353
354  my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
355
356 Returns an array of all column key and populates a hash of colunm key positions.
357
358 =cut
359
360 sub prepare_columns {
361     my ($self, $params) = @_;
362
363     my $status = $self->text_csv->parse($params->{headerrow});
364     unless( $status ) {
365         push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
366         return;
367     }
368
369     my @csvcolumns = $self->text_csv->fields();
370     my $col = 0;
371     foreach my $keycol (@csvcolumns) {
372         # columnkeys don't contain whitespace, but some stupid tools add it
373         $keycol =~ s/ +//g;
374         $params->{keycol}->{$keycol} = $col++;
375     }
376
377     return @csvcolumns;
378 }
379
380 =head2 set_attribute_types
381
382  my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
383
384 Returns an attribute type based on matchpoint parameter.
385
386 =cut
387
388 sub set_attribute_types {
389     my ($self, $params) = @_;
390
391     my $attribute_types;
392     if( $params->{extended} ) {
393         $attribute_types = C4::Members::AttributeTypes->fetch($params->{matchpoint});
394     }
395
396     return $attribute_types;
397 }
398
399 =head2 set_column_keys
400
401  my @columnkeys = set_column_keys($extended);
402
403 Returns an array of borrowers' table columns.
404
405 =cut
406
407 sub set_column_keys {
408     my ($self, $extended) = @_;
409
410     my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
411     push( @columnkeys, 'patron_attributes' ) if $extended;
412
413     return @columnkeys;
414 }
415
416 =head2 set_patron_attributes
417
418  my $patron_attributes = set_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
419
420 Returns a reference to array of hashrefs data structure as expected by SetBorrowerAttributes.
421
422 =cut
423
424 sub set_patron_attributes {
425     my ($self, $extended, $patron_attributes, $feedback) = @_;
426
427     unless( $extended ) { return; }
428     unless( defined($patron_attributes) ) { return; }
429
430     # Fixup double quotes in case we are passed smart quotes
431     $patron_attributes =~ s/\xe2\x80\x9c/"/g;
432     $patron_attributes =~ s/\xe2\x80\x9d/"/g;
433
434     push (@$feedback, { feedback => 1, name => 'attribute string', value => $patron_attributes });
435
436     my $result = extended_attributes_code_value_arrayref($patron_attributes);
437
438     return $result;
439 }
440
441 =head2 check_branch_code
442
443  check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
444
445 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
446
447 =cut
448
449 sub check_branch_code {
450     my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
451
452     # No branch code
453     unless( $branchcode ) {
454         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline, });
455         return;
456     }
457
458     # look for branch code
459     my $library = Koha::Libraries->find( $branchcode );
460     unless( $library ) {
461         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => $borrowerline,
462                                      value => $branchcode, branch_map => 1, });
463     }
464 }
465
466 =head2 check_borrower_category
467
468  check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
469
470 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
471
472 =cut
473
474 sub check_borrower_category {
475     my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
476
477     # No branch code
478     unless( $categorycode ) {
479         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline, });
480         return;
481     }
482
483     # Looking for borrower category
484     my $category = Koha::Patron::Categories->find($categorycode);
485     unless( $category ) {
486         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => $borrowerline,
487                                      value => $categorycode, category_map => 1, });
488     }
489 }
490
491 =head2 format_dates
492
493  format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
494
495 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
496 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
497
498 =cut
499
500 sub format_dates {
501     my ($self, $params) = @_;
502
503     foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry)) {
504         my $tempdate = $params->{borrower}->{$date_type} or next();
505         my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
506
507         if ($formatted_date) {
508             $params->{borrower}->{$date_type} = $formatted_date;
509         } else {
510             $params->{borrower}->{$date_type} = '';
511             push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => $params->{lineraw}, bad_date => 1 });
512         }
513     }
514 }
515
516 1;
517
518 =head1 AUTHOR
519
520 Koha Team
521
522 =cut