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 );
39 use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue;
41 use Koha::Exceptions::Hold;
43 use base qw(Koha::Object);
47 Koha::Hold - Koha Hold object class
57 returns the number of days since a hold was placed, optionally
60 my $age = $hold->age( $use_calendar );
65 my ( $self, $use_calendar ) = @_;
67 my $today = dt_from_string;
70 if ( $use_calendar ) {
71 my $calendar = Koha::Calendar->new( branchcode => $self->branchcode );
72 $age = $calendar->days_between( dt_from_string( $self->reservedate ), $today );
75 $age = $today->delta_days( dt_from_string( $self->reservedate ) );
78 $age = $age->in_units( 'days' );
85 my $hold = $hold->suspend_hold( $suspend_until_dt );
90 my ( $self, $dt ) = @_;
92 my $date = $dt ? $dt->clone()->truncate( to => 'day' )->datetime : undef;
94 if ( $self->is_found ) { # We can't suspend found holds
95 if ( $self->is_waiting ) {
96 Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'W' );
98 elsif ( $self->is_in_transit ) {
99 Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'T' );
101 elsif ( $self->is_in_processing ) {
102 Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'P' );
105 Koha::Exceptions::Hold::CannotSuspendFound->throw(
106 'Unhandled data exception on found hold (id='
115 $self->suspend_until($date);
122 payload => { hold => $self->get_from_storage }
126 logaction( 'HOLDS', 'SUSPEND', $self->reserve_id, $self )
127 if C4::Context->preference('HoldsLog');
129 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
131 biblio_ids => [ $self->biblionumber ]
140 my $hold = $hold->resume();
148 $self->suspend_until( undef );
156 payload => { hold => $self->get_from_storage }
160 logaction( 'HOLDS', 'RESUME', $self->reserve_id, $self )
161 if C4::Context->preference('HoldsLog');
163 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
165 biblio_ids => [ $self->biblionumber ]
181 my $deleted = $self->SUPER::delete($self);
183 logaction( 'HOLDS', 'DELETE', $self->reserve_id, $self )
184 if C4::Context->preference('HoldsLog');
208 my ( $self, $desk_id ) = @_;
212 my $today = dt_from_string();
216 ( !$self->waitingdate ? ( waitingdate => $today->ymd ) : () ),
220 my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
221 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
223 my $new_expiration_date = $today->clone->add(days => $max_pickup_delay);
225 if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
226 my $itemtype = $self->item ? $self->item->effective_itemtype : $self->biblio->itemtype;
227 my $daysmode = Koha::CirculationRules->get_effective_daysmode(
229 categorycode => $self->borrower->categorycode,
230 itemtype => $itemtype,
231 branchcode => $self->branchcode,
234 my $calendar = Koha::Calendar->new( branchcode => $self->branchcode, days_mode => $daysmode );
236 $new_expiration_date = $calendar->days_forward( dt_from_string(), $max_pickup_delay );
239 # If patron's requested expiration date is prior to the
240 # calculated one, we keep the patron's one.
241 if ( $self->patron_expiration_date ) {
242 my $requested_expiration = dt_from_string( $self->patron_expiration_date );
245 $requested_expiration
246 ? DateTime->compare( $requested_expiration, $new_expiration_date )
249 $new_expiration_date =
250 $cmp == -1 ? $requested_expiration : $new_expiration_date;
253 $values->{expirationdate} = $new_expiration_date->ymd;
255 $self->set($values)->store();
260 =head3 is_pickup_location_valid
262 if ($hold->is_pickup_location_valid({ library_id => $library->id }) ) {
266 Returns a I<boolean> representing if the passed pickup location is valid for the hold.
267 It throws a I<Koha::Exceptions::_MissingParameter> if the library_id parameter is not
272 sub is_pickup_location_valid {
273 my ( $self, $params ) = @_;
275 Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
276 unless $params->{library_id};
278 my $pickup_locations;
280 if ( $self->itemnumber ) { # item-level
281 $pickup_locations = $self->item->pickup_locations({ patron => $self->patron });
283 else { # biblio-level
284 $pickup_locations = $self->biblio->pickup_locations({ patron => $self->patron });
287 return any { $_->branchcode eq $params->{library_id} } $pickup_locations->as_list;
290 =head3 set_pickup_location
292 $hold->set_pickup_location(
294 library_id => $library->id,
299 Updates the hold pickup location. It throws a I<Koha::Exceptions::Hold::InvalidPickupLocation> if
300 the passed pickup location is not valid.
302 Note: It is up to the caller to verify if I<AllowHoldPolicyOverride> is set when setting the
307 sub set_pickup_location {
308 my ( $self, $params ) = @_;
310 Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
311 unless $params->{library_id};
315 || $self->is_pickup_location_valid(
316 { library_id => $params->{library_id} }
320 # all good, set the new pickup location
321 $self->branchcode( $params->{library_id} )->store;
324 Koha::Exceptions::Hold::InvalidPickupLocation->throw;
330 =head3 set_processing
332 $hold->set_processing;
334 Mark the hold as in processing.
350 Returns true if hold is waiting, in transit or in processing
357 return 0 unless $self->found();
358 return 1 if $self->found() eq 'W';
359 return 1 if $self->found() eq 'T';
360 return 1 if $self->found() eq 'P';
365 Returns true if hold is a waiting hold
372 my $found = $self->found;
373 return $found && $found eq 'W';
378 Returns true if hold is a in_transit hold
385 return 0 unless $self->found();
386 return $self->found() eq 'T';
389 =head3 is_in_processing
391 Returns true if hold is a in_processing hold
395 sub is_in_processing {
398 return 0 unless $self->found();
399 return $self->found() eq 'P';
402 =head3 is_cancelable_from_opac
404 Returns true if hold is a cancelable hold
406 Holds may be only canceled if they are not found.
408 This is used from the OPAC.
412 sub is_cancelable_from_opac {
415 return 1 unless $self->is_found();
416 return 0; # if ->is_in_transit or if ->is_waiting or ->is_in_processing
419 =head3 is_at_destination
421 Returns true if hold is waiting
422 and the hold's pickup branch matches
423 the hold item's holding branch
427 sub is_at_destination {
430 return $self->is_waiting() && ( $self->branchcode() eq $self->item()->holdingbranch() );
435 Returns the related Koha::Biblio object for this hold
442 $self->{_biblio} ||= Koha::Biblios->find( $self->biblionumber() );
444 return $self->{_biblio};
449 Returns the related Koha::Patron object for this hold
456 my $patron_rs = $self->_result->patron;
457 return Koha::Patron->_new_from_dbic($patron_rs);
462 Returns the related Koha::Item object for this Hold
469 $self->{_item} ||= Koha::Items->find( $self->itemnumber() );
471 return $self->{_item};
476 Returns the related Koha::Library object for this Hold
483 $self->{_branch} ||= Koha::Libraries->find( $self->branchcode() );
485 return $self->{_branch};
490 Returns the related Koha::Desk object for this Hold
496 my $desk_rs = $self->_result->desk;
497 return unless $desk_rs;
498 return Koha::Desk->_new_from_dbic($desk_rs);
503 Returns the related Koha::Patron object for this Hold
507 # FIXME Should be renamed with ->patron
511 $self->{_borrower} ||= Koha::Patrons->find( $self->borrowernumber() );
513 return $self->{_borrower};
518 my $bool = $hold->is_suspended();
525 return $self->suspend();
531 my $cancel_hold = $hold->cancel(
533 [ charge_cancel_fee => 1||0, ]
534 [ cancellation_reason => $cancellation_reason, ]
535 [ skip_holds_queue => 1||0 ]
540 - The hold will be moved to the old_reserves table with a priority=0
541 - The priority of other holds will be updated
542 - The patron will be charge (see ExpireReservesMaxPickUpDelayCharge) if the charge_cancel_fee parameter is set
543 - The canceled hold will have the cancellation reason added to old_reserves.cancellation_reason if one is passed in
544 - a CANCEL HOLDS log will be done if the pref HoldsLog is on
549 my ( $self, $params ) = @_;
550 $self->_result->result_source->schema->txn_do(
552 my $patron = $self->patron;
554 $self->cancellationdate( dt_from_string->strftime( '%Y-%m-%d %H:%M:%S' ) );
556 $self->cancellation_reason( $params->{cancellation_reason} );
559 if ( $params->{cancellation_reason} ) {
560 my $letter = C4::Letters::GetPreparedLetter(
561 module => 'reserves',
562 letter_code => 'HOLD_CANCELLATION',
563 message_transport_type => 'email',
564 branchcode => $self->borrower->branchcode,
565 lang => $self->borrower->lang,
567 branches => $self->borrower->branchcode,
568 borrowers => $self->borrowernumber,
569 items => $self->itemnumber,
570 biblio => $self->biblionumber,
571 biblioitems => $self->biblionumber,
572 reserves => $self->unblessed,
577 C4::Letters::EnqueueLetter(
580 borrowernumber => $self->borrowernumber,
581 message_transport_type => 'email',
587 my $old_me = $self->_move_to_old;
593 payload => { hold => $old_me->get_from_storage }
597 # anonymize if required
599 if $patron->privacy == 2;
601 $self->SUPER::delete(); # Do not add a DELETE log
603 # now fix the priority on the others....
604 C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
606 # and, if desired, charge a cancel fee
607 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
608 if ( $charge && $params->{'charge_cancel_fee'} ) {
610 Koha::Account->new( { patron_id => $self->borrowernumber } );
614 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
615 interface => C4::Context->interface,
616 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
617 type => 'RESERVE_EXPIRED',
618 item_id => $self->itemnumber
623 C4::Log::logaction( 'HOLDS', 'CANCEL', $self->reserve_id, $self )
624 if C4::Context->preference('HoldsLog');
626 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
628 biblio_ids => [ $old_me->biblionumber ]
630 ) unless $params->{skip_holds_queue};
640 This method marks the hold as filled. It effectively moves it to old_reserves.
646 $self->_result->result_source->schema->txn_do(
648 my $patron = $self->patron;
657 my $old_me = $self->_move_to_old;
663 payload => { hold => $old_me->get_from_storage }
667 # anonymize if required
669 if $patron->privacy == 2;
671 $self->SUPER::delete(); # Do not add a DELETE log
673 # now fix the priority on the others....
674 C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
676 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
677 my $fee = $patron->category->reservefee // 0;
679 $patron->account->add_debit(
682 description => $self->biblio->title,
683 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
684 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
685 interface => C4::Context->interface,
687 item_id => $self->itemnumber
693 C4::Log::logaction( 'HOLDS', 'FILL', $self->id, $self )
694 if C4::Context->preference('HoldsLog');
696 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
698 biblio_ids => [ $old_me->biblionumber ]
708 Override base store method to set default
709 expirationdate for holds.
716 if ( !$self->in_storage ) {
717 if ( ! $self->expirationdate && $self->patron_expiration_date ) {
718 $self->expirationdate($self->patron_expiration_date);
722 C4::Context->preference('DefaultHoldExpirationdate')
723 && !$self->expirationdate
726 $self->_set_default_expirationdate;
731 my %updated_columns = $self->_result->get_dirty_columns;
732 return $self->SUPER::store unless %updated_columns;
734 if ( exists $updated_columns{reservedate} ) {
736 C4::Context->preference('DefaultHoldExpirationdate')
737 && ! exists $updated_columns{expirationdate}
740 $self->_set_default_expirationdate;
745 $self = $self->SUPER::store;
748 sub _set_default_expirationdate {
751 my $period = C4::Context->preference('DefaultHoldExpirationdatePeriod') || 0;
753 C4::Context->preference('DefaultHoldExpirationdateUnitOfTime') || 'days';
755 $self->expirationdate(
756 dt_from_string( $self->reservedate )->add( $timeunit => $period ) );
761 my $is_moved = $hold->_move_to_old;
763 Move a hold to the old_reserve table following the same pattern as Koha::Patron->move_to_deleted
769 my $hold_infos = $self->unblessed;
770 return Koha::Old::Hold->new( $hold_infos )->store;
773 =head3 to_api_mapping
775 This method returns the mapping for representing a Koha::Hold object
782 reserve_id => 'hold_id',
783 borrowernumber => 'patron_id',
784 reservedate => 'hold_date',
785 biblionumber => 'biblio_id',
786 branchcode => 'pickup_library_id',
787 notificationdate => undef,
788 reminderdate => undef,
789 cancellationdate => 'cancellation_date',
790 reservenotes => 'notes',
792 itemnumber => 'item_id',
793 waitingdate => 'waiting_date',
794 expirationdate => 'expiration_date',
795 patron_expiration_date => undef,
796 lowestPriority => 'lowest_priority',
797 suspend => 'suspended',
798 suspend_until => 'suspended_until',
799 itemtype => 'item_type',
800 item_level_hold => 'item_level',
804 =head2 Internal methods
816 Kyle M Hall <kyle@bywatersolutions.com>
817 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
818 Martin Renvoize <martin.renvoize@ptfs-europe.com>