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