-
Notifications
You must be signed in to change notification settings - Fork 257
/
Circulation.pm
4682 lines (3835 loc) · 172 KB
/
Circulation.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::Circulation;
# Copyright 2000-2002 Katipo Communications
# copyright 2010 BibLibre
#
# 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 DateTime;
use POSIX qw( floor );
use Encode;
use C4::Context;
use C4::Stats qw( UpdateStats );
use C4::Reserves qw( CheckReserves CanItemBeReserved MoveReserve ModReserve ModReserveMinusPriority RevertWaitingStatus IsAvailableForItemLevelRequest );
use C4::Biblio qw( UpdateTotalIssues );
use C4::Items qw( ModItemTransfer ModDateLastSeen CartToShelf );
use C4::Accounts;
use C4::ItemCirculationAlertPreference;
use C4::Message;
use C4::Log qw( logaction ); # logaction
use C4::Overdues;
use C4::RotatingCollections qw(GetCollectionItemBranches);
use Algorithm::CheckDigits qw( CheckDigits );
use Data::Dumper qw( Dumper );
use Koha::Account;
use Koha::AuthorisedValues;
use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue;
use Koha::Biblioitems;
use Koha::DateUtils qw( dt_from_string );
use Koha::Calendar;
use Koha::Checkouts;
use Koha::ILL::Requests;
use Koha::Items;
use Koha::Patrons;
use Koha::Patron::Debarments qw( DelUniqueDebarment AddUniqueDebarment );
use Koha::Database;
use Koha::Libraries;
use Koha::Account::Lines;
use Koha::Holds;
use Koha::Account::Lines;
use Koha::Account::Offsets;
use Koha::Config::SysPrefs;
use Koha::Charges::Fees;
use Koha::Config::SysPref;
use Koha::Checkouts::ReturnClaims;
use Koha::SearchEngine::Indexer;
use Koha::Exceptions::Checkout;
use Koha::Plugins;
use Koha::Recalls;
use Koha::Library::Hours;
use Carp qw( carp );
use List::MoreUtils qw( any );
use Scalar::Util qw( looks_like_number blessed );
use Date::Calc qw( Date_to_Days );
our (@ISA, @EXPORT_OK);
BEGIN {
require Exporter;
@ISA = qw(Exporter);
# FIXME subs that should probably be elsewhere
push @EXPORT_OK, qw(
barcodedecode
LostItem
ReturnLostItem
GetPendingOnSiteCheckouts
CanBookBeIssued
checkHighHolds
CanBookBeRenewed
AddIssue
GetLoanLength
GetHardDueDate
AddRenewal
GetRenewCount
GetSoonestRenewDate
GetLatestAutoRenewDate
GetIssuingCharges
AddIssuingCharge
GetBranchBorrowerCircRule
GetBranchItemRule
GetBiblioIssues
GetUpcomingDueIssues
CheckIfIssuedToPatron
IsItemIssued
GetAgeRestriction
GetTopIssues
AddReturn
MarkIssueReturned
transferbook
TooMany
GetTransfersFromTo
CalcDateDue
CheckValidBarcode
IsBranchTransferAllowed
CreateBranchTransferLimit
DeleteBranchTransferLimits
TransferSlip
GetOfflineOperations
GetOfflineOperation
AddOfflineOperation
DeleteOfflineOperation
ProcessOfflineOperation
ProcessOfflinePayment
ProcessOfflineIssue
);
push @EXPORT_OK, '_GetCircControlBranch'; # This is wrong!
}
=head1 NAME
C4::Circulation - Koha circulation module
=head1 SYNOPSIS
use C4::Circulation;
=head1 DESCRIPTION
The functions in this module deal with circulation, issues, and
returns, as well as general information about the library.
Also deals with inventory.
=head1 FUNCTIONS
=head2 barcodedecode
$str = &barcodedecode($barcode, [$filter]);
Generic filter function for barcode string.
Called on every circ if the System Pref itemBarcodeInputFilter is set.
Will do some manipulation of the barcode for systems that deliver a barcode
to circulation.pl that differs from the barcode stored for the item.
For proper functioning of this filter, calling the function on the
correct barcode string (items.barcode) should return an unaltered barcode.
Barcode is going to be automatically trimmed of leading/trailing whitespaces.
The optional $filter argument is to allow for testing or explicit
behavior that ignores the System Pref. Valid values are the same as the
System Pref options.
=cut
# FIXME -- the &decode fcn below should be wrapped into this one.
# FIXME -- these plugins should be moved out of Circulation.pm
#
sub barcodedecode {
my ($barcode, $filter) = @_;
return unless defined $barcode;
my $branch = C4::Context::mybranch();
$barcode =~ s/^\s+|\s+$//g;
$filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter;
Koha::Plugins->call('item_barcode_transform', \$barcode );
$filter or return $barcode; # ensure filter is defined, else return untouched barcode
if ($filter eq 'whitespace') {
$barcode =~ s/\s//g;
} elsif ($filter eq 'cuecat') {
chomp($barcode);
my @fields = split( /\./, $barcode );
my @results = map( C4::Circulation::_decode($_), @fields[ 1 .. $#fields ] );
($#results == 2) and return $results[2];
} elsif ($filter eq 'T-prefix') {
if ($barcode =~ /^[Tt](\d)/) {
(defined($1) and $1 eq '0') and return $barcode;
$barcode = substr($barcode, 2) + 0; # FIXME: probably should be substr($barcode, 1)
}
return sprintf("T%07d", $barcode);
# FIXME: $barcode could be "T1", causing warning: substr outside of string
# Why drop the nonzero digit after the T?
# Why pass non-digits (or empty string) to "T%07d"?
} elsif ($filter eq 'libsuite8') {
unless($barcode =~ m/^($branch)-/i){ #if barcode starts with branch code its in Koha style. Skip it.
if($barcode =~ m/^(\d)/i){ #Some barcodes even start with 0's & numbers and are assumed to have b as the item type in the libsuite8 software
$barcode =~ s/^[0]*(\d+)$/$branch-b-$1/i;
}else{
$barcode =~ s/^(\D+)[0]*(\d+)$/$branch-$1-$2/i;
}
}
} elsif ($filter eq 'EAN13') {
my $ean = CheckDigits('ean');
if ( $ean->is_valid($barcode) ) {
#$barcode = sprintf('%013d',$barcode); # this doesn't work on 32-bit systems
$barcode = '0' x ( 13 - length($barcode) ) . $barcode;
} else {
warn "# [$barcode] not valid EAN-13/UPC-A\n";
}
}
return $barcode; # return barcode, modified or not
}
=head2 _decode
$str = &_decode($chunk);
Decodes a segment of a string emitted by a CueCat barcode scanner and
returns it.
FIXME: Should be replaced with Barcode::Cuecat from CPAN
or Javascript based decoding on the client side.
=cut
sub _decode {
my ($encoded) = @_;
my $seq =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
my @s = map { index( $seq, $_ ); } split( //, $encoded );
my $l = ( $#s + 1 ) % 4;
if ($l) {
if ( $l == 1 ) {
# warn "Error: Cuecat decode parsing failed!";
return;
}
$l = 4 - $l;
$#s += $l;
}
my $r = '';
while ( $#s >= 0 ) {
my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
$r .=
chr( ( $n >> 16 ) ^ 67 )
.chr( ( $n >> 8 & 255 ) ^ 67 )
.chr( ( $n & 255 ) ^ 67 );
@s = @s[ 4 .. $#s ];
}
$r = substr( $r, 0, length($r) - $l );
return $r;
}
=head2 transferbook
($dotransfer, $messages, $iteminformation) = &transferbook({
from_branch => $frombranch
to_branch => $tobranch,
barcode => $barcode,
ignore_reserves => $ignore_reserves,
trigger => $trigger
});
Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
C<$fbr> is the code for the branch initiating the transfer.
C<$tbr> is the code for the branch to which the item should be transferred.
C<$barcode> is the barcode of the item to be transferred.
If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
Otherwise, if an item is reserved, the transfer fails.
C<$trigger> is the enum value for what triggered the transfer.
Returns three values:
=over
=item $dotransfer
is true if the transfer was successful.
=item $messages
is a reference-to-hash which may have any of the following keys:
=over
=item C<BadBarcode>
There is no item in the catalog with the given barcode. The value is C<$barcode>.
=item C<DestinationEqualsHolding>
The item is already at the branch to which it is being transferred. The transfer is nonetheless considered to have failed. The value should be ignored.
=item C<WasReturned>
The item was on loan, and C<&transferbook> automatically returned it before transferring it. The value is the borrower number of the patron who had the item.
=item C<ResFound>
The item was reserved. The value is a reference-to-hash whose keys are fields from the reserves table of the Koha database, and C<biblioitemnumber>. It also has the key C<ResFound>, whose value is either C<Waiting> or C<Reserved>.
=item C<WasTransferred>
The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
=item C<RecallPlacedAtHoldingBranch>
A recall for this item was found, and the transfer has already been completed as the item's branch matches the recall's pickup branch.
=item C<RecallFound>
A recall for this item was found, and the item needs to be transferred to the recall's pickup branch.
=back
=back
=cut
sub transferbook {
my $params = shift;
my $tbr = $params->{to_branch};
my $fbr = $params->{from_branch};
my $ignoreRs = $params->{ignore_reserves};
my $barcode = $params->{barcode};
my $trigger = $params->{trigger};
my $messages;
my $dotransfer = 1;
my $item = $barcode ? Koha::Items->find( { barcode => $barcode } ) : undef;
Koha::Exceptions::MissingParameter->throw(
"Missing mandatory parameter: from_branch")
unless $fbr;
Koha::Exceptions::MissingParameter->throw(
"Missing mandatory parameter: to_branch")
unless $tbr;
# bad barcode..
unless ( $item ) {
$messages->{'BadBarcode'} = $barcode;
$dotransfer = 0;
return ( $dotransfer, $messages );
}
my $itemnumber = $item->itemnumber;
# get branches of book...
my $hbr = $item->homebranch;
# if using Branch Transfer Limits
if ( C4::Context->preference("UseBranchTransferLimits") == 1 ) {
my $code = C4::Context->preference("BranchTransferLimitsType") eq 'ccode' ? $item->ccode : $item->biblio->biblioitem->itemtype; # BranchTransferLimitsType is 'ccode' or 'itemtype'
if ( C4::Context->preference("item-level_itypes") && C4::Context->preference("BranchTransferLimitsType") eq 'itemtype' ) {
if ( ! IsBranchTransferAllowed( $tbr, $fbr, $item->itype ) ) {
$messages->{'NotAllowed'} = $tbr . "::" . $item->itype;
$dotransfer = 0;
}
} elsif ( ! IsBranchTransferAllowed( $tbr, $fbr, $code ) ) {
$messages->{'NotAllowed'} = $tbr . "::" . $code;
$dotransfer = 0;
}
}
# can't transfer book if is already there....
if ( $fbr eq $tbr ) {
$messages->{'DestinationEqualsHolding'} = 1;
$dotransfer = 0;
}
# check if it is still issued to someone, return it...
my $issue = $item->checkout;
if ( $issue ) {
AddReturn( $barcode, $fbr );
$messages->{'WasReturned'} = $issue->borrowernumber;
}
# find reserves.....
# That'll save a database query.
my ( $resfound, $resrec, undef ) =
C4::Reserves::CheckReserves( $item );
if ( $resfound ) {
$resrec->{'ResFound'} = $resfound;
$messages->{'ResFound'} = $resrec;
$dotransfer = 0 unless $ignoreRs;
}
# find recall
if ( C4::Context->preference('UseRecalls') ) {
my $recall = Koha::Recalls->find({ item_id => $itemnumber, status => 'in_transit' });
if ( defined $recall ) {
# do a transfer if the recall branch is different to the item holding branch
if ( $recall->pickup_library_id eq $fbr ) {
$dotransfer = 0;
$messages->{'RecallPlacedAtHoldingBranch'} = 1;
} else {
$dotransfer = 1;
$messages->{'RecallFound'} = $recall;
}
}
}
#actually do the transfer....
if ($dotransfer) {
ModItemTransfer( $itemnumber, $fbr, $tbr, $trigger );
# don't need to update MARC anymore, we do it in batch now
$messages->{'WasTransfered'} = $tbr;
}
ModDateLastSeen( $itemnumber );
return ( $dotransfer, $messages );
}
sub TooMany {
my ($patron, $item, $params) = @_;
my $onsite_checkout = $params->{onsite_checkout} || 0;
my $switch_onsite_checkout = $params->{switch_onsite_checkout} || 0;
my $cat_borrower = $patron->categorycode;
my $dbh = C4::Context->dbh;
# Get which branchcode we need
my $branch = _GetCircControlBranch($item, $patron);
my $type = $item->effective_itemtype;
my ($type_object, $parent_type, $parent_maxissueqty_rule);
$type_object = Koha::ItemTypes->find( $type );
$parent_type = $type_object->parent_type if $type_object;
my $child_types = Koha::ItemTypes->search({ parent_type => $type });
# Find any children if we are a parent_type;
# given branch, patron category, and item type, determine
# applicable issuing rule
$parent_maxissueqty_rule = Koha::CirculationRules->get_effective_rule(
{
categorycode => $cat_borrower,
itemtype => $parent_type,
branchcode => $branch,
rule_name => 'maxissueqty',
}
) if $parent_type;
# If the parent rule is for default type we discount it
$parent_maxissueqty_rule = undef if $parent_maxissueqty_rule && !defined $parent_maxissueqty_rule->itemtype;
my $maxissueqty_rule = Koha::CirculationRules->get_effective_rule(
{
categorycode => $cat_borrower,
itemtype => $type,
branchcode => $branch,
rule_name => 'maxissueqty',
}
);
my $maxonsiteissueqty_rule = Koha::CirculationRules->get_effective_rule(
{
categorycode => $cat_borrower,
itemtype => $type,
branchcode => $branch,
rule_name => 'maxonsiteissueqty',
}
);
# if a rule is found and has a loan limit set, count
# how many loans the patron already has that meet that
# rule
if (defined($maxissueqty_rule) and $maxissueqty_rule->rule_value ne "") {
my $checkouts;
if ( $maxissueqty_rule->branchcode ) {
if ( C4::Context->preference('CircControl') eq 'PickupLibrary' ) {
$checkouts = $patron->checkouts->search(
{ 'me.branchcode' => $maxissueqty_rule->branchcode } );
} elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
$checkouts = $patron->checkouts; # if branch is the patron's home branch, then count all loans by patron
} else {
my $branch_type = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch';
$checkouts = $patron->checkouts->search(
{ "item.$branch_type" => $maxissueqty_rule->branchcode } );
}
} else {
$checkouts = $patron->checkouts; # if rule is not branch specific then count all loans by patron
}
$checkouts = $checkouts->search(undef, { prefetch => 'item' });
my $sum_checkouts;
my $rule_itemtype = $maxissueqty_rule->itemtype;
my @types;
unless ( $rule_itemtype || $parent_maxissueqty_rule ) {
# matching rule has the default item type, so count only
# those existing loans that don't fall under a more
# specific rule
@types = Koha::CirculationRules->search(
{
branchcode => $maxissueqty_rule->branchcode,
categorycode => [ $maxissueqty_rule->categorycode, $cat_borrower ],
itemtype => { '!=' => undef },
rule_name => 'maxissueqty'
}
)->get_column('itemtype');
} else {
if ( $parent_maxissueqty_rule ) {
# if we have a parent item type then we count loans of the
# specific item type or its siblings or parent
my $children = Koha::ItemTypes->search({ parent_type => $parent_type });
@types = $children->get_column('itemtype');
push @types, $parent_type;
} elsif ( $child_types ) {
# If we are a parent type, we need to count all child types and our own type
@types = $child_types->get_column('itemtype');
push @types, $type; # And don't forget to count our own types
} else {
# Otherwise only count the specific itemtype
push @types, $type;
}
}
while ( my $c = $checkouts->next ) {
my $itemtype = $c->item->effective_itemtype;
unless ( $rule_itemtype || $parent_maxissueqty_rule ) {
next if grep {$_ eq $itemtype} @types;
} else {
next unless grep {$_ eq $itemtype} @types;
}
$sum_checkouts->{total}++;
$sum_checkouts->{onsite_checkouts}++ if $c->onsite_checkout;
$sum_checkouts->{itemtype}->{$itemtype}++;
}
my $checkout_count_type = $sum_checkouts->{itemtype}->{$type} || 0;
my $checkout_count = $sum_checkouts->{total} || 0;
my $onsite_checkout_count = $sum_checkouts->{onsite_checkouts} || 0;
my $checkout_rules = {
checkout_count => $checkout_count,
onsite_checkout_count => $onsite_checkout_count,
onsite_checkout => $onsite_checkout,
max_checkouts_allowed => $maxissueqty_rule ? $maxissueqty_rule->rule_value : undef,
max_onsite_checkouts_allowed => $maxonsiteissueqty_rule ? $maxonsiteissueqty_rule->rule_value : undef,
switch_onsite_checkout => $switch_onsite_checkout,
circulation_rule => $maxissueqty_rule,
onsite_circulation_rule => $maxonsiteissueqty_rule,
};
# If parent rules exists
if ( defined($parent_maxissueqty_rule) and defined($parent_maxissueqty_rule->rule_value) ){
$checkout_rules->{max_checkouts_allowed} = $parent_maxissueqty_rule ? $parent_maxissueqty_rule->rule_value : undef;
my $qty_over = _check_max_qty($checkout_rules);
return $qty_over if defined $qty_over;
# If the parent rule is less than or equal to the child, we only need check the parent
if( $maxissueqty_rule->rule_value < $parent_maxissueqty_rule->rule_value && defined($maxissueqty_rule->itemtype) ) {
$checkout_rules->{checkout_count} = $checkout_count_type;
$checkout_rules->{max_checkouts_allowed} = $maxissueqty_rule ? $maxissueqty_rule->rule_value : undef;
my $qty_over = _check_max_qty($checkout_rules);
return $qty_over if defined $qty_over;
}
} else {
my $qty_over = _check_max_qty($checkout_rules);
return $qty_over if defined $qty_over;
}
}
# Now count total loans against the limit for the branch
my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
if (defined($branch_borrower_circ_rule->{patron_maxissueqty}) and $branch_borrower_circ_rule->{patron_maxissueqty} ne '') {
my $checkouts;
if ( C4::Context->preference('CircControl') eq 'PickupLibrary' ) {
$checkouts = $patron->checkouts->search(
{ 'me.branchcode' => $branch} );
} elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
$checkouts = $patron->checkouts; # if branch is the patron's home branch, then count all loans by patron
} else {
my $branch_type = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch';
$checkouts = $patron->checkouts->search(
{ "item.$branch_type" => $branch},
{ prefetch => 'item' } );
}
my $checkout_count = $checkouts->count;
my $onsite_checkout_count = $checkouts->search({ onsite_checkout => 1 })->count;
my $max_checkouts_allowed = $branch_borrower_circ_rule->{patron_maxissueqty};
my $max_onsite_checkouts_allowed = $branch_borrower_circ_rule->{patron_maxonsiteissueqty} || undef;
my $qty_over = _check_max_qty(
{
checkout_count => $checkout_count,
onsite_checkout_count => $onsite_checkout_count,
onsite_checkout => $onsite_checkout,
max_checkouts_allowed => $max_checkouts_allowed,
max_onsite_checkouts_allowed => $max_onsite_checkouts_allowed,
switch_onsite_checkout => $switch_onsite_checkout,
circulation_rule => $branch_borrower_circ_rule,
}
);
return $qty_over if defined $qty_over;
}
if ( not defined( $maxissueqty_rule ) and not defined($branch_borrower_circ_rule->{patron_maxissueqty}) ) {
return { reason => 'NO_RULE_DEFINED', max_allowed => 0 };
}
# OK, the patron can issue !!!
return;
}
sub _check_max_qty {
my $params = shift;
my $checkout_count = $params->{checkout_count};
my $onsite_checkout_count = $params->{onsite_checkout_count};
my $onsite_checkout = $params->{onsite_checkout};
my $max_checkouts_allowed = $params->{max_checkouts_allowed};
my $max_onsite_checkouts_allowed = $params->{max_onsite_checkouts_allowed};
my $switch_onsite_checkout = $params->{switch_onsite_checkout};
my $circulation_rule = $params->{circulation_rule};
my $onsite_circulation_rule = $params->{onsite_circulation_rule};
if ( $onsite_checkout and defined $max_onsite_checkouts_allowed ) {
if ( $max_onsite_checkouts_allowed eq '' ) { return; }
if ( $onsite_checkout_count >= $max_onsite_checkouts_allowed ) {
return {
reason => 'TOO_MANY_ONSITE_CHECKOUTS',
count => $onsite_checkout_count,
max_allowed => $max_onsite_checkouts_allowed,
circulation_rule => $onsite_circulation_rule,
};
}
}
if ( C4::Context->preference('ConsiderOnSiteCheckoutsAsNormalCheckouts') ) {
if ( $max_checkouts_allowed eq '' ) { return; }
my $delta = $switch_onsite_checkout ? 1 : 0;
if ( $checkout_count >= $max_checkouts_allowed + $delta ) {
return {
reason => 'TOO_MANY_CHECKOUTS',
count => $checkout_count,
max_allowed => $max_checkouts_allowed,
circulation_rule => $circulation_rule,
};
}
}
elsif ( not $onsite_checkout ) {
if ( $max_checkouts_allowed eq '' ) { return; }
if (
$checkout_count - $onsite_checkout_count >= $max_checkouts_allowed )
{
return {
reason => 'TOO_MANY_CHECKOUTS',
count => $checkout_count - $onsite_checkout_count,
max_allowed => $max_checkouts_allowed,
circulation_rule => $circulation_rule,
};
}
}
return;
}
=head2 CanBookBeIssued
( $issuingimpossible, $needsconfirmation, [ $alerts ] ) = CanBookBeIssued( $patron,
$barcode, $duedate, $inprocess, $ignore_reserves, $params );
Check if a book can be issued.
C<$issuingimpossible> and C<$needsconfirmation> are hashrefs.
IMPORTANT: The assumption by users of this routine is that causes blocking
the issue are keyed by uppercase labels and other returned
data is keyed in lower case!
=over 4
=item C<$patron> is a Koha::Patron
=item C<$barcode> is the bar code of the book being issued.
=item C<$duedates> is a DateTime object.
=item C<$inprocess> boolean switch
=item C<$ignore_reserves> boolean switch
=item C<$params> Hashref of additional parameters
Available keys:
override_high_holds - Ignore high holds
onsite_checkout - Checkout is an onsite checkout that will not leave the library
item - Optionally pass the object for the item we are checking out to save a lookup
=back
Returns :
=over 4
=item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
Possible values are :
=back
=head3 INVALID_DATE
sticky due date is invalid
=head3 GNA
borrower gone with no address
=head3 CARD_LOST
borrower declared it's card lost
=head3 DEBARRED
borrower debarred
=head3 UNKNOWN_BARCODE
barcode unknown
=head3 NOT_FOR_LOAN
item is not for loan
=head3 WTHDRAWN
item withdrawn.
=head3 RESTRICTED
item is restricted (set by ??)
C<$needsconfirmation> a reference to a hash. It contains reasons why the loan
could be prevented, but ones that can be overriden by the operator.
Possible values are :
=head3 DEBT
borrower has debts.
=head3 RENEW_ISSUE
renewing, not issuing
=head3 ISSUED_TO_ANOTHER
issued to someone else.
=head3 RESERVED
reserved for someone else.
=head3 TRANSFERRED
reserved and being transferred for someone else.
=head3 INVALID_DATE
sticky due date is invalid or due date in the past
=head3 TOO_MANY
if the borrower borrows to much things
=head3 RECALLED
recalled by someone else
=cut
sub CanBookBeIssued {
my ( $patron, $barcode, $duedate, $inprocess, $ignore_reserves, $params ) = @_;
my %needsconfirmation; # filled with problems that needs confirmations
my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
my %alerts; # filled with messages that shouldn't stop issuing, but the librarian should be aware of.
my %messages; # filled with information messages that should be displayed.
my $onsite_checkout = $params->{onsite_checkout} || 0;
my $override_high_holds = $params->{override_high_holds} || 0;
my $item_object = $params->{item}
// Koha::Items->find( { barcode => $barcode } );
# MANDATORY CHECKS - unless item exists, nothing else matters
unless ( $item_object ) {
$issuingimpossible{UNKNOWN_BARCODE} = 1;
}
return ( \%issuingimpossible, \%needsconfirmation ) if %issuingimpossible;
my $item_unblessed = $item_object->unblessed; # Transition...
my $issue = $item_object->checkout;
my $biblio = $item_object->biblio;
my $biblioitem = $biblio->biblioitem;
my $effective_itemtype = $item_object->effective_itemtype;
my $dbh = C4::Context->dbh;
my $patron_unblessed = $patron->unblessed;
my $circ_library = Koha::Libraries->find( _GetCircControlBranch($item_object, $patron) );
my $now = dt_from_string();
$duedate ||= CalcDateDue( $now, $effective_itemtype, $circ_library->branchcode, $patron );
if (DateTime->compare($duedate,$now) == -1 ) { # duedate cannot be before now
$needsconfirmation{INVALID_DATE} = $duedate;
}
my $fees = Koha::Charges::Fees->new(
{
patron => $patron,
library => $circ_library,
item => $item_object,
to_date => $duedate,
}
);
#
# BORROWER STATUS
#
my $patron_borrowing_status = $patron->can_checkout();
if ( $patron->category->category_type eq 'X' && ( $item_object->barcode )) {
# stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1 .
C4::Stats::UpdateStats(
{
branch => C4::Context->userenv->{'branch'},
type => 'localuse',
itemnumber => $item_object->itemnumber,
itemtype => $effective_itemtype,
borrowernumber => $patron->borrowernumber,
ccode => $item_object->ccode,
categorycode => $patron->categorycode,
location => $item_object->location,
interface => C4::Context->interface,
}
);
my $block_lost_return = C4::Context->preference("BlockReturnOfLostItems") ? 1 : 0;
ModDateLastSeen( $item_object->itemnumber, $block_lost_return ); # FIXME Move to Koha::Item
return ( { STATS => 1, }, {} );
}
if ( $patron->gonenoaddress && $patron->gonenoaddress == 1 ) {
$issuingimpossible{GNA} = 1;
}
if ( $patron->lost && $patron->lost == 1 ) {
$issuingimpossible{CARD_LOST} = 1;
}
if ( $patron->is_debarred ) {
$issuingimpossible{DEBARRED} = 1;
}
if ( $patron->is_expired ) {
$issuingimpossible{EXPIRED} = 1;
}
#
# BORROWER STATUS
#
# DEBTS
my $account = $patron->account;
my $balance = $account->balance;
my $non_issues_charges = $account->non_issues_charges;
my $other_charges = $balance - $non_issues_charges;
my $allowfineoverride = C4::Context->preference("AllowFineOverride");
my $allfinesneedoverride = C4::Context->preference("AllFinesNeedOverride");
# Check the debt of this patrons guarantees
my $no_issues_charge_guarantees = $patron_borrowing_status->{NoIssuesChargeGuarantees}->{limit};
if ( defined $no_issues_charge_guarantees ) {
if ( $patron_borrowing_status->{NoIssuesChargeGuarantees}->{overlimit} && !$inprocess && !$allowfineoverride ) {
$issuingimpossible{DEBT_GUARANTEES} = $patron_borrowing_status->{NoIssuesChargeGuarantees}->{charge};
} elsif ( $patron_borrowing_status->{NoIssuesChargeGuarantees}->{overlimit}
&& !$inprocess
&& $allowfineoverride )
{
$needsconfirmation{DEBT_GUARANTEES} = $patron_borrowing_status->{NoIssuesChargeGuarantees}->{charge};
} elsif ( $allfinesneedoverride
&& $patron_borrowing_status->{NoIssuesChargeGuarantees}->{charge} > 0
&& !$inprocess )
{
$needsconfirmation{DEBT_GUARANTEES} = $patron_borrowing_status->{NoIssuesChargeGuarantees}->{charge};
}
}
# Check the debt of this patrons guarantors *and* the guarantees of those guarantors
my $no_issues_charge_guarantors = $patron_borrowing_status->{NoIssuesChargeGuarantorsWithGuarantees}->{limit};
if ( defined $no_issues_charge_guarantors ) {
if ( $patron_borrowing_status->{NoIssuesChargeGuarantorsWithGuarantees}->{overlimit}
&& !$inprocess
&& !$allowfineoverride )
{
$issuingimpossible{DEBT_GUARANTORS} =
$patron_borrowing_status->{NoIssuesChargeGuarantorsWithGuarantees}->{charge};
} elsif ( $patron_borrowing_status->{NoIssuesChargeGuarantorsWithGuarantees}->{overlimit}
&& !$inprocess
&& $allowfineoverride )
{
$needsconfirmation{DEBT_GUARANTORS} =
$patron_borrowing_status->{NoIssuesChargeGuarantorsWithGuarantees}->{charge};
} elsif ( $allfinesneedoverride
&& $patron_borrowing_status->{NoIssuesChargeGuarantorsWithGuarantees}->{charge} > 0
&& !$inprocess )
{
$needsconfirmation{DEBT_GUARANTORS} =
$patron_borrowing_status->{NoIssuesChargeGuarantorsWithGuarantees}->{charge};
}
}
if ( C4::Context->preference("IssuingInProcess") ) {
if ( $patron_borrowing_status->{noissuescharge}->{overlimit} && !$inprocess && !$allowfineoverride ) {
$issuingimpossible{DEBT} = $patron_borrowing_status->{noissuescharge}->{charge};
} elsif ( $patron_borrowing_status->{noissuescharge}->{overlimit} && !$inprocess && $allowfineoverride ) {
$needsconfirmation{DEBT} = $patron_borrowing_status->{noissuescharge}->{charge};
} elsif ( $allfinesneedoverride && $patron_borrowing_status->{noissuescharge}->{charge} > 0 && !$inprocess ) {
$needsconfirmation{DEBT} = $patron_borrowing_status->{noissuescharge}->{charge};
}
} else {
if ( $patron_borrowing_status->{noissuescharge}->{overlimit} && $allowfineoverride ) {
$needsconfirmation{DEBT} = $patron_borrowing_status->{noissuescharge}->{charge};
} elsif ( $patron_borrowing_status->{noissuescharge}->{overlimit} && !$allowfineoverride ) {
$issuingimpossible{DEBT} = $patron_borrowing_status->{noissuescharge}->{charge};
} elsif ( $patron_borrowing_status->{noissuescharge}->{charge} > 0 && $allfinesneedoverride ) {
$needsconfirmation{DEBT} = $patron_borrowing_status->{noissuescharge}->{charge};
}
}
if ($balance > 0 && $other_charges > 0) {
$alerts{OTHER_CHARGES} = sprintf( "%.2f", $other_charges );
}
$patron = Koha::Patrons->find( $patron->borrowernumber ); # FIXME Refetch just in case, to avoid regressions. But must not be needed
$patron_unblessed = $patron->unblessed;
if ( my $debarred_date = $patron->is_debarred ) {
# patron has accrued fine days or has a restriction. $count is a date
if ($debarred_date eq '9999-12-31') {
$issuingimpossible{USERBLOCKEDNOENDDATE} = $debarred_date;
}
else {
$issuingimpossible{USERBLOCKEDWITHENDDATE} = $debarred_date;
}
} elsif ( my $num_overdues = $patron->has_overdues ) {
## patron has outstanding overdue loans
if ( C4::Context->preference("OverduesBlockCirc") eq 'block'){
$issuingimpossible{USERBLOCKEDOVERDUE} = $num_overdues;
}
elsif ( C4::Context->preference("OverduesBlockCirc") eq 'confirmation'){
$needsconfirmation{USERBLOCKEDOVERDUE} = $num_overdues;
}
}
# Additional Materials Check
if ( C4::Context->preference("CircConfirmItemParts")
&& $item_object->materials )
{
$needsconfirmation{ADDITIONAL_MATERIALS} = $item_object->materials;
}
#
# CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
#
if ( $issue && $issue->borrowernumber eq $patron->borrowernumber ){
# Already issued to current borrower.
# If it is an on-site checkout if it can be switched to a normal checkout
# or ask whether the loan should be renewed
if ( $issue->onsite_checkout
and C4::Context->preference('SwitchOnSiteCheckouts') ) {
$messages{ONSITE_CHECKOUT_WILL_BE_SWITCHED} = 1;
} else {
my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed($patron, $issue);
if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
if ( $renewerror eq 'onsite_checkout' ) {
$issuingimpossible{NO_RENEWAL_FOR_ONSITE_CHECKOUTS} = 1;
}
else {
$issuingimpossible{NO_MORE_RENEWALS} = 1;
}
}
else {
$needsconfirmation{RENEW_ISSUE} = 1;
}
}
}
elsif ( $issue ) {
# issued to someone else
my $patron = Koha::Patrons->find( $issue->borrowernumber );
my ( $can_be_returned, $message ) = CanBookBeReturned( $item_unblessed, C4::Context->userenv->{branch} );
if ( !$can_be_returned ) {
$issuingimpossible{RETURN_IMPOSSIBLE} = 1;
$issuingimpossible{branch_to_return} = $message;