Bug 5342: Serial claiming improvements: add a counter
[koha.git] / t / db_dependent / Reserves.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use Test::More tests => 50;
21
22 use MARC::Record;
23 use DateTime::Duration;
24
25 use C4::Branch;
26 use C4::Biblio;
27 use C4::Items;
28 use C4::Members;
29 use C4::Circulation;
30 use t::lib::Mocks;
31
32 use Koha::DateUtils;
33
34 use Data::Dumper;
35 BEGIN {
36     use_ok('C4::Reserves');
37 }
38
39 # a very minimal mack of userenv for use by the test of DelItemCheck
40 *C4::Context::userenv = sub {
41     return {};
42 };
43
44 my $dbh = C4::Context->dbh;
45
46 # Start transaction
47 $dbh->{AutoCommit} = 0;
48 $dbh->{RaiseError} = 1;
49
50 # Setup Test------------------------
51
52 # Add branches if not existing
53 foreach my $addbra ('CPL', 'FPL', 'RPL') {
54     $dbh->do("INSERT INTO branches (branchcode,branchname) VALUES (?,?)", undef, ($addbra,"$addbra branch")) unless GetBranchName($addbra);
55 }
56
57 # Add categories if not existing
58 foreach my $addcat ('S', 'PT') {
59     $dbh->do("INSERT INTO categories (categorycode,hidelostitems,category_type) VALUES (?,?,?)",undef,($addcat, 0, $addcat eq 'S'? 'S': 'A')) unless GetBorrowercategory($addcat);
60 }
61
62 # Create a helper biblio
63 my $bib = MARC::Record->new();
64 my $title = 'Silence in the library';
65 if( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
66     $bib->append_fields(
67         MARC::Field->new('600', '', '1', a => 'Moffat, Steven'),
68         MARC::Field->new('200', '', '', a => $title),
69     );
70 }
71 else {
72     $bib->append_fields(
73         MARC::Field->new('100', '', '', a => 'Moffat, Steven'),
74         MARC::Field->new('245', '', '', a => $title),
75     );
76 }
77 my ($bibnum, $bibitemnum);
78 ($bibnum, $title, $bibitemnum) = AddBiblio($bib, '');
79
80 # Create a helper item instance for testing
81 my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => 'CPL', holdingbranch => 'CPL' } , $bibnum);
82
83 # Modify item; setting barcode.
84 my $testbarcode = '97531';
85 ModItem({ barcode => $testbarcode }, $bibnum, $itemnumber);
86
87 # Create a borrower
88 my %data = (
89     firstname =>  'my firstname',
90     surname => 'my surname',
91     categorycode => 'S',
92     branchcode => 'CPL',
93 );
94 my $borrowernumber = AddMember(%data);
95 my $borrower = GetMember( borrowernumber => $borrowernumber );
96 my $biblionumber   = $bibnum;
97 my $barcode        = $testbarcode;
98
99 my $constraint     = 'a';
100 my $bibitems       = '';
101 my $priority       = '1';
102 my $resdate        = undef;
103 my $expdate        = undef;
104 my $notes          = '';
105 my $checkitem      = undef;
106 my $found          = undef;
107
108 my @branches = GetBranchesLoop();
109 my $branch = $branches[0][0]{value};
110
111 AddReserve($branch,    $borrowernumber, $biblionumber,
112         $constraint, $bibitems,  $priority, $resdate, $expdate, $notes,
113         $title,      $checkitem, $found);
114
115 my ($status, $reserve, $all_reserves) = CheckReserves($itemnumber, $barcode);
116
117 is($status, "Reserved", "CheckReserves Test 1");
118
119 ok(exists($reserve->{reserve_id}), 'CheckReserves() include reserve_id in its response');
120
121 ($status, $reserve, $all_reserves) = CheckReserves($itemnumber);
122 is($status, "Reserved", "CheckReserves Test 2");
123
124 ($status, $reserve, $all_reserves) = CheckReserves(undef, $barcode);
125 is($status, "Reserved", "CheckReserves Test 3");
126
127 my $ReservesControlBranch = C4::Context->preference('ReservesControlBranch');
128 C4::Context->set_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
129 ok(
130     'ItemHomeLib' eq GetReservesControlBranch(
131         { homebranch => 'ItemHomeLib' },
132         { branchcode => 'PatronHomeLib' }
133     ), "GetReservesControlBranch returns item home branch when set to ItemHomeLibrary"
134 );
135 C4::Context->set_preference( 'ReservesControlBranch', 'PatronLibrary' );
136 ok(
137     'PatronHomeLib' eq GetReservesControlBranch(
138         { homebranch => 'ItemHomeLib' },
139         { branchcode => 'PatronHomeLib' }
140     ), "GetReservesControlBranch returns patron home branch when set to PatronLibrary"
141 );
142 C4::Context->set_preference( 'ReservesControlBranch', $ReservesControlBranch );
143
144 ###
145 ### Regression test for bug 10272
146 ###
147 my %requesters = ();
148 $requesters{'CPL'} = AddMember(
149     branchcode   => 'CPL',
150     categorycode => 'PT',
151     surname      => 'borrower from CPL',
152 );
153 $requesters{'FPL'} = AddMember(
154     branchcode   => 'FPL',
155     categorycode => 'PT',
156     surname      => 'borrower from FPL',
157 );
158 $requesters{'RPL'} = AddMember(
159     branchcode   => 'RPL',
160     categorycode => 'PT',
161     surname      => 'borrower from RPL',
162 );
163
164 # Configure rules so that CPL allows only CPL patrons
165 # to request its items, while FPL will allow its items
166 # to fill holds from anywhere.
167
168 $dbh->do('DELETE FROM issuingrules');
169 $dbh->do('DELETE FROM branch_item_rules');
170 $dbh->do('DELETE FROM branch_borrower_circ_rules');
171 $dbh->do('DELETE FROM default_borrower_circ_rules');
172 $dbh->do('DELETE FROM default_branch_item_rules');
173 $dbh->do('DELETE FROM default_branch_circ_rules');
174 $dbh->do('DELETE FROM default_circ_rules');
175 $dbh->do(
176     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed)
177       VALUES (?, ?, ?, ?)},
178     {},
179     '*', '*', '*', 25
180 );
181
182 # CPL allows only its own patrons to request its items
183 $dbh->do(
184     q{INSERT INTO default_branch_circ_rules (branchcode, maxissueqty, holdallowed, returnbranch)
185       VALUES (?, ?, ?, ?)},
186     {},
187     'CPL', 10, 1, 'homebranch',
188 );
189
190 # ... while FPL allows anybody to request its items
191 $dbh->do(
192     q{INSERT INTO default_branch_circ_rules (branchcode, maxissueqty, holdallowed, returnbranch)
193       VALUES (?, ?, ?, ?)},
194     {},
195     'FPL', 10, 2, 'homebranch',
196 );
197
198 # helper biblio for the bug 10272 regression test
199 my $bib2 = MARC::Record->new();
200 $bib2->append_fields(
201     MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
202     MARC::Field->new('245', ' ', ' ', a => $title),
203 );
204
205 # create one item belonging to FPL and one belonging to CPL
206 my ($bibnum2, $bibitemnum2) = AddBiblio($bib, '');
207 my ($itemnum_cpl, $itemnum_fpl);
208 (undef, undef, $itemnum_cpl) = AddItem({
209         homebranch => 'CPL',
210         holdingbranch => 'CPL',
211         barcode => 'bug10272_CPL'
212     } , $bibnum2);
213 (undef, undef, $itemnum_fpl) = AddItem({
214         homebranch => 'FPL',
215         holdingbranch => 'FPL',
216         barcode => 'bug10272_FPL'
217     } , $bibnum2);
218
219 # Ensure that priorities are numbered correcly when a hold is moved to waiting
220 # (bug 11947)
221 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
222 AddReserve('RPL',  $requesters{'RPL'}, $bibnum2,
223            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
224            $title,      $checkitem, $found);
225 AddReserve('FPL',  $requesters{'FPL'}, $bibnum2,
226            $constraint, $bibitems,  2, $resdate, $expdate, $notes,
227            $title,      $checkitem, $found);
228 AddReserve('CPL',  $requesters{'CPL'}, $bibnum2,
229            $constraint, $bibitems,  3, $resdate, $expdate, $notes,
230            $title,      $checkitem, $found);
231 ModReserveAffect($itemnum_cpl, $requesters{'RPL'}, 0);
232
233 # Now it should have different priorities.
234 my $title_reserves = GetReservesFromBiblionumber({biblionumber => $bibnum2});
235 # Sort by reserve number in case the database gives us oddly ordered results
236 my @reserves = sort { $a->{reserve_id} <=> $b->{reserve_id} } @$title_reserves;
237 is($reserves[0]{priority}, 0, 'Item is correctly waiting');
238 is($reserves[1]{priority}, 1, 'Item is correctly priority 1');
239 is($reserves[2]{priority}, 2, 'Item is correctly priority 2');
240
241
242 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
243 AddReserve('RPL',  $requesters{'RPL'}, $bibnum2,
244            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
245            $title,      $checkitem, $found);
246 AddReserve('FPL',  $requesters{'FPL'}, $bibnum2,
247            $constraint, $bibitems,  2, $resdate, $expdate, $notes,
248            $title,      $checkitem, $found);
249 AddReserve('CPL',  $requesters{'CPL'}, $bibnum2,
250            $constraint, $bibitems,  3, $resdate, $expdate, $notes,
251            $title,      $checkitem, $found);
252
253 # Ensure that the item's home library controls hold policy lookup
254 C4::Context->set_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
255
256 my $messages;
257 # Return the CPL item at FPL.  The hold that should be triggered is
258 # the one placed by the CPL patron, as the other two patron's hold
259 # requests cannot be filled by that item per policy.
260 (undef, $messages, undef, undef) = AddReturn('bug10272_CPL', 'FPL');
261 is( $messages->{ResFound}->{borrowernumber},
262     $requesters{'CPL'},
263     'restrictive library\'s items only fill requests by own patrons (bug 10272)');
264
265 # Return the FPL item at FPL.  The hold that should be triggered is
266 # the one placed by the RPL patron, as that patron is first in line
267 # and RPL imposes no restrictions on whose holds its items can fill.
268 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', 'FPL');
269 is( $messages->{ResFound}->{borrowernumber},
270     $requesters{'RPL'},
271     'for generous library, its items fill first hold request in line (bug 10272)');
272
273 my $reserves = GetReservesFromBiblionumber({biblionumber => $biblionumber});
274 isa_ok($reserves, 'ARRAY');
275 is(scalar @$reserves, 1, "Only one reserves for this biblio");
276 my $reserve_id = $reserves->[0]->{reserve_id};
277
278 $reserve = GetReserve($reserve_id);
279 isa_ok($reserve, 'HASH', "GetReserve return");
280 is($reserve->{biblionumber}, $biblionumber);
281
282 $reserve = CancelReserve({reserve_id => $reserve_id});
283 isa_ok($reserve, 'HASH', "CancelReserve return");
284 is($reserve->{biblionumber}, $biblionumber);
285
286 $reserve = GetReserve($reserve_id);
287 is($reserve, undef, "GetReserve returns undef after deletion");
288
289 $reserve = CancelReserve({reserve_id => $reserve_id});
290 is($reserve, undef, "CancelReserve return undef if reserve does not exist");
291
292
293 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
294 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
295 # Test 9761a: Add a reserve without date, CheckReserve should return it
296 $resdate= undef; #defaults to today in AddReserve
297 $expdate= undef; #no expdate
298 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
299 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
300            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
301            $title,      $checkitem, $found);
302 ($status)=CheckReserves($itemnumber,undef,undef);
303 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
304 ($status)=CheckReserves($itemnumber,undef,7);
305 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
306
307 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
308 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
309 C4::Context->set_preference('AllowHoldDateInFuture', 1);
310 $resdate= dt_from_string();
311 $resdate->add_duration(DateTime::Duration->new(days => 4));
312 $resdate=output_pref($resdate);
313 $expdate= undef; #no expdate
314 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
315            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
316            $title,      $checkitem, $found);
317 ($status)=CheckReserves($itemnumber,undef,undef);
318 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
319
320 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
321 ($status)=CheckReserves($itemnumber,undef,3);
322 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
323 ($status)=CheckReserves($itemnumber,undef,4);
324 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
325
326 # Test 9761d: Check ResFound message of AddReturn for future hold
327 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
328 # In this test we do not need an issued item; it is just a 'checkin'
329 C4::Context->set_preference('ConfirmFutureHolds', 0);
330 (my $doreturn, $messages)= AddReturn('97531','CPL');
331 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
332 C4::Context->set_preference('ConfirmFutureHolds', 3);
333 ($doreturn, $messages)= AddReturn('97531','CPL');
334 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
335 C4::Context->set_preference('ConfirmFutureHolds', 7);
336 ($doreturn, $messages)= AddReturn('97531','CPL');
337 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
338
339 # End of tests for bug 9761 (ConfirmFutureHolds)
340
341 # test marking a hold as captured
342 my $hold_notice_count = count_hold_print_messages();
343 ModReserveAffect($itemnumber, $requesters{'CPL'}, 0);
344 my $new_count = count_hold_print_messages();
345 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
346
347 # test that duplicate notices aren't generated
348 ModReserveAffect($itemnumber, $requesters{'CPL'}, 0);
349 $new_count = count_hold_print_messages();
350 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
351
352 # avoiding the not_same_branch error
353 t::lib::Mocks::mock_preference('IndependentBranches', 0);
354 is(
355     DelItemCheck($dbh, $bibnum, $itemnumber),
356     'book_reserved',
357     'item that is captured to fill a hold cannot be deleted',
358 );
359
360 my $letter = ReserveSlip('CPL', $requesters{'CPL'}, $bibnum);
361 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
362
363 # Tests for bug 9788: Does GetReservesFromItemnumber return a future wait?
364 # 9788a: GetReservesFromItemnumber does not return future next available hold
365 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
366 C4::Context->set_preference('ConfirmFutureHolds', 2);
367 C4::Context->set_preference('AllowHoldDateInFuture', 1);
368 $resdate= dt_from_string();
369 $resdate->add_duration(DateTime::Duration->new(days => 2));
370 $resdate=output_pref($resdate);
371 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
372            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
373            $title,      $checkitem, $found);
374 my @results= GetReservesFromItemnumber($itemnumber);
375 is(defined $results[3]?1:0, 0, 'GetReservesFromItemnumber does not return a future next available hold');
376 # 9788b: GetReservesFromItemnumber does not return future item level hold
377 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
378 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
379            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
380            $title,      $itemnumber, $found); #item level hold
381 @results= GetReservesFromItemnumber($itemnumber);
382 is(defined $results[3]?1:0, 0, 'GetReservesFromItemnumber does not return a future item level hold');
383 # 9788c: GetReservesFromItemnumber returns future wait (confirmed future hold)
384 ModReserveAffect( $itemnumber,  $requesters{'CPL'} , 0); #confirm hold
385 @results= GetReservesFromItemnumber($itemnumber);
386 is(defined $results[3]?1:0, 1, 'GetReservesFromItemnumber returns a future wait (confirmed future hold)');
387 # End of tests for bug 9788
388
389 # Tests for CalculatePriority (bug 8918)
390 my $p = C4::Reserves::CalculatePriority($bibnum2);
391 is($p, 4, 'CalculatePriority should now return priority 4');
392 $resdate=undef;
393 AddReserve('CPL',  $requesters{'CPL'}, $bibnum2,
394            $constraint, $bibitems,  $p, $resdate, $expdate, $notes,
395            $title,      $checkitem, $found);
396 $p = C4::Reserves::CalculatePriority($bibnum2);
397 is($p, 5, 'CalculatePriority should now return priority 5');
398 #some tests on bibnum
399 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
400 $p = C4::Reserves::CalculatePriority($bibnum);
401 is($p, 1, 'CalculatePriority should now return priority 1');
402 #add a new reserve and confirm it to waiting
403 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
404            $constraint, $bibitems,  $p, $resdate, $expdate, $notes,
405            $title,      $itemnumber, $found);
406 $p = C4::Reserves::CalculatePriority($bibnum);
407 is($p, 2, 'CalculatePriority should now return priority 2');
408 ModReserveAffect( $itemnumber,  $requesters{'CPL'} , 0);
409 $p = C4::Reserves::CalculatePriority($bibnum);
410 is($p, 1, 'CalculatePriority should now return priority 1');
411 #add another biblio hold, no resdate
412 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
413            $constraint, $bibitems,  $p, $resdate, $expdate, $notes,
414            $title,      $checkitem, $found);
415 $p = C4::Reserves::CalculatePriority($bibnum);
416 is($p, 2, 'CalculatePriority should now return priority 2');
417 #add another future hold
418 C4::Context->set_preference('AllowHoldDateInFuture', 1);
419 $resdate= dt_from_string();
420 $resdate->add_duration(DateTime::Duration->new(days => 1));
421 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
422            $constraint, $bibitems,  $p, output_pref($resdate), $expdate, $notes,
423            $title,      $checkitem, $found);
424 $p = C4::Reserves::CalculatePriority($bibnum);
425 is($p, 2, 'CalculatePriority should now still return priority 2');
426 #calc priority with future resdate
427 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
428 is($p, 3, 'CalculatePriority should now return priority 3');
429 # End of tests for bug 8918
430
431 # Tests for cancel reserves by users from OPAC.
432 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
433 AddReserve('CPL',  $requesters{'CPL'}, $item_bibnum,
434            $constraint, $bibitems,  1, undef, $expdate, $notes,
435            $title,      $checkitem, '');
436 my (undef, $canres, undef) = CheckReserves($itemnumber);
437
438 is( CanReserveBeCanceledFromOpac(), undef,
439     'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
440 );
441 is(
442     CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
443     undef,
444     'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
445 );
446 is(
447     CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
448     undef,
449     'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
450 );
451
452 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{'CPL'});
453 is($cancancel, 1, 'Can user cancel its own reserve');
454
455 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{'FPL'});
456 is($cancancel, 0, 'Other user cant cancel reserve');
457
458 ModReserveAffect($itemnumber, $requesters{'CPL'}, 1);
459 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{'CPL'});
460 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
461
462 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
463 AddReserve('CPL',  $requesters{'CPL'}, $item_bibnum,
464            $constraint, $bibitems,  1, undef, $expdate, $notes,
465            $title,      $checkitem, '');
466 (undef, $canres, undef) = CheckReserves($itemnumber);
467
468 ModReserveAffect($itemnumber, $requesters{'CPL'}, 0);
469 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{'CPL'});
470 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
471
472 # End of tests for bug 12876
473
474 $dbh->rollback;
475
476 sub count_hold_print_messages {
477     my $message_count = $dbh->selectall_arrayref(q{
478         SELECT COUNT(*)
479         FROM message_queue
480         WHERE letter_code = 'HOLD' 
481         AND   message_transport_type = 'print'
482     });
483     return $message_count->[0]->[0];
484 }