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