-
Notifications
You must be signed in to change notification settings - Fork 257
/
Reserves.pm
2249 lines (1804 loc) · 79.4 KB
/
Reserves.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package C4::Reserves;
# Copyright 2000-2002 Katipo Communications
# 2006 SAN Ouest Provence
# 2007-2010 BibLibre Paul POULAIN
# 2011 Catalyst IT
#
# This file is part of Koha.
#
# Koha is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Koha is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Koha; if not, see <http://www.gnu.org/licenses>.
use Modern::Perl;
use C4::Accounts;
use C4::Biblio qw( GetMarcFromKohaField );
use C4::Circulation qw( CheckIfIssuedToPatron GetAgeRestriction GetBranchItemRule );
use C4::Context;
use C4::Items qw( CartToShelf get_hostitemnumbers_of );
use C4::Letters;
use C4::Log qw( logaction );
use C4::Members::Messaging;
use C4::Members;
use Koha::Account::Lines;
use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue;
use Koha::Biblios;
use Koha::Calendar;
use Koha::Cache::Memory::Lite;
use Koha::CirculationRules;
use Koha::Database;
use Koha::DateUtils qw( dt_from_string output_pref );
use Koha::Holds;
use Koha::ItemTypes;
use Koha::Items;
use Koha::Libraries;
use Koha::Patrons;
use Koha::Plugins;
use Koha::Policy::Holds;
use List::MoreUtils qw( any );
=head1 NAME
C4::Reserves - Koha functions for dealing with reservation.
=head1 SYNOPSIS
use C4::Reserves;
=head1 DESCRIPTION
This modules provides somes functions to deal with reservations.
Reserves are stored in reserves table.
The following columns contains important values :
- priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
=0 : then the reserve is being dealed
- found : NULL : means the patron requested the 1st available, and we haven't chosen the item
T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
F(inished) : the reserve has been completed, and is done
P(rocessing) : reserved item has been returned using self-check machine and reserve needs to be confirmed
by librarian before notice is send and status changed to waiting.
Applicable only if HoldsNeedProcessingSIP system preference is set.
- itemnumber : empty : the reserve is still unaffected to an item
filled: the reserve is attached to an item
The complete workflow is :
==== 1st use case ====
patron request a document, 1st available : P >0, F=NULL, I=NULL
a library having it run "transfertodo", and clic on the list
if there is no transfer to do, the reserve waiting
patron can pick it up P =0, F=W, I=filled
if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
The pickup library receive the book, it check in P =0, F=W, I=filled
The patron borrow the book P =0, F=F, I=filled
==== 2nd use case ====
patron requests a document, a given item,
If pickup is holding branch P =0, F=W, I=filled
If transfer needed, write in branchtransfer P =0, F=T, I=filled
The pickup library receive the book, it checks it in P =0, F=W, I=filled
The patron borrow the book P =0, F=F, I=filled
=head1 FUNCTIONS
=cut
our (@ISA, @EXPORT_OK);
BEGIN {
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(
AddReserve
GetReserveStatus
ChargeReserveFee
GetReserveFee
ModReserveAffect
ModReserve
ModReserveStatus
ModReserveCancelAll
ModReserveMinusPriority
MoveReserve
CheckReserves
CanBookBeReserved
CanItemBeReserved
CancelExpiredReserves
AutoUnsuspendReserves
IsAvailableForItemLevelRequest
ItemsAnyAvailableAndNotRestricted
AlterPriority
ToggleLowestPriority
ReserveSlip
SuspendAll
CalculatePriority
GetMaxPatronHoldsForRecord
MergeHolds
RevertWaitingStatus
);
}
=head2 AddReserve
AddReserve(
{
branchcode => $branchcode,
borrowernumber => $borrowernumber,
biblionumber => $biblionumber,
priority => $priority,
reservation_date => $reservation_date,
expiration_date => $expiration_date,
notes => $notes,
title => $title,
itemnumber => $itemnumber,
found => $found,
itemtype => $itemtype,
item_group_id => $item_group_id
}
);
Adds reserve and generates HOLDPLACED message and HOLDPLACED_PATRON message.
The following tables are available witin the HOLDPLACED message:
branches
borrowers
biblio
biblioitems
items
reserves
The following tables are available within the HOLDPLACED_PATRON message:
borrowers
reserves
=cut
sub AddReserve {
my ($params) = @_;
my $branch = $params->{branchcode};
my $borrowernumber = $params->{borrowernumber};
my $biblionumber = $params->{biblionumber};
my $priority = $params->{priority};
my $resdate = $params->{reservation_date};
my $patron_expiration_date = $params->{expiration_date};
my $notes = $params->{notes};
my $title = $params->{title};
my $checkitem = $params->{itemnumber};
my $found = $params->{found};
my $itemtype = $params->{itemtype};
my $non_priority = $params->{non_priority};
my $item_group_id = $params->{item_group_id};
$resdate ||= dt_from_string;
# if we have an item selectionned, and the pickup branch is the same as the holdingbranch
# of the document, we force the value $priority and $found .
if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
if (
# If item is already checked out, it cannot be set waiting
!$item->onloan
# The item can't be waiting if it needs a transfer
&& $item->holdingbranch eq $branch
# Similarly, if in transit it can't be waiting
&& !$item->get_transfer
# If we can't hold damaged items, and it is damaged, it can't be waiting
&& ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
# Lastly, if this already has holds, we shouldn't make it waiting for the new hold
&& !$item->current_holds->count )
{
$priority = 0;
$found = 'W';
}
}
if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
# Make room in reserves for this if passed a priority
$priority = _ShiftPriority( $biblionumber, $priority );
}
my $waitingdate;
# If the reserv had the waiting status, we had the value of the resdate
if ( $found && $found eq 'W' ) {
$waitingdate = $resdate;
}
# Don't add itemtype limit if specific item is selected
$itemtype = undef if $checkitem;
# updates take place here
my $hold = Koha::Hold->new(
{
borrowernumber => $borrowernumber,
biblionumber => $biblionumber,
item_group_id => $item_group_id,
reservedate => $resdate,
branchcode => $branch,
priority => $priority,
reservenotes => $notes,
itemnumber => $checkitem,
found => $found,
waitingdate => $waitingdate,
patron_expiration_date => $patron_expiration_date,
itemtype => $itemtype,
item_level_hold => $checkitem ? 1 : 0,
non_priority => $non_priority ? 1 : 0,
}
)->store();
$hold->set_waiting() if $found && $found eq 'W';
# record patron activity
$hold->patron->update_lastseen('hold');
logaction( 'HOLDS', 'CREATE', $hold->id, $hold )
if C4::Context->preference('HoldsLog');
my $reserve_id = $hold->id();
# add a reserve fee if needed
if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
}
_FixPriority({ biblionumber => $biblionumber});
# Send e-mail to librarian if syspref is active
if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
my $patron = $hold->patron;
my $library = $patron->library;
if ( my $letter = C4::Letters::GetPreparedLetter (
module => 'reserves',
letter_code => 'HOLDPLACED',
branchcode => $branch,
lang => $patron->lang,
tables => {
'branches' => $library->unblessed,
'borrowers' => $patron->unblessed,
'biblio' => $biblionumber,
'biblioitems' => $biblionumber,
'items' => $checkitem,
'reserves' => $hold->unblessed,
},
) ) {
my $branch_email_address = $library->inbound_email_address;
C4::Letters::EnqueueLetter(
{
letter => $letter,
borrowernumber => $borrowernumber,
message_transport_type => 'email',
to_address => $branch_email_address,
}
);
}
}
# Send email to patron if syspref is active
if ( C4::Context->preference("EmailPatronWhenHoldIsPlaced") ) {
my $patron = $hold->patron;
if (
my $letter = C4::Letters::GetPreparedLetter(
module => 'reserves',
letter_code => 'HOLDPLACED_PATRON',
branchcode => $branch,
lang => $patron->lang,
tables => {
borrowers => $patron->unblessed,
reserves => $hold->unblessed,
},
)
)
{
C4::Letters::EnqueueLetter(
{
letter => $letter,
borrowernumber => $borrowernumber,
message_transport_type => 'email',
to_address => $patron->notice_email_address,
}
);
}
}
Koha::Plugins->call('after_hold_create', $hold);
Koha::Plugins->call(
'after_hold_action',
{
action => 'place',
payload => { hold => $hold->get_from_storage }
}
);
Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
{
biblio_ids => [ $biblionumber ]
}
) if C4::Context->preference('RealTimeHoldsQueue');
return $reserve_id;
}
=head2 CanBookBeReserved
$canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
if ($canReserve eq 'OK') { #We can reserve this Item! }
$params are passed directly through to CanItemBeReserved
See CanItemBeReserved() for possible return values.
=cut
sub CanBookBeReserved{
my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
# Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
&& C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) {
return { status =>'alreadypossession' };
}
if ( $params->{itemtype} ) {
# biblio-level, item type-contrained
my $patron = Koha::Patrons->find($borrowernumber);
my $reservesallowed = Koha::CirculationRules->get_effective_rule(
{
itemtype => $params->{itemtype},
categorycode => $patron->categorycode,
branchcode => $pickup_branchcode,
rule_name => 'reservesallowed',
}
)->rule_value;
$reservesallowed = ( $reservesallowed eq '' ) ? undef : $reservesallowed;
my $count = $patron->holds->search(
{
'-or' => [
{ 'me.itemtype' => $params->{itemtype} },
{ 'item.itype' => $params->{itemtype} }
]
},
{
join => ['item']
}
)->count;
return { status => '' }
if defined $reservesallowed and $reservesallowed < $count + 1;
}
my $items;
#get items linked via host records
my @hostitemnumbers = get_hostitemnumbers_of($biblionumber);
if (@hostitemnumbers){
$items = Koha::Items->search({
-or => [
biblionumber => $biblionumber,
itemnumber => { -in => @hostitemnumbers }
]
});
} else {
$items = Koha::Items->search({ biblionumber => $biblionumber});
}
my $canReserve = { status => '' };
my $patron = Koha::Patrons->find( $borrowernumber );
while ( my $item = $items->next ) {
$canReserve = CanItemBeReserved( $patron, $item, $pickup_branchcode, $params );
return { status => 'OK' } if $canReserve->{status} eq 'OK';
}
return $canReserve;
}
=head2 CanItemBeReserved
$canReserve = &CanItemBeReserved($patron, $item, $branchcode, $params)
if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
current params are:
'ignore_hold_counts' - we use this routine to check if an item can fill a hold - on this case we
should not check if there are too many holds as we only care about reservability
@RETURNS { status => OK }, if the Item can be reserved.
{ status => ageRestricted }, if the Item is age restricted for this borrower.
{ status => damaged }, if the Item is damaged.
{ status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
{ status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
{ status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
{ status => notReservable }, if holds on this item are not allowed
{ status => libraryNotFound }, if given branchcode is not an existing library
{ status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
{ status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
{ status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
{ status => recall }, if the borrower has already placed a recall on this item
=cut
our $CanItemBeReserved_cache_key;
sub _cache {
my ( $return ) = @_;
my $memory_cache = Koha::Cache::Memory::Lite->get_instance();
$memory_cache->set_in_cache( $CanItemBeReserved_cache_key, $return );
return $return;
}
sub CanItemBeReserved {
my ( $patron, $item, $pickup_branchcode, $params ) = @_;
my $memory_cache = Koha::Cache::Memory::Lite->get_instance();
$CanItemBeReserved_cache_key = sprintf "Hold_CanItemBeReserved:%s:%s:%s", $patron->borrowernumber, $item->itemnumber, $pickup_branchcode || "";
if ( $params->{get_from_cache} ) {
my $cached = $memory_cache->get_from_cache($CanItemBeReserved_cache_key);
return $cached if $cached;
}
my $dbh = C4::Context->dbh;
my $ruleitemtype; # itemtype of the matching issuing rule
my $allowedreserves = 0; # Total number of holds allowed across all records, default to none
# We check item branch if IndependentBranches is ON
# and canreservefromotherbranches is OFF
if ( C4::Context->preference('IndependentBranches')
and !C4::Context->preference('canreservefromotherbranches') )
{
if ( $item->homebranch ne $patron->branchcode ) {
return _cache { status => 'cannotReserveFromOtherBranches' };
}
}
# If an item is damaged and we don't allow holds on damaged items, we can stop right here
return _cache { status =>'damaged' }
if ( $item->damaged
&& !C4::Context->preference('AllowHoldsOnDamagedItems') );
if( GetMarcFromKohaField('biblioitems.agerestriction') ){
my $biblio = $item->biblio;
# Check for the age restriction
my $ageRestriction = C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction );
return _cache { status => 'ageRestricted' } if $ageRestriction && $patron->dateofbirth && $ageRestriction > $patron->get_age();
}
# Check that the patron doesn't have an item level hold on this item already
return _cache { status =>'itemAlreadyOnHold' }
if ( !$params->{ignore_hold_counts} && Koha::Holds->search( { borrowernumber => $patron->borrowernumber, itemnumber => $item->itemnumber } )->count() );
# Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
&& C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $item->biblionumber ) ) {
return _cache { status =>'alreadypossession' };
}
# check if a recall exists on this item from this borrower
return _cache { status => 'recall' }
if $patron->recalls->filter_by_current->search({ item_id => $item->itemnumber })->count;
my $controlbranch = C4::Context->preference('ReservesControlBranch');
my $reserves_control_branch;
my $branchfield = "reserves.branchcode";
if ( $controlbranch eq "ItemHomeLibrary" ) {
$branchfield = "items.homebranch";
$reserves_control_branch = $item->homebranch;
}
elsif ( $controlbranch eq "PatronLibrary" ) {
$branchfield = "borrowers.branchcode";
$reserves_control_branch = $patron->branchcode;
}
# we retrieve rights
if (
my $reservesallowed = Koha::CirculationRules->get_effective_rule({
itemtype => $item->effective_itemtype,
categorycode => $patron->categorycode,
branchcode => $reserves_control_branch,
rule_name => 'reservesallowed',
})
) {
$ruleitemtype = $reservesallowed->itemtype;
$allowedreserves = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited
}
else {
$ruleitemtype = undef;
}
my $rights = Koha::CirculationRules->get_effective_rules({
categorycode => $patron->categorycode,
itemtype => $item->effective_itemtype,
branchcode => $reserves_control_branch,
rules => ['holds_per_record','holds_per_day']
});
my $holds_per_record = $rights->{holds_per_record} // 1;
my $holds_per_day = $rights->{holds_per_day};
if ( defined $holds_per_record && $holds_per_record ne '' ){
if ( $holds_per_record == 0 ) {
return _cache { status => "noReservesAllowed" };
}
if ( !$params->{ignore_hold_counts} ) {
my $search_params = {
borrowernumber => $patron->borrowernumber,
biblionumber => $item->biblionumber,
};
my $holds = Koha::Holds->search($search_params);
return _cache { status => "tooManyHoldsForThisRecord", limit => $holds_per_record } if $holds->count() >= $holds_per_record;
}
}
if (!$params->{ignore_hold_counts} && defined $holds_per_day && $holds_per_day ne '')
{
my $today_holds = Koha::Holds->search({
borrowernumber => $patron->borrowernumber,
reservedate => dt_from_string->date
});
return _cache { status => 'tooManyReservesToday', limit => $holds_per_day } if $today_holds->count() >= $holds_per_day;
}
# we check if it's ok or not
if ( defined $allowedreserves && $allowedreserves ne '' ){
if( $allowedreserves == 0 ){
return _cache { status => 'noReservesAllowed' };
}
if ( !$params->{ignore_hold_counts} ) {
# we retrieve count
my $querycount = q{
SELECT count(*) AS count
FROM reserves
LEFT JOIN items USING (itemnumber)
LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
LEFT JOIN borrowers USING (borrowernumber)
WHERE borrowernumber = ?
};
$querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
# If using item-level itypes, fall back to the record
# level itemtype if the hold has no associated item
if ( defined $ruleitemtype ) {
if ( C4::Context->preference('item-level_itypes') ) {
$querycount .= q{
AND ( COALESCE( items.itype, biblioitems.itemtype ) = ?
OR reserves.itemtype = ? )
};
}
else {
$querycount .= q{
AND ( biblioitems.itemtype = ?
OR reserves.itemtype = ? )
};
}
}
my $sthcount = $dbh->prepare($querycount);
if ( defined $ruleitemtype ) {
$sthcount->execute( $patron->borrowernumber, $reserves_control_branch, $ruleitemtype, $ruleitemtype );
}
else {
$sthcount->execute( $patron->borrowernumber, $reserves_control_branch );
}
my $reservecount = "0";
if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
$reservecount = $rowcount->{count};
}
return _cache { status => 'tooManyReserves', limit => $allowedreserves } if $reservecount >= $allowedreserves;
}
}
# Now we need to check hold limits by patron category
my $rule = Koha::CirculationRules->get_effective_rule(
{
categorycode => $patron->categorycode,
branchcode => $reserves_control_branch,
rule_name => 'max_holds',
}
);
if (!$params->{ignore_hold_counts} && $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
my $total_holds_count = Koha::Holds->search(
{
borrowernumber => $patron->borrowernumber
}
)->count();
return _cache { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
}
my $branchitemrule =
C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->effective_itemtype );
if ( $branchitemrule->{holdallowed} eq 'not_allowed' ) {
return _cache { status => 'notReservable' };
}
if ( $branchitemrule->{holdallowed} eq 'from_home_library'
&& $patron->branchcode ne $item->homebranch )
{
return _cache { status => 'cannotReserveFromOtherBranches' };
}
my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
if ( $branchitemrule->{holdallowed} eq 'from_local_hold_group') {
if($patron->branchcode ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} )) {
return _cache { status => 'branchNotInHoldGroup' };
}
}
if ($pickup_branchcode) {
my $destination = Koha::Libraries->find({
branchcode => $pickup_branchcode,
});
unless ($destination) {
return _cache { status => 'libraryNotFound' };
}
unless ($destination->pickup_location) {
return _cache { status => 'libraryNotPickupLocation' };
}
unless ($item->can_be_transferred({ to => $destination })) {
return _cache { status => 'cannotBeTransferred' };
}
if ($branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' && !$item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
return _cache { status => 'pickupNotInHoldGroup' };
}
if ($branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' && !Koha::Libraries->find({branchcode => $patron->branchcode})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
return _cache { status => 'pickupNotInHoldGroup' };
}
}
return _cache { status => 'OK' };
}
=head2 ChargeReserveFee
$fee = ChargeReserveFee( $borrowernumber, $fee, $title );
Charge the fee for a reserve (if $fee > 0)
=cut
sub ChargeReserveFee {
my ( $borrowernumber, $fee, $title ) = @_;
return if !$fee || $fee == 0; # the last test is needed to include 0.00
Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
{
amount => $fee,
description => $title,
note => undef,
user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
interface => C4::Context->interface,
invoice_type => undef,
type => 'RESERVE',
item_id => undef
}
);
}
=head2 GetReserveFee
$fee = GetReserveFee( $borrowernumber, $biblionumber );
Calculate the fee for a reserve (if applicable).
=cut
sub GetReserveFee {
my ( $borrowernumber, $biblionumber ) = @_;
my $borquery = qq{
SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
};
my $issue_qry = qq{
SELECT COUNT(*) FROM items
LEFT JOIN issues USING (itemnumber)
WHERE items.biblionumber=? AND issues.issue_id IS NULL
};
my $holds_qry = qq{
SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
};
my $dbh = C4::Context->dbh;
my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
$fee += 0;
my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
# This is a reconstruction of the old code:
# Compare number of items with items issued, and optionally check holds
# If not all items are issued and there are no holds: charge no fee
# NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
my ( $notissued, $reserved );
( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
( $biblionumber ) );
if( $notissued == 0 ) {
# all items are issued
( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
( $biblionumber, $borrowernumber ) );
$fee = 0 if $reserved == 0;
} else {
$fee = 0;
}
}
return $fee;
}
=head2 GetReserveStatus
$reservestatus = GetReserveStatus($itemnumber);
Takes an itemnumber and returns the status of the reserve placed on it.
If several reserves exist, the reserve with the lower priority is given.
=cut
## FIXME: I don't think this does what it thinks it does.
## It only ever checks the first reserve result, even though
## multiple reserves for that bib can have the itemnumber set
## the sub is only used once in the codebase.
sub GetReserveStatus {
my ($itemnumber) = @_;
my $dbh = C4::Context->dbh;
my ($sth, $found, $priority);
if ( $itemnumber ) {
$sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
$sth->execute($itemnumber);
($found, $priority) = $sth->fetchrow_array;
}
if(defined $found) {
return 'Waiting' if $found eq 'W' and $priority == 0;
return 'Processing' if $found eq 'P';
return 'Finished' if $found eq 'F';
}
return 'Reserved' if defined $priority && $priority > 0;
return ''; # empty string here will remove need for checking undef, or less log lines
}
=head2 CheckReserves
($status, $matched_reserve, $possible_reserves) = &CheckReserves($item);
($status, $matched_reserve, $possible_reserves) = &CheckReserves($item, $lookahead);
Find a book in the reserves.
C<$item> is the book's item.
C<$lookahead> is the number of days to look in advance for future reserves.
As I understand it, C<&CheckReserves> looks for the given item in the
reserves. If it is found, that's a match, and C<$status> is set to
C<Waiting>.
Otherwise, it finds the most important item in the reserves with the
same biblio number as this book (I'm not clear on this) and returns it
with C<$status> set to C<Reserved>.
C<&CheckReserves> returns a two-element list:
C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
C<$reserve> is the reserve item that matched. It is a
reference-to-hash whose keys are mostly the fields of the reserves
table in the Koha database.
=cut
sub CheckReserves {
my ( $item, $lookahead_days, $ignore_borrowers ) = @_;
# note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
return unless $item; # bail if we got nothing.
return if ( $item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
# if item is not for loan it cannot be reserved either.....
# except where items.notforloan < 0 : This indicates the item is holdable.
my @SkipHoldTrapOnNotForLoanValue = split( '\|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
return if grep { $_ eq $item->notforloan } @SkipHoldTrapOnNotForLoanValue;
my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? $item->notforloan > 0 : $item->notforloan;
if ( !$dont_trap ) {
my $item_type = $item->effective_itemtype;
if ( $item_type ) {
return if Koha::ItemTypes->find( $item_type )->notforloan;
}
}
else {
return;
}
# Find this item in the reserves
my @reserves = _Findgroupreserve( $item->biblionumber, $item->itemnumber, $lookahead_days, $ignore_borrowers);
# $priority and $highest are used to find the most important item
# in the list returned by &_Findgroupreserve. (The lower $priority,
# the more important the item.)
# $highest is the most important item we've seen so far.
my $highest;
if (scalar @reserves) {
my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
my $priority = 10000000;
foreach my $res (@reserves) {
if ($res->{'found'} && $res->{'found'} eq 'W') {
return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
} elsif ($res->{'found'} && $res->{'found'} eq 'P') {
return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
} elsif ($res->{'found'} && $res->{'found'} eq 'T') {
return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
} else {
my $patron;
my $local_hold_match;
if ($LocalHoldsPriority) {
$patron = Koha::Patrons->find( $res->{borrowernumber} );
unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
my $local_holds_priority_item_branchcode =
$item->$LocalHoldsPriorityItemControl;
my $local_holds_priority_patron_branchcode =
( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
? $res->{branchcode}
: ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
? $patron->branchcode
: undef;
$local_hold_match =
$local_holds_priority_item_branchcode eq
$local_holds_priority_patron_branchcode;
}
}
# See if this item is more important than what we've got so far
if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
next if $res->{item_group_id} && ( !$item->item_group || $item->item_group->id != $res->{item_group_id} );
next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
$patron //= Koha::Patrons->find( $res->{borrowernumber} );
my $branch = Koha::Policy::Holds->holds_control_library( $item, $patron );
my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
next if ($branchitemrule->{'holdallowed'} eq 'not_allowed');
next if (($branchitemrule->{'holdallowed'} eq 'from_home_library') && ($item->homebranch ne $patron->branchcode));
my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
next if (($branchitemrule->{'holdallowed'} eq 'from_local_hold_group') && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
$priority = $res->{'priority'};
$highest = $res;
last if $local_hold_match;
}
}
}
}
# If we get this far, then no exact match was found.
# We return the most important (i.e. next) reservation.
if ($highest) {
$highest->{'itemnumber'} = $item->itemnumber;
return ( "Reserved", $highest, \@reserves );
}
return ( '' );
}
=head2 CancelExpiredReserves
CancelExpiredReserves();
Cancels all reserves with an expiration date from before today.
=cut
sub CancelExpiredReserves {
my $cancellation_reason = shift;
my $today = dt_from_string();
my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
my $dtf = Koha::Database->new->schema->storage->datetime_parser;
my $params = {
-or => [
{ expirationdate => { '<', $dtf->format_date($today) } },
{ patron_expiration_date => { '<' => $dtf->format_date($today) } }
]
};
$params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
# FIXME To move to Koha::Holds->search_expired (?)
my $holds = Koha::Holds->search( $params );
while ( my $hold = $holds->next ) {
my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
next if !$cancel_on_holidays && $calendar->is_holiday( $today );
my $cancel_params = {};
$cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason);
if ( defined($hold->found) && $hold->found eq 'W' ) {
$cancel_params->{charge_cancel_fee} = 1;
}
$cancel_params->{autofill} = C4::Context->preference('ExpireReservesAutoFill');
$hold->cancel( $cancel_params );
}
}
=head2 AutoUnsuspendReserves
AutoUnsuspendReserves();
Unsuspends all suspended reserves with a suspend_until date from before today.
=cut
sub AutoUnsuspendReserves {
my $today = dt_from_string();
my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } )->as_list;
map { $_->resume() } @holds;
}
=head2 ModReserve
ModReserve({ rank => $rank,
reserve_id => $reserve_id,
branchcode => $branchcode
[, itemnumber => $itemnumber ]
[, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
});
Change a hold request's priority or cancel it.
C<$rank> specifies the effect of the change. If C<$rank>
is 'n', nothing happens. This corresponds to leaving a
request alone when changing its priority in the holds queue
for a bib.
If C<$rank> is 'del', the hold request is cancelled.