3 # Copyright ByWater Solutions 2014
4 # Copyright 2017 Koha Development team
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23 use List::MoreUtils qw( any );
25 use C4::Context qw(preference);
26 use C4::Letters qw( GetPreparedLetter EnqueueLetter );
27 use C4::Log qw( logaction );
30 use Koha::AuthorisedValues;
31 use Koha::DateUtils qw( dt_from_string );
34 use Koha::Hold::CancellationRequests;
41 use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue;
44 use Koha::Exceptions::Hold;
46 use base qw(Koha::Object);
50 Koha::Hold - Koha Hold object class
60 returns the number of days since a hold was placed, optionally
63 my $age = $hold->age( $use_calendar );
68 my ( $self, $use_calendar ) = @_;
70 my $today = dt_from_string;
73 if ( $use_calendar ) {
74 my $calendar = Koha::Calendar->new( branchcode => $self->branchcode );
75 $age = $calendar->days_between( dt_from_string( $self->reservedate ), $today );
78 $age = $today->delta_days( dt_from_string( $self->reservedate ) );
81 $age = $age->in_units( 'days' );
88 my $hold = $hold->suspend_hold( $suspend_until );
93 my ( $self, $date ) = @_;
95 $date &&= dt_from_string($date)->truncate( to => 'day' )->datetime;
97 if ( $self->is_found ) { # We can't suspend found holds
98 if ( $self->is_waiting ) {
99 Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'W' );
101 elsif ( $self->is_in_transit ) {
102 Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'T' );
104 elsif ( $self->is_in_processing ) {
105 Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'P' );
108 Koha::Exceptions::Hold::CannotSuspendFound->throw(
109 'Unhandled data exception on found hold (id='
118 $self->suspend_until($date);
125 payload => { hold => $self->get_from_storage }
129 logaction( 'HOLDS', 'SUSPEND', $self->reserve_id, $self )
130 if C4::Context->preference('HoldsLog');
132 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
134 biblio_ids => [ $self->biblionumber ]
136 ) if C4::Context->preference('RealTimeHoldsQueue');
143 my $hold = $hold->resume();
151 $self->suspend_until( undef );
159 payload => { hold => $self->get_from_storage }
163 logaction( 'HOLDS', 'RESUME', $self->reserve_id, $self )
164 if C4::Context->preference('HoldsLog');
166 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
168 biblio_ids => [ $self->biblionumber ]
170 ) if C4::Context->preference('RealTimeHoldsQueue');
184 my $deleted = $self->SUPER::delete($self);
186 logaction( 'HOLDS', 'DELETE', $self->reserve_id, $self )
187 if C4::Context->preference('HoldsLog');
206 action => 'transfer',
207 payload => { hold => $self->get_from_storage }
219 my ( $self, $desk_id ) = @_;
223 my $today = dt_from_string();
227 ( !$self->waitingdate ? ( waitingdate => $today->ymd ) : () ),
231 my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
232 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
234 my $rule = Koha::CirculationRules->get_effective_rule(
236 categorycode => $self->borrower->categorycode,
237 itemtype => $self->item->effective_itemtype,
238 branchcode => $self->branchcode,
239 rule_name => 'holds_pickup_period',
242 if ( defined($rule) and $rule->rule_value ne '' ) {
244 # circulation rule overrides ReservesMaxPickUpDelay
245 $max_pickup_delay = $rule->rule_value;
248 my $new_expiration_date = dt_from_string($self->waitingdate)->clone->add( days => $max_pickup_delay );
250 if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
251 my $itemtype = $self->item ? $self->item->effective_itemtype : $self->biblio->itemtype;
252 my $daysmode = Koha::CirculationRules->get_effective_daysmode(
254 categorycode => $self->borrower->categorycode,
255 itemtype => $itemtype,
256 branchcode => $self->branchcode,
259 my $calendar = Koha::Calendar->new( branchcode => $self->branchcode, days_mode => $daysmode );
261 $new_expiration_date = $calendar->days_forward( dt_from_string($self->waitingdate), $max_pickup_delay );
264 # If patron's requested expiration date is prior to the
265 # calculated one, we keep the patron's one.
266 if ( $self->patron_expiration_date ) {
267 my $requested_expiration = dt_from_string( $self->patron_expiration_date );
270 $requested_expiration
271 ? DateTime->compare( $requested_expiration, $new_expiration_date )
274 $new_expiration_date =
275 $cmp == -1 ? $requested_expiration : $new_expiration_date;
278 $values->{expirationdate} = $new_expiration_date->ymd;
280 $self->set($values)->store();
286 payload => { hold => $self->get_from_storage }
293 =head3 is_pickup_location_valid
295 if ($hold->is_pickup_location_valid({ library_id => $library->id }) ) {
299 Returns a I<boolean> representing if the passed pickup location is valid for the hold.
300 It throws a I<Koha::Exceptions::_MissingParameter> if the library_id parameter is not
305 sub is_pickup_location_valid {
306 my ( $self, $params ) = @_;
308 Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
309 unless $params->{library_id};
311 my $pickup_locations;
313 if ( $self->itemnumber ) { # item-level
314 $pickup_locations = $self->item->pickup_locations({ patron => $self->patron });
316 else { # biblio-level
317 $pickup_locations = $self->biblio->pickup_locations({ patron => $self->patron });
320 return any { $_->branchcode eq $params->{library_id} } $pickup_locations->as_list;
323 =head3 set_pickup_location
325 $hold->set_pickup_location(
327 library_id => $library->id,
332 Updates the hold pickup location. It throws a I<Koha::Exceptions::Hold::InvalidPickupLocation> if
333 the passed pickup location is not valid.
335 Note: It is up to the caller to verify if I<AllowHoldPolicyOverride> is set when setting the
340 sub set_pickup_location {
341 my ( $self, $params ) = @_;
343 Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
344 unless $params->{library_id};
348 || $self->is_pickup_location_valid(
349 { library_id => $params->{library_id} }
353 # all good, set the new pickup location
354 $self->branchcode( $params->{library_id} )->store;
357 Koha::Exceptions::Hold::InvalidPickupLocation->throw;
363 =head3 set_processing
365 $hold->set_processing;
367 Mark the hold as in processing.
381 action => 'processing',
382 payload => { hold => $self->get_from_storage }
391 Returns true if hold is waiting, in transit or in processing
398 return 0 unless $self->found();
399 return 1 if $self->found() eq 'W';
400 return 1 if $self->found() eq 'T';
401 return 1 if $self->found() eq 'P';
406 Returns true if hold is a waiting hold
413 my $found = $self->found;
414 return $found && $found eq 'W';
419 Returns true if hold is a in_transit hold
426 return 0 unless $self->found();
427 return $self->found() eq 'T';
430 =head3 is_in_processing
432 Returns true if hold is a in_processing hold
436 sub is_in_processing {
439 return 0 unless $self->found();
440 return $self->found() eq 'P';
443 =head3 is_cancelable_from_opac
445 Returns true if hold is a cancelable hold
447 Holds may be only canceled if they are not found.
449 This is used from the OPAC.
453 sub is_cancelable_from_opac {
456 return 1 unless $self->is_found();
457 return 0; # if ->is_in_transit or if ->is_waiting or ->is_in_processing
460 =head3 cancellation_requestable_from_opac
462 if ( $hold->cancellation_requestable_from_opac ) { ... }
464 Returns a I<boolean> representing if a cancellation request can be placed on the hold
465 from the OPAC. It targets holds that cannot be cancelled from the OPAC (see the
466 B<is_cancelable_from_opac> method above), but for which circulation rules allow
467 requesting cancellation.
469 Throws a B<Koha::Exceptions::InvalidStatus> exception with the following I<invalid_status>
474 =item B<'hold_not_waiting'>: the hold is expected to be waiting and it is not.
476 =item B<'no_item_linked'>: the waiting hold doesn't have an item properly linked.
482 sub cancellation_requestable_from_opac {
485 Koha::Exceptions::InvalidStatus->throw( invalid_status => 'hold_not_waiting' )
486 unless $self->is_waiting;
488 my $item = $self->item;
490 Koha::Exceptions::InvalidStatus->throw( invalid_status => 'no_item_linked' )
493 my $patron = $self->patron;
495 my $controlbranch = $patron->branchcode;
497 if ( C4::Context->preference('ReservesControlBranch') eq 'ItemHomeLibrary' ) {
498 $controlbranch = $item->homebranch;
501 return Koha::CirculationRules->get_effective_rule_value(
503 categorycode => $patron->categorycode,
504 itemtype => $item->itype,
505 branchcode => $controlbranch,
506 rule_name => 'waiting_hold_cancellation',
511 =head3 is_at_destination
513 Returns true if hold is waiting
514 and the hold's pickup branch matches
515 the hold item's holding branch
519 sub is_at_destination {
522 return $self->is_waiting() && ( $self->branchcode() eq $self->item()->holdingbranch() );
527 Returns the related Koha::Biblio object for this hold
533 my $rs = $self->_result->biblionumber;
534 return Koha::Biblio->_new_from_dbic($rs);
539 Returns the related Koha::Patron object for this hold
545 my $rs = $self->_result->patron;
546 return Koha::Patron->_new_from_dbic($rs);
551 Returns the related Koha::Item object for this Hold
557 my $rs = $self->_result->itemnumber;
559 return Koha::Item->_new_from_dbic($rs);
564 Returns the related Koha::Biblio::ItemGroup object for this Hold
570 my $rs = $self->_result->item_group;
572 return Koha::Biblio::ItemGroup->_new_from_dbic($rs);
577 Returns the related Koha::Library object for this Hold
583 my $rs = $self->_result->branchcode;
584 return Koha::Library->_new_from_dbic($rs);
589 Returns the related Koha::Desk object for this Hold
595 my $desk_rs = $self->_result->desk;
596 return unless $desk_rs;
597 return Koha::Desk->_new_from_dbic($desk_rs);
602 Returns the related Koha::Patron object for this Hold
606 # FIXME Should be renamed with ->patron
609 my $rs = $self->_result->borrowernumber;
610 return Koha::Patron->_new_from_dbic($rs);
615 my $bool = $hold->is_suspended();
622 return $self->suspend();
625 =head3 add_cancellation_request
627 my $cancellation_request = $hold->add_cancellation_request({ [ creation_date => $creation_date ] });
629 Adds a cancellation request to the hold. Returns the generated
630 I<Koha::Hold::CancellationRequest> object.
634 sub add_cancellation_request {
635 my ( $self, $params ) = @_;
637 my $request = Koha::Hold::CancellationRequest->new(
638 { hold_id => $self->id,
639 ( $params->{creation_date} ? ( creation_date => $params->{creation_date} ) : () ),
643 $request->discard_changes;
648 =head3 cancellation_requests
650 my $cancellation_requests = $hold->cancellation_requests;
652 Returns related a I<Koha::Hold::CancellationRequests> resultset.
656 sub cancellation_requests {
659 return Koha::Hold::CancellationRequests->search( { hold_id => $self->id } );
662 =head3 cancellation_requested
664 if ( $hold->cancellation_requested ) { ... }
666 Returns true if a cancellation request has been placed for the hold.
670 sub cancellation_requested {
673 return Koha::Hold::CancellationRequests->search( { hold_id => $self->id } )->count > 0;
678 my $cancel_hold = $hold->cancel(
680 [ charge_cancel_fee => 1||0, ]
681 [ cancellation_reason => $cancellation_reason, ]
682 [ skip_holds_queue => 1||0 ]
687 - The hold will be moved to the old_reserves table with a priority=0
688 - The priority of other holds will be updated
689 - The patron will be charge (see ExpireReservesMaxPickUpDelayCharge) if the charge_cancel_fee parameter is set
690 - The canceled hold will have the cancellation reason added to old_reserves.cancellation_reason if one is passed in
691 - a CANCEL HOLDS log will be done if the pref HoldsLog is on
696 my ( $self, $params ) = @_;
698 my $autofill_next = $params->{autofill} && $self->itemnumber && $self->found && $self->found eq 'W';
700 $self->_result->result_source->schema->txn_do(
702 my $patron = $self->patron;
704 $self->cancellationdate( dt_from_string->strftime( '%Y-%m-%d %H:%M:%S' ) );
706 $self->cancellation_reason( $params->{cancellation_reason} );
709 my $dbh = $self->_result->result_source->schema->storage->dbh;
713 FROM tmp_holdsqueue q
714 INNER JOIN hold_fill_targets t
715 ON q.borrowernumber = t.borrowernumber
716 AND q.biblionumber = t.biblionumber
717 AND q.itemnumber = t.itemnumber
718 AND q.item_level_request = t.item_level_request
719 AND q.holdingbranch = t.source_branchcode
720 WHERE t.reserve_id = ?
724 if ( $params->{cancellation_reason} ) {
725 my $letter = C4::Letters::GetPreparedLetter(
726 module => 'reserves',
727 letter_code => 'HOLD_CANCELLATION',
728 message_transport_type => 'email',
729 branchcode => $self->borrower->branchcode,
730 lang => $self->borrower->lang,
732 branches => $self->borrower->branchcode,
733 borrowers => $self->borrowernumber,
734 items => $self->itemnumber,
735 biblio => $self->biblionumber,
736 biblioitems => $self->biblionumber,
737 reserves => $self->unblessed,
742 C4::Letters::EnqueueLetter(
745 borrowernumber => $self->borrowernumber,
746 message_transport_type => 'email',
752 my $old_me = $self->_move_to_old;
758 payload => { hold => $old_me->get_from_storage }
762 # anonymize if required
764 if $patron->privacy == 2;
766 $self->SUPER::delete(); # Do not add a DELETE log
767 # now fix the priority on the others....
768 C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
770 # and, if desired, charge a cancel fee
771 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
772 if ( $charge && $params->{'charge_cancel_fee'} ) {
774 Koha::Account->new( { patron_id => $self->borrowernumber } );
778 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
779 interface => C4::Context->interface,
780 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
781 type => 'RESERVE_EXPIRED',
782 item_id => $self->itemnumber
787 C4::Log::logaction( 'HOLDS', 'CANCEL', $self->reserve_id, $self )
788 if C4::Context->preference('HoldsLog');
790 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
792 biblio_ids => [ $old_me->biblionumber ]
794 ) unless $params->{skip_holds_queue} or !C4::Context->preference('RealTimeHoldsQueue');
798 if ($autofill_next) {
799 my ( undef, $next_hold ) = C4::Reserves::CheckReserves( $self->item );
801 my $is_transfer = $self->branchcode ne $next_hold->{branchcode};
803 C4::Reserves::ModReserveAffect( $self->itemnumber, $self->borrowernumber, $is_transfer, $next_hold->{reserve_id}, $self->desk_id, $autofill_next );
804 C4::Items::ModItemTransfer( $self->itemnumber, $self->branchcode, $next_hold->{branchcode}, "Reserve" ) if $is_transfer;
813 $hold->fill({ [ item_id => $item->id ] });
815 This method marks the hold as filled. It effectively moves it to old_reserves.
816 The optional I<item_id> parameter is used to set the information about the
817 item that filled the hold.
822 my ( $self, $params ) = @_;
823 $self->_result->result_source->schema->txn_do(
825 my $patron = $self->patron;
831 $params->{item_id} ? ( itemnumber => $params->{item_id} ) : (),
835 my $old_me = $self->_move_to_old;
841 payload => { hold => $old_me->get_from_storage }
845 # anonymize if required
847 if $patron->privacy == 2;
849 $self->SUPER::delete(); # Do not add a DELETE log
851 # now fix the priority on the others....
852 C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
854 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
855 my $fee = $patron->category->reservefee // 0;
857 $patron->account->add_debit(
860 description => $self->biblio->title,
861 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
862 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
863 interface => C4::Context->interface,
865 item_id => $self->itemnumber
871 C4::Log::logaction( 'HOLDS', 'FILL', $self->id, $self )
872 if C4::Context->preference('HoldsLog');
874 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
876 biblio_ids => [ $old_me->biblionumber ]
878 ) if C4::Context->preference('RealTimeHoldsQueue');
884 =head3 sub change_type
886 $hold->change_type # to record level
887 $hold->change_type( $itemnumber ) # to item level
889 Changes hold type between record and item level holds, only if record has
890 exactly one hold for a patron. This is because Koha expects all holds for
891 a patron on a record to be alike.
896 my ( $self, $itemnumber ) = @_;
898 my $record_holds_per_patron = Koha::Holds->search(
900 borrowernumber => $self->borrowernumber,
901 biblionumber => $self->biblionumber,
905 if ( $itemnumber && $self->itemnumber ) {
906 $self->itemnumber($itemnumber)->store;
910 if ( $record_holds_per_patron->count == 1 ) {
913 itemnumber => $itemnumber ? $itemnumber : undef,
914 item_level_hold => $itemnumber ? 1 : 0,
918 Koha::Exceptions::Hold::CannotChangeHoldType->throw();
926 Override base store method to set default
927 expirationdate for holds.
934 Koha::Exceptions::Hold::MissingPickupLocation->throw() unless $self->branchcode;
936 if ( !$self->in_storage ) {
937 if ( ! $self->expirationdate && $self->patron_expiration_date ) {
938 $self->expirationdate($self->patron_expiration_date);
942 C4::Context->preference('DefaultHoldExpirationdate')
943 && !$self->expirationdate
946 $self->_set_default_expirationdate;
951 my %updated_columns = $self->_result->get_dirty_columns;
952 return $self->SUPER::store unless %updated_columns;
954 if ( exists $updated_columns{reservedate} ) {
956 C4::Context->preference('DefaultHoldExpirationdate')
957 && ! exists $updated_columns{expirationdate}
960 $self->_set_default_expirationdate;
965 $self = $self->SUPER::store;
968 sub _set_default_expirationdate {
971 my $period = C4::Context->preference('DefaultHoldExpirationdatePeriod') || 0;
973 C4::Context->preference('DefaultHoldExpirationdateUnitOfTime') || 'days';
975 $self->expirationdate(
976 dt_from_string( $self->reservedate )->add( $timeunit => $period ) );
981 my $is_moved = $hold->_move_to_old;
983 Move a hold to the old_reserve table following the same pattern as Koha::Patron->move_to_deleted
989 my $hold_infos = $self->unblessed;
990 return Koha::Old::Hold->new( $hold_infos )->store;
993 =head3 to_api_mapping
995 This method returns the mapping for representing a Koha::Hold object
1000 sub to_api_mapping {
1002 reserve_id => 'hold_id',
1003 borrowernumber => 'patron_id',
1004 reservedate => 'hold_date',
1005 biblionumber => 'biblio_id',
1006 branchcode => 'pickup_library_id',
1007 notificationdate => undef,
1008 reminderdate => undef,
1009 cancellationdate => 'cancellation_date',
1010 reservenotes => 'notes',
1012 itemnumber => 'item_id',
1013 waitingdate => 'waiting_date',
1014 expirationdate => 'expiration_date',
1015 patron_expiration_date => undef,
1016 lowestPriority => 'lowest_priority',
1017 suspend => 'suspended',
1018 suspend_until => 'suspended_until',
1019 itemtype => 'item_type',
1020 item_level_hold => 'item_level',
1024 =head3 can_update_pickup_location_opac
1026 my $can_update_pickup_location_opac = $hold->can_update_pickup_location_opac;
1028 Returns if a hold can change pickup location from opac
1032 sub can_update_pickup_location_opac {
1035 my @statuses = split /,/, C4::Context->preference("OPACAllowUserToChangeBranch");
1036 foreach my $status ( @statuses ){
1037 return 1 if ($status eq 'pending' && !$self->is_found && !$self->is_suspended );
1038 return 1 if ($status eq 'intransit' && $self->is_in_transit);
1039 return 1 if ($status eq 'suspended' && $self->is_suspended);
1044 =head2 Internal methods
1056 Kyle M Hall <kyle@bywatersolutions.com>
1057 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
1058 Martin Renvoize <martin.renvoize@ptfs-europe.com>