Bug 17736: Replace GetReservesFromBiblionumber with Koha::Biblio->holds
[koha.git] / t / db_dependent / Holds.t
1 #!/usr/bin/perl
2
3 use Modern::Perl;
4
5 use t::lib::Mocks;
6 use t::lib::TestBuilder;
7
8 use C4::Context;
9
10 use Test::More tests => 61;
11 use MARC::Record;
12 use C4::Biblio;
13 use C4::Items;
14 use C4::Members;
15 use C4::Calendar;
16 use Koha::Database;
17 use Koha::DateUtils qw( dt_from_string output_pref );
18 use Koha::Biblios;
19 use Koha::Holds;
20
21 BEGIN {
22     use FindBin;
23     use lib $FindBin::Bin;
24     use_ok('C4::Reserves');
25 }
26
27 my $schema  = Koha::Database->new->schema;
28 $schema->storage->txn_begin;
29
30 my $builder = t::lib::TestBuilder->new();
31 my $dbh     = C4::Context->dbh;
32
33 # Create two random branches
34 my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode };
35 my $branch_2 = $builder->build({ source => 'Branch' })->{ branchcode };
36
37 my $category = $builder->build({ source => 'Category' });
38
39 my $borrowers_count = 5;
40
41 $dbh->do('DELETE FROM itemtypes');
42 $dbh->do('DELETE FROM reserves');
43 my $insert_sth = $dbh->prepare('INSERT INTO itemtypes (itemtype) VALUES (?)');
44 $insert_sth->execute('CAN');
45 $insert_sth->execute('CANNOT');
46 $insert_sth->execute('DUMMY');
47 $insert_sth->execute('ONLY1');
48
49 # Setup Test------------------------
50 # Create a biblio instance for testing
51 my ($bibnum, $title, $bibitemnum) = create_helper_biblio('DUMMY');
52
53 # Create item instance for testing.
54 my ($item_bibnum, $item_bibitemnum, $itemnumber)
55     = AddItem({ homebranch => $branch_1, holdingbranch => $branch_1 } , $bibnum);
56
57 # Create some borrowers
58 my @borrowernumbers;
59 foreach (1..$borrowers_count) {
60     my $borrowernumber = AddMember(
61         firstname =>  'my firstname',
62         surname => 'my surname ' . $_,
63         categorycode => $category->{categorycode},
64         branchcode => $branch_1,
65     );
66     push @borrowernumbers, $borrowernumber;
67 }
68
69 my $biblionumber = $bibnum;
70
71 # Create five item level holds
72 foreach my $borrowernumber ( @borrowernumbers ) {
73     AddReserve(
74         $branch_1,
75         $borrowernumber,
76         $biblionumber,
77         my $bibitems = q{},
78         my $priority = C4::Reserves::CalculatePriority( $biblionumber ),
79         my $resdate,
80         my $expdate,
81         my $notes = q{},
82         $title,
83         my $checkitem = $itemnumber,
84         my $found,
85     );
86 }
87
88 my $biblio = Koha::Biblios->find( $biblionumber );
89 my $holds = $biblio->holds;
90 is( $holds->count, $borrowers_count, 'Test GetReserves()' );
91 is( $holds->next->priority, 1, "Reserve 1 has a priority of 1" );
92 is( $holds->next->priority, 2, "Reserve 2 has a priority of 2" );
93 is( $holds->next->priority, 3, "Reserve 3 has a priority of 3" );
94 is( $holds->next->priority, 4, "Reserve 4 has a priority of 4" );
95 is( $holds->next->priority, 5, "Reserve 5 has a priority of 5" );
96
97 my ( $reservedate, $borrowernumber, $branch_1code, $reserve_id ) = GetReservesFromItemnumber($itemnumber);
98 is( $reservedate, output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }), "GetReservesFromItemnumber should return a valid reserve date");
99 is( $borrowernumber, $borrowernumbers[0], "GetReservesFromItemnumber should return a valid borrowernumber");
100 is( $branch_1code, $branch_1, "GetReservesFromItemnumber should return a valid branchcode");
101 ok($reserve_id, "Test GetReservesFromItemnumber()");
102
103 my $hold = Koha::Holds->find( $reserve_id );
104 ok( $hold, "Koha::Holds found the hold" );
105 my $hold_biblio = $hold->biblio();
106 ok( $hold_biblio, "Got biblio using biblio() method" );
107 ok( $hold_biblio == $hold->biblio(), "biblio method returns stashed biblio" );
108 my $hold_item = $hold->item();
109 ok( $hold_item, "Got item using item() method" );
110 ok( $hold_item == $hold->item(), "item method returns stashed item" );
111 my $hold_branch = $hold->branch();
112 ok( $hold_branch, "Got branch using branch() method" );
113 ok( $hold_branch == $hold->branch(), "branch method returns stashed branch" );
114 my $hold_found = $hold->found();
115 $hold->set({ found => 'W'})->store();
116 is( Koha::Holds->waiting()->count(), 1, "Koha::Holds->waiting returns waiting holds" );
117
118 my ( $reserve ) = GetReservesFromBorrowernumber($borrowernumbers[0]);
119 ok( $reserve->{'borrowernumber'} eq $borrowernumbers[0], "Test GetReservesFromBorrowernumber()");
120
121
122 ok( GetReserveCount( $borrowernumbers[0] ), "Test GetReserveCount()" );
123
124
125 CancelReserve({ 'reserve_id' => $reserve_id });
126 $holds = $biblio->holds;
127 is( $holds->count, $borrowers_count - 1, "Test CancelReserve()" );
128
129
130 ( $reservedate, $borrowernumber, $branch_1code, $reserve_id ) = GetReservesFromItemnumber($itemnumber);
131 ModReserve({
132     reserve_id    => $reserve_id,
133     rank          => '4',
134     branchcode    => $branch_1,
135     itemnumber    => $itemnumber,
136     suspend_until => output_pref( { dt => dt_from_string( "2013-01-01", "iso" ), dateonly => 1 } ),
137 });
138
139 $reserve = GetReserve( $reserve_id );
140 ok( $reserve->{'priority'} eq '4', "Test GetReserve(), priority changed correctly" );
141 ok( $reserve->{'suspend'}, "Test GetReserve(), suspend hold" );
142 is( $reserve->{'suspend_until'}, '2013-01-01 00:00:00', "Test GetReserve(), suspend until date" );
143
144 ToggleSuspend( $reserve_id );
145 $reserve = GetReserve( $reserve_id );
146 ok( !$reserve->{'suspend'}, "Test ToggleSuspend(), no date" );
147
148 ToggleSuspend( $reserve_id, '2012-01-01' );
149 $reserve = GetReserve( $reserve_id );
150 is( $reserve->{'suspend_until'}, '2012-01-01 00:00:00', "Test ToggleSuspend(), with date" );
151
152 AutoUnsuspendReserves();
153 $reserve = GetReserve( $reserve_id );
154 ok( !$reserve->{'suspend'}, "Test AutoUnsuspendReserves()" );
155
156 SuspendAll(
157     borrowernumber => $borrowernumber,
158     biblionumber   => $biblionumber,
159     suspend => 1,
160     suspend_until => '2012-01-01',
161 );
162 $reserve = GetReserve( $reserve_id );
163 is( $reserve->{'suspend'}, 1, "Test SuspendAll()" );
164 is( $reserve->{'suspend_until'}, '2012-01-01 00:00:00', "Test SuspendAll(), with date" );
165
166 SuspendAll(
167     borrowernumber => $borrowernumber,
168     biblionumber   => $biblionumber,
169     suspend => 0,
170 );
171 $reserve = GetReserve( $reserve_id );
172 is( $reserve->{'suspend'}, 0, "Test resuming with SuspendAll()" );
173 is( $reserve->{'suspend_until'}, undef, "Test resuming with SuspendAll(), should have no suspend until date" );
174
175 # Add a new hold for the borrower whose hold we canceled earlier, this time at the bib level
176 AddReserve(
177     $branch_1,
178     $borrowernumbers[0],
179     $biblionumber,
180     my $bibitems = q{},
181     my $priority,
182     my $resdate,
183     my $expdate,
184     my $notes = q{},
185     $title,
186     my $checkitem,
187     my $found,
188 );
189 ( $reserve ) = GetReservesFromBorrowernumber($borrowernumber);
190 my $reserveid = C4::Reserves::GetReserveId(
191     {
192         biblionumber => $biblionumber,
193         borrowernumber => $borrowernumber
194     }
195 );
196 is( $reserveid, $reserve->{reserve_id}, "Test GetReserveId" );
197 ModReserveMinusPriority( $itemnumber, $reserve->{'reserve_id'} );
198 ( $reserve ) = GetReservesFromBorrowernumber($borrowernumber);
199 ok( $reserve->{'itemnumber'} eq $itemnumber, "Test ModReserveMinusPriority()" );
200
201
202 my $reserve2 = GetReserveInfo( $reserve->{'reserve_id'} );
203 ok( $reserve->{'reserve_id'} eq $reserve2->{'reserve_id'}, "Test GetReserveInfo()" );
204
205
206 $holds = $biblio->holds;
207 my $hold = $holds->next;
208 AlterPriority( 'top', $hold->reserve_id );
209 $reserve = GetReserve( $reserve->{'reserve_id'} );
210 is( $reserve->{'priority'}, '1', "Test AlterPriority(), move to top" );
211
212 AlterPriority( 'down', $reserve->{'reserve_id'} );
213 $reserve = GetReserve( $reserve->{'reserve_id'} );
214 is( $reserve->{'priority'}, '2', "Test AlterPriority(), move down" );
215
216 AlterPriority( 'up', $reserve->{'reserve_id'} );
217 $reserve = GetReserve( $reserve->{'reserve_id'} );
218 is( $reserve->{'priority'}, '1', "Test AlterPriority(), move up" );
219
220 AlterPriority( 'bottom', $reserve->{'reserve_id'} );
221 $reserve = GetReserve( $reserve->{'reserve_id'} );
222 is( $reserve->{'priority'}, '5', "Test AlterPriority(), move to bottom" );
223
224 # Regression test for bug 2394
225 #
226 # If IndependentBranches is ON and canreservefromotherbranches is OFF,
227 # a patron is not permittedo to request an item whose homebranch (i.e.,
228 # owner of the item) is different from the patron's own library.
229 # However, if canreservefromotherbranches is turned ON, the patron can
230 # create such hold requests.
231 #
232 # Note that canreservefromotherbranches has no effect if
233 # IndependentBranches is OFF.
234
235 my ($foreign_bibnum, $foreign_title, $foreign_bibitemnum) = create_helper_biblio('DUMMY');
236 my ($foreign_item_bibnum, $foreign_item_bibitemnum, $foreign_itemnumber)
237   = AddItem({ homebranch => $branch_2, holdingbranch => $branch_2 } , $foreign_bibnum);
238 $dbh->do('DELETE FROM issuingrules');
239 $dbh->do(
240     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed, holds_per_record)
241       VALUES (?, ?, ?, ?, ?)},
242     {},
243     '*', '*', '*', 25, 99
244 );
245 $dbh->do(
246     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed, holds_per_record)
247       VALUES (?, ?, ?, ?, ?)},
248     {},
249     '*', '*', 'CANNOT', 0, 99
250 );
251
252 # make sure some basic sysprefs are set
253 t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
254 t::lib::Mocks::mock_preference('item-level_itypes', 1);
255
256 # if IndependentBranches is OFF, a $branch_1 patron can reserve an $branch_2 item
257 t::lib::Mocks::mock_preference('IndependentBranches', 0);
258 ok(
259     CanItemBeReserved($borrowernumbers[0], $foreign_itemnumber) eq 'OK',
260     '$branch_1 patron allowed to reserve $branch_2 item with IndependentBranches OFF (bug 2394)'
261 );
262
263 # if IndependentBranches is OFF, a $branch_1 patron cannot reserve an $branch_2 item
264 t::lib::Mocks::mock_preference('IndependentBranches', 1);
265 t::lib::Mocks::mock_preference('canreservefromotherbranches', 0);
266 ok(
267     CanItemBeReserved($borrowernumbers[0], $foreign_itemnumber) eq 'cannotReserveFromOtherBranches',
268     '$branch_1 patron NOT allowed to reserve $branch_2 item with IndependentBranches ON ... (bug 2394)'
269 );
270
271 # ... unless canreservefromotherbranches is ON
272 t::lib::Mocks::mock_preference('canreservefromotherbranches', 1);
273 ok(
274     CanItemBeReserved($borrowernumbers[0], $foreign_itemnumber) eq 'OK',
275     '... unless canreservefromotherbranches is ON (bug 2394)'
276 );
277
278 # Regression test for bug 11336
279 ($bibnum, $title, $bibitemnum) = create_helper_biblio('DUMMY');
280 ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $branch_1, holdingbranch => $branch_1 } , $bibnum);
281 AddReserve(
282     $branch_1,
283     $borrowernumbers[0],
284     $bibnum,
285     '',
286     1,
287 );
288
289 my $reserveid1 = C4::Reserves::GetReserveId(
290     {
291         biblionumber => $bibnum,
292         borrowernumber => $borrowernumbers[0]
293     }
294 );
295
296 ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $branch_1, holdingbranch => $branch_1 } , $bibnum);
297 AddReserve(
298     $branch_1,
299     $borrowernumbers[1],
300     $bibnum,
301     '',
302     2,
303 );
304 my $reserveid2 = C4::Reserves::GetReserveId(
305     {
306         biblionumber => $bibnum,
307         borrowernumber => $borrowernumbers[1]
308     }
309 );
310
311 CancelReserve({ reserve_id => $reserveid1 });
312
313 $reserve2 = GetReserve( $reserveid2 );
314 is( $reserve2->{priority}, 1, "After cancelreserve, the 2nd reserve becomes the first on the waiting list" );
315
316 ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $branch_1, holdingbranch => $branch_1 } , $bibnum);
317 AddReserve(
318     $branch_1,
319     $borrowernumbers[0],
320     $bibnum,
321     '',
322     2,
323 );
324 my $reserveid3 = C4::Reserves::GetReserveId(
325     {
326         biblionumber => $bibnum,
327         borrowernumber => $borrowernumbers[0]
328     }
329 );
330
331 my $reserve3 = GetReserve( $reserveid3 );
332 is( $reserve3->{priority}, 2, "New reserve for patron 0, the reserve has a priority = 2" );
333
334 ModReserve({ reserve_id => $reserveid2, rank => 'del' });
335 $reserve3 = GetReserve( $reserveid3 );
336 is( $reserve3->{priority}, 1, "After ModReserve, the 3rd reserve becomes the first on the waiting list" );
337
338 ModItem({ damaged => 1 }, $item_bibnum, $itemnumber);
339 t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', 1 );
340 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber), 'OK', "Patron can reserve damaged item with AllowHoldsOnDamagedItems enabled" );
341 ok( defined( ( CheckReserves($itemnumber) )[1] ), "Hold can be trapped for damaged item with AllowHoldsOnDamagedItems enabled" );
342
343 $hold = Koha::Hold->new(
344     {
345         borrowernumber => $borrowernumbers[0],
346         itemnumber     => $itemnumber,
347         biblionumber   => $item_bibnum,
348     }
349 )->store();
350 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber ),
351     'itemAlreadyOnHold',
352     "Patron cannot place a second item level hold for a given item" );
353 $hold->delete();
354
355 t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', 0 );
356 ok( CanItemBeReserved( $borrowernumbers[0], $itemnumber) eq 'damaged', "Patron cannot reserve damaged item with AllowHoldsOnDamagedItems disabled" );
357 ok( !defined( ( CheckReserves($itemnumber) )[1] ), "Hold cannot be trapped for damaged item with AllowHoldsOnDamagedItems disabled" );
358
359 # Regression test for bug 9532
360 ($bibnum, $title, $bibitemnum) = create_helper_biblio('CANNOT');
361 ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $branch_1, holdingbranch => $branch_1, itype => 'CANNOT' } , $bibnum);
362 AddReserve(
363     $branch_1,
364     $borrowernumbers[0],
365     $bibnum,
366     '',
367     1,
368 );
369 is(
370     CanItemBeReserved( $borrowernumbers[0], $itemnumber), 'tooManyReserves',
371     "cannot request item if policy that matches on item-level item type forbids it"
372 );
373 ModItem({ itype => 'CAN' }, $item_bibnum, $itemnumber);
374 ok(
375     CanItemBeReserved( $borrowernumbers[0], $itemnumber) eq 'OK',
376     "can request item if policy that matches on item type allows it"
377 );
378
379 t::lib::Mocks::mock_preference('item-level_itypes', 0);
380 ModItem({ itype => undef }, $item_bibnum, $itemnumber);
381 ok(
382     CanItemBeReserved( $borrowernumbers[0], $itemnumber) eq 'tooManyReserves',
383     "cannot request item if policy that matches on bib-level item type forbids it (bug 9532)"
384 );
385
386
387 # Test branch item rules
388
389 $dbh->do('DELETE FROM issuingrules');
390 $dbh->do(
391     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed)
392       VALUES (?, ?, ?, ?)},
393     {},
394     '*', '*', '*', 25
395 );
396 $dbh->do('DELETE FROM branch_item_rules');
397 $dbh->do('DELETE FROM default_branch_circ_rules');
398 $dbh->do('DELETE FROM default_branch_item_rules');
399 $dbh->do('DELETE FROM default_circ_rules');
400 $dbh->do(q{
401     INSERT INTO branch_item_rules (branchcode, itemtype, holdallowed, returnbranch)
402     VALUES (?, ?, ?, ?)
403 }, {}, $branch_1, 'CANNOT', 0, 'homebranch');
404 $dbh->do(q{
405     INSERT INTO branch_item_rules (branchcode, itemtype, holdallowed, returnbranch)
406     VALUES (?, ?, ?, ?)
407 }, {}, $branch_1, 'CAN', 1, 'homebranch');
408 ($bibnum, $title, $bibitemnum) = create_helper_biblio('CANNOT');
409 ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem(
410     { homebranch => $branch_1, holdingbranch => $branch_1, itype => 'CANNOT' } , $bibnum);
411 is(CanItemBeReserved($borrowernumbers[0], $itemnumber), 'notReservable',
412     "CanItemBeReserved should returns 'notReservable'");
413
414 ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem(
415     { homebranch => $branch_2, holdingbranch => $branch_1, itype => 'CAN' } , $bibnum);
416 is(CanItemBeReserved($borrowernumbers[0], $itemnumber),
417     'cannotReserveFromOtherBranches',
418     "CanItemBeReserved should returns 'cannotReserveFromOtherBranches'");
419
420 ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem(
421     { homebranch => $branch_1, holdingbranch => $branch_1, itype => 'CAN' } , $bibnum);
422 is(CanItemBeReserved($borrowernumbers[0], $itemnumber), 'OK',
423     "CanItemBeReserved should returns 'OK'");
424
425
426 # Test CancelExpiredReserves
427 t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelay', 1);
428 t::lib::Mocks::mock_preference('ReservesMaxPickUpDelay', 1);
429
430 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime(time);
431 $year += 1900;
432 $mon += 1;
433 my $reserves = $dbh->selectall_arrayref('SELECT * FROM reserves', { Slice => {} });
434 $reserve = $reserves->[0];
435 my $calendar = C4::Calendar->new(branchcode => $reserve->{branchcode});
436 $calendar->insert_single_holiday(
437     day         => $mday,
438     month       => $mon,
439     year        => $year,
440     title       => 'Test',
441     description => 'Test',
442 );
443 $reserve_id = $reserve->{reserve_id};
444 $dbh->do("UPDATE reserves SET waitingdate = DATE_SUB( NOW(), INTERVAL 5 DAY ), found = 'W', priority = 0 WHERE reserve_id = ?", undef, $reserve_id );
445 t::lib::Mocks::mock_preference('ExpireReservesOnHolidays', 0);
446 CancelExpiredReserves();
447 my $count = $dbh->selectrow_array("SELECT COUNT(*) FROM reserves WHERE reserve_id = ?", undef, $reserve_id );
448 is( $count, 1, "Waiting reserve beyond max pickup delay *not* canceled on holiday" );
449 t::lib::Mocks::mock_preference('ExpireReservesOnHolidays', 1);
450 CancelExpiredReserves();
451 $count = $dbh->selectrow_array("SELECT COUNT(*) FROM reserves WHERE reserve_id = ?", undef, $reserve_id );
452 is( $count, 0, "Waiting reserve beyond max pickup delay canceled on holiday" );
453
454 # Test expirationdate
455 $reserve = $reserves->[1];
456 $reserve_id = $reserve->{reserve_id};
457 $dbh->do("UPDATE reserves SET expirationdate = DATE_SUB( NOW(), INTERVAL 1 DAY ) WHERE reserve_id = ?", undef, $reserve_id );
458 CancelExpiredReserves();
459 $count = $dbh->selectrow_array("SELECT COUNT(*) FROM reserves WHERE reserve_id = ?", undef, $reserve_id );
460 is( $count, 0, "Reserve with manual expiration date canceled correctly" );
461
462 # Bug 12632
463 t::lib::Mocks::mock_preference( 'item-level_itypes',     1 );
464 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
465
466 $dbh->do('DELETE FROM reserves');
467 $dbh->do('DELETE FROM issues');
468 $dbh->do('DELETE FROM items');
469 $dbh->do('DELETE FROM biblio');
470
471 ( $bibnum, $title, $bibitemnum ) = create_helper_biblio('ONLY1');
472 ( $item_bibnum, $item_bibitemnum, $itemnumber )
473     = AddItem( { homebranch => $branch_1, holdingbranch => $branch_1 }, $bibnum );
474
475 $dbh->do(
476     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed, holds_per_record)
477       VALUES (?, ?, ?, ?, ?)},
478     {},
479     '*', '*', 'ONLY1', 1, 99
480 );
481 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber ),
482     'OK', 'Patron can reserve item with hold limit of 1, no holds placed' );
483
484 my $res_id = AddReserve( $branch_1, $borrowernumbers[0], $bibnum, '', 1, );
485
486 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber ),
487     'tooManyReserves', 'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed' );
488
489
490 # Helper method to set up a Biblio.
491 sub create_helper_biblio {
492     my $itemtype = shift;
493     my $bib = MARC::Record->new();
494     my $title = 'Silence in the library';
495     $bib->append_fields(
496         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
497         MARC::Field->new('245', ' ', ' ', a => $title),
498         MARC::Field->new('942', ' ', ' ', c => $itemtype),
499     );
500     return ($bibnum, $title, $bibitemnum) = AddBiblio($bib, '');
501 }