Bug 18789: Send Koha::Patron object to the templates
[koha.git] / tools / import_borrowers.pl
index ad29a66..d17bc40 100755 (executable)
 # dates should be in the format you have set up Koha to expect
 # branchcode and categorycode need to be valid
 
-use strict;
-use warnings;
+use Modern::Perl;
 
 use C4::Auth;
 use C4::Output;
 use C4::Context;
-use C4::Branch qw/GetBranchesLoop GetBranchName/;
 use C4::Members;
 use C4::Members::Attributes qw(:all);
 use C4::Members::AttributeTypes;
 use C4::Members::Messaging;
 use C4::Reports::Guided;
 use C4::Templates;
-use Koha::Borrower::Debarments;
+use Koha::Patron::Debarments;
+use Koha::Patrons;
 use Koha::DateUtils;
+use Koha::Token;
+use Koha::Libraries;
+use Koha::Patron::Categories;
+use Koha::List::Patron;
 
 use Text::CSV;
 # Text::CSV::Unicode, even in binary mode, fails to parse lines with these diacriticals:
@@ -56,12 +59,11 @@ use Text::CSV;
 # č
 
 use CGI qw ( -utf8 );
-# use encoding 'utf8';    # don't do this
 
 my (@errors, @feedback);
 my $extended = C4::Context->preference('ExtendedPatronAttributes');
 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
-my @columnkeys = C4::Members::columns();
+my @columnkeys = Koha::Patrons->columns();
 @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } @columnkeys;
 if ($extended) {
     push @columnkeys, 'patron_attributes';
@@ -80,12 +82,9 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
         debug           => 1,
 });
 
-# get the branches and pass them to the template
-my $branches = GetBranchesLoop();
-$template->param( branches => $branches ) if ( $branches );
 # get the patron categories and pass them to the template
-my $categories = GetBorrowercategoryList();
-$template->param( categories => $categories ) if ( $categories );
+my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
+$template->param( categories => \@patron_categories );
 my $columns = C4::Templates::GetColumnDefs( $input )->{borrowers};
 $columns = [ grep { $_->{field} ne 'borrowernumber' ? $_ : () } @$columns ];
 $template->param( borrower_fields => $columns );
@@ -97,7 +96,7 @@ if ($input->param('sample')) {
     );
     $csv->combine(@columnkeys);
     print $csv->string, "\n";
-    exit 1;
+    exit 0;
 }
 my $uploadborrowers = $input->param('uploadborrowers');
 my $matchpoint      = $input->param('matchpoint');
@@ -106,16 +105,30 @@ if ($matchpoint) {
 }
 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
 
+#create a patronlist
+my $createpatronlist = $input->param('createpatronlist') || 0;
+my $dt = dt_from_string();
+my $timestamp = $dt->ymd('-').' '.$dt->hms(':');
+my $patronlistname = $uploadborrowers . ' (' . $timestamp .')';
+
 $template->param( SCRIPT_NAME => '/cgi-bin/koha/tools/import_borrowers.pl' );
 
 if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
+    die "Wrong CSRF token"
+        unless Koha::Token->new->check_csrf({
+            session_id => scalar $input->cookie('CGISESSID'),
+            token  => scalar $input->param('csrf_token'),
+        });
+
     push @feedback, {feedback=>1, name=>'filename', value=>$uploadborrowers, filename=>$uploadborrowers};
     my $handle = $input->upload('uploadborrowers');
     my $uploadinfo = $input->uploadInfo($uploadborrowers);
     foreach (keys %$uploadinfo) {
         push @feedback, {feedback=>1, name=>$_, value=>$uploadinfo->{$_}, $_=>$uploadinfo->{$_}};
     }
+
     my $imported    = 0;
+    my @imported_borrowers;
     my $alreadyindb = 0;
     my $overwritten = 0;
     my $invalid     = 0;
@@ -141,7 +154,7 @@ if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
     }
 
     push @feedback, {feedback=>1, name=>'headerrow', value=>join(', ', @csvcolumns)};
