From 0fa9b7815c5700b0f5b54218c55728c259aa1a81 Mon Sep 17 00:00:00 2001
From: Tomas Cohen Arazi <tomascohen@theke.io>
Date: Tue, 10 May 2022 12:27:02 -0300
Subject: [PATCH] Bug 30727: Avoid holds queue updates multiple times on
 BatchDeleteBiblio

This patch makes the background job only enqueue holds queue updates
once per biblio, when appropriate.

To test:
1. Apply the regression tests patch
2. Run:
   $ kshell
  k$ prove t/db_dependent/Koha/BackgroundJobs/BatchDeleteBiblio.t
=> FAIL: It enqueues 3 times for a bib!
3. Apply this patch
4. Repeat 2
=> SUCCESS: It only enqueues once!
5. Sign off :-D

Signed-off-by: Tomas Cohen Arazi <tomascohen@theke.io>
---
 Koha/BackgroundJob/BatchDeleteBiblio.pm | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/Koha/BackgroundJob/BatchDeleteBiblio.pm b/Koha/BackgroundJob/BatchDeleteBiblio.pm
index 2f75bcf9b3..d834f29b7c 100644
--- a/Koha/BackgroundJob/BatchDeleteBiblio.pm
+++ b/Koha/BackgroundJob/BatchDeleteBiblio.pm
@@ -5,6 +5,7 @@ use JSON qw( encode_json decode_json );
 
 use C4::Biblio;
 
+use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue;
 use Koha::DateUtils qw( dt_from_string );
 use Koha::SearchEngine;
 use Koha::SearchEngine::Indexer;
@@ -91,7 +92,7 @@ sub process {
         my $holds = $biblio->holds;
         while ( my $hold = $holds->next ) {
             eval{
-                $hold->cancel;
+                $hold->cancel({ skip_holds_queue => 1 });
             };
             if ( $@ ) {
                 push @messages, {
@@ -110,7 +111,7 @@ sub process {
         # Delete items
         my $items = Koha::Items->search({ biblionumber => $biblionumber });
         while ( my $item = $items->next ) {
-            my $deleted = $item->safe_delete({ skip_record_index => 1 });
+            my $deleted = $item->safe_delete({ skip_record_index => 1, skip_holds_queue => 1 });
             unless ( $deleted ) {
                 push @messages, {
                     type => 'error',
@@ -127,7 +128,7 @@ sub process {
 
         # Finally, delete the biblio
         my $error = eval {
-            C4::Biblio::DelBiblio( $biblionumber, { skip_record_index => 1 } );
+            C4::Biblio::DelBiblio( $biblionumber, { skip_record_index => 1, skip_holds_queue => 1 } );
         };
         if ( $error or $@ ) {
             push @messages, {
@@ -158,6 +159,12 @@ sub process {
     if ( @deleted_biblionumbers ) {
         my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
         $indexer->index_records( \@deleted_biblionumbers, "recordDelete", "biblioserver" );
+
+        Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
+            {
+                biblio_ids => \@deleted_biblionumbers
+            }
+        );
     }
 
     my $job_data = decode_json $self->data;
-- 
2.34.1