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 $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
197     my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
198
199     my $new_expiration_date = $today->clone->add(days => $max_pickup_delay);
200
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(
204             {
205                 categorycode => $self->borrower->categorycode,
206                 itemtype     => $itemtype,
207                 branchcode   => $self->branchcode,
208             }
209         );
210         my $calendar = Koha::Calendar->new( branchcode => $self->branchcode, days_mode => $daysmode );
211
212         $new_expiration_date = $calendar->days_forward( dt_from_string(), $max_pickup_delay );
213     }
214
215     # If patron's requested expiration date is prior to the
216     # calculated one, we keep the patron's one.
217     if ( $self->patron_expiration_date ) {
218         my $requested_expiration = dt_from_string( $self->patron_expiration_date );
219
220         my $cmp =
221           $requested_expiration
222           ? DateTime->compare( $requested_expiration, $new_expiration_date )
223           : 0;
224
225         $new_expiration_date =
226           $cmp == -1 ? $requested_expiration : $new_expiration_date;
227     }
228
229     $values->{expirationdate} = $new_expiration_date->ymd;
230
231     $self->set($values)->store();
232
233     return $self;
234 }
235
236 =head3 is_pickup_location_valid
237
238     if ($hold->is_pickup_location_valid({ library_id => $library->id }) ) {
239         ...
240     }
241
242 Returns a I<boolean> representing if the passed pickup location is valid for the hold.
243 It throws a I<Koha::Exceptions::_MissingParameter> if the library_id parameter is not
244 passed.
245
246 =cut
247
248 sub is_pickup_location_valid {
249     my ( $self, $params ) = @_;
250
251     Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
252         unless $params->{library_id};
253
254     my $pickup_locations;
255
256     if ( $self->itemnumber ) { # item-level
257         $pickup_locations = $self->item->pickup_locations({ patron => $self->patron });
258     }
259     else { # biblio-level
260         $pickup_locations = $self->biblio->pickup_locations({ patron => $self->patron });
261     }
262
263     return any { $_->branchcode eq $params->{library_id} } $pickup_locations->as_list;
264 }
265
266 =head3 set_pickup_location
267
268     $hold->set_pickup_location(
269         {
270             library_id => $library->id,
271           [ force   => 0|1 ]
272         }
273     );
274
275 Updates the hold pickup location. It throws a I<Koha::Exceptions::Hold::InvalidPickupLocation> if
276 the passed pickup location is not valid.
277
278 Note: It is up to the caller to verify if I<AllowHoldPolicyOverride> is set when setting the
279 B<force> parameter.
280
281 =cut
282
283 sub set_pickup_location {
284     my ( $self, $params ) = @_;
285
286     Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
287         unless $params->{library_id};
288
289     if (
290         $params->{force}
291         || $self->is_pickup_location_valid(
292             { library_id => $params->{library_id} }
293         )
294       )
295     {
296         # all good, set the new pickup location
297         $self->branchcode( $params->{library_id} )->store;
298     }
299     else {
300         Koha::Exceptions::Hold::InvalidPickupLocation->throw;
301     }
302
303     return $self;
304 }
305
306 =head3 set_processing
307
308 $hold->set_processing;
309
310 Mark the hold as in processing.
311
312 =cut
313
314 sub set_processing {
315     my ( $self ) = @_;
316
317     $self->priority(0);
318     $self->found('P');
319     $self->store();
320
321     return $self;
322 }
323
324 =head3 is_found
325
326 Returns true if hold is waiting, in transit or in processing
327
328 =cut
329
330 sub is_found {
331     my ($self) = @_;
332
333     return 0 unless $self->found();
334     return 1 if $self->found() eq 'W';
335     return 1 if $self->found() eq 'T';
336     return 1 if $self->found() eq 'P';
337 }
338
339 =head3 is_waiting
340
341 Returns true if hold is a waiting hold
342
343 =cut
344
345 sub is_waiting {
346     my ($self) = @_;
347
348     my $found = $self->found;
349     return $found && $found eq 'W';
350 }
351
352 =head3 is_in_transit
353
354 Returns true if hold is a in_transit hold
355
356 =cut
357
358 sub is_in_transit {
359     my ($self) = @_;
360
361     return 0 unless $self->found();
362     return $self->found() eq 'T';
363 }
364
365 =head3 is_in_processing
366
367 Returns true if hold is a in_processing hold
368
369 =cut
370
371 sub is_in_processing {
372     my ($self) = @_;
373
374     return 0 unless $self->found();
375     return $self->found() eq 'P';
376 }
377
378 =head3 is_cancelable_from_opac
379
380 Returns true if hold is a cancelable hold
381
382 Holds may be only canceled if they are not found.
383
384 This is used from the OPAC.
385
386 =cut
387
388 sub is_cancelable_from_opac {
389     my ($self) = @_;
390
391     return 1 unless $self->is_found();
392     return 0; # if ->is_in_transit or if ->is_waiting or ->is_in_processing
393 }
394
395 =head3 is_at_destination
396
397 Returns true if hold is waiting
398 and the hold's pickup branch matches
399 the hold item's holding branch
400
401 =cut
402
403 sub is_at_destination {
404     my ($self) = @_;
405
406     return $self->is_waiting() && ( $self->branchcode() eq $self->item()->holdingbranch() );
407 }
408
409 =head3 biblio
410
411 Returns the related Koha::Biblio object for this hold
412
413 =cut
414
415 sub biblio {
416     my ($self) = @_;
417
418     $self->{_biblio} ||= Koha::Biblios->find( $self->biblionumber() );
419
420     return $self->{_biblio};
421 }
422
423 =head3 patron
424
425 Returns the related Koha::Patron object for this hold
426
427 =cut
428
429 sub patron {
430     my ($self) = @_;
431
432     my $patron_rs = $self->_result->patron;
433     return Koha::Patron->_new_from_dbic($patron_rs);
434 }
435
436 =head3 item
437
438 Returns the related Koha::Item object for this Hold
439
440 =cut
441
442 sub item {
443     my ($self) = @_;
444
445     $self->{_item} ||= Koha::Items->find( $self->itemnumber() );
446
447     return $self->{_item};
448 }
449
450 =head3 branch
451
452 Returns the related Koha::Library object for this Hold
453
454 =cut
455
456 sub branch {
457     my ($self) = @_;
458
459     $self->{_branch} ||= Koha::Libraries->find( $self->branchcode() );
460
461     return $self->{_branch};
462 }
463
464 =head3 desk
465
466 Returns the related Koha::Desk object for this Hold
467
468 =cut
469
470 sub desk {
471     my $self = shift;
472     my $desk_rs = $self->_result->desk;
473     return unless $desk_rs;
474     return Koha::Desk->_new_from_dbic($desk_rs);
475 }
476
477 =head3 borrower
478
479 Returns the related Koha::Patron object for this Hold
480
481 =cut
482
483 # FIXME Should be renamed with ->patron
484 sub borrower {
485     my ($self) = @_;
486
487     $self->{_borrower} ||= Koha::Patrons->find( $self->borrowernumber() );
488
489     return $self->{_borrower};
490 }
491
492 =head3 is_suspended
493
494 my $bool = $hold->is_suspended();
495
496 =cut
497
498 sub is_suspended {
499     my ( $self ) = @_;
500
501     return $self->suspend();
502 }
503
504
505 =head3 cancel
506
507 my $cancel_hold = $hold->cancel(
508     {
509         [ charge_cancel_fee => 1||0, ]
510         [ cancellation_reason => $cancellation_reason, ]
511     }
512 );
513
514 Cancel a hold:
515 - The hold will be moved to the old_reserves table with a priority=0
516 - The priority of other holds will be updated
517 - The patron will be charge (see ExpireReservesMaxPickUpDelayCharge) if the charge_cancel_fee parameter is set
518 - The canceled hold will have the cancellation reason added to old_reserves.cancellation_reason if one is passed in
519 - a CANCEL HOLDS log will be done if the pref HoldsLog is on
520
521 =cut
522
523 sub cancel {
524     my ( $self, $params ) = @_;
525     $self->_result->result_source->schema->txn_do(
526         sub {
527             $self->cancellationdate( dt_from_string->strftime( '%Y-%m-%d %H:%M:%S' ) );
528             $self->priority(0);
529             $self->cancellation_reason( $params->{cancellation_reason} );
530             $self->store();
531
532             if ( $params->{cancellation_reason} ) {
533                 my $letter = C4::Letters::GetPreparedLetter(
534                     module                 => 'reserves',
535                     letter_code            => 'HOLD_CANCELLATION',
536                     message_transport_type => 'email',
537                     branchcode             => $self->borrower->branchcode,
538                     lang                   => $self->borrower->lang,
539                     tables => {
540                         branches    => $self->borrower->branchcode,
541                         borrowers   => $self->borrowernumber,
542                         items       => $self->itemnumber,
543                         biblio      => $self->biblionumber,
544                         biblioitems => $self->biblionumber,
545                         reserves    => $self->unblessed,
546                     }
547                 );
548
549                 if ($letter) {
550                     C4::Letters::EnqueueLetter(
551                         {
552                             letter                   => $letter,
553                             borrowernumber         => $self->borrowernumber,
554                             message_transport_type => 'email',
555                         }
556                     );
557                 }
558             }
559
560             $self->_move_to_old;
561             $self->SUPER::delete(); # Do not add a DELETE log
562
563             # now fix the priority on the others....
564             C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
565
566             # and, if desired, charge a cancel fee
567             my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
568             if ( $charge && $params->{'charge_cancel_fee'} ) {
569                 my $account =
570                   Koha::Account->new( { patron_id => $self->borrowernumber } );
571                 $account->add_debit(
572                     {
573                         amount     => $charge,
574                         user_id    => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
575                         interface  => C4::Context->interface,
576                         library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
577                         type       => 'RESERVE_EXPIRED',
578                         item_id    => $self->itemnumber
579                     }
580                 );
581             }
582
583             C4::Log::logaction( 'HOLDS', 'CANCEL', $self->reserve_id, $self )
584                 if C4::Context->preference('HoldsLog');
585         }
586     );
587     return $self;
588 }
589
590 =head3 store
591
592 Override base store method to set default
593 expirationdate for holds.
594
595 =cut
596
597 sub store {
598     my ($self) = @_;
599
600     if ( !$self->in_storage ) {
601         if ( ! $self->expirationdate && $self->patron_expiration_date ) {
602             $self->expirationdate($self->patron_expiration_date);
603         }
604
605         if (
606             C4::Context->preference('DefaultHoldExpirationdate')
607                 && !$self->expirationdate
608           )
609         {
610             $self->_set_default_expirationdate;
611         }
612     }
613     else {
614
615         my %updated_columns = $self->_result->get_dirty_columns;
616         return $self->SUPER::store unless %updated_columns;
617
618         if ( exists $updated_columns{reservedate} ) {
619             if (
620                 C4::Context->preference('DefaultHoldExpirationdate')
621                 && ! exists $updated_columns{expirationdate}
622               )
623             {
624                 $self->_set_default_expirationdate;
625             }
626         }
627     }
628
629     $self = $self->SUPER::store;
630 }
631
632 sub _set_default_expirationdate {
633     my $self = shift;
634
635     my $period = C4::Context->preference('DefaultHoldExpirationdatePeriod') || 0;
636     my $timeunit =
637       C4::Context->preference('DefaultHoldExpirationdateUnitOfTime') || 'days';
638
639     $self->expirationdate(
640         dt_from_string( $self->reservedate )->add( $timeunit => $period ) );
641 }
642
643 =head3 _move_to_old
644
645 my $is_moved = $hold->_move_to_old;
646
647 Move a hold to the old_reserve table following the same pattern as Koha::Patron->move_to_deleted
648
649 =cut
650
651 sub _move_to_old {
652     my ($self) = @_;
653     my $hold_infos = $self->unblessed;
654     return Koha::Old::Hold->new( $hold_infos )->store;
655 }
656
657 =head3 to_api_mapping
658
659 This method returns the mapping for representing a Koha::Hold object
660 on the API.
661
662 =cut
663
664 sub to_api_mapping {
665     return {
666         reserve_id       => 'hold_id',
667         borrowernumber   => 'patron_id',
668         reservedate      => 'hold_date',
669         biblionumber     => 'biblio_id',
670         branchcode       => 'pickup_library_id',
671         notificationdate => undef,
672         reminderdate     => undef,
673         cancellationdate => 'cancellation_date',
674         reservenotes     => 'notes',
675         found            => 'status',
676         itemnumber       => 'item_id',
677         waitingdate      => 'waiting_date',
678         expirationdate   => 'expiration_date',
679         lowestPriority   => 'lowest_priority',
680         suspend          => 'suspended',
681         suspend_until    => 'suspended_until',
682         itemtype         => 'item_type',
683         item_level_hold  => 'item_level',
684     };
685 }
686
687 =head2 Internal methods
688
689 =head3 _type
690
691 =cut
692
693 sub _type {
694     return 'Reserve';
695 }
696
697 =head1 AUTHORS
698
699 Kyle M Hall <kyle@bywatersolutions.com>
700 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
701 Martin Renvoize <martin.renvoize@ptfs-europe.com>
702
703 =cut
704
705 1;