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