From 3469e3dd8128f313d927f2b42a5ef9ad08bcec93 Mon Sep 17 00:00:00 2001
From: Martin Renvoize <martin.renvoize@ptfs-europe.com>
Date: Thu, 6 May 2021 13:53:51 +0100
Subject: [PATCH] Bug 24434: Reinstate updateWrongTransfer

This patch re-instates the call to updateWrongTransfer to ensure the
transfer line is updated to reflect the new frombranch.

Test plan
1/ Check an item out from it's home library
2/ Check the item in at another library (with the return to home branch
system preferences enabled)
2a/ Accept the transfer and note we now have a transfer present from the
items check-in library to it's home library
3/ Check the item in at a third library
3a/ Note you are asked to return the item to it's home library.
3b/ With the patch applied, the modal title should highlight that a
'Wrong transfer' was detected.
4/ Go to the item record and note the holding library has been updated
to reflect where the item was most recently checked in.
4a/ With the patch applied the item status should reflect the last
checked in branch as the 'from' branch of the transfer.
5/ Work through the above again, but use the 'Print slip' option for
accepting the transfer and confirm that also works.
6/ Work through the above again, but use the 'Cancel' option and check
that this results in the item staying at it's current location and the
final transfer having been cancelled.
---
 C4/Circulation.pm                             | 32 +++++----
 Koha/Item/Transfer.pm                         | 14 ++++
 circ/returns.pl                               | 30 +++++---
 .../prog/en/modules/circ/returns.tt           | 72 ++++++++++---------
 4 files changed, 94 insertions(+), 54 deletions(-)

