From c1fe7406b9f4a3d253ed282f2cb510258dac732e Mon Sep 17 00:00:00 2001
From: Tomas Cohen Arazi <tomascohen@theke.io>
Date: Thu, 11 May 2023 16:54:26 -0300
Subject: [PATCH] Bug 33053: Handle invalid biblio_id more robustly

This patch addresses the fact the invalid FK error might differ under
some circumstances. We could try to catch the exception adding another
case, but I think this pattern is cleaner and the authors didn't provide
a fix.

We can discuss it later, as this controller class has several things to
review.

Signed-off-by: Tomas Cohen Arazi <tomascohen@theke.io>
---
 Koha/REST/V1/Biblios/ItemGroups.pm | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/Koha/REST/V1/Biblios/ItemGroups.pm b/Koha/REST/V1/Biblios/ItemGroups.pm
index ddfdac3aa54..b81eee76201 100644
--- a/Koha/REST/V1/Biblios/ItemGroups.pm
+++ b/Koha/REST/V1/Biblios/ItemGroups.pm
@@ -105,9 +105,16 @@ sub add {
     my $c = shift->openapi->valid_input or return;
 
     return try {
-        my $item_group_data = $c->validation->param('body');
+
+        my $biblio = Koha::Biblios->find( $c->param('biblio_id') );
+        return $c->render(
+            status  => 404,
+            openapi => { error => 'Object not found' }
+        ) unless $biblio;
+
+        my $item_group_data = $c->req->json;
         # biblio_id comes from the path
-        $item_group_data->{biblio_id} = $c->validation->param('biblio_id');
+        $item_group_data->{biblio_id} = $biblio->id;
 
         my $item_group = Koha::Biblio::ItemGroup->new_from_api($item_group_data);
         $item_group->store->discard_changes();
-- 
2.40.1