Bug 21652: Only set waitingdate to today if there is no waitingdate already
[koha.git] / Koha / Hold.pm
1 package Koha::Hold;
2
3 # Copyright ByWater Solutions 2014
4 # Copyright 2017 Koha Development team
5 #
6 # This file is part of Koha.
7 #
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.
12 #
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.
17 #
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>.
20
21 use Modern::Perl;
22
23 use List::MoreUtils qw( any );
24
25 use C4::Context;
26 use C4::Letters qw( GetPreparedLetter EnqueueLetter );
27 use C4::Log qw( logaction );
28
29 use Koha::AuthorisedValues;
30 use Koha::DateUtils qw( dt_from_string );
31 use Koha::Patrons;
32 use Koha::Biblios;
33 use Koha::Items;
34 use Koha::Libraries;
35 use Koha::Old::Holds;
36 use Koha::Calendar;
37
38 use Koha::Exceptions::Hold;
39
40 use base qw(Koha::Object);
41
42 =head1 NAME
43
44 Koha::Hold - Koha Hold object class
45
46 =head1 API
47
48 =head2 Class methods
49
50 =cut
51
52 =head3 age
53
54 returns the number of days since a hold was placed, optionally
55 using the calendar
56
57 my $age = $hold->age( $use_calendar );
58
59 =cut
60
61 sub age {
62     my ( $self, $use_calendar ) = @_;
63
64     my $today = dt_from_string;
65     my $age;
66
67     if ( $use_calendar ) {
68         my $calendar = Koha::Calendar->new( branchcode => $self->branchcode );
69         $age = $calendar->days_between( dt_from_string( $self->reservedate ), $today );
70     }
71     else {
72         $age = $today->delta_days( dt_from_string( $self->reservedate ) );
73     }
74
75     $age = $age->in_units( 'days' );
76
77     return $age;
78 }
79
80 =head3 suspend_hold
81
82 my $hold = $hold->suspend_hold( $suspend_until_dt );
83
84 =cut
85
86 sub suspend_hold {
87     my ( $self, $dt ) = @_;
88
89     my $date = $dt ? $dt->clone()->truncate( to => 'day' )->datetime : undef;
90
91     if ( $self->is_found ) {    # We can't suspend found holds
92         if ( $self->is_waiting ) {
93             Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'W' );
94         }
95         elsif ( $self->is_in_transit ) {
96             Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'T' );
97         }
98         elsif ( $self->is_in_processing ) {
99             Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'P' );
100         }
101         else {
102             Koha::Exceptions::Hold::CannotSuspendFound->throw(
103                       'Unhandled data exception on found hold (id='
104                     . $self->id
105                     . ', found='
106                     . $self->found
107                     . ')' );
108         }
109     }
110
111     $self->suspend(1);
112     $self->suspend_until($date);
113     $self->store();
114
115     logaction( 'HOLDS', 'SUSPEND', $self->reserve_id, $self )
116         if C4::Context->preference('HoldsLog');
117
118     return $self;
119 }
120
121 =head3 resume
122
123 my $hold = $hold->resume();
124
125 =cut
126
127 sub resume {
128     my ( $self ) = @_;
129
130     $self->suspend(0);
131     $self->suspend_until( undef );
132
133     $self->store();
134
135     logaction( 'HOLDS', 'RESUME', $self->reserve_id, $self )
136         if C4::Context->preference('HoldsLog');
137
138     return $self;
139 }
140
141 =head3 delete
142
143 $hold->delete();
144
145 =cut
146
147 sub delete {
148     my ( $self ) = @_;
149
150     my $deleted = $self->SUPER::delete($self);
151
152     logaction( 'HOLDS', 'DELETE', $self->reserve_id, $self )
153         if C4::Context->preference('HoldsLog');
154
155     return $deleted;
156 }
157
158 =head3 set_transfer
159
160 =cut
161
162 sub set_transfer {
163     my ( $self ) = @_;
164
165     $self->priority(0);
166     $self->found('T');
167     $self->store();
168
169     return $self;
170 }
171
172 =head3 set_waiting
173
174 =cut
175
176 sub set_waiting {
177     my ( $self, $desk_id ) = @_;
178
179     $self->priority(0);
180
181     my $waiting_date;
182     my $today = dt_from_string();
183
184     if ( $self->waitingdate ) {
185         $waiting_date = $self->waitingdate;
186     } else {
187         $waiting_date = $today->ymd;
188     }
189
190     my $values = {
191         found => 'W',
192         waitingdate => $waiting_date,
193         desk_id => $desk_id,
194     };
195
196     my $requested_expiration;
197     if ($self->expirationdate) {
198         $requested_expiration = dt_from_string($self->expirationdate);
199     }
200
201     my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
202     my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
203
204     my $expirationdate = $today->clone;
205     $expirationdate->add(days => $max_pickup_delay);
206
207     if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
208         my $itemtype = $self->item ? $self->item->effective_itemtype : $self->biblio->itemtype;
209         my $daysmode = Koha::CirculationRules->get_effective_daysmode(
210             {
211                 categorycode => $self->borrower->categorycode,
212                 itemtype     => $itemtype,
213                 branchcode   => $self->branchcode,
214             }
215         );
216         my $calendar = Koha::Calendar->new( branchcode => $self->branchcode, days_mode => $daysmode );
217
218         $expirationdate = $calendar->days_forward( dt_from_string(), $max_pickup_delay );
219     }
220
221     # If patron's requested expiration date is prior to the
222     # calculated one, we keep the patron's one.
223     my $cmp = $requested_expiration ? DateTime->compare($requested_expiration, $expirationdate) : 0;
224     $values->{expirationdate} = $cmp == -1 ? $requested_expiration->ymd : $expirationdate->ymd;
225
226     $self->set($values)->store();
227
228     return $self;
229 }
230
231 =head3 is_pickup_location_valid
232
233     if ($hold->is_pickup_location_valid({ library_id => $library->id }) ) {
234         ...
235     }
236
237 Returns a I<boolean> representing if the passed pickup location is valid for the hold.
238 It throws a I<Koha::Exceptions::_MissingParameter> if the library_id parameter is not
239 passed.
240
241 =cut
242
243 sub is_pickup_location_valid {
244     my ( $self, $params ) = @_;
245
246     Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
247         unless $params->{library_id};
248
249     my $pickup_locations;
250
251     if ( $self->itemnumber ) { # item-level
252         $pickup_locations = $self->item->pickup_locations({ patron => $self->patron });
253     }
254     else { # biblio-level
255         $pickup_locations = $self->biblio->pickup_locations({ patron => $self->patron });
256     }
257
258     return any { $_->branchcode eq $params->{library_id} } $pickup_locations->as_list;
259 }
260
261 =head3 set_pickup_location
262
263     $hold->set_pickup_location(
264         {
265             library_id => $library->id,
266           [ force   => 0|1 ]
267         }
268     );
269
270 Updates the hold pickup location. It throws a I<Koha::Exceptions::Hold::InvalidPickupLocation> if
271 the passed pickup location is not valid.
272
273 Note: It is up to the caller to verify if I<AllowHoldPolicyOverride> is set when setting the
274 B<force> parameter.
275
276 =cut
277
278 sub set_pickup_location {
279     my ( $self, $params ) = @_;
280
281     Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
282         unless $params->{library_id};
283
284     if (
285         $params->{force}
286         || $self->is_pickup_location_valid(
287             { library_id => $params->{library_id} }
288         )
289       )
290     {
291         # all good, set the new pickup location
292         $self->branchcode( $params->{library_id} )->store;
293     }
294     else {
295         Koha::Exceptions::Hold::InvalidPickupLocation->throw;
296     }
297
298     return $self;
299 }
300
301 =head3 set_processing
302
303 $hold->set_processing;
304
305 Mark the hold as in processing.
306
307 =cut
308
309 sub set_processing {
310     my ( $self ) = @_;
311
312     $self->priority(0);
313     $self->found('P');
314     $self->store();
315
316     return $self;
317 }
318
319 =head3 is_found
320
321 Returns true if hold is waiting, in transit or in processing
322
323 =cut
324
325 sub is_found {
326     my ($self) = @_;
327
328     return 0 unless $self->found();
329     return 1 if $self->found() eq 'W';
330     return 1 if $self->found() eq 'T';
331     return 1 if $self->found() eq 'P';
332 }
333
334 =head3 is_waiting
335
336 Returns true if hold is a waiting hold
337
338 =cut
339
340 sub is_waiting {
341     my ($self) = @_;
342
343     my $found = $self->found;
344     return $found && $found eq 'W';
345 }
346
347 =head3 is_in_transit
348
349 Returns true if hold is a in_transit hold
350
351 =cut
352
353 sub is_in_transit {
354     my ($self) = @_;
355
356     return 0 unless $self->found();
357     return $self->found() eq 'T';
358 }
359
360 =head3 is_in_processing
361
362 Returns true if hold is a in_processing hold
363
364 =cut
365
366 sub is_in_processing {
367     my ($self) = @_;
368
369     return 0 unless $self->found();
370     return $self->found() eq 'P';
371 }
372
373 =head3 is_cancelable_from_opac
374
375 Returns true if hold is a cancelable hold
376
377 Holds may be only canceled if they are not found.
378
379 This is used from the OPAC.
380
381 =cut
382
383 sub is_cancelable_from_opac {
384     my ($self) = @_;
385
386     return 1 unless $self->is_found();
387     return 0; # if ->is_in_transit or if ->is_waiting or ->is_in_processing
388 }
389
390 =head3 is_at_destination
391
392 Returns true if hold is waiting
393 and the hold's pickup branch matches
394 the hold item's holding branch
395
396 =cut
397
398 sub is_at_destination {
399     my ($self) = @_;
400
401     return $self->is_waiting() && ( $self->branchcode() eq $self->item()->holdingbranch() );
402 }
403
404 =head3 biblio
405
406 Returns the related Koha::Biblio object for this hold
407
408 =cut
409
410 sub biblio {
411     my ($self) = @_;
412
413     $self->{_biblio} ||= Koha::Biblios->find( $self->biblionumber() );
414
415     return $self->{_biblio};
416 }
417
418 =head3 patron
419
420 Returns the related Koha::Patron object for this hold
421
422 =cut
423
424 sub patron {
425     my ($self) = @_;
426
427     my $patron_rs = $self->_result->patron;
428     return Koha::Patron->_new_from_dbic($patron_rs);
429 }
430
431 =head3 item
432
433 Returns the related Koha::Item object for this Hold
434
435 =cut
436
437 sub item {
438     my ($self) = @_;
439
440     $self->{_item} ||= Koha::Items->find( $self->itemnumber() );
441
442     return $self->{_item};
443 }
444
445 =head3 branch
446
447 Returns the related Koha::Library object for this Hold
448
449 =cut
450
451 sub branch {
452     my ($self) = @_;
453
454     $self->{_branch} ||= Koha::Libraries->find( $self->branchcode() );
455
456     return $self->{_branch};
457 }
458
459 =head3 desk
460
461 Returns the related Koha::Desk object for this Hold
462
463 =cut
464
465 sub desk {
466     my $self = shift;
467     my $desk_rs = $self->_result->desk;
468     return unless $desk_rs;
469     return Koha::Desk->_new_from_dbic($desk_rs);
470 }
471
472 =head3 borrower
473
474 Returns the related Koha::Patron object for this Hold
475
476 =cut
477
478 # FIXME Should be renamed with ->patron
479 sub borrower {
480     my ($self) = @_;
481
482     $self->{_borrower} ||= Koha::Patrons->find( $self->borrowernumber() );
483
484     return $self->{_borrower};
485 }
486
487 =head3 is_suspended
488
489 my $bool = $hold->is_suspended();
490
491 =cut
492
493 sub is_suspended {
494     my ( $self ) = @_;
495
496     return $self->suspend();
497 }
498
499
500 =head3 cancel
501
502 my $cancel_hold = $hold->cancel(
503     {
504         [ charge_cancel_fee => 1||0, ]
505         [ cancellation_reason => $cancellation_reason, ]
506     }
507 );
508
509 Cancel a hold:
510 - The hold will be moved to the old_reserves table with a priority=0
511 - The priority of other holds will be updated
512 - The patron will be charge (see ExpireReservesMaxPickUpDelayCharge) if the charge_cancel_fee parameter is set
513 - The canceled hold will have the cancellation reason added to old_reserves.cancellation_reason if one is passed in
514 - a CANCEL HOLDS log will be done if the pref HoldsLog is on
515
516 =cut
517
518 sub cancel {
519     my ( $self, $params ) = @_;
520     $self->_result->result_source->schema->txn_do(
521         sub {
522             $self->cancellationdate( dt_from_string->strftime( '%Y-%m-%d %H:%M:%S' ) );
523             $self->priority(0);
524             $self->cancellation_reason( $params->{cancellation_reason} );
525             $self->store();
526
527             if ( $params->{cancellation_reason} ) {
528                 my $letter = C4::Letters::GetPreparedLetter(
529                     module                 => 'reserves',
530                     letter_code            => 'HOLD_CANCELLATION',
531                     message_transport_type => 'email',
532                     branchcode             => $self->borrower->branchcode,
533                     lang                   => $self->borrower->lang,
534                     tables => {
535                         branches    => $self->borrower->branchcode,
536                         borrowers   => $self->borrowernumber,
537                         items       => $self->itemnumber,
538                         biblio      => $self->biblionumber,
539                         biblioitems => $self->biblionumber,
540                         reserves    => $self->unblessed,
541                     }
542                 );
543
544                 if ($letter) {
545                     C4::Letters::EnqueueLetter(
546                         {
547                             letter                   => $letter,
548                             borrowernumber         => $self->borrowernumber,
549                             message_transport_type => 'email',
550                         }
551                     );
552                 }
553             }
554
555             $self->_move_to_old;
556             $self->SUPER::delete(); # Do not add a DELETE log
557
558             # now fix the priority on the others....
559             C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
560
561             # and, if desired, charge a cancel fee
562             my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
563             if ( $charge && $params->{'charge_cancel_fee'} ) {
564                 my $account =
565                   Koha::Account->new( { patron_id => $self->borrowernumber } );
566                 $account->add_debit(
567                     {
568                         amount     => $charge,
569                         user_id    => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
570                         interface  => C4::Context->interface,
571                         library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
572                         type       => 'RESERVE_EXPIRED',
573                         item_id    => $self->itemnumber
574                     }
575                 );
576             }
577
578             C4::Log::logaction( 'HOLDS', 'CANCEL', $self->reserve_id, $self )
579                 if C4::Context->preference('HoldsLog');
580         }
581     );
582     return $self;
583 }
584
585 =head3 store
586
587 Override base store method to set default
588 expirationdate for holds.
589
590 =cut
591
592 sub store {
593     my ($self) = @_;
594
595     if ( !$self->in_storage ) {
596         if (
597             C4::Context->preference('DefaultHoldExpirationdate')
598             and ( not defined $self->expirationdate
599                 or $self->expirationdate eq '' )
600           )
601         {
602             $self->_set_default_expirationdate;
603         }
604     }
605     else {
606
607         my %updated_columns = $self->_result->get_dirty_columns;
608         return $self->SUPER::store unless %updated_columns;
609
610         if ( exists $updated_columns{reservedate} ) {
611             if (
612                 C4::Context->preference('DefaultHoldExpirationdate')
613                 and ( not exists $updated_columns{expirationdate}
614                     or exists $updated_columns{expirationdate}
615                     and $updated_columns{expirationdate} eq '' )
616               )
617             {
618                 $self->_set_default_expirationdate;
619             }
620         }
621     }
622
623     $self = $self->SUPER::store;
624 }
625
626 sub _set_default_expirationdate {
627     my $self = shift;
628
629     my $period = C4::Context->preference('DefaultHoldExpirationdatePeriod') || 0;
630     my $timeunit =
631       C4::Context->preference('DefaultHoldExpirationdateUnitOfTime') || 'days';
632
633     $self->expirationdate(
634         dt_from_string( $self->reservedate )->add( $timeunit => $period ) );
635 }
636
637 =head3 _move_to_old
638
639 my $is_moved = $hold->_move_to_old;
640
641 Move a hold to the old_reserve table following the same pattern as Koha::Patron->move_to_deleted
642
643 =cut
644
645 sub _move_to_old {
646     my ($self) = @_;
647     my $hold_infos = $self->unblessed;
648     return Koha::Old::Hold->new( $hold_infos )->store;
649 }
650
651 =head3 to_api_mapping
652
653 This method returns the mapping for representing a Koha::Hold object
654 on the API.
655
656 =cut
657
658 sub to_api_mapping {
659     return {
660         reserve_id       => 'hold_id',
661         borrowernumber   => 'patron_id',
662         reservedate      => 'hold_date',
663         biblionumber     => 'biblio_id',
664         branchcode       => 'pickup_library_id',
665         notificationdate => undef,
666         reminderdate     => undef,
667         cancellationdate => 'cancellation_date',
668         reservenotes     => 'notes',
669         found            => 'status',
670         itemnumber       => 'item_id',
671         waitingdate      => 'waiting_date',
672         expirationdate   => 'expiration_date',
673         lowestPriority   => 'lowest_priority',
674         suspend          => 'suspended',
675         suspend_until    => 'suspended_until',
676         itemtype         => 'item_type',
677         item_level_hold  => 'item_level',
678     };
679 }
680
681 =head2 Internal methods
682
683 =head3 _type
684
685 =cut
686
687 sub _type {
688     return 'Reserve';
689 }
690
691 =head1 AUTHORS
692
693 Kyle M Hall <kyle@bywatersolutions.com>
694 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
695 Martin Renvoize <martin.renvoize@ptfs-europe.com>
696
697 =cut
698
699 1;