Bug 17829: Move GetMember to Koha::Patron
[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 => 72;
21 use Test::MockModule;
22 use Test::Warn;
23
24 use t::lib::Mocks;
25 use t::lib::TestBuilder;
26
27 use MARC::Record;
28 use DateTime::Duration;
29
30 use C4::Biblio;
31 use C4::Circulation;
32 use C4::Items;
33 use C4::Members;
34 use C4::Reserves;
35 use Koha::Caches;
36 use Koha::DateUtils;
37 use Koha::Holds;
38 use Koha::Libraries;
39 use Koha::Notice::Templates;
40 use Koha::Patrons;
41 use Koha::Patron::Categories;
42
43 BEGIN {
44     require_ok('C4::Reserves');
45 }
46
47 # Start transaction
48 my $database = Koha::Database->new();
49 my $schema = $database->schema();
50 $schema->storage->txn_begin();
51 my $dbh = C4::Context->dbh;
52
53 my $builder = t::lib::TestBuilder->new;
54
55 my $frameworkcode = q||;
56
57 # Somewhat arbitrary field chosen for age restriction unit tests. Must be added to db before the framework is cached
58 $dbh->do("update marc_subfield_structure set kohafield='biblioitems.agerestriction' where tagfield='521' and tagsubfield='a' and frameworkcode=?", undef, $frameworkcode);
59 my $cache = Koha::Caches->get_instance;
60 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
61 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
62 $cache->clear_from_cache("default_value_for_mod_marc-$frameworkcode");
63 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
64
65 ## Setup Test
66 # Add branches
67 my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode };
68 my $branch_2 = $builder->build({ source => 'Branch' })->{ branchcode };
69 my $branch_3 = $builder->build({ source => 'Branch' })->{ branchcode };
70 # Add categories
71 my $category_1 = $builder->build({ source => 'Category' })->{ categorycode };
72 my $category_2 = $builder->build({ source => 'Category' })->{ categorycode };
73 # Add an item type
74 my $itemtype = $builder->build(
75     { source => 'Itemtype', value => { notforloan => undef } } )->{itemtype};
76
77 C4::Context->set_userenv(
78     undef, undef, undef, undef, undef, undef, $branch_1
79 );
80
81 # Create a helper biblio
82 my $bib = MARC::Record->new();
83 my $title = 'Silence in the library';
84 if( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
85     $bib->append_fields(
86         MARC::Field->new('600', '', '1', a => 'Moffat, Steven'),
87         MARC::Field->new('200', '', '', a => $title),
88     );
89 }
90 else {
91     $bib->append_fields(
92         MARC::Field->new('100', '', '', a => 'Moffat, Steven'),
93         MARC::Field->new('245', '', '', a => $title),
94     );
95 }
96 my ($bibnum, $bibitemnum);
97 ($bibnum, $title, $bibitemnum) = AddBiblio($bib, $frameworkcode);
98
99 # Create a helper item instance for testing
100 my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
101     {   homebranch    => $branch_1,
102         holdingbranch => $branch_1,
103         itype         => $itemtype
104     },
105     $bibnum
106 );
107
108
109 # Modify item; setting barcode.
110 my $testbarcode = '97531';
111 ModItem({ barcode => $testbarcode }, $bibnum, $itemnumber);
112
113 # Create a borrower
114 my %data = (
115     firstname =>  'my firstname',
116     surname => 'my surname',
117     categorycode => $category_1,
118     branchcode => $branch_1,
119 );
120 Koha::Patron::Categories->find($category_1)->set({ enrolmentfee => 0})->store;
121 my $borrowernumber = AddMember(%data);
122 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
123 my $biblionumber   = $bibnum;
124 my $barcode        = $testbarcode;
125
126 my $bibitems       = '';
127 my $priority       = '1';
128 my $resdate        = undef;
129 my $expdate        = undef;
130 my $notes          = '';
131 my $checkitem      = undef;
132 my $found          = undef;
133
134 my $branchcode = Koha::Libraries->search->next->branchcode;
135
136 AddReserve($branchcode,    $borrowernumber, $biblionumber,
137         $bibitems,  $priority, $resdate, $expdate, $notes,
138         $title,      $checkitem, $found);
139
140 my ($status, $reserve, $all_reserves) = CheckReserves($itemnumber, $barcode);
141
142 is($status, "Reserved", "CheckReserves Test 1");
143
144 ok(exists($reserve->{reserve_id}), 'CheckReserves() include reserve_id in its response');
145
146 ($status, $reserve, $all_reserves) = CheckReserves($itemnumber);
147 is($status, "Reserved", "CheckReserves Test 2");
148
149 ($status, $reserve, $all_reserves) = CheckReserves(undef, $barcode);
150 is($status, "Reserved", "CheckReserves Test 3");
151
152 my $ReservesControlBranch = C4::Context->preference('ReservesControlBranch');
153 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
154 ok(
155     'ItemHomeLib' eq GetReservesControlBranch(
156         { homebranch => 'ItemHomeLib' },
157         { branchcode => 'PatronHomeLib' }
158     ), "GetReservesControlBranch returns item home branch when set to ItemHomeLibrary"
159 );
160 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
161 ok(
162     'PatronHomeLib' eq GetReservesControlBranch(
163         { homebranch => 'ItemHomeLib' },
164         { branchcode => 'PatronHomeLib' }
165     ), "GetReservesControlBranch returns patron home branch when set to PatronLibrary"
166 );
167 t::lib::Mocks::mock_preference( 'ReservesControlBranch', $ReservesControlBranch );
168
169 ###
170 ### Regression test for bug 10272
171 ###
172 my %requesters = ();
173 $requesters{$branch_1} = AddMember(
174     branchcode   => $branch_1,
175     categorycode => $category_2,
176     surname      => "borrower from $branch_1",
177 );
178 for my $i ( 2 .. 5 ) {
179     $requesters{"CPL$i"} = AddMember(
180         branchcode   => $branch_1,
181         categorycode => $category_2,
182         surname      => "borrower $i from $branch_1",
183     );
184 }
185 $requesters{$branch_2} = AddMember(
186     branchcode   => $branch_2,
187     categorycode => $category_2,
188     surname      => "borrower from $branch_2",
189 );
190 $requesters{$branch_3} = AddMember(
191     branchcode   => $branch_3,
192     categorycode => $category_2,
193     surname      => "borrower from $branch_3",
194 );
195
196 # Configure rules so that $branch_1 allows only $branch_1 patrons
197 # to request its items, while $branch_2 will allow its items
198 # to fill holds from anywhere.
199
200 $dbh->do('DELETE FROM issuingrules');
201 $dbh->do('DELETE FROM branch_item_rules');
202 $dbh->do('DELETE FROM branch_borrower_circ_rules');
203 $dbh->do('DELETE FROM default_borrower_circ_rules');
204 $dbh->do('DELETE FROM default_branch_item_rules');
205 $dbh->do('DELETE FROM default_branch_circ_rules');
206 $dbh->do('DELETE FROM default_circ_rules');
207 $dbh->do(
208     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed)
209       VALUES (?, ?, ?, ?)},
210     {},
211     '*', '*', '*', 25
212 );
213
214 # CPL allows only its own patrons to request its items
215 $dbh->do(
216     q{INSERT INTO default_branch_circ_rules (branchcode, maxissueqty, holdallowed, returnbranch)
217       VALUES (?, ?, ?, ?)},
218     {},
219     $branch_1, 10, 1, 'homebranch',
220 );
221
222 # ... while FPL allows anybody to request its items
223 $dbh->do(
224     q{INSERT INTO default_branch_circ_rules (branchcode, maxissueqty, holdallowed, returnbranch)
225       VALUES (?, ?, ?, ?)},
226     {},
227     $branch_2, 10, 2, 'homebranch',
228 );
229
230 # helper biblio for the bug 10272 regression test
231 my $bib2 = MARC::Record->new();
232 $bib2->append_fields(
233     MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
234     MARC::Field->new('245', ' ', ' ', a => $title),
235 );
236
237 # create one item belonging to FPL and one belonging to CPL
238 my ($bibnum2, $bibitemnum2) = AddBiblio($bib, $frameworkcode);
239 my ($itemnum_cpl, $itemnum_fpl);
240 ( undef, undef, $itemnum_cpl ) = AddItem(
241     {   homebranch    => $branch_1,
242         holdingbranch => $branch_1,
243         barcode       => 'bug10272_CPL',
244         itype         => $itemtype
245     },
246     $bibnum2
247 );
248 ( undef, undef, $itemnum_fpl ) = AddItem(
249     {   homebranch    => $branch_2,
250         holdingbranch => $branch_2,
251         barcode       => 'bug10272_FPL',
252         itype         => $itemtype
253     },
254     $bibnum2
255 );
256
257
258 # Ensure that priorities are numbered correcly when a hold is moved to waiting
259 # (bug 11947)
260 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
261 AddReserve($branch_3,  $requesters{$branch_3}, $bibnum2,
262            $bibitems,  1, $resdate, $expdate, $notes,
263            $title,      $checkitem, $found);
264 AddReserve($branch_2,  $requesters{$branch_2}, $bibnum2,
265            $bibitems,  2, $resdate, $expdate, $notes,
266            $title,      $checkitem, $found);
267 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum2,
268            $bibitems,  3, $resdate, $expdate, $notes,
269            $title,      $checkitem, $found);
270 ModReserveAffect($itemnum_cpl, $requesters{$branch_3}, 0);
271
272 # Now it should have different priorities.
273 my $biblio = Koha::Biblios->find( $bibnum2 );
274 my $holds = $biblio->holds({}, { order_by => 'reserve_id' });;
275 is($holds->next->priority, 0, 'Item is correctly waiting');
276 is($holds->next->priority, 1, 'Item is correctly priority 1');
277 is($holds->next->priority, 2, 'Item is correctly priority 2');
278
279 my @reserves = Koha::Holds->search({ borrowernumber => $requesters{$branch_3} })->waiting();
280 is( @reserves, 1, 'GetWaiting got only the waiting reserve' );
281 is( $reserves[0]->borrowernumber(), $requesters{$branch_3}, 'GetWaiting got the reserve for the correct borrower' );
282
283
284 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
285 AddReserve($branch_3,  $requesters{$branch_3}, $bibnum2,
286            $bibitems,  1, $resdate, $expdate, $notes,
287            $title,      $checkitem, $found);
288 AddReserve($branch_2,  $requesters{$branch_2}, $bibnum2,
289            $bibitems,  2, $resdate, $expdate, $notes,
290            $title,      $checkitem, $found);
291 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum2,
292            $bibitems,  3, $resdate, $expdate, $notes,
293            $title,      $checkitem, $found);
294
295 # Ensure that the item's home library controls hold policy lookup
296 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
297
298 my $messages;
299 # Return the CPL item at FPL.  The hold that should be triggered is
300 # the one placed by the CPL patron, as the other two patron's hold
301 # requests cannot be filled by that item per policy.
302 (undef, $messages, undef, undef) = AddReturn('bug10272_CPL', $branch_2);
303 is( $messages->{ResFound}->{borrowernumber},
304     $requesters{$branch_1},
305     'restrictive library\'s items only fill requests by own patrons (bug 10272)');
306
307 # Return the FPL item at FPL.  The hold that should be triggered is
308 # the one placed by the RPL patron, as that patron is first in line
309 # and RPL imposes no restrictions on whose holds its items can fill.
310
311 # Ensure that the preference 'LocalHoldsPriority' is not set (Bug 15244):
312 t::lib::Mocks::mock_preference( 'LocalHoldsPriority', '' );
313
314 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', $branch_2);
315 is( $messages->{ResFound}->{borrowernumber},
316     $requesters{$branch_3},
317     'for generous library, its items fill first hold request in line (bug 10272)');
318
319 $biblio = Koha::Biblios->find( $biblionumber );
320 $holds = $biblio->holds;
321 is($holds->count, 1, "Only one reserves for this biblio");
322 my $reserve_id = $holds->next->reserve_id;
323
324 $reserve = GetReserve($reserve_id);
325 isa_ok($reserve, 'HASH', "GetReserve return");
326 is($reserve->{biblionumber}, $biblionumber);
327
328 $reserve = CancelReserve({reserve_id => $reserve_id});
329 isa_ok($reserve, 'HASH', "CancelReserve return");
330 is($reserve->{biblionumber}, $biblionumber);
331
332 $reserve = GetReserve($reserve_id);
333 is($reserve, undef, "GetReserve returns undef after deletion");
334
335 $reserve = CancelReserve({reserve_id => $reserve_id});
336 is($reserve, undef, "CancelReserve return undef if reserve does not exist");
337
338
339 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
340 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
341 # Test 9761a: Add a reserve without date, CheckReserve should return it
342 $resdate= undef; #defaults to today in AddReserve
343 $expdate= undef; #no expdate
344 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
345 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
346            $bibitems,  1, $resdate, $expdate, $notes,
347            $title,      $checkitem, $found);
348 ($status)=CheckReserves($itemnumber,undef,undef);
349 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
350 ($status)=CheckReserves($itemnumber,undef,7);
351 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
352
353 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
354 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
355 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
356 $resdate= dt_from_string();
357 $resdate->add_duration(DateTime::Duration->new(days => 4));
358 $resdate=output_pref($resdate);
359 $expdate= undef; #no expdate
360 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
361            $bibitems,  1, $resdate, $expdate, $notes,
362            $title,      $checkitem, $found);
363 ($status)=CheckReserves($itemnumber,undef,undef);
364 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
365
366 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
367 ($status)=CheckReserves($itemnumber,undef,3);
368 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
369 ($status)=CheckReserves($itemnumber,undef,4);
370 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
371
372 # Test 9761d: Check ResFound message of AddReturn for future hold
373 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
374 # In this test we do not need an issued item; it is just a 'checkin'
375 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
376 (my $doreturn, $messages)= AddReturn('97531',$branch_1);
377 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
378 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3);
379 ($doreturn, $messages)= AddReturn('97531',$branch_1);
380 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
381 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7);
382 ($doreturn, $messages)= AddReturn('97531',$branch_1);
383 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
384
385 # End of tests for bug 9761 (ConfirmFutureHolds)
386
387 # test marking a hold as captured
388 my $hold_notice_count = count_hold_print_messages();
389 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
390 my $new_count = count_hold_print_messages();
391 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
392
393 # test that duplicate notices aren't generated
394 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
395 $new_count = count_hold_print_messages();
396 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
397
398 # avoiding the not_same_branch error
399 t::lib::Mocks::mock_preference('IndependentBranches', 0);
400 is(
401     DelItemCheck( $bibnum, $itemnumber),
402     'book_reserved',
403     'item that is captured to fill a hold cannot be deleted',
404 );
405
406 my $letter = ReserveSlip($branch_1, $requesters{$branch_1}, $bibnum);
407 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
408
409 # Tests for bug 9788: Does Koha::Item->current_holds return a future wait?
410 # 9788a: current_holds does not return future next available hold
411 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
412 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
413 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
414 $resdate= dt_from_string();
415 $resdate->add_duration(DateTime::Duration->new(days => 2));
416 $resdate=output_pref($resdate);
417 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
418            $bibitems,  1, $resdate, $expdate, $notes,
419            $title,      $checkitem, $found);
420 my $item = Koha::Items->find( $itemnumber );
421 $holds = $item->current_holds;
422 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
423 my $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
424 is( $future_holds->count, 0, 'current_holds does not return a future next available hold');
425 # 9788b: current_holds does not return future item level hold
426 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
427 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
428            $bibitems,  1, $resdate, $expdate, $notes,
429            $title,      $itemnumber, $found); #item level hold
430 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
431 is( $future_holds->count, 0, 'current_holds does not return a future item level hold' );
432 # 9788c: current_holds returns future wait (confirmed future hold)
433 ModReserveAffect( $itemnumber,  $requesters{$branch_1} , 0); #confirm hold
434 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
435 is( $future_holds->count, 1, 'current_holds returns a future wait (confirmed future hold)' );
436 # End of tests for bug 9788
437
438 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
439 # Tests for CalculatePriority (bug 8918)
440 my $p = C4::Reserves::CalculatePriority($bibnum2);
441 is($p, 4, 'CalculatePriority should now return priority 4');
442 $resdate=undef;
443 AddReserve($branch_1,  $requesters{'CPL2'}, $bibnum2,
444            $bibitems,  $p, $resdate, $expdate, $notes,
445            $title,      $checkitem, $found);
446 $p = C4::Reserves::CalculatePriority($bibnum2);
447 is($p, 5, 'CalculatePriority should now return priority 5');
448 #some tests on bibnum
449 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
450 $p = C4::Reserves::CalculatePriority($bibnum);
451 is($p, 1, 'CalculatePriority should now return priority 1');
452 #add a new reserve and confirm it to waiting
453 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
454            $bibitems,  $p, $resdate, $expdate, $notes,
455            $title,      $itemnumber, $found);
456 $p = C4::Reserves::CalculatePriority($bibnum);
457 is($p, 2, 'CalculatePriority should now return priority 2');
458 ModReserveAffect( $itemnumber,  $requesters{$branch_1} , 0);
459 $p = C4::Reserves::CalculatePriority($bibnum);
460 is($p, 1, 'CalculatePriority should now return priority 1');
461 #add another biblio hold, no resdate
462 AddReserve($branch_1,  $requesters{'CPL2'}, $bibnum,
463            $bibitems,  $p, $resdate, $expdate, $notes,
464            $title,      $checkitem, $found);
465 $p = C4::Reserves::CalculatePriority($bibnum);
466 is($p, 2, 'CalculatePriority should now return priority 2');
467 #add another future hold
468 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
469 $resdate= dt_from_string();
470 $resdate->add_duration(DateTime::Duration->new(days => 1));
471 AddReserve($branch_1,  $requesters{'CPL3'}, $bibnum,
472            $bibitems,  $p, output_pref($resdate), $expdate, $notes,
473            $title,      $checkitem, $found);
474 $p = C4::Reserves::CalculatePriority($bibnum);
475 is($p, 2, 'CalculatePriority should now still return priority 2');
476 #calc priority with future resdate
477 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
478 is($p, 3, 'CalculatePriority should now return priority 3');
479 # End of tests for bug 8918
480
481 # Tests for cancel reserves by users from OPAC.
482 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
483 AddReserve($branch_1,  $requesters{$branch_1}, $item_bibnum,
484            $bibitems,  1, undef, $expdate, $notes,
485            $title,      $checkitem, '');
486 my (undef, $canres, undef) = CheckReserves($itemnumber);
487
488 is( CanReserveBeCanceledFromOpac(), undef,
489     'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
490 );
491 is(
492     CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
493     undef,
494     'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
495 );
496 is(
497     CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
498     undef,
499     'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
500 );
501
502 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
503 is($cancancel, 1, 'Can user cancel its own reserve');
504
505 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_2});
506 is($cancancel, 0, 'Other user cant cancel reserve');
507
508 ModReserveAffect($itemnumber, $requesters{$branch_1}, 1);
509 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
510 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
511
512 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
513 AddReserve($branch_1,  $requesters{$branch_1}, $item_bibnum,
514            $bibitems,  1, undef, $expdate, $notes,
515            $title,      $checkitem, '');
516 (undef, $canres, undef) = CheckReserves($itemnumber);
517
518 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
519 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
520 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
521
522 # End of tests for bug 12876
523
524        ####
525 ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>>
526        ####
527
528 t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' );
529
530 #Reserving an not-agerestricted Biblio by a Borrower with no dateofbirth is tested previously.
531
532 #Set the ageRestriction for the Biblio
533 my $record = GetMarcBiblio( $bibnum );
534 my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" );
535 $record->append_fields(  MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16')  );
536 C4::Biblio::ModBiblio( $record, $bibnum, $frameworkcode );
537
538 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" );
539
540 #Set the dateofbirth for the Borrower making them "too young".
541 $borrower->{dateofbirth} = DateTime->now->add( years => -15 );
542 C4::Members::ModMember( borrowernumber => $borrowernumber, dateofbirth => $borrower->{dateofbirth} );
543
544 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails");
545
546 #Set the dateofbirth for the Borrower making them "too old".
547 $borrower->{dateofbirth} = DateTime->now->add( years => -30 );
548 C4::Members::ModMember( borrowernumber => $borrowernumber, dateofbirth => $borrower->{dateofbirth} );
549
550 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds");
551        ####
552 ####### EO Bug 13113 <<<
553        ####
554
555 $item = GetItem($itemnumber);
556
557 ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $borrower), "Reserving a book on item level" );
558
559 my $itype = C4::Reserves::_get_itype($item);
560 my $categorycode = $borrower->{categorycode};
561 my $holdingbranch = $item->{holdingbranch};
562 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule(
563     {
564         categorycode => $categorycode,
565         itemtype     => $itype,
566         branchcode   => $holdingbranch
567     }
568 );
569
570 $dbh->do(
571     "UPDATE issuingrules SET onshelfholds = 1 WHERE categorycode = ? AND itemtype= ? and branchcode = ?",
572     undef,
573     $issuing_rule->categorycode, $issuing_rule->itemtype, $issuing_rule->branchcode
574 );
575 ok( C4::Reserves::OnShelfHoldsAllowed($item, $borrower), "OnShelfHoldsAllowed() allowed" );
576 $dbh->do(
577     "UPDATE issuingrules SET onshelfholds = 0 WHERE categorycode = ? AND itemtype= ? and branchcode = ?",
578     undef,
579     $issuing_rule->categorycode, $issuing_rule->itemtype, $issuing_rule->branchcode
580 );
581 ok( !C4::Reserves::OnShelfHoldsAllowed($item, $borrower), "OnShelfHoldsAllowed() disallowed" );
582
583 # Tests for bug 14464
584
585 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
586 my $patron = Koha::Patrons->find( $borrowernumber );
587 my $bz14464_fines = $patron->account->balance;
588 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines at beginning' );
589
590 # First, test cancelling a reserve when there's no charge configured.
591 t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 0);
592
593 my $bz14464_reserve = AddReserve(
594     $branch_1,
595     $borrowernumber,
596     $bibnum,
597     undef,
598     '1',
599     undef,
600     undef,
601     '',
602     $title,
603     $itemnumber,
604     'W'
605 );
606
607 ok( $bz14464_reserve, 'Bug 14464 - 1st reserve correctly created' );
608
609 CancelReserve({ reserve_id => $bz14464_reserve, charge_cancel_fee => 1 });
610
611 my $old_reserve = Koha::Database->new()->schema()->resultset('OldReserve')->find( $bz14464_reserve );
612 is($old_reserve->get_column('found'), 'W', 'Bug 14968 - Keep found column from reserve');
613
614 $bz14464_fines = $patron->account->balance;
615 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines after cancelling reserve with no charge configured' );
616
617 # Then, test cancelling a reserve when there's no charge desired.
618 t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 42);
619
620 $bz14464_reserve = AddReserve(
621     $branch_1,
622     $borrowernumber,
623     $bibnum,
624     undef,
625     '1',
626     undef,
627     undef,
628     '',
629     $title,
630     $itemnumber,
631     'W'
632 );
633
634 ok( $bz14464_reserve, 'Bug 14464 - 2nd reserve correctly created' );
635
636 CancelReserve({ reserve_id => $bz14464_reserve });
637
638 $bz14464_fines = $patron->account->balance;
639 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines after cancelling reserve with no charge desired' );
640
641 # Finally, test cancelling a reserve when there's a charge desired and configured.
642 $bz14464_reserve = AddReserve(
643     $branch_1,
644     $borrowernumber,
645     $bibnum,
646     undef,
647     '1',
648     undef,
649     undef,
650     '',
651     $title,
652     $itemnumber,
653     'W'
654 );
655
656 ok( $bz14464_reserve, 'Bug 14464 - 1st reserve correctly created' );
657
658 CancelReserve({ reserve_id => $bz14464_reserve, charge_cancel_fee => 1 });
659
660 $bz14464_fines = $patron->account->balance;
661 is( int( $bz14464_fines ), 42, 'Bug 14464 - Fine applied after cancelling reserve with charge desired and configured' );
662
663 # tests for MoveReserve in relation to ConfirmFutureHolds (BZ 14526)
664 #   hold from A pos 1, today, no fut holds: MoveReserve should fill it
665 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
666 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
667 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
668 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
669     $bibitems,  1, undef, $expdate, $notes, $title, $checkitem, '');
670 MoveReserve( $itemnumber, $borrowernumber );
671 ($status)=CheckReserves( $itemnumber );
672 is( $status, '', 'MoveReserve filled hold');
673 #   hold from A waiting, today, no fut holds: MoveReserve should fill it
674 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
675    $bibitems,  1, undef, $expdate, $notes, $title, $checkitem, 'W');
676 MoveReserve( $itemnumber, $borrowernumber );
677 ($status)=CheckReserves( $itemnumber );
678 is( $status, '', 'MoveReserve filled waiting hold');
679 #   hold from A pos 1, tomorrow, no fut holds: not filled
680 $resdate= dt_from_string();
681 $resdate->add_duration(DateTime::Duration->new(days => 1));
682 $resdate=output_pref($resdate);
683 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
684     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
685 MoveReserve( $itemnumber, $borrowernumber );
686 ($status)=CheckReserves( $itemnumber, undef, 1 );
687 is( $status, 'Reserved', 'MoveReserve did not fill future hold');
688 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
689 #   hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it
690 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
691 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
692     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
693 MoveReserve( $itemnumber, $borrowernumber );
694 ($status)=CheckReserves( $itemnumber, undef, 2 );
695 is( $status, '', 'MoveReserve filled future hold now');
696 #   hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it
697 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
698     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, 'W');
699 MoveReserve( $itemnumber, $borrowernumber );
700 ($status)=CheckReserves( $itemnumber, undef, 2 );
701 is( $status, '', 'MoveReserve filled future waiting hold now');
702 #   hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it
703 $resdate= dt_from_string();
704 $resdate->add_duration(DateTime::Duration->new(days => 3));
705 $resdate=output_pref($resdate);
706 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
707     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
708 MoveReserve( $itemnumber, $borrowernumber );
709 ($status)=CheckReserves( $itemnumber, undef, 3 );
710 is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days');
711 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
712
713 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
714 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
715 $cache->clear_from_cache("default_value_for_mod_marc-$frameworkcode");
716 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
717
718 subtest '_koha_notify_reserve() tests' => sub {
719
720     plan tests => 2;
721
722     my $wants_hold_and_email = {
723         wants_digest => '0',
724         transports => {
725             sms => 'HOLD',
726             email => 'HOLD',
727             },
728         letter_code => 'HOLD'
729     };
730
731     my $mp = Test::MockModule->new( 'C4::Members::Messaging' );
732
733     $mp->mock("GetMessagingPreferences",$wants_hold_and_email);
734
735     $dbh->do('DELETE FROM letter');
736
737     my $email_hold_notice = $builder->build({
738             source => 'Letter',
739             value => {
740                 message_transport_type => 'email',
741                 branchcode => '',
742                 code => 'HOLD',
743                 module => 'reserves',
744                 lang => 'default',
745             }
746         });
747
748     my $sms_hold_notice = $builder->build({
749             source => 'Letter',
750             value => {
751                 message_transport_type => 'sms',
752                 branchcode => '',
753                 code => 'HOLD',
754                 module => 'reserves',
755                 lang=>'default',
756             }
757         });
758
759     my $hold_borrower = $builder->build({
760             source => 'Borrower',
761             value => {
762                 smsalertnumber=>'5555555555',
763                 email=>'a@b.com',
764             }
765         })->{borrowernumber};
766
767     my $hold = $builder->build({
768             source => 'Reserve',
769             value => {
770                borrowernumber=>$hold_borrower
771             }
772         });
773
774     ModReserveAffect($hold->{itemnumber}, $hold->{borrowernumber}, 0);
775     my $sms_message_address = $schema->resultset('MessageQueue')->search({
776             letter_code     => 'HOLD',
777             message_transport_type => 'sms',
778             borrowernumber => $hold_borrower,
779         })->next()->to_address();
780     is($sms_message_address, undef ,"We should not populate the sms message with the sms number, sending will do so");
781
782     my $email_message_address = $schema->resultset('MessageQueue')->search({
783             letter_code     => 'HOLD',
784             message_transport_type => 'email',
785             borrowernumber => $hold_borrower,
786         })->next()->to_address();
787     is($email_message_address, undef ,"We should not populate the hold message with the email address, sending will do so");
788
789 };
790
791 sub count_hold_print_messages {
792     my $message_count = $dbh->selectall_arrayref(q{
793         SELECT COUNT(*)
794         FROM message_queue
795         WHERE letter_code = 'HOLD' 
796         AND   message_transport_type = 'print'
797     });
798     return $message_count->[0]->[0];
799 }
800
801 # we reached the finish
802 $schema->storage->txn_rollback();