Bug 29948: OPACAuthorIdentifiersAndInformation
[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 qw(preference);
26 use C4::Letters qw( GetPreparedLetter EnqueueLetter );
27 use C4::Log qw( logaction );
28 use C4::Reserves;
29
30 use Koha::AuthorisedValues;
31 use Koha::DateUtils qw( dt_from_string );
32 use Koha::Patrons;
33 use Koha::Biblios;
34 use Koha::Hold::CancellationRequests;
35 use Koha::Items;
36 use Koha::Libraries;
37 use Koha::Old::Holds;
38 use Koha::Calendar;
39 use Koha::Plugins;
40
41 use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue;
42
43 use Koha::Exceptions;
44 use Koha::Exceptions::Hold;
45
46 use base qw(Koha::Object);
47
48 =head1 NAME
49
50 Koha::Hold - Koha Hold object class
51
52 =head1 API
53
54 =head2 Class methods
55
56 =cut
57
58 =head3 age
59
60 returns the number of days since a hold was placed, optionally
61 using the calendar
62
63 my $age = $hold->age( $use_calendar );
64
65 =cut
66
67 sub age {
68     my ( $self, $use_calendar ) = @_;
69
70     my $today = dt_from_string;
71     my $age;
72
73     if ( $use_calendar ) {
74         my $calendar = Koha::Calendar->new( branchcode => $self->branchcode );
75         $age = $calendar->days_between( dt_from_string( $self->reservedate ), $today );
76     }
77     else {
78         $age = $today->delta_days( dt_from_string( $self->reservedate ) );
79     }
80
81     $age = $age->in_units( 'days' );
82
83     return $age;
84 }
85
86 =head3 suspend_hold
87
88 my $hold = $hold->suspend_hold( $suspend_until );
89
90 =cut
91
92 sub suspend_hold {
93     my ( $self, $date ) = @_;
94
95     my $original = C4::Context->preference('HoldsLog') ? $self->unblessed : undef;
96
97     $date &&= dt_from_string($date)->truncate( to => 'day' )->datetime;
98
99     if ( $self->is_found ) {    # We can't suspend found holds
100         if ( $self->is_waiting ) {
101             Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'W' );
102         }
103         elsif ( $self->is_in_transit ) {
104             Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'T' );
105         }
106         elsif ( $self->is_in_processing ) {
107             Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'P' );
108         }
109         else {
110             Koha::Exceptions::Hold::CannotSuspendFound->throw(
111                       'Unhandled data exception on found hold (id='
112                     . $self->id
113                     . ', found='
114                     . $self->found
115                     . ')' );
116         }
117     }
118
119     $self->suspend(1);
120     $self->suspend_until($date);
121     $self->store();
122
123     Koha::Plugins->call(
124         'after_hold_action',
125         {
126             action  => 'suspend',
127             payload => { hold => $self->get_from_storage }
128         }
129     );
130
131     logaction( 'HOLDS', 'SUSPEND', $self->reserve_id, $self, undef, $original )
132         if C4::Context->preference('HoldsLog');
133
134     Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
135         {
136             biblio_ids => [ $self->biblionumber ]
137         }
138     ) if C4::Context->preference('RealTimeHoldsQueue');
139
140     return $self;
141 }
142
143 =head3 resume
144
145 my $hold = $hold->resume();
146
147 =cut
148
149 sub resume {
150     my ( $self ) = @_;
151
152     my $original = C4::Context->preference('HoldsLog') ? $self->unblessed : undef;
153
154     $self->suspend(0);
155     $self->suspend_until( undef );
156
157     $self->store();
158
159     Koha::Plugins->call(
160         'after_hold_action',
161         {
162             action  => 'resume',
163             payload => { hold => $self->get_from_storage }
164         }
165     );
166
167     logaction( 'HOLDS', 'RESUME', $self->reserve_id, $self, undef, $original )
168         if C4::Context->preference('HoldsLog');
169
170     Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
171         {
172             biblio_ids => [ $self->biblionumber ]
173         }
174     ) if C4::Context->preference('RealTimeHoldsQueue');
175
176     return $self;
177 }
178
179 =head3 delete
180
181 $hold->delete();
182
183 =cut
184
185 sub delete {
186     my ( $self ) = @_;
187
188     my $deleted = $self->SUPER::delete($self);
189
190     logaction( 'HOLDS', 'DELETE', $self->reserve_id, $self )
191         if C4::Context->preference('HoldsLog');
192
193     return $deleted;
194 }
195
196 =head3 set_transfer
197
198 =cut
199
200 sub set_transfer {
201     my ( $self ) = @_;
202
203     $self->priority(0);
204     $self->found('T');
205     $self->store();
206
207     Koha::Plugins->call(
208         'after_hold_action',
209         {
210             action  => 'transfer',
211             payload => { hold => $self->get_from_storage }
212         }
213     );
214
215     return $self;
216 }
217
218 =head3 set_waiting
219
220 =cut
221
222 sub set_waiting {
223     my ( $self, $desk_id ) = @_;
224
225     $self->priority(0);
226
227     my $today = dt_from_string();
228
229     my $values = {
230         found => 'W',
231         ( !$self->waitingdate ? ( waitingdate => $today->ymd ) : () ),
232         desk_id => $desk_id,
233     };
234
235     my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
236     my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
237
238     my $rule = Koha::CirculationRules->get_effective_rule(
239         {
240             categorycode => $self->borrower->categorycode,
241             itemtype     => $self->item->effective_itemtype,
242             branchcode   => $self->branchcode,
243             rule_name    => 'holds_pickup_period',
244         }
245     );
246     if ( defined($rule) and $rule->rule_value ne '' ) {
247
248         # circulation rule overrides ReservesMaxPickUpDelay
249         $max_pickup_delay = $rule->rule_value;
250     }
251
252     my $new_expiration_date = dt_from_string($self->waitingdate)->clone->add( days => $max_pickup_delay );
253
254     if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
255         my $itemtype = $self->item ? $self->item->effective_itemtype : $self->biblio->itemtype;
256         my $daysmode = Koha::CirculationRules->get_effective_daysmode(
257             {
258                 categorycode => $self->borrower->categorycode,
259                 itemtype     => $itemtype,
260                 branchcode   => $self->branchcode,
261             }
262         );
263         my $calendar = Koha::Calendar->new( branchcode => $self->branchcode, days_mode => $daysmode );
264
265         $new_expiration_date = $calendar->days_forward( dt_from_string($self->waitingdate), $max_pickup_delay );
266     }
267
268     # If patron's requested expiration date is prior to the
269     # calculated one, we keep the patron's one.
270     if ( $self->patron_expiration_date ) {
271         my $requested_expiration = dt_from_string( $self->patron_expiration_date );
272
273         my $cmp =
274           $requested_expiration
275           ? DateTime->compare( $requested_expiration, $new_expiration_date )
276           : 0;
277
278         $new_expiration_date =
279           $cmp == -1 ? $requested_expiration : $new_expiration_date;
280     }
281
282     $values->{expirationdate} = $new_expiration_date->ymd;
283
284     $self->set($values)->store();
285
286     Koha::Plugins->call(
287         'after_hold_action',
288         {
289             action  => 'waiting',
290             payload => { hold => $self->get_from_storage }
291         }
292     );
293
294     return $self;
295 }
296
297 =head3 is_pickup_location_valid
298
299     if ($hold->is_pickup_location_valid({ library_id => $library->id }) ) {
300         ...
301     }
302
303 Returns a I<boolean> representing if the passed pickup location is valid for the hold.
304 It throws a I<Koha::Exceptions::_MissingParameter> if the library_id parameter is not
305 passed.
306
307 =cut
308
309 sub is_pickup_location_valid {
310     my ( $self, $params ) = @_;
311
312     Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
313         unless $params->{library_id};
314
315     my $pickup_locations;
316
317     if ( $self->itemnumber ) { # item-level
318         $pickup_locations = $self->item->pickup_locations({ patron => $self->patron });
319     }
320     else { # biblio-level
321         $pickup_locations = $self->biblio->pickup_locations({ patron => $self->patron });
322     }
323
324     return any { $_->branchcode eq $params->{library_id} } $pickup_locations->as_list;
325 }
326
327 =head3 set_pickup_location
328
329     $hold->set_pickup_location(
330         {
331             library_id => $library->id,
332           [ force   => 0|1 ]
333         }
334     );
335
336 Updates the hold pickup location. It throws a I<Koha::Exceptions::Hold::InvalidPickupLocation> if
337 the passed pickup location is not valid.
338
339 Note: It is up to the caller to verify if I<AllowHoldPolicyOverride> is set when setting the
340 B<force> parameter.
341
342 =cut
343
344 sub set_pickup_location {
345     my ( $self, $params ) = @_;
346
347     Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
348         unless $params->{library_id};
349
350     if (
351         $params->{force}
352         || $self->is_pickup_location_valid(
353             { library_id => $params->{library_id} }
354         )
355       )
356     {
357         # all good, set the new pickup location
358         $self->branchcode( $params->{library_id} )->store;
359     }
360     else {
361         Koha::Exceptions::Hold::InvalidPickupLocation->throw;
362     }
363
364     return $self;
365 }
366
367 =head3 set_processing
368
369 $hold->set_processing;
370
371 Mark the hold as in processing.
372
373 =cut
374
375 sub set_processing {
376     my ( $self ) = @_;
377
378     $self->priority(0);
379     $self->found('P');
380     $self->store();
381
382     Koha::Plugins->call(
383         'after_hold_action',
384         {
385             action  => 'processing',
386             payload => { hold => $self->get_from_storage }
387         }
388     );
389
390     return $self;
391 }
392
393 =head3 is_found
394
395 Returns true if hold is waiting, in transit or in processing
396
397 =cut
398
399 sub is_found {
400     my ($self) = @_;
401
402     return 0 unless $self->found();
403     return 1 if $self->found() eq 'W';
404     return 1 if $self->found() eq 'T';
405     return 1 if $self->found() eq 'P';
406 }
407
408 =head3 is_waiting
409
410 Returns true if hold is a waiting hold
411
412 =cut
413
414 sub is_waiting {
415     my ($self) = @_;
416
417     my $found = $self->found;
418     return $found && $found eq 'W';
419 }
420
421 =head3 is_in_transit
422
423 Returns true if hold is a in_transit hold
424
425 =cut
426
427 sub is_in_transit {
428     my ($self) = @_;
429
430     return 0 unless $self->found();
431     return $self->found() eq 'T';
432 }
433
434 =head3 is_in_processing
435
436 Returns true if hold is a in_processing hold
437
438 =cut
439
440 sub is_in_processing {
441     my ($self) = @_;
442
443     return 0 unless $self->found();
444     return $self->found() eq 'P';
445 }
446
447 =head3 is_cancelable_from_opac
448
449 Returns true if hold is a cancelable hold
450
451 Holds may be only canceled if they are not found.
452
453 This is used from the OPAC.
454
455 =cut
456
457 sub is_cancelable_from_opac {
458     my ($self) = @_;
459
460     return 1 unless $self->is_found();
461     return 0; # if ->is_in_transit or if ->is_waiting or ->is_in_processing
462 }
463
464 =head3 cancellation_requestable_from_opac
465
466     if ( $hold->cancellation_requestable_from_opac ) { ... }
467
468 Returns a I<boolean> representing if a cancellation request can be placed on the hold
469 from the OPAC. It targets holds that cannot be cancelled from the OPAC (see the
470 B<is_cancelable_from_opac> method above), but for which circulation rules allow
471 requesting cancellation.
472
473 Throws a B<Koha::Exceptions::InvalidStatus> exception with the following I<invalid_status>
474 values:
475
476 =over 4
477
478 =item B<'hold_not_waiting'>: the hold is expected to be waiting and it is not.
479
480 =item B<'no_item_linked'>: the waiting hold doesn't have an item properly linked.
481
482 =back
483
484 =cut
485
486 sub cancellation_requestable_from_opac {
487     my ( $self ) = @_;
488
489     Koha::Exceptions::InvalidStatus->throw( invalid_status => 'hold_not_waiting' )
490       unless $self->is_waiting;
491
492     my $item = $self->item;
493
494     Koha::Exceptions::InvalidStatus->throw( invalid_status => 'no_item_linked' )
495       unless $item;
496
497     my $patron = $self->patron;
498
499     my $controlbranch = $patron->branchcode;
500
501     if ( C4::Context->preference('ReservesControlBranch') eq 'ItemHomeLibrary' ) {
502         $controlbranch = $item->homebranch;
503     }
504
505     return Koha::CirculationRules->get_effective_rule_value(
506         {
507             categorycode => $patron->categorycode,
508             itemtype     => $item->itype,
509             branchcode   => $controlbranch,
510             rule_name    => 'waiting_hold_cancellation',
511         }
512     ) ? 1 : 0;
513 }
514
515 =head3 is_at_destination
516
517 Returns true if hold is waiting
518 and the hold's pickup branch matches
519 the hold item's holding branch
520
521 =cut
522
523 sub is_at_destination {
524     my ($self) = @_;
525
526     return $self->is_waiting() && ( $self->branchcode() eq $self->item()->holdingbranch() );
527 }
528
529 =head3 biblio
530
531 Returns the related Koha::Biblio object for this hold
532
533 =cut
534
535 sub biblio {
536     my ($self) = @_;
537     my $rs = $self->_result->biblionumber;
538     return Koha::Biblio->_new_from_dbic($rs);
539 }
540
541 =head3 patron
542
543 Returns the related Koha::Patron object for this hold
544
545 =cut
546
547 sub patron {
548     my ($self) = @_;
549     my $rs = $self->_result->patron;
550     return Koha::Patron->_new_from_dbic($rs);
551 }
552
553 =head3 item
554
555 Returns the related Koha::Item object for this Hold
556
557 =cut
558
559 sub item {
560     my ($self) = @_;
561     my $rs = $self->_result->itemnumber;
562     return unless $rs;
563     return Koha::Item->_new_from_dbic($rs);
564 }
565
566 =head3 item_group
567
568 Returns the related Koha::Biblio::ItemGroup object for this Hold
569
570 =cut
571
572 sub item_group {
573     my ($self) = @_;
574     my $rs = $self->_result->item_group;
575     return unless $rs;
576     return Koha::Biblio::ItemGroup->_new_from_dbic($rs);
577 }
578
579 =head3 branch
580
581 Returns the related Koha::Library object for this hold
582
583 DEPRECATED
584
585 =cut
586
587 sub branch {
588     return shift->pickup_library(@_);
589 }
590
591 =head3 pickup_library
592
593 Returns the related Koha::Library object for this hold
594
595 =cut
596
597 sub pickup_library {
598     my ($self) = @_;
599     my $rs = $self->_result->pickup_library;
600     return Koha::Library->_new_from_dbic($rs);
601 }
602
603 =head3 desk
604
605 Returns the related Koha::Desk object for this Hold
606
607 =cut
608
609 sub desk {
610     my $self = shift;
611     my $desk_rs = $self->_result->desk;
612     return unless $desk_rs;
613     return Koha::Desk->_new_from_dbic($desk_rs);
614 }
615
616 =head3 borrower
617
618 Returns the related Koha::Patron object for this Hold
619
620 =cut
621
622 # FIXME Should be renamed with ->patron
623 sub borrower {
624     my ($self) = @_;
625     my $rs = $self->_result->borrowernumber;
626     return Koha::Patron->_new_from_dbic($rs);
627 }
628
629 =head3 is_suspended
630
631 my $bool = $hold->is_suspended();
632
633 =cut
634
635 sub is_suspended {
636     my ( $self ) = @_;
637
638     return $self->suspend();
639 }
640
641 =head3 add_cancellation_request
642
643     my $cancellation_request = $hold->add_cancellation_request({ [ creation_date => $creation_date ] });
644
645 Adds a cancellation request to the hold. Returns the generated
646 I<Koha::Hold::CancellationRequest> object.
647
648 =cut
649
650 sub add_cancellation_request {
651     my ( $self, $params ) = @_;
652
653     my $request = Koha::Hold::CancellationRequest->new(
654         {   hold_id      => $self->id,
655             ( $params->{creation_date} ? ( creation_date => $params->{creation_date} ) : () ),
656         }
657     )->store;
658
659     $request->discard_changes;
660
661     return $request;
662 }
663
664 =head3 cancellation_requests
665
666     my $cancellation_requests = $hold->cancellation_requests;
667
668 Returns related a I<Koha::Hold::CancellationRequests> resultset.
669
670 =cut
671
672 sub cancellation_requests {
673     my ($self) = @_;
674
675     return Koha::Hold::CancellationRequests->search( { hold_id => $self->id } );
676 }
677
678 =head3 cancellation_requested
679
680     if ( $hold->cancellation_requested ) { ... }
681
682 Returns true if a cancellation request has been placed for the hold.
683
684 =cut
685
686 sub cancellation_requested {
687     my ($self) = @_;
688
689     return Koha::Hold::CancellationRequests->search( { hold_id => $self->id } )->count > 0;
690 }
691
692 =head3 cancel
693
694 my $cancel_hold = $hold->cancel(
695     {
696         [ charge_cancel_fee   => 1||0, ]
697         [ cancellation_reason => $cancellation_reason, ]
698         [ skip_holds_queue    => 1||0 ]
699     }
700 );
701
702 Cancel a hold:
703 - The hold will be moved to the old_reserves table with a priority=0
704 - The priority of other holds will be updated
705 - The patron will be charge (see ExpireReservesMaxPickUpDelayCharge) if the charge_cancel_fee parameter is set
706 - The canceled hold will have the cancellation reason added to old_reserves.cancellation_reason if one is passed in
707 - a CANCEL HOLDS log will be done if the pref HoldsLog is on
708
709 =cut
710
711 sub cancel {
712     my ( $self, $params ) = @_;
713
714     my $autofill_next = $params->{autofill} && $self->itemnumber && $self->found && $self->found eq 'W';
715
716     my $original = C4::Context->preference('HoldsLog') ? $self->unblessed : undef;
717
718     $self->_result->result_source->schema->txn_do(
719         sub {
720             my $patron = $self->patron;
721
722             $self->cancellationdate( dt_from_string->strftime( '%Y-%m-%d %H:%M:%S' ) );
723             $self->priority(0);
724             $self->cancellation_reason( $params->{cancellation_reason} );
725             $self->store();
726
727             my $dbh = $self->_result->result_source->schema->storage->dbh;
728             $dbh->do(
729                 q{
730                     DELETE  q, t
731                     FROM    tmp_holdsqueue q
732                     INNER JOIN hold_fill_targets t
733                     ON  q.borrowernumber = t.borrowernumber
734                         AND q.biblionumber = t.biblionumber
735                         AND q.itemnumber = t.itemnumber
736                         AND q.item_level_request = t.item_level_request
737                         AND q.holdingbranch = t.source_branchcode
738                     WHERE t.reserve_id = ?
739                 }, undef, $self->id
740             );
741
742             if ( $params->{cancellation_reason} ) {
743                 my $letter = C4::Letters::GetPreparedLetter(
744                     module                 => 'reserves',
745                     letter_code            => 'HOLD_CANCELLATION',
746                     message_transport_type => 'email',
747                     branchcode             => $self->borrower->branchcode,
748                     lang                   => $self->borrower->lang,
749                     tables => {
750                         branches    => $self->borrower->branchcode,
751                         borrowers   => $self->borrowernumber,
752                         items       => $self->itemnumber,
753                         biblio      => $self->biblionumber,
754                         biblioitems => $self->biblionumber,
755                         reserves    => $self->unblessed,
756                     }
757                 );
758
759                 if ($letter) {
760                     C4::Letters::EnqueueLetter(
761                         {
762                             letter                   => $letter,
763                             borrowernumber         => $self->borrowernumber,
764                             message_transport_type => 'email',
765                         }
766                     );
767                 }
768             }
769
770             my $old_me = $self->_move_to_old;
771
772             Koha::Plugins->call(
773                 'after_hold_action',
774                 {
775                     action  => 'cancel',
776                     payload => { hold => $old_me->get_from_storage }
777                 }
778             );
779
780             # anonymize if required
781             $old_me->anonymize
782                 if $patron->privacy == 2;
783
784             $self->SUPER::delete(); # Do not add a DELETE log
785             # now fix the priority on the others....
786             C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
787
788             # and, if desired, charge a cancel fee
789             my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
790             if ( $charge && $params->{'charge_cancel_fee'} ) {
791                 my $account =
792                   Koha::Account->new( { patron_id => $self->borrowernumber } );
793                 $account->add_debit(
794                     {
795                         amount     => $charge,
796                         user_id    => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
797                         interface  => C4::Context->interface,
798                         library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
799                         type       => 'RESERVE_EXPIRED',
800                         item_id    => $self->itemnumber
801                     }
802                 );
803             }
804
805             C4::Log::logaction( 'HOLDS', 'CANCEL', $self->reserve_id, $self, undef, $original )
806                 if C4::Context->preference('HoldsLog');
807
808             Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
809                 {
810                     biblio_ids => [ $old_me->biblionumber ]
811                 }
812             ) unless $params->{skip_holds_queue} or !C4::Context->preference('RealTimeHoldsQueue');
813         }
814     );
815
816     if ($autofill_next) {
817         my ( undef, $next_hold ) = C4::Reserves::CheckReserves( $self->item );
818         if ($next_hold) {
819             my $is_transfer = $self->branchcode ne $next_hold->{branchcode};
820
821             C4::Reserves::ModReserveAffect( $self->itemnumber, $self->borrowernumber, $is_transfer, $next_hold->{reserve_id}, $self->desk_id, $autofill_next );
822             C4::Items::ModItemTransfer( $self->itemnumber, $self->branchcode, $next_hold->{branchcode}, "Reserve" ) if $is_transfer;
823         }
824     }
825
826     return $self;
827 }
828
829 =head3 fill
830
831     $hold->fill({ [ item_id => $item->id ] });
832
833 This method marks the hold as filled. It effectively moves it to old_reserves.
834 The optional I<item_id> parameter is used to set the information about the
835 item that filled the hold.
836
837 =cut
838
839 sub fill {
840     my ( $self, $params ) = @_;
841     $self->_result->result_source->schema->txn_do(
842         sub {
843             my $patron = $self->patron;
844
845             my $original = C4::Context->preference('HoldsLog') ? $self->unblessed : undef;
846
847             $self->set(
848                 {
849                     found    => 'F',
850                     priority => 0,
851                     $params->{item_id} ? ( itemnumber => $params->{item_id} ) : (),
852                 }
853             );
854
855             my $old_me = $self->_move_to_old;
856
857             Koha::Plugins->call(
858                 'after_hold_action',
859                 {
860                     action  => 'fill',
861                     payload => { hold => $old_me->get_from_storage }
862                 }
863             );
864
865             # anonymize if required
866             $old_me->anonymize
867                 if $patron->privacy == 2;
868
869             $self->SUPER::delete(); # Do not add a DELETE log
870
871             # now fix the priority on the others....
872             C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
873
874             if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
875                 my $fee = $patron->category->reservefee // 0;
876                 if ( $fee > 0 ) {
877                     $patron->account->add_debit(
878                         {
879                             amount       => $fee,
880                             description  => $self->biblio->title,
881                             user_id      => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
882                             library_id   => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
883                             interface    => C4::Context->interface,
884                             type         => 'RESERVE',
885                             item_id      => $self->itemnumber
886                         }
887                     );
888                 }
889             }
890
891             C4::Log::logaction( 'HOLDS', 'FILL', $self->id, $self, undef, $original )
892                 if C4::Context->preference('HoldsLog');
893
894             Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
895                 {
896                     biblio_ids => [ $old_me->biblionumber ]
897                 }
898             ) if C4::Context->preference('RealTimeHoldsQueue');
899         }
900     );
901     return $self;
902 }
903
904 =head3 sub change_type
905
906     $hold->change_type                # to record level
907     $hold->change_type( $itemnumber ) # to item level
908
909 Changes hold type between record and item level holds, only if record has
910 exactly one hold for a patron. This is because Koha expects all holds for
911 a patron on a record to be alike.
912
913 =cut
914
915 sub change_type {
916     my ( $self, $itemnumber ) = @_;
917
918     my $record_holds_per_patron = Koha::Holds->search(
919         {
920             borrowernumber => $self->borrowernumber,
921             biblionumber   => $self->biblionumber,
922         }
923     );
924
925     if ( $itemnumber && $self->itemnumber ) {
926         $self->itemnumber($itemnumber)->store;
927         return $self;
928     }
929
930     if ( $record_holds_per_patron->count == 1 ) {
931         $self->set(
932             {
933                 itemnumber      => $itemnumber ? $itemnumber : undef,
934                 item_level_hold => $itemnumber ? 1           : 0,
935             }
936         )->store;
937     } else {
938         Koha::Exceptions::Hold::CannotChangeHoldType->throw();
939     }
940
941     return $self;
942 }
943
944 =head3 store
945
946 Override base store method to set default
947 expirationdate for holds.
948
949 =cut
950
951 sub store {
952     my ($self, $params) = @_;
953
954     my $hold_reverted = $params->{hold_reverted} // 0;
955
956     Koha::Exceptions::Hold::MissingPickupLocation->throw() unless $self->branchcode;
957
958     if ( !$self->in_storage ) {
959         if ( ! $self->expirationdate && $self->patron_expiration_date ) {
960             $self->expirationdate($self->patron_expiration_date);
961         }
962
963         if (
964             C4::Context->preference('DefaultHoldExpirationdate')
965                 && !$self->expirationdate
966           )
967         {
968             $self->_set_default_expirationdate;
969         }
970     }
971     else {
972
973         my %updated_columns = $self->_result->get_dirty_columns;
974         return $self->SUPER::store unless %updated_columns;
975         if ( exists $updated_columns{reservedate} || $hold_reverted ) {
976             if (
977                 (
978                     C4::Context->preference('DefaultHoldExpirationdate')
979                     && ( !exists $updated_columns{expirationdate} || $hold_reverted )
980                 )
981                 )
982             {
983                 if ( $self->patron_expiration_date ) {
984                     $self->expirationdate( $self->patron_expiration_date );
985                 } else {
986                     $self->_set_default_expirationdate;
987                 }
988             }
989         }
990     }
991
992     $self = $self->SUPER::store;
993 }
994
995 sub _set_default_expirationdate {
996     my $self = shift;
997
998     my $period = C4::Context->preference('DefaultHoldExpirationdatePeriod') || 0;
999     my $timeunit =
1000       C4::Context->preference('DefaultHoldExpirationdateUnitOfTime') || 'days';
1001
1002     $self->expirationdate(
1003         dt_from_string( $self->reservedate )->add( $timeunit => $period ) );
1004 }
1005
1006 =head3 _move_to_old
1007
1008 my $is_moved = $hold->_move_to_old;
1009
1010 Move a hold to the old_reserve table following the same pattern as Koha::Patron->move_to_deleted
1011
1012 =cut
1013
1014 sub _move_to_old {
1015     my ($self) = @_;
1016     my $hold_infos = $self->unblessed;
1017     return Koha::Old::Hold->new( $hold_infos )->store;
1018 }
1019
1020 =head3 to_api_mapping
1021
1022 This method returns the mapping for representing a Koha::Hold object
1023 on the API.
1024
1025 =cut
1026
1027 sub to_api_mapping {
1028     return {
1029         reserve_id       => 'hold_id',
1030         borrowernumber   => 'patron_id',
1031         reservedate      => 'hold_date',
1032         biblionumber     => 'biblio_id',
1033         branchcode       => 'pickup_library_id',
1034         notificationdate => undef,
1035         reminderdate     => undef,
1036         cancellationdate => 'cancellation_date',
1037         reservenotes     => 'notes',
1038         found            => 'status',
1039         itemnumber       => 'item_id',
1040         waitingdate      => 'waiting_date',
1041         expirationdate   => 'expiration_date',
1042         patron_expiration_date => undef,
1043         lowestPriority   => 'lowest_priority',
1044         suspend          => 'suspended',
1045         suspend_until    => 'suspended_until',
1046         itemtype         => 'item_type',
1047         item_level_hold  => 'item_level',
1048     };
1049 }
1050
1051 =head3 can_update_pickup_location_opac
1052
1053     my $can_update_pickup_location_opac = $hold->can_update_pickup_location_opac;
1054
1055 Returns if a hold can change pickup location from opac
1056
1057 =cut
1058
1059 sub can_update_pickup_location_opac {
1060     my ($self) = @_;
1061
1062     my @statuses = split /,/, C4::Context->preference("OPACAllowUserToChangeBranch");
1063     foreach my $status ( @statuses ){
1064         return 1 if ($status eq 'pending' && !$self->is_found && !$self->is_suspended );
1065         return 1 if ($status eq 'intransit' && $self->is_in_transit);
1066         return 1 if ($status eq 'suspended' && $self->is_suspended);
1067     }
1068     return 0;
1069 }
1070
1071 =head3 strings_map
1072
1073 Returns a map of column name to string representations including the string.
1074
1075 =cut
1076
1077 sub strings_map {
1078     my ($self) = @_;
1079     return {
1080         pickup_library_id => { str => $self->branch->branchname, type => 'library' },
1081     };
1082 }
1083
1084 =head2 Internal methods
1085
1086 =head3 _type
1087
1088 =cut
1089
1090 sub _type {
1091     return 'Reserve';
1092 }
1093
1094 =head1 AUTHORS
1095
1096 Kyle M Hall <kyle@bywatersolutions.com>
1097 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
1098 Martin Renvoize <martin.renvoize@ptfs-europe.com>
1099
1100 =cut
1101
1102 1;