Bug 11694: Improve handling of individual hold suspension in Bootstrap OPAC
[koha.git] / t / db_dependent / Reserves.t
1 #!/usr/bin/perl
2
3 use Modern::Perl;
4
5 use Test::More tests => 31;
6 use MARC::Record;
7 use DateTime::Duration;
8
9 use C4::Branch;
10 use C4::Biblio;
11 use C4::Items;
12 use C4::Members;
13 use C4::Circulation;
14 use t::lib::Mocks;
15
16 use Koha::DateUtils;
17
18 BEGIN {
19     use_ok('C4::Reserves');
20 }
21
22 # a very minimal mack of userenv for use by the test of DelItemCheck
23 *C4::Context::userenv = sub {
24     return {};
25 };
26
27 my $dbh = C4::Context->dbh;
28
29 # Start transaction
30 $dbh->{AutoCommit} = 0;
31 $dbh->{RaiseError} = 1;
32
33 # Setup Test------------------------
34
35 # Add branches if not existing
36 foreach my $addbra ('CPL', 'FPL', 'RPL') {
37     $dbh->do("INSERT INTO branches (branchcode,branchname) VALUES (?,?)", undef, ($addbra,"$addbra branch")) unless GetBranchName($addbra);
38 }
39
40 # Add categories if not existing
41 foreach my $addcat ('S', 'PT') {
42     $dbh->do("INSERT INTO categories (categorycode,hidelostitems,category_type) VALUES (?,?,?)",undef,($addcat, 0, $addcat eq 'S'? 'S': 'A')) unless GetBorrowercategory($addcat);
43 }
44
45 # Helper biblio.
46 diag("\nCreating biblio instance for testing.");
47 my $bib = MARC::Record->new();
48 my $title = 'Silence in the library';
49 if( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
50     $bib->append_fields(
51         MARC::Field->new('600', '', '1', a => 'Moffat, Steven'),
52         MARC::Field->new('200', '', '', a => $title),
53     );
54 }
55 else {
56     $bib->append_fields(
57         MARC::Field->new('100', '', '', a => 'Moffat, Steven'),
58         MARC::Field->new('245', '', '', a => $title),
59     );
60 }
61 my ($bibnum, $bibitemnum);
62 ($bibnum, $title, $bibitemnum) = AddBiblio($bib, '');
63
64 # Helper item for that biblio.
65 diag("Creating item instance for testing.");
66 my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => 'CPL', holdingbranch => 'CPL' } , $bibnum);
67
68 # Modify item; setting barcode.
69 my $testbarcode = '97531';
70 ModItem({ barcode => $testbarcode }, $bibnum, $itemnumber);
71
72 # Create a borrower
73 my %data = (
74     firstname =>  'my firstname',
75     surname => 'my surname',
76     categorycode => 'S',
77     branchcode => 'CPL',
78 );
79 my $borrowernumber = AddMember(%data);
80 my $borrower = GetMember( borrowernumber => $borrowernumber );
81 my $biblionumber   = $bibnum;
82 my $barcode        = $testbarcode;
83
84 my $constraint     = 'a';
85 my $bibitems       = '';
86 my $priority       = '1';
87 my $resdate        = undef;
88 my $expdate        = undef;
89 my $notes          = '';
90 my $checkitem      = undef;
91 my $found          = undef;
92
93 my @branches = GetBranchesLoop();
94 my $branch = $branches[0][0]{value};
95
96 AddReserve($branch,    $borrowernumber, $biblionumber,
97         $constraint, $bibitems,  $priority, $resdate, $expdate, $notes,
98         $title,      $checkitem, $found);
99
100 my ($status, $reserve, $all_reserves) = CheckReserves($itemnumber, $barcode);
101
102 is($status, "Reserved", "CheckReserves Test 1");
103
104 ($status, $reserve, $all_reserves) = CheckReserves($itemnumber);
105 is($status, "Reserved", "CheckReserves Test 2");
106
107 ($status, $reserve, $all_reserves) = CheckReserves(undef, $barcode);
108 is($status, "Reserved", "CheckReserves Test 3");
109
110 my $ReservesControlBranch = C4::Context->preference('ReservesControlBranch');
111 C4::Context->set_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
112 ok(
113     'ItemHomeLib' eq GetReservesControlBranch(
114         { homebranch => 'ItemHomeLib' },
115         { branchcode => 'PatronHomeLib' }
116     ), "GetReservesControlBranch returns item home branch when set to ItemHomeLibrary"
117 );
118 C4::Context->set_preference( 'ReservesControlBranch', 'PatronLibrary' );
119 ok(
120     'PatronHomeLib' eq GetReservesControlBranch(
121         { homebranch => 'ItemHomeLib' },
122         { branchcode => 'PatronHomeLib' }
123     ), "GetReservesControlBranch returns patron home branch when set to PatronLibrary"
124 );
125 C4::Context->set_preference( 'ReservesControlBranch', $ReservesControlBranch );
126
127 ###
128 ### Regression test for bug 10272
129 ###
130 my %requesters = ();
131 $requesters{'CPL'} = AddMember(
132     branchcode   => 'CPL',
133     categorycode => 'PT',
134     surname      => 'borrower from CPL',
135 );
136 $requesters{'FPL'} = AddMember(
137     branchcode   => 'FPL',
138     categorycode => 'PT',
139     surname      => 'borrower from FPL',
140 );
141 $requesters{'RPL'} = AddMember(
142     branchcode   => 'RPL',
143     categorycode => 'PT',
144     surname      => 'borrower from RPL',
145 );
146
147 # Configure rules so that CPL allows only CPL patrons
148 # to request its items, while FPL will allow its items
149 # to fill holds from anywhere.
150
151 $dbh->do('DELETE FROM issuingrules');
152 $dbh->do('DELETE FROM branch_item_rules');
153 $dbh->do('DELETE FROM branch_borrower_circ_rules');
154 $dbh->do('DELETE FROM default_borrower_circ_rules');
155 $dbh->do('DELETE FROM default_branch_item_rules');
156 $dbh->do('DELETE FROM default_branch_circ_rules');
157 $dbh->do('DELETE FROM default_circ_rules');
158 $dbh->do(
159     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed)
160       VALUES (?, ?, ?, ?)},
161     {},
162     '*', '*', '*', 25
163 );
164
165 # CPL allows only its own patrons to request its items
166 $dbh->do(
167     q{INSERT INTO default_branch_circ_rules (branchcode, maxissueqty, holdallowed, returnbranch)
168       VALUES (?, ?, ?, ?)},
169     {},
170     'CPL', 10, 1, 'homebranch',
171 );
172
173 # ... while FPL allows anybody to request its items
174 $dbh->do(
175     q{INSERT INTO default_branch_circ_rules (branchcode, maxissueqty, holdallowed, returnbranch)
176       VALUES (?, ?, ?, ?)},
177     {},
178     'FPL', 10, 2, 'homebranch',
179 );
180
181 # helper biblio for the bug 10272 regression test
182 my $bib2 = MARC::Record->new();
183 $bib2->append_fields(
184     MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
185     MARC::Field->new('245', ' ', ' ', a => $title),
186 );
187
188 # create one item belonging to FPL and one belonging to CPL
189 my ($bibnum2, $bibitemnum2) = AddBiblio($bib, '');
190 my ($itemnum_cpl, $itemnum_fpl);
191 (undef, undef, $itemnum_cpl) = AddItem({
192         homebranch => 'CPL',
193         holdingbranch => 'CPL',
194         barcode => 'bug10272_CPL'
195     } , $bibnum2);
196 (undef, undef, $itemnum_fpl) = AddItem({
197         homebranch => 'FPL',
198         holdingbranch => 'FPL',
199         barcode => 'bug10272_FPL'
200     } , $bibnum2);
201
202 AddReserve('RPL',  $requesters{'RPL'}, $bibnum2,
203            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
204            $title,      $checkitem, $found);
205 AddReserve('FPL',  $requesters{'FPL'}, $bibnum2,
206            $constraint, $bibitems,  2, $resdate, $expdate, $notes,
207            $title,      $checkitem, $found);
208 AddReserve('CPL',  $requesters{'CPL'}, $bibnum2,
209            $constraint, $bibitems,  3, $resdate, $expdate, $notes,
210            $title,      $checkitem, $found);
211
212 # Ensure that the item's home library controls hold policy lookup
213 C4::Context->set_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
214
215 my $messages;
216 # Return the CPL item at FPL.  The hold that should be triggered is
217 # the one placed by the CPL patron, as the other two patron's hold
218 # requests cannot be filled by that item per policy.
219 (undef, $messages, undef, undef) = AddReturn('bug10272_CPL', 'FPL');
220 is( $messages->{ResFound}->{borrowernumber},
221     $requesters{'CPL'},
222     'restrictive library\'s items only fill requests by own patrons (bug 10272)');
223
224 # Return the FPL item at FPL.  The hold that should be triggered is
225 # the one placed by the RPL patron, as that patron is first in line
226 # and RPL imposes no restrictions on whose holds its items can fill.
227 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', 'FPL');
228 is( $messages->{ResFound}->{borrowernumber},
229     $requesters{'RPL'},
230     'for generous library, its items fill first hold request in line (bug 10272)');
231
232 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
233 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
234 # Test 9761a: Add a reserve without date, CheckReserve should return it
235 $resdate= undef; #defaults to today in AddReserve
236 $expdate= undef; #no expdate
237 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
238 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
239            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
240            $title,      $checkitem, $found);
241 ($status)=CheckReserves($itemnumber,undef,undef);
242 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
243 ($status)=CheckReserves($itemnumber,undef,7);
244 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
245
246 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
247 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
248 C4::Context->set_preference('AllowHoldDateInFuture', 1);
249 $resdate= dt_from_string();
250 $resdate->add_duration(DateTime::Duration->new(days => 4));
251 $resdate=output_pref($resdate);
252 $expdate= undef; #no expdate
253 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
254            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
255            $title,      $checkitem, $found);
256 ($status)=CheckReserves($itemnumber,undef,undef);
257 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
258
259 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
260 ($status)=CheckReserves($itemnumber,undef,3);
261 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
262 ($status)=CheckReserves($itemnumber,undef,4);
263 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
264
265 # Test 9761d: Check ResFound message of AddReturn for future hold
266 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
267 # In this test we do not need an issued item; it is just a 'checkin'
268 C4::Context->set_preference('ConfirmFutureHolds', 0);
269 (my $doreturn, $messages)= AddReturn('97531','CPL');
270 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
271 C4::Context->set_preference('ConfirmFutureHolds', 3);
272 ($doreturn, $messages)= AddReturn('97531','CPL');
273 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
274 C4::Context->set_preference('ConfirmFutureHolds', 7);
275 ($doreturn, $messages)= AddReturn('97531','CPL');
276 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
277
278 # End of tests for bug 9761 (ConfirmFutureHolds)
279
280 # test marking a hold as captured
281 my $hold_notice_count = count_hold_print_messages();
282 ModReserveAffect($itemnumber, $requesters{'CPL'}, 0);
283 my $new_count = count_hold_print_messages();
284 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
285
286 # test that duplicate notices aren't generated
287 ModReserveAffect($itemnumber, $requesters{'CPL'}, 0);
288 $new_count = count_hold_print_messages();
289 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
290
291 # avoiding the not_same_branch error
292 t::lib::Mocks::mock_preference('IndependentBranches', 0);
293 is(
294     DelItemCheck($dbh, $bibnum, $itemnumber),
295     'book_reserved',
296     'item that is captured to fill a hold cannot be deleted',
297 );
298
299 my $letter = ReserveSlip('CPL', $requesters{'CPL'}, $bibnum);
300 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
301
302 # Tests for bug 9788: Does GetReservesFromItemnumber return a future wait?
303 # 9788a: GetReservesFromItemnumber does not return future next available hold
304 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
305 C4::Context->set_preference('ConfirmFutureHolds', 2);
306 C4::Context->set_preference('AllowHoldDateInFuture', 1);
307 $resdate= dt_from_string();
308 $resdate->add_duration(DateTime::Duration->new(days => 2));
309 $resdate=output_pref($resdate);
310 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
311            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
312            $title,      $checkitem, $found);
313 my @results= GetReservesFromItemnumber($itemnumber);
314 is(defined $results[3]?1:0, 0, 'GetReservesFromItemnumber does not return a future next available hold');
315 # 9788b: GetReservesFromItemnumber does not return future item level hold
316 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
317 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
318            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
319            $title,      $itemnumber, $found); #item level hold
320 @results= GetReservesFromItemnumber($itemnumber);
321 is(defined $results[3]?1:0, 0, 'GetReservesFromItemnumber does not return a future item level hold');
322 # 9788c: GetReservesFromItemnumber returns future wait (confirmed future hold)
323 ModReserveAffect( $itemnumber,  $requesters{'CPL'} , 0); #confirm hold
324 @results= GetReservesFromItemnumber($itemnumber);
325 is(defined $results[3]?1:0, 1, 'GetReservesFromItemnumber returns a future wait (confirmed future hold)');
326 # End of tests for bug 9788
327
328 # Tests for CalculatePriority (bug 8918)
329 my $p = C4::Reserves::CalculatePriority($bibnum2);
330 is($p, 4, 'CalculatePriority should now return priority 4');
331 $resdate=undef;
332 AddReserve('CPL',  $requesters{'CPL'}, $bibnum2,
333            $constraint, $bibitems,  $p, $resdate, $expdate, $notes,
334            $title,      $checkitem, $found);
335 $p = C4::Reserves::CalculatePriority($bibnum2);
336 is($p, 5, 'CalculatePriority should now return priority 5');
337 #some tests on bibnum
338 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
339 $p = C4::Reserves::CalculatePriority($bibnum);
340 is($p, 1, 'CalculatePriority should now return priority 1');
341 #add a new reserve and confirm it to waiting
342 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
343            $constraint, $bibitems,  $p, $resdate, $expdate, $notes,
344            $title,      $itemnumber, $found);
345 $p = C4::Reserves::CalculatePriority($bibnum);
346 is($p, 2, 'CalculatePriority should now return priority 2');
347 ModReserveAffect( $itemnumber,  $requesters{'CPL'} , 0);
348 $p = C4::Reserves::CalculatePriority($bibnum);
349 is($p, 1, 'CalculatePriority should now return priority 1');
350 #add another biblio hold, no resdate
351 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
352            $constraint, $bibitems,  $p, $resdate, $expdate, $notes,
353            $title,      $checkitem, $found);
354 $p = C4::Reserves::CalculatePriority($bibnum);
355 is($p, 2, 'CalculatePriority should now return priority 2');
356 #add another future hold
357 C4::Context->set_preference('AllowHoldDateInFuture', 1);
358 $resdate= dt_from_string();
359 $resdate->add_duration(DateTime::Duration->new(days => 1));
360 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
361            $constraint, $bibitems,  $p, output_pref($resdate), $expdate, $notes,
362            $title,      $checkitem, $found);
363 $p = C4::Reserves::CalculatePriority($bibnum);
364 is($p, 2, 'CalculatePriority should now still return priority 2');
365 #calc priority with future resdate
366 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
367 is($p, 3, 'CalculatePriority should now return priority 3');
368 # End of tests for bug 8918
369
370 $dbh->rollback;
371
372 sub count_hold_print_messages {
373     my $message_count = $dbh->selectall_arrayref(q{
374         SELECT COUNT(*) FROM message_queue WHERE letter_code = 'HOLD_PRINT'
375     });
376     return $message_count->[0]->[0];
377 }