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 );
26 use C4::Letters qw( GetPreparedLetter EnqueueLetter );
27 use C4::Log qw( logaction );
29 use Koha::AuthorisedValues;
30 use Koha::DateUtils qw( dt_from_string );
33 use Koha::Hold::CancellationRequests;
40 use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue;
43 use Koha::Exceptions::Hold;
45 use base qw(Koha::Object);
49 Koha::Hold - Koha Hold object class
59 returns the number of days since a hold was placed, optionally
62 my $age = $hold->age( $use_calendar );
67 my ( $self, $use_calendar ) = @_;
69 my $today = dt_from_string;
72 if ( $use_calendar ) {
73 my $calendar = Koha::Calendar->new( branchcode => $self->branchcode );
74 $age = $calendar->days_between( dt_from_string( $self->reservedate ), $today );
77 $age = $today->delta_days( dt_from_string( $self->reservedate ) );
80 $age = $age->in_units( 'days' );
87 my $hold = $hold->suspend_hold( $suspend_until_dt );
92 my ( $self, $dt ) = @_;
94 my $date = $dt ? $dt->clone()->truncate( to => 'day' )->datetime : undef;
96 if ( $self->is_found ) { # We can't suspend found holds
97 if ( $self->is_waiting ) {
98 Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'W' );
100 elsif ( $self->is_in_transit ) {
101 Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'T' );
103 elsif ( $self->is_in_processing ) {
104 Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'P' );
107 Koha::Exceptions::Hold::CannotSuspendFound->throw(
108 'Unhandled data exception on found hold (id='
117 $self->suspend_until($date);
124 payload => { hold => $self->get_from_storage }
128 logaction( 'HOLDS', 'SUSPEND', $self->reserve_id, $self )
129 if C4::Context->preference('HoldsLog');
131 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
133 biblio_ids => [ $self->biblionumber ]
135 ) if C4::Context->preference('RealTimeHoldsQueue');
142 my $hold = $hold->resume();
150 $self->suspend_until( undef );
158 payload => { hold => $self->get_from_storage }
162 logaction( 'HOLDS', 'RESUME', $self->reserve_id, $self )
163 if C4::Context->preference('HoldsLog');
165 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
167 biblio_ids => [ $self->biblionumber ]
169 ) if C4::Context->preference('RealTimeHoldsQueue');
183 my $deleted = $self->SUPER::delete($self);
185 logaction( 'HOLDS', 'DELETE', $self->reserve_id, $self )
186 if C4::Context->preference('HoldsLog');
210 my ( $self, $desk_id ) = @_;
214 my $today = dt_from_string();
218 ( !$self->waitingdate ? ( waitingdate => $today->ymd ) : () ),
222 my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
223 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
225 my $new_expiration_date = $today->clone->add(days => $max_pickup_delay);
227 if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
228 my $itemtype = $self->item ? $self->item->effective_itemtype : $self->biblio->itemtype;
229 my $daysmode = Koha::CirculationRules->get_effective_daysmode(
231 categorycode => $self->borrower->categorycode,
232 itemtype => $itemtype,
233 branchcode => $self->branchcode,
236 my $calendar = Koha::Calendar->new( branchcode => $self->branchcode, days_mode => $daysmode );
238 $new_expiration_date = $calendar->days_forward( dt_from_string(), $max_pickup_delay );
241 # If patron's requested expiration date is prior to the
242 # calculated one, we keep the patron's one.
243 if ( $self->patron_expiration_date ) {
244 my $requested_expiration = dt_from_string( $self->patron_expiration_date );
247 $requested_expiration
248 ? DateTime->compare( $requested_expiration, $new_expiration_date )
251 $new_expiration_date =
252 $cmp == -1 ? $requested_expiration : $new_expiration_date;
255 $values->{expirationdate} = $new_expiration_date->ymd;
257 $self->set($values)->store();
262 =head3 is_pickup_location_valid
264 if ($hold->is_pickup_location_valid({ library_id => $library->id }) ) {
268 Returns a I<boolean> representing if the passed pickup location is valid for the hold.
269 It throws a I<Koha::Exceptions::_MissingParameter> if the library_id parameter is not
274 sub is_pickup_location_valid {
275 my ( $self, $params ) = @_;
277 Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
278 unless $params->{library_id};
280 my $pickup_locations;
282 if ( $self->itemnumber ) { # item-level
283 $pickup_locations = $self->item->pickup_locations({ patron => $self->patron });
285 else { # biblio-level
286 $pickup_locations = $self->biblio->pickup_locations({ patron => $self->patron });
289 return any { $_->branchcode eq $params->{library_id} } $pickup_locations->as_list;
292 =head3 set_pickup_location
294 $hold->set_pickup_location(
296 library_id => $library->id,
301 Updates the hold pickup location. It throws a I<Koha::Exceptions::Hold::InvalidPickupLocation> if
302 the passed pickup location is not valid.
304 Note: It is up to the caller to verify if I<AllowHoldPolicyOverride> is set when setting the
309 sub set_pickup_location {
310 my ( $self, $params ) = @_;
312 Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
313 unless $params->{library_id};
317 || $self->is_pickup_location_valid(
318 { library_id => $params->{library_id} }
322 # all good, set the new pickup location
323 $self->branchcode( $params->{library_id} )->store;
326 Koha::Exceptions::Hold::InvalidPickupLocation->throw;
332 =head3 set_processing
334 $hold->set_processing;
336 Mark the hold as in processing.
352 Returns true if hold is waiting, in transit or in processing
359 return 0 unless $self->found();
360 return 1 if $self->found() eq 'W';
361 return 1 if $self->found() eq 'T';
362 return 1 if $self->found() eq 'P';
367 Returns true if hold is a waiting hold
374 my $found = $self->found;
375 return $found && $found eq 'W';
380 Returns true if hold is a in_transit hold
387 return 0 unless $self->found();
388 return $self->found() eq 'T';
391 =head3 is_in_processing
393 Returns true if hold is a in_processing hold
397 sub is_in_processing {
400 return 0 unless $self->found();
401 return $self->found() eq 'P';
404 =head3 is_cancelable_from_opac
406 Returns true if hold is a cancelable hold
408 Holds may be only canceled if they are not found.
410 This is used from the OPAC.
414 sub is_cancelable_from_opac {
417 return 1 unless $self->is_found();
418 return 0; # if ->is_in_transit or if ->is_waiting or ->is_in_processing
421 =head3 cancellation_requestable_from_opac
423 if ( $hold->cancellation_requestable_from_opac ) { ... }
425 Returns a I<boolean> representing if a cancellation request can be placed on the hold
426 from the OPAC. It targets holds that cannot be cancelled from the OPAC (see the
427 B<is_cancelable_from_opac> method above), but for which circulation rules allow
428 requesting cancellation.
430 Throws a B<Koha::Exceptions::InvalidStatus> exception with the following I<invalid_status>
435 =item B<'hold_not_waiting'>: the hold is expected to be waiting and it is not.
437 =item B<'no_item_linked'>: the waiting hold doesn't have an item properly linked.
443 sub cancellation_requestable_from_opac {
446 Koha::Exceptions::InvalidStatus->throw( invalid_status => 'hold_not_waiting' )
447 unless $self->is_waiting;
449 my $item = $self->item;
451 Koha::Exceptions::InvalidStatus->throw( invalid_status => 'no_item_linked' )
454 my $patron = $self->patron;
456 my $controlbranch = $patron->branchcode;
458 if ( C4::Context->preference('ReservesControlBranch') eq 'ItemHomeLibrary' ) {
459 $controlbranch = $item->homebranch;
462 return Koha::CirculationRules->get_effective_rule(
464 categorycode => $patron->categorycode,
465 itemtype => $item->itype,
466 branchcode => $controlbranch,
467 rule_name => 'waiting_hold_cancellation',
469 )->rule_value ? 1 : 0;
472 =head3 is_at_destination
474 Returns true if hold is waiting
475 and the hold's pickup branch matches
476 the hold item's holding branch
480 sub is_at_destination {
483 return $self->is_waiting() && ( $self->branchcode() eq $self->item()->holdingbranch() );
488 Returns the related Koha::Biblio object for this hold
495 $self->{_biblio} ||= Koha::Biblios->find( $self->biblionumber() );
497 return $self->{_biblio};
502 Returns the related Koha::Patron object for this hold
509 my $patron_rs = $self->_result->patron;
510 return Koha::Patron->_new_from_dbic($patron_rs);
515 Returns the related Koha::Item object for this Hold
522 $self->{_item} ||= Koha::Items->find( $self->itemnumber() );
524 return $self->{_item};
529 Returns the related Koha::Library object for this Hold
536 $self->{_branch} ||= Koha::Libraries->find( $self->branchcode() );
538 return $self->{_branch};
543 Returns the related Koha::Desk object for this Hold
549 my $desk_rs = $self->_result->desk;
550 return unless $desk_rs;
551 return Koha::Desk->_new_from_dbic($desk_rs);
556 Returns the related Koha::Patron object for this Hold
560 # FIXME Should be renamed with ->patron
564 $self->{_borrower} ||= Koha::Patrons->find( $self->borrowernumber() );
566 return $self->{_borrower};
571 my $bool = $hold->is_suspended();
578 return $self->suspend();
581 =head3 add_cancellation_request
583 my $cancellation_request = $hold->add_cancellation_request({ [ creation_date => $creation_date ] });
585 Adds a cancellation request to the hold. Returns the generated
586 I<Koha::Hold::CancellationRequest> object.
590 sub add_cancellation_request {
591 my ( $self, $params ) = @_;
593 my $request = Koha::Hold::CancellationRequest->new(
594 { hold_id => $self->id,
595 ( $params->{creation_date} ? ( creation_date => $params->{creation_date} ) : () ),
599 $request->discard_changes;
604 =head3 cancellation_requests
606 my $cancellation_requests = $hold->cancellation_requests;
608 Returns related a I<Koha::Hold::CancellationRequests> resultset.
612 sub cancellation_requests {
615 return Koha::Hold::CancellationRequests->search( { hold_id => $self->id } );
620 my $cancel_hold = $hold->cancel(
622 [ charge_cancel_fee => 1||0, ]
623 [ cancellation_reason => $cancellation_reason, ]
624 [ skip_holds_queue => 1||0 ]
629 - The hold will be moved to the old_reserves table with a priority=0
630 - The priority of other holds will be updated
631 - The patron will be charge (see ExpireReservesMaxPickUpDelayCharge) if the charge_cancel_fee parameter is set
632 - The canceled hold will have the cancellation reason added to old_reserves.cancellation_reason if one is passed in
633 - a CANCEL HOLDS log will be done if the pref HoldsLog is on
638 my ( $self, $params ) = @_;
639 $self->_result->result_source->schema->txn_do(
641 my $patron = $self->patron;
643 $self->cancellationdate( dt_from_string->strftime( '%Y-%m-%d %H:%M:%S' ) );
645 $self->cancellation_reason( $params->{cancellation_reason} );
648 if ( $params->{cancellation_reason} ) {
649 my $letter = C4::Letters::GetPreparedLetter(
650 module => 'reserves',
651 letter_code => 'HOLD_CANCELLATION',
652 message_transport_type => 'email',
653 branchcode => $self->borrower->branchcode,
654 lang => $self->borrower->lang,
656 branches => $self->borrower->branchcode,
657 borrowers => $self->borrowernumber,
658 items => $self->itemnumber,
659 biblio => $self->biblionumber,
660 biblioitems => $self->biblionumber,
661 reserves => $self->unblessed,
666 C4::Letters::EnqueueLetter(
669 borrowernumber => $self->borrowernumber,
670 message_transport_type => 'email',
676 my $old_me = $self->_move_to_old;
682 payload => { hold => $old_me->get_from_storage }
686 # anonymize if required
688 if $patron->privacy == 2;
690 $self->SUPER::delete(); # Do not add a DELETE log
692 # now fix the priority on the others....
693 C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
695 # and, if desired, charge a cancel fee
696 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
697 if ( $charge && $params->{'charge_cancel_fee'} ) {
699 Koha::Account->new( { patron_id => $self->borrowernumber } );
703 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
704 interface => C4::Context->interface,
705 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
706 type => 'RESERVE_EXPIRED',
707 item_id => $self->itemnumber
712 C4::Log::logaction( 'HOLDS', 'CANCEL', $self->reserve_id, $self )
713 if C4::Context->preference('HoldsLog');
715 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
717 biblio_ids => [ $old_me->biblionumber ]
719 ) unless $params->{skip_holds_queue} or !C4::Context->preference('RealTimeHoldsQueue');
729 This method marks the hold as filled. It effectively moves it to old_reserves.
735 $self->_result->result_source->schema->txn_do(
737 my $patron = $self->patron;
746 my $old_me = $self->_move_to_old;
752 payload => { hold => $old_me->get_from_storage }
756 # anonymize if required
758 if $patron->privacy == 2;
760 $self->SUPER::delete(); # Do not add a DELETE log
762 # now fix the priority on the others....
763 C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
765 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
766 my $fee = $patron->category->reservefee // 0;
768 $patron->account->add_debit(
771 description => $self->biblio->title,
772 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
773 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
774 interface => C4::Context->interface,
776 item_id => $self->itemnumber
782 C4::Log::logaction( 'HOLDS', 'FILL', $self->id, $self )
783 if C4::Context->preference('HoldsLog');
785 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
787 biblio_ids => [ $old_me->biblionumber ]
789 ) if C4::Context->preference('RealTimeHoldsQueue');
797 Override base store method to set default
798 expirationdate for holds.
805 Koha::Exceptions::Hold::MissingPickupLocation->throw() unless $self->branchcode;
807 if ( !$self->in_storage ) {
808 if ( ! $self->expirationdate && $self->patron_expiration_date ) {
809 $self->expirationdate($self->patron_expiration_date);
813 C4::Context->preference('DefaultHoldExpirationdate')
814 && !$self->expirationdate
817 $self->_set_default_expirationdate;
822 my %updated_columns = $self->_result->get_dirty_columns;
823 return $self->SUPER::store unless %updated_columns;
825 if ( exists $updated_columns{reservedate} ) {
827 C4::Context->preference('DefaultHoldExpirationdate')
828 && ! exists $updated_columns{expirationdate}
831 $self->_set_default_expirationdate;
836 $self = $self->SUPER::store;
839 sub _set_default_expirationdate {
842 my $period = C4::Context->preference('DefaultHoldExpirationdatePeriod') || 0;
844 C4::Context->preference('DefaultHoldExpirationdateUnitOfTime') || 'days';
846 $self->expirationdate(
847 dt_from_string( $self->reservedate )->add( $timeunit => $period ) );
852 my $is_moved = $hold->_move_to_old;
854 Move a hold to the old_reserve table following the same pattern as Koha::Patron->move_to_deleted
860 my $hold_infos = $self->unblessed;
861 return Koha::Old::Hold->new( $hold_infos )->store;
864 =head3 to_api_mapping
866 This method returns the mapping for representing a Koha::Hold object
873 reserve_id => 'hold_id',
874 borrowernumber => 'patron_id',
875 reservedate => 'hold_date',
876 biblionumber => 'biblio_id',
877 branchcode => 'pickup_library_id',
878 notificationdate => undef,
879 reminderdate => undef,
880 cancellationdate => 'cancellation_date',
881 reservenotes => 'notes',
883 itemnumber => 'item_id',
884 waitingdate => 'waiting_date',
885 expirationdate => 'expiration_date',
886 patron_expiration_date => undef,
887 lowestPriority => 'lowest_priority',
888 suspend => 'suspended',
889 suspend_until => 'suspended_until',
890 itemtype => 'item_type',
891 item_level_hold => 'item_level',
895 =head2 Internal methods
907 Kyle M Hall <kyle@bywatersolutions.com>
908 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
909 Martin Renvoize <martin.renvoize@ptfs-europe.com>