From 4bfe8268eb3981a9a36b8e99dbf5756de08140c9 Mon Sep 17 00:00:00 2001
From: Martin Renvoize <martin.renvoize@ptfs-europe.com>
Date: Wed, 23 Oct 2024 11:09:06 +0100
Subject: [PATCH] Bug 38175: Handle status in item auto-assignment for bookings

Signed-off-by: Martin Renvoize <martin.renvoize@ptfs-europe.com>
---
 Koha/Booking.pm | 45 ++++++++++++++++++++++++++-------------------
 1 file changed, 26 insertions(+), 19 deletions(-)

diff --git a/Koha/Booking.pm b/Koha/Booking.pm
index e32b0f50358..2450465649b 100644
--- a/Koha/Booking.pm
+++ b/Koha/Booking.pm
@@ -197,24 +197,31 @@ sub _assign_item_for_booking {
     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
 
     my $existing_bookings = $biblio->bookings(
-        [
-            start_date => {
-                '-between' => [
-                    $dtf->format_datetime($start_date),
-                    $dtf->format_datetime($end_date)
-                ]
-            },
-            end_date => {
-                '-between' => [
-                    $dtf->format_datetime($start_date),
-                    $dtf->format_datetime($end_date)
-                ]
-            },
-            {
-                start_date => { '<' => $dtf->format_datetime($start_date) },
-                end_date   => { '>' => $dtf->format_datetime($end_date) }
-            }
-        ]
+        {
+            '-and' => [
+                {
+                    '-or' => [
+                        start_date => {
+                            '-between' => [
+                                $dtf->format_datetime($start_date),
+                                $dtf->format_datetime($end_date)
+                            ]
+                        },
+                        end_date => {
+                            '-between' => [
+                                $dtf->format_datetime($start_date),
+                                $dtf->format_datetime($end_date)
+                            ]
+                        },
+                        {
+                            start_date => { '<' => $dtf->format_datetime($start_date) },
+                            end_date   => { '>' => $dtf->format_datetime($end_date) }
+                        }
+                    ]
+                },
+                { status => { '-not_in' => [ 'cancelled', 'completed' ] } }
+            ]
+        }
     );
 
     my $checkouts =
@@ -227,7 +234,7 @@ sub _assign_item_for_booking {
                 { '-not_in' => $checkouts->_resultset->get_column('itemnumber')->as_query }
             ]
         },
-        { rows => 1 }
+        { order_by => \'RAND()', rows => 1 }
     );
 
     my $itemnumber = $bookable_items->single->itemnumber;
-- 
2.47.0