Bug 34621: implement Patron import option to 'Renew existing patrons' 'from the curre...
[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
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 use Moo;
20
21 use Carp qw( carp );
22 use Text::CSV;
23 use Encode qw( decode_utf8 );
24 use Try::Tiny qw( catch try );
25
26 use C4::Letters qw( GetPreparedLetter EnqueueLetter );
27
28 use Koha::Libraries;
29 use Koha::Patrons;
30 use Koha::Patron::Categories;
31 use Koha::Patron::Debarments qw( AddDebarment );
32 use Koha::Policy::Patrons::Cardnumber;
33 use Koha::DateUtils qw( dt_from_string output_pref );
34
35 =head1 NAME
36
37 Koha::Patrons::Import - Perl Module containing import_patrons method exported from import_borrowers script.
38
39 =head1 SYNOPSIS
40
41 use Koha::Patrons::Import;
42
43 =head1 DESCRIPTION
44
45 This module contains one method for importing patrons in bulk.
46
47 =head1 FUNCTIONS
48
49 =head2 import_patrons
50
51  my $return = Koha::Patrons::Import::import_patrons($params);
52
53 Applies various checks and imports patrons in bulk from a csv file.
54
55 Further pod documentation needed here.
56
57 =cut
58
59 has 'today_iso' => ( is => 'ro', lazy => 1,
60     # FIXME We shouldn't need to call output_pref here, passing a DateTime object should work
61     default => sub { output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); }, );
62
63 has 'text_csv' => ( is => 'rw', lazy => 1,
64     default => sub { Text::CSV->new( { binary => 1, } ); },  );
65
66 sub import_patrons {
67     my ($self, $params) = @_;
68
69     my $handle = $params->{file};
70     unless( $handle ) { carp('No file handle passed in!'); return; }
71
72     my $matchpoint                      = $params->{matchpoint};
73     my $defaults                        = $params->{defaults};
74     my $preserve_fields                 = $params->{preserve_fields};
75     my $ext_preserve                    = $params->{preserve_extended_attributes};
76     my $overwrite_cardnumber            = $params->{overwrite_cardnumber};
77     my $overwrite_passwords             = $params->{overwrite_passwords};
78     my $dry_run                         = $params->{dry_run};
79     my $send_welcome                    = $params->{send_welcome};
80     my $update_dateexpiry               = $params->{update_dateexpiry};
81     my $update_dateexpiry_from_today    = $params->{update_dateexpiry_from_today};
82     my $update_dateexpiry_from_existing = $params->{update_dateexpiry_from_existing};
83
84     my $extended            = C4::Context->preference('ExtendedPatronAttributes');
85     my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
86
87     my $schema = Koha::Database->new->schema;
88     $schema->storage->txn_begin if $dry_run;
89
90     my @columnkeys = $self->set_column_keys($extended);
91     my @feedback;
92     my @errors;
93
94     my $imported    = 0;
95     my $alreadyindb = 0;
96     my $overwritten = 0;
97     my $invalid     = 0;
98     my @imported_borrowers;
99     my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
100
101     # Use header line to construct key to column map
102     my %csvkeycol;
103     my $borrowerline = <$handle>;
104     my @csvcolumns   = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
105     push(@feedback, { feedback => 1, name => 'headerrow', value => join( ', ', @csvcolumns ) });
106
107     my @criticals = qw( surname );    # there probably should be others - rm branchcode && categorycode
108   LINE: while ( my $borrowerline = <$handle> ) {
109         my $line_number = $.;
110         my %borrower;
111         my @missing_criticals;
112
113         my $status  = $self->text_csv->parse($borrowerline);
114         my @columns = $self->text_csv->fields();
115         if ( !$status ) {
116             push @missing_criticals, { badparse => 1, line => $line_number, lineraw => decode_utf8($borrowerline) };
117         }
118         elsif ( @columns == @columnkeys ) {
119             @borrower{@columnkeys} = @columns;
120
121             # MJR: try to fill blanks gracefully by using default values
122             foreach my $key (@columnkeys) {
123                 if ( $borrower{$key} !~ /\S/ ) {
124                     $borrower{$key} = $defaults->{$key};
125                 }
126             }
127         }
128         else {
129             # MJR: try to recover gracefully by using default values
130             foreach my $key (@columnkeys) {
131                 if ( defined( $csvkeycol{$key} ) and $columns[ $csvkeycol{$key} ] =~ /\S/ ) {
132                     $borrower{$key} = $columns[ $csvkeycol{$key} ];
133                 }
134                 elsif ( $defaults->{$key} ) {
135                     $borrower{$key} = $defaults->{$key};
136                 }
137                 elsif ( scalar grep { $key eq $_ } @criticals ) {
138
139                     # a critical field is undefined
140                     push @missing_criticals, { key => $key, line => $., lineraw => decode_utf8($borrowerline) };
141                 }
142                 else {
143                     $borrower{$key} = '';
144                 }
145             }
146         }
147
148         $borrower{cardnumber} = undef if $borrower{cardnumber} eq "";
149         $borrower{auth_method} = undef if $borrower{auth_method} eq "";
150
151         $borrower{protected} = 0 unless $borrower{protected};
152
153         # Check if borrower category code exists and if it matches to a known category. Pushing error to missing_criticals otherwise.
154         $self->check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
155
156         # Check if branch code exists and if it matches to a branch name. Pushing error to missing_criticals otherwise.
157         $self->check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
158
159         # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
160         $self->format_dates({borrower => \%borrower, lineraw => $borrowerline, line => $line_number, missing_criticals => \@missing_criticals, });
161
162         if (@missing_criticals) {
163             foreach (@missing_criticals) {
164                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
165                 $_->{surname}        = $borrower{surname}        || 'UNDEF';
166             }
167             $invalid++;
168             ( 25 > scalar @errors ) and push @errors, { missing_criticals => \@missing_criticals };
169
170             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
171             next LINE;
172         }
173
174         # Generate patron attributes if extended.
175         my $patron_attributes = $self->generate_patron_attributes($extended, $borrower{patron_attributes}, \@feedback);
176         if( $extended ) { delete $borrower{patron_attributes}; } # Not really a field in borrowers.
177
178         # Default date enrolled and date expiry if not already set.
179         $borrower{dateenrolled} = $self->today_iso() unless $borrower{dateenrolled};
180         my $expiration_start_date = $update_dateexpiry_from_today ? dt_from_string : $borrower{dateenrolled};
181         $borrower{dateexpiry} = Koha::Patron::Categories->find( $borrower{categorycode} )->get_expiry_date( $expiration_start_date ) if $update_dateexpiry;
182
183         my $borrowernumber;
184         my ( $member, $patron );
185         if ( defined($matchpoint) && ( $matchpoint eq 'cardnumber' ) && ( $borrower{'cardnumber'} ) ) {
186             $patron = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
187         }
188         elsif ( defined($matchpoint) && ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
189             $patron = Koha::Patrons->find( { userid => $borrower{userid} } );
190         }
191         elsif ($extended) {
192             if ( defined($matchpoint_attr_type) ) {
193                 foreach my $attr (@$patron_attributes) {
194                     if ( $attr->{code} eq $matchpoint and $attr->{attribute} ne '' ) {
195                         my @borrowernumbers = Koha::Patron::Attributes->search(
196                             {
197                                 code      => $matchpoint_attr_type->code,
198                                 attribute => $attr->{attribute}
199                             }
200                         )->get_column('borrowernumber');
201
202                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
203                         $patron = Koha::Patrons->find( $borrowernumber );
204                         last;
205                     }
206                 }
207             }
208         }
209
210         if ( $patron && $update_dateexpiry_from_existing ) {
211             $patron->dateexpiry( Koha::Patron::Categories->find( $borrower{categorycode} )->get_expiry_date( $patron->dateexpiry ) );
212             delete $borrower{dateexpiry};
213         }
214
215         my $is_new = 0;
216         if ($patron) {
217             $member = $patron->unblessed;
218             $borrowernumber = $member->{'borrowernumber'};
219         } else {
220             $member = {};
221             $is_new = 1;
222         }
223
224         my $is_valid = Koha::Policy::Patrons::Cardnumber->is_valid($borrower{cardnumber}, $patron);
225         unless ( $is_valid ) {
226             push @errors,
227               {
228                 invalid_cardnumber => 1,
229                 borrowernumber     => $borrowernumber,
230                 cardnumber         => $borrower{cardnumber}
231               };
232             $invalid++;
233             next;
234         }
235
236
237         # Check if the userid provided does not exist yet
238         if (    defined($matchpoint)
239             and $matchpoint ne 'userid'
240             and exists $borrower{userid}
241             and $borrower{userid}
242             and not ( $borrowernumber ? $patron->userid( $borrower{userid} )->has_valid_userid : Koha::Patron->new( { userid => $borrower{userid} } )->has_valid_userid )
243         ) {
244             push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
245             $invalid++;
246             next LINE;
247         }
248
249         my $guarantor_relationship = $borrower{guarantor_relationship};
250         delete $borrower{guarantor_relationship};
251         my $guarantor_id = $borrower{guarantor_id};
252         delete $borrower{guarantor_id};
253
254         # Remove warning for int datatype that cannot be null
255         # Argument "" isn't numeric in numeric eq (==) at /usr/share/perl5/DBIx/Class/Row.pm line 1018
256         for my $field (
257             qw( privacy privacy_guarantor_fines privacy_guarantor_checkouts anonymized login_attempts ))
258         {
259             delete $borrower{$field}
260               if exists $borrower{$field} and $borrower{$field} eq "";
261         }
262
263         my $success = 1;
264         if ($borrowernumber) {
265
266             # borrower exists
267             unless ($overwrite_cardnumber) {
268                 $alreadyindb++;
269                 push(
270                     @feedback,
271                     {
272                         already_in_db => 1,
273                         value         => $borrower{'surname'} . ' / ' . $borrowernumber
274                     }
275                 );
276                 next LINE;
277             }
278             $borrower{'borrowernumber'} = $borrowernumber;
279
280             if ( $preserve_fields ) {
281                 for my $field ( @$preserve_fields ) {
282                     $borrower{$field} = $patron->$field;
283                 }
284             }
285
286             for my $col ( keys %borrower ) {
287
288                 # use values from extant patron unless our csv file includes this column or we provided a default.
289                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
290
291                 # The password is always encrypted, skip it unless we are forcing overwrite!
292                 next if $col eq 'password'   && !$overwrite_passwords;
293                 next if $col eq 'dateexpiry' && $update_dateexpiry;
294
295                 $borrower{$col} = $member->{$col} if $col eq 'dateexpiry' && !$columns[ $csvkeycol{$col} ];
296
297                 unless ( exists( $csvkeycol{$col} ) || $defaults->{$col} ) {
298                     $borrower{$col} = $member->{$col} if ( $member->{$col} );
299                 }
300             }
301
302             try {
303                 $schema->storage->txn_do(sub {
304                     $patron->set(\%borrower)->store;
305                     # Don't add a new restriction if the existing 'combined' restriction matches this one
306                     if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
307
308                         # Check to see if this debarment already exists
309                         my $restrictions = $patron->restrictions->search(
310                             {
311                                 expiration => $borrower{debarred},
312                                 comment    => $borrower{debarredcomment}
313                             }
314                         );
315
316                         # If it doesn't, then add it!
317                         unless ($restrictions->count) {
318                             AddDebarment(
319                                 {
320                                     borrowernumber => $borrowernumber,
321                                     expiration     => $borrower{debarred},
322                                     comment        => $borrower{debarredcomment}
323                                 }
324                             );
325                         }
326                     }
327                     if ($patron->category->category_type ne 'S' && $overwrite_passwords && defined $borrower{password} && $borrower{password} ne ''){
328                         try {
329                             $patron->set_password({ password => $borrower{password} });
330                         }
331                         catch {
332                             if ( $_->isa('Koha::Exceptions::Password::TooShort') ) {
333                                 push @errors, { passwd_too_short => 1, borrowernumber => $borrowernumber, length => $_->{length}, min_length => $_->{min_length} };
334                             }
335                             elsif ( $_->isa('Koha::Exceptions::Password::WhitespaceCharacters') ) {
336                                 push @errors, { passwd_whitespace => 1, borrowernumber => $borrowernumber } ;
337                             }
338                             elsif ( $_->isa('Koha::Exceptions::Password::TooWeak') ) {
339                                 push @errors, { passwd_too_weak => 1, borrowernumber => $borrowernumber } ;
340                             }
341                             elsif ( $_->isa('Koha::Exceptions::Password::Plugin') ) {
342                                 push @errors, { passwd_plugin_err => 1, borrowernumber => $borrowernumber } ;
343                             }
344                             else {
345                                 push @errors, { passwd_unknown_err => 1, borrowernumber => $borrowernumber } ;
346                             }
347                         }
348                     }
349                     if ($extended && @$patron_attributes) {
350                         if ($ext_preserve) {
351                             $patron_attributes = $patron->extended_attributes->merge_and_replace_with( $patron_attributes );
352                         }
353                         # We do not want to filter by branch, maybe we should?
354                         Koha::Patrons->find($borrowernumber)->extended_attributes->delete;
355                         $patron->extended_attributes($patron_attributes);
356                     }
357                     $overwritten++;
358                     push(
359                         @feedback,
360                         {
361                             feedback => 1,
362                             name     => 'lastoverwritten',
363                             value    => $borrower{'surname'} . ' / ' . $borrowernumber
364                         }
365                     );
366                 });
367             } catch {
368                 $invalid++;
369                 $success = 0;
370
371                 my $patron_id = defined $matchpoint ? $borrower{$matchpoint} : $matchpoint_attr_type;
372                 if ( $_->isa('Koha::Exceptions::Patron::Attribute::UniqueIDConstraint') ) {
373                     push @errors, { patron_attribute_unique_id_constraint => 1, borrowernumber => $borrowernumber, attribute => $_->attribute };
374                 } elsif ( $_->isa('Koha::Exceptions::Patron::Attribute::InvalidType') ) {
375                     push @errors, { patron_attribute_invalid_type => 1, borrowernumber => $borrowernumber, attribute_type_code => $_->type };
376                 } elsif ( $_->isa('Koha::Exceptions::Patron::Attribute::NonRepeatable') ) {
377                     push @errors, { patron_attribute_non_repeatable => 1, borrowernumber => $borrowernumber, attribute => $_->attribute };
378                 } else {
379                     warn $_;
380                     push @errors, { unknown_error => 1 };
381                 }
382
383                 push(
384                     @errors,
385                     {
386                         # TODO We can raise a better error
387                         name  => 'lastinvalid',
388                         value => $borrower{'surname'} . ' / ' . $borrowernumber
389                     }
390                 );
391             }
392         }
393         else {
394             try {
395                 $schema->storage->txn_do(sub {
396                     $patron = Koha::Patron->new(\%borrower)->store;
397                     $borrowernumber = $patron->id;
398
399                     if ( $patron->is_debarred ) {
400                         AddDebarment(
401                             {
402                                 borrowernumber => $patron->borrowernumber,
403                                 expiration     => $patron->debarred,
404                                 comment        => $patron->debarredcomment,
405                             }
406                         );
407                     }
408
409                     if ($extended && @$patron_attributes) {
410                         # FIXME Hum, we did not filter earlier and now we do?
411                         $patron->extended_attributes->filter_by_branch_limitations->delete;
412                         $patron->extended_attributes($patron_attributes);
413                     }
414
415                     if ($set_messaging_prefs) {
416                         C4::Members::Messaging::SetMessagingPreferencesFromDefaults(
417                             {
418                                 borrowernumber => $patron->borrowernumber,
419                                 categorycode   => $patron->categorycode,
420                             }
421                         );
422                     }
423
424                     $imported++;
425                     push @imported_borrowers, $patron->borrowernumber; #for patronlist
426                     push(
427                         @feedback,
428                         {
429                             feedback => 1,
430                             name     => 'lastimported',
431                             value    => $patron->surname . ' / ' . $patron->borrowernumber,
432                         }
433                     );
434                 });
435             } catch {
436                 $invalid++;
437                 $success = 0;
438                 my $patron_id = defined $matchpoint ? $borrower{$matchpoint} : $matchpoint_attr_type;
439                 if ( $_->isa('Koha::Exceptions::Patron::Attribute::UniqueIDConstraint') ) {
440                     push @errors, { patron_attribute_unique_id_constraint => 1, patron_id => $patron_id, attribute => $_->attribute };
441                 } elsif ( $_->isa('Koha::Exceptions::Patron::Attribute::InvalidType') ) {
442                     push @errors, { patron_attribute_invalid_type => 1, patron_id => $patron_id, attribute_type_code => $_->type };
443                 } elsif ( $_->isa('Koha::Exceptions::Patron::Attribute::NonRepeatable') ) {
444                     push @errors, { patron_attribute_non_repeatable => 1, patron_id => $patron_id, attribute => $_->attribute };
445
446                 } else {
447                     warn $_;
448                     push @errors, { unknown_error => 1 };
449                 }
450                 push(
451                     @errors,
452                     {
453                         name  => 'lastinvalid',
454                         value => $borrower{'surname'} . ' / Create patron',
455                     }
456                 );
457             };
458         }
459
460         next LINE unless $success;
461
462         # Send WELCOME welcome email is the user is new and we're set to send mail
463         if ($send_welcome && $is_new) {
464             my $emailaddr = $patron->notice_email_address;
465
466             # if we manage to find a valid email address, send notice
467             if ($emailaddr) {
468                 eval {
469                     my $letter = GetPreparedLetter(
470                         module      => 'members',
471                         letter_code => 'WELCOME',
472                         branchcode  => $patron->branchcode,,
473                         lang        => $patron->lang || 'default',
474                         tables      => {
475                             'branches'  => $patron->branchcode,
476                             'borrowers' => $patron->borrowernumber,
477                         },
478                         want_librarian => 1,
479                     ) or return;
480
481                     my $message_id = EnqueueLetter(
482                         {
483                             letter                 => $letter,
484                             borrowernumber         => $patron->id,
485                             to_address             => $emailaddr,
486                             message_transport_type => 'email'
487                         }
488                     );
489                 };
490                 if ($@) {
491                     push @errors, { welcome_email_err => 1, borrowernumber => $borrowernumber };
492                 } else {
493                     push(
494                         @feedback,
495                         {
496                             feedback     => 1,
497                             name         => 'welcome_sent',
498                             value        => $borrower{'surname'} . ' / ' . $borrowernumber . ' / ' . $emailaddr
499                         }
500                     );
501                 }
502             }
503         }
504
505         # Add a guarantor if we are given a relationship
506         if ( $guarantor_id ) {
507             my $relationship = Koha::Patron::Relationships->find(
508                 {
509                     guarantee_id => $borrowernumber,
510                     guarantor_id => $guarantor_id,
511                 }
512             );
513
514             if ( $relationship ) {
515                 $relationship->relationship( $guarantor_relationship );
516                 $relationship->store();
517             }
518             else {
519                 Koha::Patron::Relationship->new(
520                     {
521                         guarantee_id => $borrowernumber,
522                         relationship => $guarantor_relationship,
523                         guarantor_id => $guarantor_id,
524                     }
525                 )->store();
526             }
527         }
528     }
529
530     $schema->storage->txn_rollback if $dry_run;
531
532     return {
533         feedback      => \@feedback,
534         errors        => \@errors,
535         imported      => $imported,
536         overwritten   => $overwritten,
537         already_in_db => $alreadyindb,
538         invalid       => $invalid,
539         imported_borrowers => \@imported_borrowers,
540     };
541 }
542
543 =head2 prepare_columns
544
545  my @csvcolumns = $self->prepare_columns({headerrow => $borrowerline, keycol => \%csvkeycol, errors => \@errors, });
546
547 Returns an array of all column key and populates a hash of colunm key positions.
548
549 =cut
550
551 sub prepare_columns {
552     my ($self, $params) = @_;
553
554     my $status = $self->text_csv->parse($params->{headerrow});
555     unless( $status ) {
556         push( @{$params->{errors}}, { badheader => 1, line => 1, lineraw => $params->{headerrow} });
557         return;
558     }
559
560     my @csvcolumns = $self->text_csv->fields();
561     my $col = 0;
562     foreach my $keycol (@csvcolumns) {
563         # columnkeys don't contain whitespace, but some stupid tools add it
564         $keycol =~ s/ +//g;
565         $keycol =~ s/^\N{BOM}//; # Strip BOM if exists, otherwise it will be part of first column key
566         $params->{keycol}->{$keycol} = $col++;
567     }
568
569     return @csvcolumns;
570 }
571
572 =head2 set_attribute_types
573
574  my $matchpoint_attr_type = $self->set_attribute_types({ extended => $extended, matchpoint => $matchpoint, });
575
576 Returns an attribute type based on matchpoint parameter.
577
578 =cut
579
580 sub set_attribute_types {
581     my ($self, $params) = @_;
582
583     my $attribute_type;
584     if( $params->{extended} ) {
585         $attribute_type = Koha::Patron::Attribute::Types->find($params->{matchpoint});
586     }
587
588     return $attribute_type;
589 }
590
591 =head2 set_column_keys
592
593  my @columnkeys = set_column_keys($extended);
594
595 Returns an array of borrowers' table columns.
596
597 =cut
598
599 sub set_column_keys {
600     my ($self, $extended) = @_;
601
602     my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
603     push( @columnkeys, 'patron_attributes' ) if $extended;
604     push( @columnkeys, qw( guarantor_relationship guarantor_id ) );
605
606     return @columnkeys;
607 }
608
609 =head2 generate_patron_attributes
610
611  my $patron_attributes = generate_patron_attributes($extended, $borrower{patron_attributes}, $feedback);
612
613 Returns a Koha::Patron::Attributes as expected by Koha::Patron->extended_attributes
614
615 =cut
616
617 sub generate_patron_attributes {
618     my ($self, $extended, $string, $feedback) = @_;
619
620     unless( $extended ) { return; }
621     unless( defined $string ) { return; }
622
623     # Fixup double quotes in case we are passed smart quotes
624     $string =~ s/\xe2\x80\x9c/"/g;
625     $string =~ s/\xe2\x80\x9d/"/g;
626
627     push (@$feedback, { feedback => 1, name => 'attribute string', value => $string });
628     return [] unless $string; # Unit tests want the feedback, is it really needed?
629
630     my $csv = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
631     my $ok   = $csv->parse($string);  # parse field again to get subfields!
632     my @list = $csv->fields();
633     my @patron_attributes =
634       sort { $a->{code} cmp $b->{code} || $a->{attribute} cmp $b->{attribute} }
635       map {
636         my @arr = split /:/, $_, 2;
637         { code => $arr[0], attribute => $arr[1] }
638       } @list;
639     return \@patron_attributes;
640     # TODO: error handling (check $ok)
641 }
642
643 =head2 check_branch_code
644
645  check_branch_code($borrower{branchcode}, $borrowerline, $line_number, \@missing_criticals);
646
647 Pushes a 'missing_criticals' error entry if no branch code or branch code does not map to a branch name.
648
649 =cut
650
651 sub check_branch_code {
652     my ($self, $branchcode, $borrowerline, $line_number, $missing_criticals) = @_;
653
654     # No branch code
655     unless( $branchcode ) {
656         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => decode_utf8($borrowerline), });
657         return;
658     }
659
660     # look for branch code
661     my $library = Koha::Libraries->find( $branchcode );
662     unless( $library ) {
663         push (@$missing_criticals, { key => 'branchcode', line => $line_number, lineraw => decode_utf8($borrowerline),
664                                      value => $branchcode, branch_map => 1, });
665     }
666 }
667
668 =head2 check_borrower_category
669
670  check_borrower_category($borrower{categorycode}, $borrowerline, $line_number, \@missing_criticals);
671
672 Pushes a 'missing_criticals' error entry if no category code or category code does not map to a known category.
673
674 =cut
675
676 sub check_borrower_category {
677     my ($self, $categorycode, $borrowerline, $line_number, $missing_criticals) = @_;
678
679     # No branch code
680     unless( $categorycode ) {
681         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => decode_utf8($borrowerline), });
682         return;
683     }
684
685     # Looking for borrower category
686     my $category = Koha::Patron::Categories->find($categorycode);
687     unless( $category ) {
688         push (@$missing_criticals, { key => 'categorycode', line => $line_number, lineraw => decode_utf8($borrowerline),
689                                      value => $categorycode, category_map => 1, });
690     }
691 }
692
693 =head2 format_dates
694
695  format_dates({borrower => \%borrower, lineraw => $lineraw, line => $line_number, missing_criticals => \@missing_criticals, });
696
697 Pushes a 'missing_criticals' error entry for each of the 3 date types dateofbirth, dateenrolled and dateexpiry if it can not
698 be formatted to the chosen date format. Populates the correctly formatted date otherwise.
699
700 =cut
701
702 sub format_dates {
703     my ($self, $params) = @_;
704
705     foreach my $date_type (qw(dateofbirth dateenrolled dateexpiry date_renewed)) {
706         my $tempdate = $params->{borrower}->{$date_type} or next();
707         my $formatted_date = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
708
709         if ($formatted_date) {
710             $params->{borrower}->{$date_type} = $formatted_date;
711         } else {
712             $params->{borrower}->{$date_type} = '';
713             push (@{$params->{missing_criticals}}, { key => $date_type, line => $params->{line}, lineraw => decode_utf8($params->{lineraw}), bad_date => 1 });
714         }
715     }
716 }
717
718 1;
719
720 =head1 AUTHOR
721
722 Koha Team
723
724 =cut