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>.
24 use Data::Dumper qw(Dumper);
25 use List::MoreUtils qw(any);
27 use C4::Context qw(preference);
31 use Koha::AuthorisedValues;
32 use Koha::DateUtils qw(dt_from_string output_pref);
40 use Koha::Exceptions::Hold;
42 use base qw(Koha::Object);
46 Koha::Hold - Koha Hold object class
56 returns the number of days since a hold was placed, optionally
59 my $age = $hold->age( $use_calendar );
64 my ( $self, $use_calendar ) = @_;
66 my $today = dt_from_string;
69 if ( $use_calendar ) {
70 my $calendar = Koha::Calendar->new( branchcode => $self->branchcode );
71 $age = $calendar->days_between( dt_from_string( $self->reservedate ), $today );
74 $age = $today->delta_days( dt_from_string( $self->reservedate ) );
77 $age = $age->in_units( 'days' );
84 my $hold = $hold->suspend_hold( $suspend_until_dt );
89 my ( $self, $dt ) = @_;
91 my $date = $dt ? $dt->clone()->truncate( to => 'day' )->datetime : undef;
93 if ( $self->is_found ) { # We can't suspend found holds
94 if ( $self->is_waiting ) {
95 Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'W' );
97 elsif ( $self->is_in_transit ) {
98 Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'T' );
100 elsif ( $self->is_in_processing ) {
101 Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'P' );
104 Koha::Exceptions::Hold::CannotSuspendFound->throw(
105 'Unhandled data exception on found hold (id='
114 $self->suspend_until($date);
117 logaction( 'HOLDS', 'SUSPEND', $self->reserve_id, Dumper( $self->unblessed ) )
118 if C4::Context->preference('HoldsLog');
125 my $hold = $hold->resume();
133 $self->suspend_until( undef );
137 logaction( 'HOLDS', 'RESUME', $self->reserve_id, Dumper($self->unblessed) )
138 if C4::Context->preference('HoldsLog');
152 my $deleted = $self->SUPER::delete($self);
154 logaction( 'HOLDS', 'DELETE', $self->reserve_id, Dumper($self->unblessed) )
155 if C4::Context->preference('HoldsLog');
179 my ( $self, $desk_id ) = @_;
183 my $today = dt_from_string();
186 waitingdate => $today->ymd,
190 my $requested_expiration;
191 if ($self->expirationdate) {
192 $requested_expiration = dt_from_string($self->expirationdate);
195 my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
196 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
198 my $expirationdate = $today->clone;
199 $expirationdate->add(days => $max_pickup_delay);
201 if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
202 my $itemtype = $self->item ? $self->item->effective_itemtype : $self->biblio->itemtype;
203 my $daysmode = Koha::CirculationRules->get_effective_daysmode(
205 categorycode => $self->borrower->categorycode,
206 itemtype => $itemtype,
207 branchcode => $self->branchcode,
210 my $calendar = Koha::Calendar->new( branchcode => $self->branchcode, days_mode => $daysmode );
212 $expirationdate = $calendar->days_forward( dt_from_string(), $max_pickup_delay );
215 # If patron's requested expiration date is prior to the
216 # calculated one, we keep the patron's one.
217 my $cmp = $requested_expiration ? DateTime->compare($requested_expiration, $expirationdate) : 0;
218 $values->{expirationdate} = $cmp == -1 ? $requested_expiration->ymd : $expirationdate->ymd;
220 $self->set($values)->store();
225 =head3 is_pickup_location_valid
227 if ($hold->is_pickup_location_valid({ library_id => $library->id }) ) {
231 Returns a I<boolean> representing if the passed pickup location is valid for the hold.
232 It throws a I<Koha::Exceptions::_MissingParameter> if the library_id parameter is not
237 sub is_pickup_location_valid {
238 my ( $self, $params ) = @_;
240 Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
241 unless $params->{library_id};
243 my @pickup_locations;
245 if ( $self->itemnumber ) { # item-level
246 @pickup_locations = $self->item->pickup_locations({ patron => $self->patron });
248 else { # biblio-level
249 @pickup_locations = $self->biblio->pickup_locations({ patron => $self->patron });
252 return any { $_->branchcode eq $params->{library_id} } @pickup_locations;
255 =head3 set_pickup_location
257 $hold->set_pickup_location(
259 library_id => $library->id,
264 Updates the hold pickup location. It throws a I<Koha::Exceptions::Hold::InvalidPickupLocation> if
265 the passed pickup location is not valid.
267 Note: It is up to the caller to verify if I<AllowHoldPolicyOverride> is set when setting the
272 sub set_pickup_location {
273 my ( $self, $params ) = @_;
275 Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
276 unless $params->{library_id};
280 || $self->is_pickup_location_valid(
281 { library_id => $params->{library_id} }
285 # all good, set the new pickup location
286 $self->branchcode( $params->{library_id} )->store;
289 Koha::Exceptions::Hold::InvalidPickupLocation->throw;
295 =head3 set_processing
297 $hold->set_processing;
299 Mark the hold as in processing.
315 Returns true if hold is waiting, in transit or in processing
322 return 0 unless $self->found();
323 return 1 if $self->found() eq 'W';
324 return 1 if $self->found() eq 'T';
325 return 1 if $self->found() eq 'P';
330 Returns true if hold is a waiting hold
337 my $found = $self->found;
338 return $found && $found eq 'W';
343 Returns true if hold is a in_transit hold
350 return 0 unless $self->found();
351 return $self->found() eq 'T';
354 =head3 is_in_processing
356 Returns true if hold is a in_processing hold
360 sub is_in_processing {
363 return 0 unless $self->found();
364 return $self->found() eq 'P';
367 =head3 is_cancelable_from_opac
369 Returns true if hold is a cancelable hold
371 Holds may be only canceled if they are not found.
373 This is used from the OPAC.
377 sub is_cancelable_from_opac {
380 return 1 unless $self->is_found();
381 return 0; # if ->is_in_transit or if ->is_waiting or ->is_in_processing
384 =head3 is_at_destination
386 Returns true if hold is waiting
387 and the hold's pickup branch matches
388 the hold item's holding branch
392 sub is_at_destination {
395 return $self->is_waiting() && ( $self->branchcode() eq $self->item()->holdingbranch() );
400 Returns the related Koha::Biblio object for this hold
407 $self->{_biblio} ||= Koha::Biblios->find( $self->biblionumber() );
409 return $self->{_biblio};
414 Returns the related Koha::Patron object for this hold
421 my $patron_rs = $self->_result->patron;
422 return Koha::Patron->_new_from_dbic($patron_rs);
427 Returns the related Koha::Item object for this Hold
434 $self->{_item} ||= Koha::Items->find( $self->itemnumber() );
436 return $self->{_item};
441 Returns the related Koha::Library object for this Hold
448 $self->{_branch} ||= Koha::Libraries->find( $self->branchcode() );
450 return $self->{_branch};
455 Returns the related Koha::Desk object for this Hold
461 my $desk_rs = $self->_result->desk;
462 return unless $desk_rs;
463 return Koha::Desk->_new_from_dbic($desk_rs);
468 Returns the related Koha::Patron object for this Hold
472 # FIXME Should be renamed with ->patron
476 $self->{_borrower} ||= Koha::Patrons->find( $self->borrowernumber() );
478 return $self->{_borrower};
483 my $bool = $hold->is_suspended();
490 return $self->suspend();
496 my $cancel_hold = $hold->cancel(
498 [ charge_cancel_fee => 1||0, ]
499 [ cancellation_reason => $cancellation_reason, ]
504 - The hold will be moved to the old_reserves table with a priority=0
505 - The priority of other holds will be updated
506 - The patron will be charge (see ExpireReservesMaxPickUpDelayCharge) if the charge_cancel_fee parameter is set
507 - The canceled hold will have the cancellation reason added to old_reserves.cancellation_reason if one is passed in
508 - a CANCEL HOLDS log will be done if the pref HoldsLog is on
513 my ( $self, $params ) = @_;
515 $self->_result->result_source->schema->txn_do(
517 if ( $self->is_in_transit ) {
518 my $transfer = $self->item->get_transfer;
519 # NOTE: Transfers are well bound with Holds.. as such we have to check that there is actually a
520 # transfer enqueued and in transit here prior to trying to cancel it.
521 if ( $transfer && $transfer->in_transit ) {
522 $transfer->cancel({ reason => 'CancelReserve', force => 1 });
525 $self->cancellationdate( dt_from_string->strftime( '%Y-%m-%d %H:%M:%S' ) );
527 $self->cancellation_reason( $params->{cancellation_reason} );
530 if ( $params->{cancellation_reason} ) {
531 my $letter = C4::Letters::GetPreparedLetter(
532 module => 'reserves',
533 letter_code => 'HOLD_CANCELLATION',
534 message_transport_type => 'email',
535 branchcode => $self->borrower->branchcode,
536 lang => $self->borrower->lang,
538 branches => $self->borrower->branchcode,
539 borrowers => $self->borrowernumber,
540 items => $self->itemnumber,
541 biblio => $self->biblionumber,
542 biblioitems => $self->biblionumber,
543 reserves => $self->unblessed,
548 C4::Letters::EnqueueLetter(
551 borrowernumber => $self->borrowernumber,
552 message_transport_type => 'email',
559 $self->SUPER::delete(); # Do not add a DELETE log
561 # now fix the priority on the others....
562 C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
564 # and, if desired, charge a cancel fee
565 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
566 if ( $charge && $params->{'charge_cancel_fee'} ) {
568 Koha::Account->new( { patron_id => $self->borrowernumber } );
572 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
573 interface => C4::Context->interface,
574 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
575 type => 'RESERVE_EXPIRED',
576 item_id => $self->itemnumber
581 C4::Log::logaction( 'HOLDS', 'CANCEL', $self->reserve_id, Dumper($self->unblessed) )
582 if C4::Context->preference('HoldsLog');
590 Override base store method to set default
591 expirationdate for holds.
598 if ( !$self->in_storage ) {
600 C4::Context->preference('DefaultHoldExpirationdate')
601 and ( not defined $self->expirationdate
602 or $self->expirationdate eq '' )
605 $self->_set_default_expirationdate;
610 my %updated_columns = $self->_result->get_dirty_columns;
611 return $self->SUPER::store unless %updated_columns;
613 if ( exists $updated_columns{reservedate} ) {
615 C4::Context->preference('DefaultHoldExpirationdate')
616 and ( not exists $updated_columns{expirationdate}
617 or exists $updated_columns{expirationdate}
618 and $updated_columns{expirationdate} eq '' )
621 $self->_set_default_expirationdate;
626 $self = $self->SUPER::store;
629 sub _set_default_expirationdate {
632 my $period = C4::Context->preference('DefaultHoldExpirationdatePeriod') || 0;
634 C4::Context->preference('DefaultHoldExpirationdateUnitOfTime') || 'days';
636 $self->expirationdate(
637 dt_from_string( $self->reservedate )->add( $timeunit => $period ) );
642 my $is_moved = $hold->_move_to_old;
644 Move a hold to the old_reserve table following the same pattern as Koha::Patron->move_to_deleted
650 my $hold_infos = $self->unblessed;
651 return Koha::Old::Hold->new( $hold_infos )->store;
654 =head3 to_api_mapping
656 This method returns the mapping for representing a Koha::Hold object
663 reserve_id => 'hold_id',
664 borrowernumber => 'patron_id',
665 reservedate => 'hold_date',
666 biblionumber => 'biblio_id',
667 branchcode => 'pickup_library_id',
668 notificationdate => undef,
669 reminderdate => undef,
670 cancellationdate => 'cancellation_date',
671 reservenotes => 'notes',
673 itemnumber => 'item_id',
674 waitingdate => 'waiting_date',
675 expirationdate => 'expiration_date',
676 lowestPriority => 'lowest_priority',
677 suspend => 'suspended',
678 suspend_until => 'suspended_until',
679 itemtype => 'item_type',
680 item_level_hold => 'item_level',
684 =head2 Internal methods
696 Kyle M Hall <kyle@bywatersolutions.com>
697 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
698 Martin Renvoize <martin.renvoize@ptfs-europe.com>