Bug 28555: (follow-up) Make verbose count flags passed
[koha-ffzg.git] / misc / cronjobs / cleanup_database.pl
index 85967e7..dc62ef8 100755 (executable)
@@ -28,20 +28,13 @@ use constant DEFAULT_SEARCHHISTORY_PURGEDAYS      => 30;
 use constant DEFAULT_SHARE_INVITATION_EXPIRY_DAYS => 14;
 use constant DEFAULT_DEBARMENTS_PURGEDAYS         => 30;
 
-BEGIN {
-    # find Koha's Perl modules
-    # test carefully before changing this
-    use FindBin;
-    eval { require "$FindBin::Bin/../kohalib.pl" };
-}
-
 use Koha::Script -cron;
 use C4::Context;
 use C4::Search;
 use C4::Search::History;
-use Getopt::Long;
-use C4::Log;
-use C4::Accounts;
+use Getopt::Long qw( GetOptions );
+use C4::Log qw( cronlogaction );
+use C4::Accounts qw( purge_zero_balance_fees );
 use Koha::UploadedFiles;
 use Koha::Old::Biblios;
 use Koha::Old::Items;
@@ -52,6 +45,7 @@ use Koha::Old::Patrons;
 use Koha::Item::Transfers;
 use Koha::PseudonymizedTransactions;
 use Koha::Patron::Messages;
+use Koha::Patron::Debarments qw( DelDebarment );
 
 sub usage {
     print STDERR <<USAGE;
@@ -80,6 +74,8 @@ Usage: $0 [-h|--help] [--confirm] [--sessions] [--sessdays DAYS] [-v|--verbose]
                       amountoutstanding is 0 or NULL.
                       In the case of --fees, DAYS must be greater than
                       or equal to 1.
+   --log-modules      Specify which action log modules to trim. Repeatable.
+   --preserve-log     Specify which action logs to exclude. Repeatable.
    --logs DAYS        purge entries from action_logs older than DAYS days.
                       Defaults to 180 days if no days specified.
    --searchhistory DAYS  purge entries from search_history older than DAYS days.
@@ -88,7 +84,7 @@ Usage: $0 [-h|--help] [--confirm] [--sessions] [--sessdays DAYS] [-v|--verbose]
                          days.  Defaults to 14 days if no days specified.
    --restrictions DAYS   purge patrons restrictions expired since more than DAYS days.
                          Defaults to 30 days if no days specified.
-    --all-restrictions   purge all expired patrons restrictions.
+   --all-restrictions   purge all expired patrons restrictions.
    --del-exp-selfreg  Delete expired self registration accounts
    --del-unv-selfreg  DAYS  Delete unverified self registrations older than DAYS
    --unique-holidays DAYS  Delete all unique holidays older than DAYS
@@ -109,7 +105,8 @@ Usage: $0 [-h|--help] [--confirm] [--sessions] [--sessdays DAYS] [-v|--verbose]
                                     --pseudo-transactions-from YYYY-MM-DD and/or --pseudo-transactions-to YYYY-MM-DD
    --labels DAYS           Purge item label batches last added to more than DAYS days ago.
    --cards DAY             Purge card creator batches last added to more than DAYS days ago.
-
+   --return-claims         Purge all resolved return claims older than the number of days specified in
+                           the system preference CleanUpDatabaseReturnClaims.
 USAGE
     exit $_[0];
 }
@@ -129,6 +126,7 @@ my $pZ3950;
 my $pListShareInvites;
 my $pDebarments;
 my $allDebarments;
+my $return_claims;
 my $pExpSelfReg;
 my $pUnvSelfReg;
 my $fees_days;
@@ -148,6 +146,10 @@ my $pMessages;
 my $lock_days = C4::Context->preference('LockExpiredDelay');
 my $labels;
 my $cards;