-    my $today_iso = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
+    my $today = output_pref;
     my @criticals = qw(surname branchcode categorycode);    # there probably should be others
     my @bad_dates;  # I've had a few.
     LINE: while ( my $borrowerline = <$handle> ) {
@@ -178,13 +191,13 @@ if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
         #warn join(':',%borrower);
         if ($borrower{categorycode}) {
             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline, value=>$borrower{categorycode}, category_map=>1}
-                unless GetBorrowercategory($borrower{categorycode});
+                unless Koha::Patron::Categories->find($borrower{categorycode});
         } else {
             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline};
         }
         if ($borrower{branchcode}) {
             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline, value=>$borrower{branchcode}, branch_map=>1}
-                unless GetBranchName($borrower{branchcode});
+                unless Koha::Libraries->find($borrower{branchcode});
         } else {
             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline};
         }
@@ -217,20 +230,14 @@ if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
                 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
             }
         }
-       $borrower{dateenrolled} = $today_iso unless $borrower{dateenrolled};
-       $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry}; 
+        $borrower{dateenrolled} ||= $today;
+        $borrower{dateexpiry}   ||= Koha::Patron::Categories->find( $borrower{categorycode} )->get_expiry_date( $borrower{dateenrolled} );
         my $borrowernumber;
         my $member;
         if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
-            $member = GetMember( 'cardnumber' => $borrower{'cardnumber'} );
-            if ($member) {
-                $borrowernumber = $member->{'borrowernumber'};
-            }
+            $member = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
         } elsif ( ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
-            $member = GetMember( 'userid' => $borrower{'userid'} );
-            if ($member) {
-                $borrowernumber = $member->{'borrowernumber'};
-            }
+            $member = Koha::Patrons->find( { userid => $borrower{'userid'} } );
         } elsif ($extended) {
             if (defined($matchpoint_attr_type)) {
                 foreach my $attr (@$patron_attributes) {
@@ -243,6 +250,13 @@ if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
             }
         }
 
+        if ($member) {
+            $member = $member->unblessed;
+            $borrowernumber = $member->{'borrowernumber'};
+        } else {
+            $member = {};
+        }
+
         if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
             push @errors, {
                 invalid_cardnumber => 1,
@@ -253,7 +267,6 @@ if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
             next;
         }
 
-
         if ($borrowernumber) {
             # borrower exists
             unless ($overwrite_cardnumber) {
@@ -273,6 +286,16 @@ if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
                     $borrower{$col} = $member->{$col} if($member->{$col}) ;
                 }
             }
+
+            # Check if the userid provided does not exist yet
+            if (  exists $borrower{userid}
+                     and $borrower{userid}
+                 and not Check_Userid( $borrower{userid}, $borrower{borrowernumber} ) ) {
+                push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
+                $invalid++;
+                next LINE;
+            }
+
             unless (ModMember(%borrower)) {
                 $invalid++;
                 # until we have better error trapping, we have no way of knowing why ModMember errored out...
@@ -308,7 +331,7 @@ if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
                     $patron_attributes = extended_attributes_merge($old_attributes, $patron_attributes);  #TODO: expose repeatable options in template
                 }
-                push @errors, {unknown_error => 1} unless SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes);
+                push @errors, {unknown_error => 1} unless SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
             }
             $overwritten++;
             $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
@@ -341,6 +364,7 @@ if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
 
                 $imported++;
                 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
+                push @imported_borrowers, $borrowernumber; #for patronlist
             } else {
                 $invalid++;
                 push @errors, {unknown_error => 1};
@@ -348,6 +372,13 @@ if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
             }
         }
     }
+
+    if ( $imported && $createpatronlist ) {
+        my $patronlist = AddPatronList({ name => $patronlistname });
+        AddPatronsToList({ list => $patronlist, borrowernumbers => \@imported_borrowers });
+        $template->param('patronlistname' => $patronlistname);
+    }
+
     (@errors  ) and $template->param(  ERRORS=>\@errors  );
     (@feedback) and $template->param(FEEDBACK=>\@feedback);
     $template->param(
@@ -371,6 +402,13 @@ if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
         }
         $template->param(matchpoints => \@matchpoints);
     }
+
+    $template->param(
+        csrf_token => Koha::Token->new->generate_csrf(
+            { session_id => scalar $input->cookie('CGISESSID'), }
+        ),
+    );
+
 }
 
 output_html_with_http_headers $input, $cookie, $template->output;