diff --git a/C4/Circulation.pm b/C4/Circulation.pm
index 10db0d226a..c42277d3b5 100644
--- a/C4/Circulation.pm
+++ b/C4/Circulation.pm
@@ -2175,6 +2175,7 @@ sub AddReturn {
             else {
                 $messages->{'WrongTransfer'}     = $transfer->tobranch;
                 $messages->{'WrongTransferItem'} = $item->itemnumber;
+                $messages->{'TransferTrigger'}   = $transfer->reason;
             }
         }
         else {
@@ -3589,19 +3590,24 @@ This function validate the line of brachtransfer but with the wrong destination
 
 sub updateWrongTransfer {
 	my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
-	my $dbh = C4::Context->dbh;	
-# first step validate the actual line of transfert .
-	my $sth =
-        	$dbh->prepare(
-			"update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
-          	);
-        	$sth->execute($FromLibrary,$itemNumber);
-
-# second step create a new line of branchtransfer to the right location .
-	ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
-
-#third step changing holdingbranch of item
-    my $item = Koha::Items->find($itemNumber)->holdingbranch($FromLibrary)->store;
+
+    # first step: cancel the original transfer
+    my $item = Koha::Items->find($itemNumber);
+    my $transfer = $item->get_transfer;
+    $transfer->set({ datecancelled => dt_from_string, cancellation_reason => 'WrongTransfer' })->store();
+
+    # second step: create a new transfer to the right location
+    my $new_transfer = $item->request_transfer(
+        {
+            to            => $transfer->to_library,
+            reason        => $transfer->reason,
+            comment       => $transfer->comments,
+            ignore_limits => 1,
+            enqueue       => 1
+        }
+    );
+
+    return $new_transfer;
 }
 
 =head2 CalcDateDue
diff --git a/Koha/Item/Transfer.pm b/Koha/Item/Transfer.pm
index 4112b3fab9..d5602a9ba7 100644
--- a/Koha/Item/Transfer.pm
+++ b/Koha/Item/Transfer.pm
@@ -66,6 +66,20 @@ sub from_library {
     return Koha::Library->_new_from_dbic($from_library_rs);
 }
 
+=head3 to_library
+
+  my $to_library = $transfer->to_library;
+
+Returns the associated to_library for this transfer.
+
+=cut
+
+sub to_library {
+    my ($self) = @_;
+    my $to_library_rs = $self->_result->tobranch;
+    return Koha::Library->_new_from_dbic($to_library_rs);
+}
+
 =head3 transit
 
 Set the transfer as in transit by updating the datesent time.
diff --git a/circ/returns.pl b/circ/returns.pl
index 94e4b5e287..3dd21de1b2 100755
--- a/circ/returns.pl
+++ b/circ/returns.pl
@@ -55,6 +55,7 @@ use Koha::Checkouts;
 use Koha::DateUtils;
 use Koha::Holds;
 use Koha::Items;
+use Koha::Item::Transfers;
 use Koha::Patrons;
 
 my $query = CGI->new;
@@ -132,11 +133,6 @@ foreach ( $query->param ) {
 
 ############
 # Deal with the requests....
-
-if ($query->param('WT-itemNumber')){
-	updateWrongTransfer ($query->param('WT-itemNumber'),$query->param('WT-waitingAt'),$query->param('WT-From'));
-}
-
 my $itemnumber = $query->param('itemnumber');
 if ( $query->param('reserve_id') ) {
     my $borrowernumber = $query->param('borrowernumber');
@@ -190,6 +186,7 @@ if (
 my $dropboxmode = $query->param('dropboxmode');
 my $dotransfer  = $query->param('dotransfer');
 my $canceltransfer = $query->param('canceltransfer');
+my $transit = $query->param('transit');
 my $dest = $query->param('dest');
 #dropbox: get last open day (today - 1)
 my $dropboxdate = Koha::Checkouts::calculate_dropbox_date();
@@ -227,7 +224,15 @@ if ($dotransfer){
     ModItemTransfer($transferitem, $userenv_branch, $tobranch, $trigger);
 }
 
-if ($canceltransfer){
+if ($transit) {
+    my $transfer = Koha::Item::Transfers->find($transit);
+    if ( $canceltransfer ) {
+        $transfer->cancel({ reason => 'Manual', force => 1});
+        $template->param( transfercancelled => 1);
+    } else {
+        $transfer->transit;
+    }
+} elsif ($canceltransfer){
     my $item = Koha::Items->find($itemnumber);
     my $transfer = $item->get_transfer;
     $transfer->cancel({ reason => 'Manual', force => 1});
@@ -239,6 +244,7 @@ if ($canceltransfer){
     }
 }
 
+
 # actually return book and prepare item table.....
 my $returnbranch;
 if ($barcode) {
@@ -389,10 +395,19 @@ if ( $messages->{'Wrongbranch'} ){
 # case of wrong transfert, if the document wasn't transferred to the right library (according to branchtransfer (tobranch) BDD)
 
 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
+
+    # Trigger modal to prompt librarian
     $template->param(
         WrongTransfer  => 1,
         TransferWaitingAt => $messages->{'WrongTransfer'},
         WrongTransferItem => $messages->{'WrongTransferItem'},
+        trigger           => $messages->{'TransferTrigger'},
+    );
+
+    # Update the transfer to reflect the new item holdingbranch
+	my $new_transfer = updateWrongTransfer($messages->{'WrongTransferItem'},$messages->{'WrongTransfer'}, $userenv_branch);
+    $template->param(
+        NewTransfer => $new_transfer->id
     );
 
     my $reserve    = $messages->{'ResFound'};
@@ -402,9 +417,6 @@ if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
             patron => $patron,
         );
     }
-    $template->param(
-        wtransfertFrom  => $userenv_branch,
-    );
 }
 
 #
diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/returns.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/returns.tt
index 0fdb3fd6c6..668e67db58 100644
--- a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/returns.tt
+++ b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/returns.tt
@@ -430,38 +430,40 @@
                                 [% END %]
                                     <div class="modal-dialog">
                                         <div class="modal-content">
-                                            <div class="modal-header">
-                                                <h3>
-                                                    Please return item to: [% Branches.GetName( TransferWaitingAt ) | html %]
-                                                </h3>
-                                            </div>
-                                            <div class="modal-body">
-                                                <p>
-                                                    <a href="/cgi-bin/koha/catalogue/detail.pl?type=intra&amp;biblionumber=[% itembiblionumber | uri %]">
-                                                        [% item.barcode | html %]: [% title | html %]
-                                                    </a>
-                                                </p>
-                                                [% INCLUDE all_checkin_messages %]
-                                            </div>
-                                            <div class="modal-footer">
-                                                <!-- CONFIRM -->
-                                                <button type="button" data-dismiss="modal" class="btn btn-default approve"><i class="fa fa-check"></i> OK</button>
-                                                <!-- PRINT SLIP -->
-                                                <button type="button" data-dismiss="modal" class="btn btn-default openWin" data-url="transfer-slip.pl?transferitem=[% itemnumber | uri %]&amp;&amp;branchcode=[% TransferWaitingAt | uri %]&amp;op=slip"><i class="fa fa-print"></i> Print transfer slip</button>
-                                                <!-- CANCEL TRANSFER -->
-                                                <form method="post" action="returns.pl" name="mainform">
-                                                    <button class="btn btn-default deny" type="submit"><i class="fa fa-times"></i> Cancel transfer</button>
-                                                    <input type="hidden" name="return_date_override" value="[% return_date_override | html %]" />
-                                                    <input type="hidden" name="return_date_override_remember" value="[% return_date_override_remember | html %]" />
-                                                    <input type="hidden" name="itemnumber" value="[% itemnumber | html %]" />
-                                                    <input type="hidden" name="canceltransfer" value="1" />
-                                                    [% FOREACH inputloo IN inputloop %]
-                                                        <input type="hidden" name="ri-[% inputloo.counter | html %]" value="[% inputloo.barcode | html %]" />
-                                                        <input type="hidden" name="dd-[% inputloo.counter | html %]" value="[% inputloo.duedate | html %]" />
-                                                        <input type="hidden" name="bn-[% inputloo.counter | html %]" value="[% inputloo.borrowernumber | html %]" />
-                                                    [% END %]
-                                                </form> <!-- /mainform -->
-                                            </div> <!-- /.modal-footer -->
+                                            <form method="post" action="returns.pl" name="wrongtransferform" id="wrongtransferform">
+                                                <input type="hidden" name="return_date_override" value="[% return_date_override | html %]" />
+                                                <input type="hidden" name="return_date_override_remember" value="[% return_date_override_remember | html %]" />
+                                                <input type="hidden" name="itemnumber" value="[% itemnumber | html %]" />
+                                                <input type="hidden" name="transit" value="[% NewTransfer | html %]" />
+                                                [% FOREACH inputloo IN inputloop %]
+                                                    <input type="hidden" name="ri-[% inputloo.counter | html %]" value="[% inputloo.barcode | html %]" />
+                                                    <input type="hidden" name="dd-[% inputloo.counter | html %]" value="[% inputloo.duedate | html %]" />
+                                                    <input type="hidden" name="bn-[% inputloo.counter | html %]" value="[% inputloo.borrowernumber | html %]" />
+                                                [% END %]
+
+                                                <div class="modal-header">
+                                                    <h3>
+                                                        Wrong transfer detected, please return item to: [% Branches.GetName( TransferWaitingAt ) | html %]
+                                                    </h3>
+                                                </div>
+
+                                                <div class="modal-body">
+                                                    <p>
+                                                        <a href="/cgi-bin/koha/catalogue/detail.pl?type=intra&amp;biblionumber=[% itembiblionumber | uri %]">[% item.barcode | html %]: [% title | html %]</a>
+                                                    </p>
+
+                                                    [% INCLUDE all_checkin_messages %]
+                                                </div>
+
+                                                <div class="modal-footer">
+                                                    <!-- CONFIRM -->
+                                                    <button class="btn btn-default approve" type="submit"><i class="fa fa-check"></i> OK</button>
+                                                    <!-- PRINT SLIP -->
+                                                    <button type="button" data-dismiss="modal" class="btn btn-default transit openWin" data-transfer="[% NewTransfer | html %]" data-url="transfer-slip.pl?transferitem=[% itemnumber | uri %]&amp;&amp;branchcode=[% TransferWaitingAt | uri %]&amp;op=slip"><i class="fa fa-print"></i> Print transfer slip</button>
+                                                    <!-- CANCEL TRANSFER -->
+                                                    <button type="button" data-dismiss="modal" class="btn btn-default deny cancel"><i class="fa fa-times"></i> Cancel transfer</button>
+                                                </div> <!-- /.modal-footer -->
+                                            </form> <!-- /wrongtransferform -->
                                         </div> <!-- /.modal-content -->
                                     </div> <!-- /.modal-dialog -->
                                 </div> <!-- /#wrong-transfer-modal -->
@@ -1126,6 +1128,12 @@
                 Dopop( $(this).data("url") );
             });
 
+            $('.cancel').on("click",function(e){
+                var docancel = $("<input>").attr("type", "hidden").attr("name", "canceltransfer").val(1);
+                $('#wrongtransferform').append(docancel);
+                this.form.submit();
+            });
+
             $('.print').on("click",function(e){
                 this.form.print_slip.value = 1;
                 let barcode = document.getElementById('confirm-hold-barcode');
-- 
2.20.1