Bug 22330: (QA follow-up) Remove duplicate use lines, combine and sort remaning lines
[koha.git] / C4 / Members.pm
index 7fc67fb..205f45b 100644 (file)
@@ -39,23 +39,15 @@ use C4::NewsChannels; #get slip news
 use DateTime;
 use Koha::Database;
 use Koha::DateUtils;
-use Text::Unaccent qw( unac_string );
 use Koha::AuthUtils qw(hash_password);
 use Koha::Database;
 use Koha::Holds;
 use Koha::List::Patron;
 use Koha::Patrons;
 use Koha::Patron::Categories;
-use Koha::Schema;
 
 our (@ISA,@EXPORT,@EXPORT_OK,$debug);
 
-use Module::Load::Conditional qw( can_load );
-if ( ! can_load( modules => { 'Koha::NorwegianPatronDB' => undef } ) ) {
-   $debug && warn "Unable to load Koha::NorwegianPatronDB";
-}
-
-
 BEGIN {
     $debug = $ENV{DEBUG} || 0;
     require Exporter;
@@ -70,17 +62,6 @@ BEGIN {
         &IssueSlip
     );
 
-    #Modify data
-    push @EXPORT, qw(
-        &ModMember
-        &changepassword
-    );
-
-    #Insert data
-    push @EXPORT, qw(
-        &AddMember_Opac
-    );
-
     #Check data
     push @EXPORT, qw(
         &checkuserpassword
@@ -98,7 +79,7 @@ use C4::Members;
 
 =head1 DESCRIPTION
 
-This module contains routines for adding, modifying and deleting members/patrons/borrowers 
+This module contains routines for adding, modifying and deleting members/patrons/borrowers
 
 =head1 FUNCTIONS
 
@@ -140,7 +121,7 @@ The following will be set where applicable:
  $flags->{WAITING}->{message}       Message -- deprecated
  $flags->{WAITING}->{itemlist}      ref-to-array: list of available items
 
-=over 
+=over
 
 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
 overdue items. Its elements are references-to-hash, each describing an
@@ -156,7 +137,7 @@ fields from the reserves table of the Koha database.
 
 =back
 
-All the "message" fields that include language generated in this function are deprecated, 
+All the "message" fields that include language generated in this function are deprecated,
 because such strings belong properly in the display layer.
 
 The "message" field that comes from the DB is OK.
@@ -266,113 +247,6 @@ sub patronflags {
     return ( \%flags );
 }
 
-
-=head2 ModMember
-
-  my $success = ModMember(borrowernumber => $borrowernumber,
-                                            [ field => value ]... );
-
-Modify borrower's data.  All date fields should ALREADY be in ISO format.
-
-return :
-true on success, or false on failure
-
-=cut
-
-sub ModMember {
-    my (%data) = @_;
-
-    # trim whitespace from data which has some non-whitespace in it.
-    foreach my $field_name (keys(%data)) {
-        if ( defined $data{$field_name} && $data{$field_name} =~ /\S/ ) {
-            $data{$field_name} =~ s/^\s*|\s*$//g;
-        }
-    }
-
-    # test to know if you must update or not the borrower password
-    if (exists $data{password}) {
-        if ($data{password} eq '****' or $data{password} eq '') {
-            delete $data{password};
-        } else {
-            if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
-                # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
-                Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
-            }
-            $data{password} = hash_password($data{password});
-        }
-    }
-
-    my $old_categorycode = Koha::Patrons->find( $data{borrowernumber} )->categorycode;
-
-    # get only the columns of a borrower
-    my $schema = Koha::Database->new()->schema;
-    my @columns = $schema->source('Borrower')->columns;
-    my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
-
-    $new_borrower->{dateofbirth}     ||= undef if exists $new_borrower->{dateofbirth};
-    $new_borrower->{dateenrolled}    ||= undef if exists $new_borrower->{dateenrolled};
-    $new_borrower->{dateexpiry}      ||= undef if exists $new_borrower->{dateexpiry};
-    $new_borrower->{debarred}        ||= undef if exists $new_borrower->{debarred};
-    $new_borrower->{sms_provider_id} ||= undef if exists $new_borrower->{sms_provider_id};
-    $new_borrower->{guarantorid}     ||= undef if exists $new_borrower->{guarantorid};
-
-    my $patron = Koha::Patrons->find( $new_borrower->{borrowernumber} );
-
-    my $borrowers_log = C4::Context->preference("BorrowersLog");
-    if ( $borrowers_log && $patron->cardnumber ne $new_borrower->{cardnumber} )
-    {
-        logaction(
-            "MEMBERS",
-            "MODIFY",
-            $data{'borrowernumber'},
-            to_json(
-                {
-                    cardnumber_replaced => {
-                        previous_cardnumber => $patron->cardnumber,
-                        new_cardnumber      => $new_borrower->{cardnumber},
-                    }
-                },
-                { utf8 => 1, pretty => 1 }
-            )
-        );
-    }
-
-    delete $new_borrower->{userid} if exists $new_borrower->{userid} and not $new_borrower->{userid};
-
-    my $execute_success = $patron->store if $patron->set($new_borrower);
-
-    if ($execute_success) { # only proceed if the update was a success
-        # If the patron changes to a category with enrollment fee, we add a fee
-        if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
-            if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
-                $patron->add_enrolment_fee_if_needed;
-            }
-        }
-
-        # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
-        # cronjob will use for syncing with NL
-        if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
-            my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
-                'synctype'       => 'norwegianpatrondb',
-                'borrowernumber' => $data{'borrowernumber'}
-            });
-            # Do not set to "edited" if syncstatus is "new". We need to sync as new before
-            # we can sync as changed. And the "new sync" will pick up all changes since
-            # the patron was created anyway.
-            if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
-                $borrowersync->update( { 'syncstatus' => 'edited' } );
-            }
-            # Set the value of 'sync'
-            $borrowersync->update( { 'sync' => $data{'sync'} } );
-            # Try to do the live sync
-            Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
-        }
-
-        logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if $borrowers_log;
-    }
-    return $execute_success;
-}
-
 =head2 GetAllIssues
 
   $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
