From a25241c62cc24e2709408eed0362f2b32c21e96e Mon Sep 17 00:00:00 2001
From: Andrew Isherwood <andrew.isherwood@ptfs-europe.com>
Date: Thu, 3 Oct 2019 15:14:12 +0100
Subject: [PATCH] Bug 23681: Clean up on delete

When a patron restriction type is deleted, any debarments that use that
type need to revert to the default type, this patch implements this
behaviour

Signed-off-by: Benjamin Veasey <B.T.Veasey@lboro.ac.uk>
Sponsored-by: Loughborough University
---
 Koha/RestrictionType.pm  | 34 ++++++++++++++++++++++++++++++++++
 Koha/RestrictionTypes.pm |  8 +++-----
 2 files changed, 37 insertions(+), 5 deletions(-)

diff --git a/Koha/RestrictionType.pm b/Koha/RestrictionType.pm
index 1121c9ea83..7966ff1bcb 100644
--- a/Koha/RestrictionType.pm
+++ b/Koha/RestrictionType.pm
@@ -19,6 +19,9 @@ use Modern::Perl;
 
 use base qw(Koha::Object);
 
+use Koha::RestrictionTypes;
+use C4::Context;
+
 =head1 NAME
 
 Koha::RestrictionType - Koha RestrictionType Object class
@@ -27,8 +30,39 @@ Koha::RestrictionType - Koha RestrictionType Object class
 
 =head2 Class Methods
 
+=head3 delete
+
+Overloaded delete method that does extra clean up:
+- Reset all restrictions using the restriction type about to be deleted
+  back to whichever restriction is marked as default
+
 =cut
 
+sub delete {
+    my ( $self ) = @_;
+
+    # Find out what the default is
+    my $default = Koha::RestrictionTypes->find({ dflt => 1 })->code;
+    # Ensure we're not trying to delete a readonly type (this includes
+    # the default type)
+    return 0 if $self->ronly == 1;
+    # We can't use Koha objects here because Koha::Patron::Debarments
+    # is not a Koha object. So we'll do it old skool
+    my $rows = C4::Context->dbh->do(
+        "UPDATE borrower_debarments SET type = ? WHERE type = ?",
+        undef,
+        ($default, $self->code)
+    );
+
+    # Now do the delete if the update was successful
+    if ($rows) {
+        my $deleted = $self->SUPER::delete($self);
+        return $deleted
+    }
+
+    return 0;
+}
+
 =head2 Internal methods
 
 =head3 type
diff --git a/Koha/RestrictionTypes.pm b/Koha/RestrictionTypes.pm
index 560e5fdbba..d553853aa1 100644
--- a/Koha/RestrictionTypes.pm
+++ b/Koha/RestrictionTypes.pm
@@ -36,7 +36,7 @@ Koha::RestrictionTypes - Koha Restriction Types Object set class
 
 =cut
 
-=head3 type
+=head3 keyed_on_code
 
 Return all restriction types as a hashref keyed on the code
 
@@ -54,7 +54,7 @@ sub keyed_on_code {
     return $out;
 }
 
-=head3 type
+=head3 _type
 
 =cut
 
@@ -62,9 +62,7 @@ sub _type {
     return 'DebarmentType';
 }
 
-=head3 type
-
-Object class
+=head3 object_class
 
 =cut
 
-- 
2.11.0