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