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');
211 my ( $self, $desk_id ) = @_;
215 my $today = dt_from_string();
219 ( !$self->waitingdate ? ( waitingdate => $today->ymd ) : () ),
223 my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
224 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
226 my $new_expiration_date = $today->clone->add(days => $max_pickup_delay);
228 if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
229 my $itemtype = $self->item ? $self->item->effective_itemtype : $self->biblio->itemtype;
230 my $daysmode = Koha::CirculationRules->get_effective_daysmode(
232 categorycode => $self->borrower->categorycode,
233 itemtype => $itemtype,
234 branchcode => $self->branchcode,
237 my $calendar = Koha::Calendar->new( branchcode => $self->branchcode, days_mode => $daysmode );
239 $new_expiration_date = $calendar->days_forward( dt_from_string(), $max_pickup_delay );
242 # If patron's requested expiration date is prior to the
243 # calculated one, we keep the patron's one.
244 if ( $self->patron_expiration_date ) {
245 my $requested_expiration = dt_from_string( $self->patron_expiration_date );
248 $requested_expiration
249 ? DateTime->compare( $requested_expiration, $new_expiration_date )
252 $new_expiration_date =
253 $cmp == -1 ? $requested_expiration : $new_expiration_date;
256 $values->{expirationdate} = $new_expiration_date->ymd;
258 $self->set($values)->store();
263 =head3 is_pickup_location_valid
265 if ($hold->is_pickup_location_valid({ library_id => $library->id }) ) {
269 Returns a I<boolean> representing if the passed pickup location is valid for the hold.
270 It throws a I<Koha::Exceptions::_MissingParameter> if the library_id parameter is not
275 sub is_pickup_location_valid {
276 my ( $self, $params ) = @_;
278 Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
279 unless $params->{library_id};
281 my $pickup_locations;
283 if ( $self->itemnumber ) { # item-level
284 $pickup_locations = $self->item->pickup_locations({ patron => $self->patron });
286 else { # biblio-level
287 $pickup_locations = $self->biblio->pickup_locations({ patron => $self->patron });
290 return any { $_->branchcode eq $params->{library_id} } $pickup_locations->as_list;
293 =head3 set_pickup_location
295 $hold->set_pickup_location(
297 library_id => $library->id,
302 Updates the hold pickup location. It throws a I<Koha::Exceptions::Hold::InvalidPickupLocation> if
303 the passed pickup location is not valid.
305 Note: It is up to the caller to verify if I<AllowHoldPolicyOverride> is set when setting the
310 sub set_pickup_location {
311 my ( $self, $params ) = @_;
313 Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
314 unless $params->{library_id};
318 || $self->is_pickup_location_valid(
319 { library_id => $params->{library_id} }
323 # all good, set the new pickup location
324 $self->branchcode( $params->{library_id} )->store;
327 Koha::Exceptions::Hold::InvalidPickupLocation->throw;
333 =head3 set_processing
335 $hold->set_processing;
337 Mark the hold as in processing.
353 Returns true if hold is waiting, in transit or in processing
360 return 0 unless $self->found();
361 return 1 if $self->found() eq 'W';
362 return 1 if $self->found() eq 'T';
363 return 1 if $self->found() eq 'P';
368 Returns true if hold is a waiting hold
375 my $found = $self->found;
376 return $found && $found eq 'W';
381 Returns true if hold is a in_transit hold
388 return 0 unless $self->found();
389 return $self->found() eq 'T';
392 =head3 is_in_processing
394 Returns true if hold is a in_processing hold
398 sub is_in_processing {
401 return 0 unless $self->found();
402 return $self->found() eq 'P';
405 =head3 is_cancelable_from_opac
407 Returns true if hold is a cancelable hold
409 Holds may be only canceled if they are not found.
411 This is used from the OPAC.
415 sub is_cancelable_from_opac {
418 return 1 unless $self->is_found();
419 return 0; # if ->is_in_transit or if ->is_waiting or ->is_in_processing
422 =head3 cancellation_requestable_from_opac
424 if ( $hold->cancellation_requestable_from_opac ) { ... }
426 Returns a I<boolean> representing if a cancellation request can be placed on the hold
427 from the OPAC. It targets holds that cannot be cancelled from the OPAC (see the
428 B<is_cancelable_from_opac> method above), but for which circulation rules allow
429 requesting cancellation.
431 Throws a B<Koha::Exceptions::InvalidStatus> exception with the following I<invalid_status>
436 =item B<'hold_not_waiting'>: the hold is expected to be waiting and it is not.
438 =item B<'no_item_linked'>: the waiting hold doesn't have an item properly linked.
444 sub cancellation_requestable_from_opac {
447 Koha::Exceptions::InvalidStatus->throw( invalid_status => 'hold_not_waiting' )
448 unless $self->is_waiting;
450 my $item = $self->item;
452 Koha::Exceptions::InvalidStatus->throw( invalid_status => 'no_item_linked' )
455 my $patron = $self->patron;
457 my $controlbranch = $patron->branchcode;
459 if ( C4::Context->preference('ReservesControlBranch') eq 'ItemHomeLibrary' ) {
460 $controlbranch = $item->homebranch;
463 return Koha::CirculationRules->get_effective_rule_value(
465 categorycode => $patron->categorycode,
466 itemtype => $item->itype,
467 branchcode => $controlbranch,
468 rule_name => 'waiting_hold_cancellation',
473 =head3 is_at_destination
475 Returns true if hold is waiting
476 and the hold's pickup branch matches
477 the hold item's holding branch
481 sub is_at_destination {
484 return $self->is_waiting() && ( $self->branchcode() eq $self->item()->holdingbranch() );
489 Returns the related Koha::Biblio object for this hold
496 $self->{_biblio} ||= Koha::Biblios->find( $self->biblionumber() );
498 return $self->{_biblio};
503 Returns the related Koha::Patron object for this hold
510 my $patron_rs = $self->_result->patron;
511 return Koha::Patron->_new_from_dbic($patron_rs);
516 Returns the related Koha::Item object for this Hold
523 $self->{_item} ||= Koha::Items->find( $self->itemnumber() );
525 return $self->{_item};
530 Returns the related Koha::Library object for this Hold
537 $self->{_branch} ||= Koha::Libraries->find( $self->branchcode() );
539 return $self->{_branch};
544 Returns the related Koha::Desk object for this Hold
550 my $desk_rs = $self->_result->desk;
551 return unless $desk_rs;
552 return Koha::Desk->_new_from_dbic($desk_rs);
557 Returns the related Koha::Patron object for this Hold
561 # FIXME Should be renamed with ->patron
565 $self->{_borrower} ||= Koha::Patrons->find( $self->borrowernumber() );
567 return $self->{_borrower};
572 my $bool = $hold->is_suspended();
579 return $self->suspend();
582 =head3 add_cancellation_request
584 my $cancellation_request = $hold->add_cancellation_request({ [ creation_date => $creation_date ] });
586 Adds a cancellation request to the hold. Returns the generated
587 I<Koha::Hold::CancellationRequest> object.
591 sub add_cancellation_request {
592 my ( $self, $params ) = @_;
594 my $request = Koha::Hold::CancellationRequest->new(
595 { hold_id => $self->id,
596 ( $params->{creation_date} ? ( creation_date => $params->{creation_date} ) : () ),
600 $request->discard_changes;
605 =head3 cancellation_requests
607 my $cancellation_requests = $hold->cancellation_requests;
609 Returns related a I<Koha::Hold::CancellationRequests> resultset.
613 sub cancellation_requests {
616 return Koha::Hold::CancellationRequests->search( { hold_id => $self->id } );
621 my $cancel_hold = $hold->cancel(
623 [ charge_cancel_fee => 1||0, ]
624 [ cancellation_reason => $cancellation_reason, ]
625 [ skip_holds_queue => 1||0 ]
630 - The hold will be moved to the old_reserves table with a priority=0
631 - The priority of other holds will be updated
632 - The patron will be charge (see ExpireReservesMaxPickUpDelayCharge) if the charge_cancel_fee parameter is set
633 - The canceled hold will have the cancellation reason added to old_reserves.cancellation_reason if one is passed in
634 - a CANCEL HOLDS log will be done if the pref HoldsLog is on
639 my ( $self, $params ) = @_;
641 my $autofill_next = $params->{autofill} && $self->itemnumber && $self->found && $self->found eq 'W';
643 $self->_result->result_source->schema->txn_do(
645 my $patron = $self->patron;
647 $self->cancellationdate( dt_from_string->strftime( '%Y-%m-%d %H:%M:%S' ) );
649 $self->cancellation_reason( $params->{cancellation_reason} );
652 if ( $params->{cancellation_reason} ) {
653 my $letter = C4::Letters::GetPreparedLetter(
654 module => 'reserves',
655 letter_code => 'HOLD_CANCELLATION',
656 message_transport_type => 'email',
657 branchcode => $self->borrower->branchcode,
658 lang => $self->borrower->lang,
660 branches => $self->borrower->branchcode,
661 borrowers => $self->borrowernumber,
662 items => $self->itemnumber,
663 biblio => $self->biblionumber,
664 biblioitems => $self->biblionumber,
665 reserves => $self->unblessed,
670 C4::Letters::EnqueueLetter(
673 borrowernumber => $self->borrowernumber,
674 message_transport_type => 'email',
680 my $old_me = $self->_move_to_old;
686 payload => { hold => $old_me->get_from_storage }
690 # anonymize if required
692 if $patron->privacy == 2;
694 $self->SUPER::delete(); # Do not add a DELETE log
695 # now fix the priority on the others....
696 C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
698 # and, if desired, charge a cancel fee
699 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
700 if ( $charge && $params->{'charge_cancel_fee'} ) {
702 Koha::Account->new( { patron_id => $self->borrowernumber } );
706 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
707 interface => C4::Context->interface,
708 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
709 type => 'RESERVE_EXPIRED',
710 item_id => $self->itemnumber
715 C4::Log::logaction( 'HOLDS', 'CANCEL', $self->reserve_id, $self )
716 if C4::Context->preference('HoldsLog');
718 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
720 biblio_ids => [ $old_me->biblionumber ]
722 ) unless $params->{skip_holds_queue} or !C4::Context->preference('RealTimeHoldsQueue');
726 if ($autofill_next) {
727 my ( undef, $next_hold ) = C4::Reserves::CheckReserves( $self->itemnumber );
729 my $is_transfer = $self->branchcode ne $next_hold->{branchcode};
731 C4::Reserves::ModReserveAffect( $self->itemnumber, $self->borrowernumber, $is_transfer, $next_hold->{reserve_id}, $self->desk_id, $autofill_next );
732 C4::Items::ModItemTransfer( $self->itemnumber, $self->branchcode, $next_hold->{branchcode}, "Reserve" ) if $is_transfer;
743 This method marks the hold as filled. It effectively moves it to old_reserves.
749 $self->_result->result_source->schema->txn_do(
751 my $patron = $self->patron;
760 my $old_me = $self->_move_to_old;
766 payload => { hold => $old_me->get_from_storage }
770 # anonymize if required
772 if $patron->privacy == 2;
774 $self->SUPER::delete(); # Do not add a DELETE log
776 # now fix the priority on the others....
777 C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
779 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
780 my $fee = $patron->category->reservefee // 0;
782 $patron->account->add_debit(
785 description => $self->biblio->title,
786 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
787 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
788 interface => C4::Context->interface,
790 item_id => $self->itemnumber
796 C4::Log::logaction( 'HOLDS', 'FILL', $self->id, $self )
797 if C4::Context->preference('HoldsLog');
799 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
801 biblio_ids => [ $old_me->biblionumber ]
803 ) if C4::Context->preference('RealTimeHoldsQueue');
811 Override base store method to set default
812 expirationdate for holds.
819 Koha::Exceptions::Hold::MissingPickupLocation->throw() unless $self->branchcode;
821 if ( !$self->in_storage ) {
822 if ( ! $self->expirationdate && $self->patron_expiration_date ) {
823 $self->expirationdate($self->patron_expiration_date);
827 C4::Context->preference('DefaultHoldExpirationdate')
828 && !$self->expirationdate
831 $self->_set_default_expirationdate;
836 my %updated_columns = $self->_result->get_dirty_columns;
837 return $self->SUPER::store unless %updated_columns;
839 if ( exists $updated_columns{reservedate} ) {
841 C4::Context->preference('DefaultHoldExpirationdate')
842 && ! exists $updated_columns{expirationdate}
845 $self->_set_default_expirationdate;
850 $self = $self->SUPER::store;
853 sub _set_default_expirationdate {
856 my $period = C4::Context->preference('DefaultHoldExpirationdatePeriod') || 0;
858 C4::Context->preference('DefaultHoldExpirationdateUnitOfTime') || 'days';
860 $self->expirationdate(
861 dt_from_string( $self->reservedate )->add( $timeunit => $period ) );
866 my $is_moved = $hold->_move_to_old;
868 Move a hold to the old_reserve table following the same pattern as Koha::Patron->move_to_deleted
874 my $hold_infos = $self->unblessed;
875 return Koha::Old::Hold->new( $hold_infos )->store;
878 =head3 to_api_mapping
880 This method returns the mapping for representing a Koha::Hold object
887 reserve_id => 'hold_id',
888 borrowernumber => 'patron_id',
889 reservedate => 'hold_date',
890 biblionumber => 'biblio_id',
891 branchcode => 'pickup_library_id',
892 notificationdate => undef,
893 reminderdate => undef,
894 cancellationdate => 'cancellation_date',
895 reservenotes => 'notes',
897 itemnumber => 'item_id',
898 waitingdate => 'waiting_date',
899 expirationdate => 'expiration_date',
900 patron_expiration_date => undef,
901 lowestPriority => 'lowest_priority',
902 suspend => 'suspended',
903 suspend_until => 'suspended_until',
904 itemtype => 'item_type',
905 item_level_hold => 'item_level',
909 =head2 Internal methods
921 Kyle M Hall <kyle@bywatersolutions.com>
922 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
923 Martin Renvoize <martin.renvoize@ptfs-europe.com>