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