From 7f0e3487646fcb4b7f9df65a3985e0184ac03697 Mon Sep 17 00:00:00 2001
From: Matt Blenkinsop <matt.blenkinsop@openfifth.co.uk>
Date: Wed, 30 Apr 2025 16:07:29 +0100
Subject: [PATCH] Bug 38010: Add protection logic to the DELETE endpoint

Amended-by: Jonathan Druart
typo: subsicriptions => subscriptions

Signed-off-by: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
---
 Koha/REST/V1/Acquisitions/Vendors.pm           | 11 ++++++++++-
 api/v1/swagger/paths/acquisitions_vendors.yaml |  4 ++++
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/Koha/REST/V1/Acquisitions/Vendors.pm b/Koha/REST/V1/Acquisitions/Vendors.pm
index 28cf1e65f82..07b8554fc3b 100644
--- a/Koha/REST/V1/Acquisitions/Vendors.pm
+++ b/Koha/REST/V1/Acquisitions/Vendors.pm
@@ -171,7 +171,16 @@ sub delete {
     my $c = shift->openapi->valid_input or return;
 
     return try {
-        my $vendor = Koha::Acquisition::Booksellers->find( $c->param('vendor_id') );
+        my $vendor             = Koha::Acquisition::Booksellers->find( $c->param('vendor_id') );
+        my $basket_count       = $vendor->baskets->count;
+        my $subscription_count = $vendor->subscriptions->count;
+        my $invoice_count      = $vendor->invoices->count;
+
+        my $safe_to_delete = ( $basket_count == 0 && $subscription_count == 0 && $invoice_count == 0 ) ? 1 : 0;
+        return $c->render(
+            status  => 409,
+            openapi => { error => "Vendor cannot be deleted with existing baskets, subscriptions or invoices" }
+        ) unless $safe_to_delete;
 
         return $c->render_resource_not_found("Vendor")
             unless $vendor;
diff --git a/api/v1/swagger/paths/acquisitions_vendors.yaml b/api/v1/swagger/paths/acquisitions_vendors.yaml
index bae07ec8aab..7290fba1e9b 100644
--- a/api/v1/swagger/paths/acquisitions_vendors.yaml
+++ b/api/v1/swagger/paths/acquisitions_vendors.yaml
@@ -272,6 +272,10 @@
         description: Vendor not found
         schema:
           $ref: "../swagger.yaml#/definitions/error"
+      "409":
+        description: Unable to perform action on vendor
+        schema:
+          $ref: "../swagger.yaml#/definitions/error"
       "500":
         description: |
           Internal server error. Possible `error_code` attribute values:
-- 
2.34.1