+my @log_modules;
+my @preserve_logs;
+
+my $command_line_options = join(" ",@ARGV);
 
 GetOptions(
     'h|help'            => \$help,
@@ -161,6 +163,8 @@ GetOptions(
     'import:i'          => \$pImport,
     'z3950'             => \$pZ3950,
     'logs:i'            => \$pLogs,
+    'log-module:s'      => \@log_modules,
+    'preserve-log:s'    => \@preserve_logs,
     'messages:i'        => \$pMessages,
     'fees:i'            => \$fees_days,
     'searchhistory:i'   => \$pSearchhistory,
@@ -168,7 +172,7 @@ GetOptions(
     'restrictions:i'    => \$pDebarments,
     'all-restrictions'  => \$allDebarments,
     'del-exp-selfreg'   => \$pExpSelfReg,
-    'del-unv-selfreg'   => \$pUnvSelfReg,
+    'del-unv-selfreg:i' => \$pUnvSelfReg,
     'unique-holidays:i' => \$special_holidays_days,
     'temp-uploads'      => \$temp_uploads,
     'temp-uploads-days:i' => \$temp_uploads_days,
@@ -185,6 +189,7 @@ GetOptions(
     'pseudo-transactions-to:s'   => \$pPseudoTransactionsTo,
     'labels'            => \$labels,
     'cards'             => \$cards,
+    'return-claims'     => \$return_claims,
 ) || usage(1);
 
 # Use default values
@@ -233,6 +238,7 @@ unless ( $sessions
     || defined $lock_days && $lock_days ne q{}
     || $labels
     || $cards
+    || $return_claims
 ) {
     print "You did not specify any cleanup work for the script to do.\n\n";
     usage(1);
@@ -245,7 +251,7 @@ if ($pDebarments && $allDebarments) {
 
 say "Confirm flag not passed, running in dry-run mode..." unless $confirm;
 
-cronlogaction() unless $confirm;
+cronlogaction({ info => $command_line_options });
 
 my $dbh = C4::Context->dbh();
 my $sth;
@@ -283,9 +289,7 @@ if ($zebraqueue_days) {
             WHERE done=1 AND time < date_sub(curdate(), INTERVAL ? DAY)
         }
     );
-    if ( $confirm ) {
-        $sth->execute($zebraqueue_days) or die $dbh->errstr;
-    }
+    $sth->execute($zebraqueue_days) or die $dbh->errstr;
     $sth2 = $dbh->prepare(q{ DELETE FROM zebraqueue WHERE id=? });
     while ( my $record = $sth->fetchrow_hashref ) {
         if ( $confirm ) {
@@ -341,14 +345,22 @@ if ($pZ3950) {
 
 if ($pLogs) {
     print "Purging records from action_logs.\n" if $verbose;
-    $sth = $dbh->prepare(
-        q{
+    my $log_query = q{
             DELETE FROM action_logs
             WHERE timestamp < date_sub(curdate(), INTERVAL ? DAY)
-        }
-    );
+    };
+    my @query_params = ();
+    if( @preserve_logs ){
+        $log_query .= " AND module NOT IN (" . join(',',('?') x @preserve_logs ) . ")";
+        push @query_params, @preserve_logs;
+    }
+    if( @log_modules ){
+        $log_query .= " AND module IN (" . join(',',('?') x @log_modules ) . ")";
+        push @query_params, @log_modules;
+    }
+    $sth = $dbh->prepare( $log_query );
     if ( $confirm ) {
-        $sth->execute($pLogs) or die $dbh->errstr;
+        $sth->execute($pLogs, @query_params) or die $dbh->errstr;
     }
     print "Done with purging action_logs.\n" if $verbose;
 }
@@ -528,6 +540,26 @@ if ($pStatistics) {
     }
 }
 
+if( $return_claims && ( my $days = C4::Context->preference('CleanUpDatabaseReturnClaims') )) {
+    print "Purging return claims older than $days days.\n" if $verbose;
+
+    $return_claims = Koha::Checkouts::ReturnClaims->filter_by_last_update(
+        {
+            timestamp_column_name => 'resolved_on',
+            days => $days,
+        }
+    );
+
+    my $count = $return_claims->count;
+    $return_claims->delete if $confirm;
+
+    if ($verbose) {
+        say $confirm
+            ? sprintf "Done with purging %d resolved return claims.", $count
+            : sprintf "%d resolved return claims would have been purged.", $count;
+    }
+}
+
 if ($pDeletedCatalog) {
     print "Purging deleted catalog older than $pDeletedCatalog days.\n"
       if $verbose;
@@ -579,7 +611,7 @@ if ($pOldReserves) {
     print "Purging old reserves older than $pOldReserves days.\n" if $verbose;
     my $old_reserves = Koha::Old::Holds->filter_by_last_update( { days => $pOldReserves } );
     my $count = $old_reserves->count;
-    $old_reserves->delete if $verbose;
+    $old_reserves->delete if $confirm;
     if ($verbose) {
         say $confirm
           ? sprintf "Done with purging %d old reserves.", $count
@@ -596,7 +628,7 @@ if ($pTransfers) {
         }
     );
     my $count = $transfers->count;
-    $transfers->delete if $verbose;
+    $transfers->delete if $confirm;
     if ($verbose) {
         say $confirm
           ? sprintf "Done with purging %d transfers.", $count
@@ -625,40 +657,26 @@ if (defined $pPseudoTransactions or $pPseudoTransactionsFrom or $pPseudoTransact
 
 if ($labels) {
     print "Purging item label batches last added to more than $labels days ago.\n" if $verbose;
-    $sth = $dbh->prepare(
-        q{
-        DELETE from creator_batches
-        WHERE batch_id in
-            (SELECT batch_id
-            FROM (SELECT batch_id
-                    FROM creator_batches
-                    WHERE creator='labels'
-                    GROUP BY batch_id
-                    HAVING max(timestamp) < date_sub(curdate(),interval ? day)) a)
-        }
-    );
-    $sth->execute($labels) or die $dbh->errstr;
-    print "Done with purging item label batches last added to more than $labels days ago.\n" if $verbose;
+    my $count = PurgeCreatorBatches($labels, 'labels', $confirm);
+    if ($verbose) {
+        say $confirm
+          ? sprintf "Done with purging %d item label batches last added to more than %d days ago.\n", $count, $labels
+          : sprintf "%d item label batches would have been purged.", $count;
+    }
 }
 
 if ($cards) {
     print "Purging card creator batches last added to more than $cards days ago.\n" if $verbose;
-    $sth = $dbh->prepare(
-        q{
-        DELETE from creator_batches
-        WHERE batch_id in
-            (SELECT batch_id
-            FROM (SELECT batch_id
-                    FROM creator_batches
-                    WHERE creator='patroncards'
-                    GROUP BY batch_id
-                    HAVING max(timestamp) < date_sub(curdate(),interval ? day)) a);
-        }
-    );
-    $sth->execute($cards) or die $dbh->errstr;
-    print "Done with purging card creator batches last added to more than $cards days ago.\n" if $verbose;
+    my $count = PurgeCreatorBatches($labels, 'patroncards', $confirm);
+    if ($verbose) {
+        say $confirm
+          ? sprintf "Done with purging %d card creator batches last added to more than %d days ago.\n", $count, $labels
+          : sprintf "%d card creator batches would have been purged.", $count;
+    }
 }
 
+cronlogaction({ action => 'End', info => "COMPLETED" });
+
 exit(0);
 
 sub RemoveOldSessions {
@@ -747,6 +765,33 @@ sub PurgeDebarments {
     return $count;
 }
 
+sub PurgeCreatorBatches {
+    require C4::Labels::Batch;
+    my ( $days, $creator, $doit ) = @_;
+    my $count = 0;
+    $sth = $dbh->prepare(
+        q{
+            SELECT batch_id, branch_code FROM creator_batches
+            WHERE batch_id in
+                (SELECT batch_id
+                FROM (SELECT batch_id
+                        FROM creator_batches
+                        WHERE creator=?
+                        GROUP BY batch_id
+                        HAVING max(timestamp) <= date_sub(curdate(),interval ? day)) a)
+        }
+    );
+    $sth->execute( $creator, $days ) or die $dbh->errstr;
+    while ( my ( $batch_id, $branch_code ) = $sth->fetchrow_array ) {
+        C4::Labels::Batch::delete(
+            batch_id    => $batch_id,
+            branch_code => $branch_code
+        ) if $doit;
+        $count++;
+    }
+    return $count;
+}
+
 sub DeleteExpiredSelfRegs {
     my $cnt= C4::Members::DeleteExpiredOpacRegistrations();
     print "Removed $cnt expired self-registered borrowers\n" if $verbose;