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