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 $new_expiration_date = dt_from_string($self->waitingdate)->clone->add( days => $max_pickup_delay );
236 if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
237 my $itemtype = $self->item ? $self->item->effective_itemtype : $self->biblio->itemtype;
238 my $daysmode = Koha::CirculationRules->get_effective_daysmode(
240 categorycode => $self->borrower->categorycode,
241 itemtype => $itemtype,
242 branchcode => $self->branchcode,
245 my $calendar = Koha::Calendar->new( branchcode => $self->branchcode, days_mode => $daysmode );
247 $new_expiration_date = $calendar->days_forward( dt_from_string($self->waitingdate), $max_pickup_delay );
250 # If patron's requested expiration date is prior to the
251 # calculated one, we keep the patron's one.
252 if ( $self->patron_expiration_date ) {
253 my $requested_expiration = dt_from_string( $self->patron_expiration_date );
256 $requested_expiration
257 ? DateTime->compare( $requested_expiration, $new_expiration_date )
260 $new_expiration_date =
261 $cmp == -1 ? $requested_expiration : $new_expiration_date;
264 $values->{expirationdate} = $new_expiration_date->ymd;
266 $self->set($values)->store();
272 payload => { hold => $self->get_from_storage }
279 =head3 is_pickup_location_valid
281 if ($hold->is_pickup_location_valid({ library_id => $library->id }) ) {
285 Returns a I<boolean> representing if the passed pickup location is valid for the hold.
286 It throws a I<Koha::Exceptions::_MissingParameter> if the library_id parameter is not
291 sub is_pickup_location_valid {
292 my ( $self, $params ) = @_;
294 Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
295 unless $params->{library_id};
297 my $pickup_locations;
299 if ( $self->itemnumber ) { # item-level
300 $pickup_locations = $self->item->pickup_locations({ patron => $self->patron });
302 else { # biblio-level
303 $pickup_locations = $self->biblio->pickup_locations({ patron => $self->patron });
306 return any { $_->branchcode eq $params->{library_id} } $pickup_locations->as_list;
309 =head3 set_pickup_location
311 $hold->set_pickup_location(
313 library_id => $library->id,
318 Updates the hold pickup location. It throws a I<Koha::Exceptions::Hold::InvalidPickupLocation> if
319 the passed pickup location is not valid.
321 Note: It is up to the caller to verify if I<AllowHoldPolicyOverride> is set when setting the
326 sub set_pickup_location {
327 my ( $self, $params ) = @_;
329 Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
330 unless $params->{library_id};
334 || $self->is_pickup_location_valid(
335 { library_id => $params->{library_id} }
339 # all good, set the new pickup location
340 $self->branchcode( $params->{library_id} )->store;
343 Koha::Exceptions::Hold::InvalidPickupLocation->throw;
349 =head3 set_processing
351 $hold->set_processing;
353 Mark the hold as in processing.
367 action => 'processing',
368 payload => { hold => $self->get_from_storage }
377 Returns true if hold is waiting, in transit or in processing
384 return 0 unless $self->found();
385 return 1 if $self->found() eq 'W';
386 return 1 if $self->found() eq 'T';
387 return 1 if $self->found() eq 'P';
392 Returns true if hold is a waiting hold
399 my $found = $self->found;
400 return $found && $found eq 'W';
405 Returns true if hold is a in_transit hold
412 return 0 unless $self->found();
413 return $self->found() eq 'T';
416 =head3 is_in_processing
418 Returns true if hold is a in_processing hold
422 sub is_in_processing {
425 return 0 unless $self->found();
426 return $self->found() eq 'P';
429 =head3 is_cancelable_from_opac
431 Returns true if hold is a cancelable hold
433 Holds may be only canceled if they are not found.
435 This is used from the OPAC.
439 sub is_cancelable_from_opac {
442 return 1 unless $self->is_found();
443 return 0; # if ->is_in_transit or if ->is_waiting or ->is_in_processing
446 =head3 cancellation_requestable_from_opac
448 if ( $hold->cancellation_requestable_from_opac ) { ... }
450 Returns a I<boolean> representing if a cancellation request can be placed on the hold
451 from the OPAC. It targets holds that cannot be cancelled from the OPAC (see the
452 B<is_cancelable_from_opac> method above), but for which circulation rules allow
453 requesting cancellation.
455 Throws a B<Koha::Exceptions::InvalidStatus> exception with the following I<invalid_status>
460 =item B<'hold_not_waiting'>: the hold is expected to be waiting and it is not.
462 =item B<'no_item_linked'>: the waiting hold doesn't have an item properly linked.
468 sub cancellation_requestable_from_opac {
471 Koha::Exceptions::InvalidStatus->throw( invalid_status => 'hold_not_waiting' )
472 unless $self->is_waiting;
474 my $item = $self->item;
476 Koha::Exceptions::InvalidStatus->throw( invalid_status => 'no_item_linked' )
479 my $patron = $self->patron;
481 my $controlbranch = $patron->branchcode;
483 if ( C4::Context->preference('ReservesControlBranch') eq 'ItemHomeLibrary' ) {
484 $controlbranch = $item->homebranch;
487 return Koha::CirculationRules->get_effective_rule_value(
489 categorycode => $patron->categorycode,
490 itemtype => $item->itype,
491 branchcode => $controlbranch,
492 rule_name => 'waiting_hold_cancellation',
497 =head3 is_at_destination
499 Returns true if hold is waiting
500 and the hold's pickup branch matches
501 the hold item's holding branch
505 sub is_at_destination {
508 return $self->is_waiting() && ( $self->branchcode() eq $self->item()->holdingbranch() );
513 Returns the related Koha::Biblio object for this hold
520 $self->{_biblio} ||= Koha::Biblios->find( $self->biblionumber() );
522 return $self->{_biblio};
527 Returns the related Koha::Patron object for this hold
534 my $patron_rs = $self->_result->patron;
535 return Koha::Patron->_new_from_dbic($patron_rs);
540 Returns the related Koha::Item object for this Hold
547 $self->{_item} ||= Koha::Items->find( $self->itemnumber() );
549 return $self->{_item};
554 Returns the related Koha::Biblio::ItemGroup object for this Hold
561 my $item_group_rs = $self->_result->item_group;
562 return unless $item_group_rs;
563 return Koha::Biblio::ItemGroup->_new_from_dbic($item_group_rs);
568 Returns the related Koha::Library object for this Hold
575 $self->{_branch} ||= Koha::Libraries->find( $self->branchcode() );
577 return $self->{_branch};
582 Returns the related Koha::Desk object for this Hold
588 my $desk_rs = $self->_result->desk;
589 return unless $desk_rs;
590 return Koha::Desk->_new_from_dbic($desk_rs);
595 Returns the related Koha::Patron object for this Hold
599 # FIXME Should be renamed with ->patron
603 $self->{_borrower} ||= Koha::Patrons->find( $self->borrowernumber() );
605 return $self->{_borrower};
610 my $bool = $hold->is_suspended();
617 return $self->suspend();
620 =head3 add_cancellation_request
622 my $cancellation_request = $hold->add_cancellation_request({ [ creation_date => $creation_date ] });
624 Adds a cancellation request to the hold. Returns the generated
625 I<Koha::Hold::CancellationRequest> object.
629 sub add_cancellation_request {
630 my ( $self, $params ) = @_;
632 my $request = Koha::Hold::CancellationRequest->new(
633 { hold_id => $self->id,
634 ( $params->{creation_date} ? ( creation_date => $params->{creation_date} ) : () ),
638 $request->discard_changes;
643 =head3 cancellation_requests
645 my $cancellation_requests = $hold->cancellation_requests;
647 Returns related a I<Koha::Hold::CancellationRequests> resultset.
651 sub cancellation_requests {
654 return Koha::Hold::CancellationRequests->search( { hold_id => $self->id } );
659 my $cancel_hold = $hold->cancel(
661 [ charge_cancel_fee => 1||0, ]
662 [ cancellation_reason => $cancellation_reason, ]
663 [ skip_holds_queue => 1||0 ]
668 - The hold will be moved to the old_reserves table with a priority=0
669 - The priority of other holds will be updated
670 - The patron will be charge (see ExpireReservesMaxPickUpDelayCharge) if the charge_cancel_fee parameter is set
671 - The canceled hold will have the cancellation reason added to old_reserves.cancellation_reason if one is passed in
672 - a CANCEL HOLDS log will be done if the pref HoldsLog is on
677 my ( $self, $params ) = @_;
679 my $autofill_next = $params->{autofill} && $self->itemnumber && $self->found && $self->found eq 'W';
681 $self->_result->result_source->schema->txn_do(
683 my $patron = $self->patron;
685 $self->cancellationdate( dt_from_string->strftime( '%Y-%m-%d %H:%M:%S' ) );
687 $self->cancellation_reason( $params->{cancellation_reason} );
690 if ( $params->{cancellation_reason} ) {
691 my $letter = C4::Letters::GetPreparedLetter(
692 module => 'reserves',
693 letter_code => 'HOLD_CANCELLATION',
694 message_transport_type => 'email',
695 branchcode => $self->borrower->branchcode,
696 lang => $self->borrower->lang,
698 branches => $self->borrower->branchcode,
699 borrowers => $self->borrowernumber,
700 items => $self->itemnumber,
701 biblio => $self->biblionumber,
702 biblioitems => $self->biblionumber,
703 reserves => $self->unblessed,
708 C4::Letters::EnqueueLetter(
711 borrowernumber => $self->borrowernumber,
712 message_transport_type => 'email',
718 my $old_me = $self->_move_to_old;
724 payload => { hold => $old_me->get_from_storage }
728 # anonymize if required
730 if $patron->privacy == 2;
732 $self->SUPER::delete(); # Do not add a DELETE log
733 # now fix the priority on the others....
734 C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
736 # and, if desired, charge a cancel fee
737 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
738 if ( $charge && $params->{'charge_cancel_fee'} ) {
740 Koha::Account->new( { patron_id => $self->borrowernumber } );
744 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
745 interface => C4::Context->interface,
746 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
747 type => 'RESERVE_EXPIRED',
748 item_id => $self->itemnumber
753 C4::Log::logaction( 'HOLDS', 'CANCEL', $self->reserve_id, $self )
754 if C4::Context->preference('HoldsLog');
756 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
758 biblio_ids => [ $old_me->biblionumber ]
760 ) unless $params->{skip_holds_queue} or !C4::Context->preference('RealTimeHoldsQueue');
764 if ($autofill_next) {
765 my ( undef, $next_hold ) = C4::Reserves::CheckReserves( $self->itemnumber );
767 my $is_transfer = $self->branchcode ne $next_hold->{branchcode};
769 C4::Reserves::ModReserveAffect( $self->itemnumber, $self->borrowernumber, $is_transfer, $next_hold->{reserve_id}, $self->desk_id, $autofill_next );
770 C4::Items::ModItemTransfer( $self->itemnumber, $self->branchcode, $next_hold->{branchcode}, "Reserve" ) if $is_transfer;
781 This method marks the hold as filled. It effectively moves it to old_reserves.
787 $self->_result->result_source->schema->txn_do(
789 my $patron = $self->patron;
798 my $old_me = $self->_move_to_old;
804 payload => { hold => $old_me->get_from_storage }
808 # anonymize if required
810 if $patron->privacy == 2;
812 $self->SUPER::delete(); # Do not add a DELETE log
814 # now fix the priority on the others....
815 C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
817 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
818 my $fee = $patron->category->reservefee // 0;
820 $patron->account->add_debit(
823 description => $self->biblio->title,
824 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
825 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
826 interface => C4::Context->interface,
828 item_id => $self->itemnumber
834 C4::Log::logaction( 'HOLDS', 'FILL', $self->id, $self )
835 if C4::Context->preference('HoldsLog');
837 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
839 biblio_ids => [ $old_me->biblionumber ]
841 ) if C4::Context->preference('RealTimeHoldsQueue');
849 Override base store method to set default
850 expirationdate for holds.
857 Koha::Exceptions::Hold::MissingPickupLocation->throw() unless $self->branchcode;
859 if ( !$self->in_storage ) {
860 if ( ! $self->expirationdate && $self->patron_expiration_date ) {
861 $self->expirationdate($self->patron_expiration_date);
865 C4::Context->preference('DefaultHoldExpirationdate')
866 && !$self->expirationdate
869 $self->_set_default_expirationdate;
874 my %updated_columns = $self->_result->get_dirty_columns;
875 return $self->SUPER::store unless %updated_columns;
877 if ( exists $updated_columns{reservedate} ) {
879 C4::Context->preference('DefaultHoldExpirationdate')
880 && ! exists $updated_columns{expirationdate}
883 $self->_set_default_expirationdate;
888 $self = $self->SUPER::store;
891 sub _set_default_expirationdate {
894 my $period = C4::Context->preference('DefaultHoldExpirationdatePeriod') || 0;
896 C4::Context->preference('DefaultHoldExpirationdateUnitOfTime') || 'days';
898 $self->expirationdate(
899 dt_from_string( $self->reservedate )->add( $timeunit => $period ) );
904 my $is_moved = $hold->_move_to_old;
906 Move a hold to the old_reserve table following the same pattern as Koha::Patron->move_to_deleted
912 my $hold_infos = $self->unblessed;
913 return Koha::Old::Hold->new( $hold_infos )->store;
916 =head3 to_api_mapping
918 This method returns the mapping for representing a Koha::Hold object
925 reserve_id => 'hold_id',
926 borrowernumber => 'patron_id',
927 reservedate => 'hold_date',
928 biblionumber => 'biblio_id',
929 branchcode => 'pickup_library_id',
930 notificationdate => undef,
931 reminderdate => undef,
932 cancellationdate => 'cancellation_date',
933 reservenotes => 'notes',
935 itemnumber => 'item_id',
936 waitingdate => 'waiting_date',
937 expirationdate => 'expiration_date',
938 patron_expiration_date => undef,
939 lowestPriority => 'lowest_priority',
940 suspend => 'suspended',
941 suspend_until => 'suspended_until',
942 itemtype => 'item_type',
943 item_level_hold => 'item_level',
947 =head3 can_update_pickup_location_opac
949 my $can_update_pickup_location_opac = $hold->can_update_pickup_location_opac;
951 Returns if a hold can change pickup location from opac
955 sub can_update_pickup_location_opac {
958 my @statuses = split /,/, C4::Context->preference("OPACAllowUserToChangeBranch");
959 foreach my $status ( @statuses ){
960 return 1 if ($status eq 'pending' && !$self->is_found && !$self->is_suspended );
961 return 1 if ($status eq 'intransit' && $self->is_in_transit);
962 return 1 if ($status eq 'suspended' && $self->is_suspended);
967 =head2 Internal methods
979 Kyle M Hall <kyle@bywatersolutions.com>
980 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
981 Martin Renvoize <martin.renvoize@ptfs-europe.com>