@@ -402,14 +276,14 @@ sub GetAllIssues {
     my $dbh = C4::Context->dbh;
     my $query =
 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
-  FROM issues 
+  FROM issues
   LEFT JOIN items on items.itemnumber=issues.itemnumber
   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
-  WHERE borrowernumber=? 
+  WHERE borrowernumber=?
   UNION ALL
-  SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
-  FROM old_issues 
+  SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
+  FROM old_issues
   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
@@ -461,7 +335,7 @@ database column.
 =cut
 
 sub get_cardnumber_length {
-    my $borrower = Koha::Schema->resultset('Borrower');
+    my $borrower = Koha::Database->new->schema->resultset('Borrower');
     my $field_size = $borrower->result_source->column_info('cardnumber')->{size};
     my ( $min, $max ) = ( 0, $field_size ); # borrowers.cardnumber is a nullable varchar(20)
     $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
@@ -506,11 +380,11 @@ sub GetBorrowersToExpunge {
     my $filtercategory   = $params->{'category_code'};
     my $filterbranch     = $params->{'branchcode'} ||
                         ((C4::Context->preference('IndependentBranches')
-                             && C4::Context->userenv 
+                             && C4::Context->userenv
                              && !C4::Context->IsSuperLibrarian()
                              && C4::Context->userenv->{branch})
                          ? C4::Context->userenv->{branch}
-                         : "");  
+                         : "");
     my $filterpatronlist = $params->{'patron_list_id'};
 
     my $dbh   = C4::Context->dbh;
@@ -568,13 +442,13 @@ sub GetBorrowersToExpunge {
     warn $query if $debug;
 
     my $sth = $dbh->prepare($query);
-    if (scalar(@query_params)>0){  
+    if (scalar(@query_params)>0){
         $sth->execute(@query_params);
     }
     else {
         $sth->execute;
     }
-    
+
     my @results;
     while ( my $data = $sth->fetchrow_hashref ) {
         push @results, $data;
@@ -738,27 +612,6 @@ sub IssueSlip {
     );
 }
 
-=head2 AddMember_Opac
-
-=cut
-
-sub AddMember_Opac {
-    my ( %borrower ) = @_;
-
-    $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
-    my $password = $borrower{password};
-    if (not defined $password){
-        my $sr = new String::Random;
-        $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
-        $password = $sr->randpattern("AAAAAAAAAA");
-        $borrower{'password'} = $password;
-    }
-
-    my $patron = Koha::Patron->new(\%borrower)->store;
-
-    return ( $patron->borrowernumber, $password );
-}
-
 =head2 DeleteExpiredOpacRegistrations
 
     Delete accounts that haven't been upgraded from the 'temporary' category
@@ -772,18 +625,18 @@ sub DeleteExpiredOpacRegistrations {
     my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
 
     return 0 if not $category_code or not defined $delay or $delay eq q||;
+    my $date_enrolled = dt_from_string();
+    $date_enrolled->subtract( days => $delay );
 
-    my $query = qq|
-SELECT borrowernumber
-FROM borrowers
-WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
+    my $registrations_to_del = Koha::Patrons->search({
+        dateenrolled => {'<=' => $date_enrolled->ymd},
+        categorycode => $category_code,
+    });
 
-    my $dbh = C4::Context->dbh;
-    my $sth = $dbh->prepare($query);
-    $sth->execute( $category_code, $delay );
     my $cnt=0;
-    while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
-        Koha::Patrons->find($borrowernumber)->delete;
+    while ( my $registration = $registrations_to_del->next() ) {
+        next if $registration->checkouts->count || $registration->account->balance;
+        $registration->delete;
         $cnt++;
     }
     return $cnt;