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