Bug 26057: (QA follow-up) Fix Biblios, Reserves, Z3950Responder and XSLT tests
[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 => 66;
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::Circulation;
31 use C4::Items;
32 use C4::Biblio;
33 use C4::Members;
34 use C4::Reserves;
35 use Koha::Caches;
36 use Koha::DateUtils;
37 use Koha::Holds;
38 use Koha::Items;
39 use Koha::Libraries;
40 use Koha::Notice::Templates;
41 use Koha::Patrons;
42 use Koha::Patron::Categories;
43 use Koha::CirculationRules;
44
45 BEGIN {
46     require_ok('C4::Reserves');
47 }
48
49 # Start transaction
50 my $database = Koha::Database->new();
51 my $schema = $database->schema();
52 $schema->storage->txn_begin();
53 my $dbh = C4::Context->dbh;
54 $dbh->do('DELETE FROM circulation_rules');
55
56 my $builder = t::lib::TestBuilder->new;
57
58 my $frameworkcode = q//;
59
60
61 t::lib::Mocks::mock_preference('ReservesNeedReturns', 1);
62
63 # Somewhat arbitrary field chosen for age restriction unit tests. Must be added to db before the framework is cached
64 $dbh->do("update marc_subfield_structure set kohafield='biblioitems.agerestriction' where tagfield='521' and tagsubfield='a' and frameworkcode=?", undef, $frameworkcode);
65 my $cache = Koha::Caches->get_instance;
66 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
67 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
68 $cache->clear_from_cache("default_value_for_mod_marc-");
69 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
70
71 ## Setup Test
72 # Add branches
73 my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode };
74 my $branch_2 = $builder->build({ source => 'Branch' })->{ branchcode };
75 my $branch_3 = $builder->build({ source => 'Branch' })->{ branchcode };
76 # Add categories
77 my $category_1 = $builder->build({ source => 'Category' })->{ categorycode };
78 my $category_2 = $builder->build({ source => 'Category' })->{ categorycode };
79 # Add an item type
80 my $itemtype = $builder->build(
81     { source => 'Itemtype', value => { notforloan => undef } } )->{itemtype};
82
83 t::lib::Mocks::mock_userenv({ branchcode => $branch_1 });
84
85 my $bibnum = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber;
86
87 # Create a helper item instance for testing
88 my $item = $builder->build_sample_item({ biblionumber => $bibnum, library => $branch_1, itype => $itemtype });
89
90 my $biblio_with_no_item = $builder->build_sample_biblio;
91
92 # Modify item; setting barcode.
93 my $testbarcode = '97531';
94 $item->barcode($testbarcode)->store; # FIXME We should not hardcode a barcode! Also, what's the purpose of this?
95
96 # Create a borrower
97 my %data = (
98     firstname =>  'my firstname',
99     surname => 'my surname',
100     categorycode => $category_1,
101     branchcode => $branch_1,
102 );
103 Koha::Patron::Categories->find($category_1)->set({ enrolmentfee => 0})->store;
104 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
105 my $patron = Koha::Patrons->find( $borrowernumber );
106 my $borrower = $patron->unblessed;
107 my $biblionumber   = $bibnum;
108 my $barcode        = $testbarcode;
109
110 my $branchcode = Koha::Libraries->search->next->branchcode;
111
112 AddReserve(
113     {
114         branchcode     => $branchcode,
115         borrowernumber => $borrowernumber,
116         biblionumber   => $biblionumber,
117         priority       => 1,
118     }
119 );
120
121 my ($status, $reserve, $all_reserves) = CheckReserves($item->itemnumber, $barcode);
122
123 is($status, "Reserved", "CheckReserves Test 1");
124
125 ok(exists($reserve->{reserve_id}), 'CheckReserves() include reserve_id in its response');
126
127 ($status, $reserve, $all_reserves) = CheckReserves($item->itemnumber);
128 is($status, "Reserved", "CheckReserves Test 2");
129
130 ($status, $reserve, $all_reserves) = CheckReserves(undef, $barcode);
131 is($status, "Reserved", "CheckReserves Test 3");
132
133 my $ReservesControlBranch = C4::Context->preference('ReservesControlBranch');
134 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
135 ok(
136     'ItemHomeLib' eq GetReservesControlBranch(
137         { homebranch => 'ItemHomeLib' },
138         { branchcode => 'PatronHomeLib' }
139     ), "GetReservesControlBranch returns item home branch when set to ItemHomeLibrary"
140 );
141 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
142 ok(
143     'PatronHomeLib' eq GetReservesControlBranch(
144         { homebranch => 'ItemHomeLib' },
145         { branchcode => 'PatronHomeLib' }
146     ), "GetReservesControlBranch returns patron home branch when set to PatronLibrary"
147 );
148 t::lib::Mocks::mock_preference( 'ReservesControlBranch', $ReservesControlBranch );
149
150 ###
151 ### Regression test for bug 10272
152 ###
153 my %requesters = ();
154 $requesters{$branch_1} = Koha::Patron->new({
155     branchcode   => $branch_1,
156     categorycode => $category_2,
157     surname      => "borrower from $branch_1",
158 })->store->borrowernumber;
159 for my $i ( 2 .. 5 ) {
160     $requesters{"CPL$i"} = Koha::Patron->new({
161         branchcode   => $branch_1,
162         categorycode => $category_2,
163         surname      => "borrower $i from $branch_1",
164     })->store->borrowernumber;
165 }
166 $requesters{$branch_2} = Koha::Patron->new({
167     branchcode   => $branch_2,
168     categorycode => $category_2,
169     surname      => "borrower from $branch_2",
170 })->store->borrowernumber;
171 $requesters{$branch_3} = Koha::Patron->new({
172     branchcode   => $branch_3,
173     categorycode => $category_2,
174     surname      => "borrower from $branch_3",
175 })->store->borrowernumber;
176
177 # Configure rules so that $branch_1 allows only $branch_1 patrons
178 # to request its items, while $branch_2 will allow its items
179 # to fill holds from anywhere.
180
181 $dbh->do('DELETE FROM circulation_rules');
182 Koha::CirculationRules->set_rules(
183     {
184         branchcode   => undef,
185         categorycode => undef,
186         itemtype     => undef,
187         rules        => {
188             reservesallowed => 25,
189             holds_per_record => 1,
190         }
191     }
192 );
193
194 # CPL allows only its own patrons to request its items
195 Koha::CirculationRules->set_rules(
196     {
197         branchcode   => $branch_1,
198         itemtype     => undef,
199         rules        => {
200             holdallowed  => 1,
201             returnbranch => 'homebranch',
202         }
203     }
204 );
205
206 # ... while FPL allows anybody to request its items
207 Koha::CirculationRules->set_rules(
208     {
209         branchcode   => $branch_2,
210         itemtype     => undef,
211         rules        => {
212             holdallowed  => 2,
213             returnbranch => 'homebranch',
214         }
215     }
216 );
217
218 my $bibnum2 = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber;
219
220 my ($itemnum_cpl, $itemnum_fpl);
221 $itemnum_cpl = $builder->build_sample_item(
222     {
223         biblionumber => $bibnum2,
224         library      => $branch_1,
225         barcode      => 'bug10272_CPL',
226         itype        => $itemtype
227     }
228 )->itemnumber;
229 $itemnum_fpl = $builder->build_sample_item(
230     {
231         biblionumber => $bibnum2,
232         library      => $branch_2,
233         barcode      => 'bug10272_FPL',
234         itype        => $itemtype
235     }
236 )->itemnumber;
237
238 # Ensure that priorities are numbered correcly when a hold is moved to waiting
239 # (bug 11947)
240 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
241 AddReserve(
242     {
243         branchcode     => $branch_3,
244         borrowernumber => $requesters{$branch_3},
245         biblionumber   => $bibnum2,
246         priority       => 1,
247     }
248 );
249 AddReserve(
250     {
251         branchcode     => $branch_2,
252         borrowernumber => $requesters{$branch_2},
253         biblionumber   => $bibnum2,
254         priority       => 2,
255     }
256 );
257 AddReserve(
258     {
259         branchcode     => $branch_1,
260         borrowernumber => $requesters{$branch_1},
261         biblionumber   => $bibnum2,
262         priority       => 3,
263     }
264 );
265 ModReserveAffect($itemnum_cpl, $requesters{$branch_3}, 0);
266
267 # Now it should have different priorities.
268 my $biblio = Koha::Biblios->find( $bibnum2 );
269 my $holds = $biblio->holds({}, { order_by => 'reserve_id' });;
270 is($holds->next->priority, 0, 'Item is correctly waiting');
271 is($holds->next->priority, 1, 'Item is correctly priority 1');
272 is($holds->next->priority, 2, 'Item is correctly priority 2');
273
274 my @reserves = Koha::Holds->search({ borrowernumber => $requesters{$branch_3} })->waiting();
275 is( @reserves, 1, 'GetWaiting got only the waiting reserve' );
276 is( $reserves[0]->borrowernumber(), $requesters{$branch_3}, 'GetWaiting got the reserve for the correct borrower' );
277
278
279 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
280 AddReserve(
281     {
282         branchcode     => $branch_3,
283         borrowernumber => $requesters{$branch_3},
284         biblionumber   => $bibnum2,
285         priority       => 1,
286     }
287 );
288 AddReserve(
289     {
290         branchcode     => $branch_2,
291         borrowernumber => $requesters{$branch_2},
292         biblionumber   => $bibnum2,
293         priority       => 2,
294     }
295 );
296
297 AddReserve(
298     {
299         branchcode     => $branch_1,
300         borrowernumber => $requesters{$branch_1},
301         biblionumber   => $bibnum2,
302         priority       => 3,
303     }
304 );
305
306 # Ensure that the item's home library controls hold policy lookup
307 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
308
309 my $messages;
310 # Return the CPL item at FPL.  The hold that should be triggered is
311 # the one placed by the CPL patron, as the other two patron's hold
312 # requests cannot be filled by that item per policy.
313 (undef, $messages, undef, undef) = AddReturn('bug10272_CPL', $branch_2);
314 is( $messages->{ResFound}->{borrowernumber},
315     $requesters{$branch_1},
316     'restrictive library\'s items only fill requests by own patrons (bug 10272)');
317
318 # Return the FPL item at FPL.  The hold that should be triggered is
319 # the one placed by the RPL patron, as that patron is first in line
320 # and RPL imposes no restrictions on whose holds its items can fill.
321
322 # Ensure that the preference 'LocalHoldsPriority' is not set (Bug 15244):
323 t::lib::Mocks::mock_preference( 'LocalHoldsPriority', '' );
324
325 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', $branch_2);
326 is( $messages->{ResFound}->{borrowernumber},
327     $requesters{$branch_3},
328     'for generous library, its items fill first hold request in line (bug 10272)');
329
330 $biblio = Koha::Biblios->find( $biblionumber );
331 $holds = $biblio->holds;
332 is($holds->count, 1, "Only one reserves for this biblio");
333 $holds->next->reserve_id;
334
335 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
336 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
337 # Test 9761a: Add a reserve without date, CheckReserve should return it
338 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
339 AddReserve(
340     {
341         branchcode     => $branch_1,
342         borrowernumber => $requesters{$branch_1},
343         biblionumber   => $bibnum,
344         priority       => 1,
345     }
346 );
347 ($status)=CheckReserves($item->itemnumber,undef,undef);
348 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
349 ($status)=CheckReserves($item->itemnumber,undef,7);
350 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
351
352 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
353 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
354 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
355 my $resdate= dt_from_string();
356 $resdate->add_duration(DateTime::Duration->new(days => 4));
357 $resdate=output_pref($resdate);
358 my $reserve_id = AddReserve(
359     {
360         branchcode       => $branch_1,
361         borrowernumber   => $requesters{$branch_1},
362         biblionumber     => $bibnum,
363         priority         => 1,
364         reservation_date => $resdate,
365     }
366 );
367 ($status)=CheckReserves($item->itemnumber,undef,undef);
368 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
369
370 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
371 ($status)=CheckReserves($item->itemnumber,undef,3);
372 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
373 ($status)=CheckReserves($item->itemnumber,undef,4);
374 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
375
376 # Test 9761d: Check ResFound message of AddReturn for future hold
377 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
378 # In this test we do not need an issued item; it is just a 'checkin'
379 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
380 (my $doreturn, $messages)= AddReturn('97531',$branch_1);
381 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
382 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3);
383 ($doreturn, $messages)= AddReturn('97531',$branch_1);
384 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
385 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7);
386 ($doreturn, $messages)= AddReturn('97531',$branch_1);
387 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
388
389 # End of tests for bug 9761 (ConfirmFutureHolds)
390
391 # test marking a hold as captured
392 my $hold_notice_count = count_hold_print_messages();
393 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
394 my $new_count = count_hold_print_messages();
395 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
396
397 # test that duplicate notices aren't generated
398 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
399 $new_count = count_hold_print_messages();
400 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
401
402 # avoiding the not_same_branch error
403 t::lib::Mocks::mock_preference('IndependentBranches', 0);
404 $item = Koha::Items->find($item->itemnumber);
405 is(
406     $item->safe_delete,
407     'book_reserved',
408     'item that is captured to fill a hold cannot be deleted',
409 );
410
411 my $letter = ReserveSlip( { branchcode => $branch_1, reserve_id => $reserve_id } );
412 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
413
414 # Tests for bug 9788: Does Koha::Item->current_holds return a future wait?
415 # 9788a: current_holds does not return future next available hold
416 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
417 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
418 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
419 $resdate= dt_from_string();
420 $resdate->add_duration(DateTime::Duration->new(days => 2));
421 $resdate=output_pref($resdate);
422 AddReserve(
423     {
424         branchcode       => $branch_1,
425         borrowernumber   => $requesters{$branch_1},
426         biblionumber     => $bibnum,
427         priority         => 1,
428         reservation_date => $resdate,
429     }
430 );
431
432 $holds = $item->current_holds;
433 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
434 my $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
435 is( $future_holds->count, 0, 'current_holds does not return a future next available hold');
436 # 9788b: current_holds does not return future item level hold
437 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
438 AddReserve(
439     {
440         branchcode       => $branch_1,
441         borrowernumber   => $requesters{$branch_1},
442         biblionumber     => $bibnum,
443         priority         => 1,
444         reservation_date => $resdate,
445         itemnumber       => $item->itemnumber,
446     }
447 ); #item level hold
448 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
449 is( $future_holds->count, 0, 'current_holds does not return a future item level hold' );
450 # 9788c: current_holds returns future wait (confirmed future hold)
451 ModReserveAffect( $item->itemnumber,  $requesters{$branch_1} , 0); #confirm hold
452 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
453 is( $future_holds->count, 1, 'current_holds returns a future wait (confirmed future hold)' );
454 # End of tests for bug 9788
455
456 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
457 # Tests for CalculatePriority (bug 8918)
458 my $p = C4::Reserves::CalculatePriority($bibnum2);
459 is($p, 4, 'CalculatePriority should now return priority 4');
460 AddReserve(
461     {
462         branchcode     => $branch_1,
463         borrowernumber => $requesters{'CPL2'},
464         biblionumber   => $bibnum2,
465         priority       => $p,
466     }
467 );
468 $p = C4::Reserves::CalculatePriority($bibnum2);
469 is($p, 5, 'CalculatePriority should now return priority 5');
470 #some tests on bibnum
471 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
472 $p = C4::Reserves::CalculatePriority($bibnum);
473 is($p, 1, 'CalculatePriority should now return priority 1');
474 #add a new reserve and confirm it to waiting
475 AddReserve(
476     {
477         branchcode     => $branch_1,
478         borrowernumber => $requesters{$branch_1},
479         biblionumber   => $bibnum,
480         priority       => $p,
481         itemnumber     => $item->itemnumber,
482     }
483 );
484 $p = C4::Reserves::CalculatePriority($bibnum);
485 is($p, 2, 'CalculatePriority should now return priority 2');
486 ModReserveAffect( $item->itemnumber,  $requesters{$branch_1} , 0);
487 $p = C4::Reserves::CalculatePriority($bibnum);
488 is($p, 1, 'CalculatePriority should now return priority 1');
489 #add another biblio hold, no resdate
490 AddReserve(
491     {
492         branchcode     => $branch_1,
493         borrowernumber => $requesters{'CPL2'},
494         biblionumber   => $bibnum,
495         priority       => $p,
496     }
497 );
498 $p = C4::Reserves::CalculatePriority($bibnum);
499 is($p, 2, 'CalculatePriority should now return priority 2');
500 #add another future hold
501 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
502 $resdate= dt_from_string();
503 $resdate->add_duration(DateTime::Duration->new(days => 1));
504 AddReserve(
505     {
506         branchcode     => $branch_1,
507         borrowernumber => $requesters{'CPL2'},
508         biblionumber   => $bibnum,
509         priority       => $p,
510         reservation_date => output_pref($resdate),
511     }
512 );
513 $p = C4::Reserves::CalculatePriority($bibnum);
514 is($p, 2, 'CalculatePriority should now still return priority 2');
515 #calc priority with future resdate
516 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
517 is($p, 3, 'CalculatePriority should now return priority 3');
518 # End of tests for bug 8918
519
520 # Tests for cancel reserves by users from OPAC.
521 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
522 AddReserve(
523     {
524         branchcode     => $branch_1,
525         borrowernumber => $requesters{$branch_1},
526         biblionumber   => $bibnum,
527         priority       => 1,
528     }
529 );
530 my (undef, $canres, undef) = CheckReserves($item->itemnumber);
531
532 is( CanReserveBeCanceledFromOpac(), undef,
533     'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
534 );
535 is(
536     CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
537     undef,
538     'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
539 );
540 is(
541     CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
542     undef,
543     'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
544 );
545
546 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
547 is($cancancel, 1, 'Can user cancel its own reserve');
548
549 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_2});
550 is($cancancel, 0, 'Other user cant cancel reserve');
551
552 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 1);
553 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
554 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
555
556 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
557 AddReserve(
558     {
559         branchcode     => $branch_1,
560         borrowernumber => $requesters{$branch_1},
561         biblionumber   => $bibnum,
562         priority       => 1,
563     }
564 );
565 (undef, $canres, undef) = CheckReserves($item->itemnumber);
566
567 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
568 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
569 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
570
571 # End of tests for bug 12876
572
573        ####
574 ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>>
575        ####
576
577 t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' );
578
579 #Reserving an not-agerestricted Biblio by a Borrower with no dateofbirth is tested previously.
580
581 #Set the ageRestriction for the Biblio
582 my $record = GetMarcBiblio({ biblionumber =>  $bibnum });
583 my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" );
584 $record->append_fields(  MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16')  );
585 C4::Biblio::ModBiblio( $record, $bibnum, $frameworkcode );
586
587 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" );
588
589 #Set the dateofbirth for the Borrower making them "too young".
590 $borrower->{dateofbirth} = DateTime->now->add( years => -15 );
591 Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store;
592
593 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails");
594
595 #Set the dateofbirth for the Borrower making them "too old".
596 $borrower->{dateofbirth} = DateTime->now->add( years => -30 );
597 Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store;
598
599 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds");
600
601 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblio_with_no_item->biblionumber)->{status} , '', "Biblio with no item. Status is empty");
602        ####
603 ####### EO Bug 13113 <<<
604        ####
605
606 ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron), "Reserving a book on item level" );
607
608 my $pickup_branch = $builder->build({ source => 'Branch' })->{ branchcode };
609 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits',  '1' );
610 t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' );
611 my $limit = Koha::Item::Transfer::Limit->new(
612     {
613         toBranch   => $pickup_branch,
614         fromBranch => $item->holdingbranch,
615         itemtype   => $item->effective_itemtype,
616     }
617 )->store();
618 is( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron, $pickup_branch), 0, "Item level request not available due to transfer limit" );
619 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits',  '0' );
620
621 my $categorycode = $borrower->{categorycode};
622 my $holdingbranch = $item->{holdingbranch};
623 Koha::CirculationRules->set_rules(
624     {
625         categorycode => $categorycode,
626         itemtype     => $item->effective_itemtype,
627         branchcode   => $holdingbranch,
628         rules => {
629             onshelfholds => 1,
630         }
631     }
632 );
633
634 # tests for MoveReserve in relation to ConfirmFutureHolds (BZ 14526)
635 #   hold from A pos 1, today, no fut holds: MoveReserve should fill it
636 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
637 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
638 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
639 AddReserve(
640     {
641         branchcode     => $branch_1,
642         borrowernumber => $borrowernumber,
643         biblionumber   => $bibnum,
644         priority       => 1,
645     }
646 );
647 MoveReserve( $item->itemnumber, $borrowernumber );
648 ($status)=CheckReserves( $item->itemnumber );
649 is( $status, '', 'MoveReserve filled hold');
650 #   hold from A waiting, today, no fut holds: MoveReserve should fill it
651 AddReserve(
652     {
653         branchcode     => $branch_1,
654         borrowernumber => $borrowernumber,
655         biblionumber   => $bibnum,
656         priority       => 1,
657         found          => 'W',
658     }
659 );
660 MoveReserve( $item->itemnumber, $borrowernumber );
661 ($status)=CheckReserves( $item->itemnumber );
662 is( $status, '', 'MoveReserve filled waiting hold');
663 #   hold from A pos 1, tomorrow, no fut holds: not filled
664 $resdate= dt_from_string();
665 $resdate->add_duration(DateTime::Duration->new(days => 1));
666 $resdate=output_pref($resdate);
667 AddReserve(
668     {
669         branchcode     => $branch_1,
670         borrowernumber => $borrowernumber,
671         biblionumber   => $bibnum,
672         priority       => 1,
673         reservation_date => $resdate,
674     }
675 );
676 MoveReserve( $item->itemnumber, $borrowernumber );
677 ($status)=CheckReserves( $item->itemnumber, undef, 1 );
678 is( $status, 'Reserved', 'MoveReserve did not fill future hold');
679 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
680 #   hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it
681 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
682 AddReserve(
683     {
684         branchcode     => $branch_1,
685         borrowernumber => $borrowernumber,
686         biblionumber   => $bibnum,
687         priority       => 1,
688         reservation_date => $resdate,
689     }
690 );
691 MoveReserve( $item->itemnumber, $borrowernumber );
692 ($status)=CheckReserves( $item->itemnumber, undef, 2 );
693 is( $status, '', 'MoveReserve filled future hold now');
694 #   hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it
695 AddReserve(
696     {
697         branchcode     => $branch_1,
698         borrowernumber => $borrowernumber,
699         biblionumber   => $bibnum,
700         priority       => 1,
701         reservation_date => $resdate,
702     }
703 );
704 MoveReserve( $item->itemnumber, $borrowernumber );
705 ($status)=CheckReserves( $item->itemnumber, undef, 2 );
706 is( $status, '', 'MoveReserve filled future waiting hold now');
707 #   hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it
708 $resdate= dt_from_string();
709 $resdate->add_duration(DateTime::Duration->new(days => 3));
710 $resdate=output_pref($resdate);
711 AddReserve(
712     {
713         branchcode     => $branch_1,
714         borrowernumber => $borrowernumber,
715         biblionumber   => $bibnum,
716         priority       => 1,
717         reservation_date => $resdate,
718     }
719 );
720 MoveReserve( $item->itemnumber, $borrowernumber );
721 ($status)=CheckReserves( $item->itemnumber, undef, 3 );
722 is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days');
723 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
724
725 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
726 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
727 $cache->clear_from_cache("default_value_for_mod_marc-");
728 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
729
730 subtest '_koha_notify_reserve() tests' => sub {
731
732     plan tests => 2;
733
734     my $wants_hold_and_email = {
735         wants_digest => '0',
736         transports => {
737             sms => 'HOLD',
738             email => 'HOLD',
739             },
740         letter_code => 'HOLD'
741     };
742
743     my $mp = Test::MockModule->new( 'C4::Members::Messaging' );
744
745     $mp->mock("GetMessagingPreferences",$wants_hold_and_email);
746
747     $dbh->do('DELETE FROM letter');
748
749     my $email_hold_notice = $builder->build({
750             source => 'Letter',
751             value => {
752                 message_transport_type => 'email',
753                 branchcode => '',
754                 code => 'HOLD',
755                 module => 'reserves',
756                 lang => 'default',
757             }
758         });
759
760     my $sms_hold_notice = $builder->build({
761             source => 'Letter',
762             value => {
763                 message_transport_type => 'sms',
764                 branchcode => '',
765                 code => 'HOLD',
766                 module => 'reserves',
767                 lang=>'default',
768             }
769         });
770
771     my $hold_borrower = $builder->build({
772             source => 'Borrower',
773             value => {
774                 smsalertnumber=>'5555555555',
775                 email=>'a@b.com',
776             }
777         })->{borrowernumber};
778
779     C4::Reserves::AddReserve(
780         {
781             branchcode     => $item->homebranch,
782             borrowernumber => $hold_borrower,
783             biblionumber   => $item->biblionumber,
784         }
785     );
786
787     ModReserveAffect($item->itemnumber, $hold_borrower, 0);
788     my $sms_message_address = $schema->resultset('MessageQueue')->search({
789             letter_code     => 'HOLD',
790             message_transport_type => 'sms',
791             borrowernumber => $hold_borrower,
792         })->next()->to_address();
793     is($sms_message_address, undef ,"We should not populate the sms message with the sms number, sending will do so");
794
795     my $email_message_address = $schema->resultset('MessageQueue')->search({
796             letter_code     => 'HOLD',
797             message_transport_type => 'email',
798             borrowernumber => $hold_borrower,
799         })->next()->to_address();
800     is($email_message_address, undef ,"We should not populate the hold message with the email address, sending will do so");
801
802 };
803
804 subtest 'ReservesNeedReturns' => sub {
805     plan tests => 18;
806
807     my $library    = $builder->build_object( { class => 'Koha::Libraries' } );
808     my $item_info  = {
809         homebranch       => $library->branchcode,
810         holdingbranch    => $library->branchcode,
811     };
812     my $item = $builder->build_sample_item($item_info);
813     my $patron   = $builder->build_object(
814         {
815             class => 'Koha::Patrons',
816             value => { branchcode => $library->branchcode, }
817         }
818     );
819     my $patron_2   = $builder->build_object(
820         {
821             class => 'Koha::Patrons',
822             value => { branchcode => $library->branchcode, }
823         }
824     );
825
826     my $priority = 1;
827
828     t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Test with feature disabled
829     my $hold = place_item_hold( $patron, $item, $library, $priority );
830     is( $hold->priority, $priority, 'If ReservesNeedReturns is 1, priority must not have been set to changed' );
831     is( $hold->found, undef, 'If ReservesNeedReturns is 1, found must not have been set waiting' );
832     $hold->delete;
833
834     t::lib::Mocks::mock_preference('ReservesNeedReturns', 0); # '0' means 'Automatically mark a hold as found and waiting'
835     $hold = place_item_hold( $patron, $item, $library, $priority );
836     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
837     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
838     $hold->delete;
839
840     $item->onloan('2010-01-01')->store;
841     $hold = place_item_hold( $patron, $item, $library, $priority );
842     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item onloan priority must be set to 1' );
843     $hold->delete;
844
845     t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 0); # '0' means damaged holds not allowed
846     $item->onloan(undef)->damaged(1)->store;
847     $hold = place_item_hold( $patron, $item, $library, $priority );
848     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item damaged and not allowed holds on damaged items priority must be set to 1' );
849     $hold->delete;
850     t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 1); # '0' means damaged holds not allowed
851     $hold = place_item_hold( $patron, $item, $library, $priority );
852     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and damaged holds allowed, priority must have been set to 0' );
853     is( $hold->found,  'W', 'If ReservesNeedReturns is 0 and damaged holds allowed, found must have been set waiting' );
854     $hold->delete;
855
856     my $hold_1 = place_item_hold( $patron, $item, $library, $priority );
857     is( $hold_1->found,  'W', 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
858     is( $hold_1->priority, 0, 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
859     $hold = place_item_hold( $patron_2, $item, $library, $priority );
860     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item already on hold priority must be set to 1' );
861     $hold->delete;
862     $hold_1->delete;
863
864     my $transfer = $builder->build_object({
865         class => "Koha::Item::Transfers",
866         value => {
867           itemnumber  => $item->itemnumber,
868           datearrived => undef,
869           datecancelled => undef
870         }
871     });
872     $item->damaged(0)->store;
873     $hold = place_item_hold( $patron, $item, $library, $priority );
874     is( $hold->found, undef, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
875     is( $hold->priority, 1,  'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
876     $hold->delete;
877     $transfer->delete;
878
879     $hold = place_item_hold( $patron, $item, $library, $priority );
880     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
881     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
882     $hold_1 = place_item_hold( $patron, $item, $library, $priority );
883     is( $hold_1->priority, 1, 'If ReservesNeedReturns is 0 but item has a hold priority is 1' );
884     $hold_1->suspend(1)->store; # We suspend the hold
885     $hold->delete; # Delete the waiting hold
886     $hold = place_item_hold( $patron, $item, $library, $priority );
887     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and other hold(s) suspended, priority must have been set to 0' );
888     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and other  hold(s) suspended, found must have been set waiting' );
889
890
891
892
893     t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Don't affect other tests
894 };
895
896 subtest 'ChargeReserveFee tests' => sub {
897
898     plan tests => 8;
899
900     my $library = $builder->build_object({ class => 'Koha::Libraries' });
901     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
902
903     my $fee   = 20;
904     my $title = 'A title';
905
906     my $context = Test::MockModule->new('C4::Context');
907     $context->mock( userenv => { branch => $library->id } );
908
909     my $line = C4::Reserves::ChargeReserveFee( $patron->id, $fee, $title );
910
911     is( ref($line), 'Koha::Account::Line' , 'Returns a Koha::Account::Line object');
912     ok( $line->is_debit, 'Generates a debit line' );
913     is( $line->debit_type_code, 'RESERVE' , 'generates RESERVE debit_type');
914     is( $line->borrowernumber, $patron->id , 'generated line belongs to the passed patron');
915     is( $line->amount, $fee , 'amount set correctly');
916     is( $line->amountoutstanding, $fee , 'amountoutstanding set correctly');
917     is( $line->description, "$title" , 'description is title of reserved item');
918     is( $line->branchcode, $library->id , "Library id is picked from userenv and stored correctly" );
919 };
920
921 subtest 'reserves.item_level_hold' => sub {
922     plan tests => 2;
923
924     my $item   = $builder->build_sample_item;
925     my $patron = $builder->build_object(
926         {
927             class => 'Koha::Patrons',
928             value => { branchcode => $item->homebranch }
929         }
930     );
931
932     subtest 'item level hold' => sub {
933         plan tests => 2;
934         my $reserve_id = AddReserve(
935             {
936                 branchcode     => $item->homebranch,
937                 borrowernumber => $patron->borrowernumber,
938                 biblionumber   => $item->biblionumber,
939                 priority       => 1,
940                 itemnumber     => $item->itemnumber,
941             }
942         );
943
944         my $hold = Koha::Holds->find($reserve_id);
945         is( $hold->item_level_hold, 1, 'item_level_hold should be set when AddReserve is called with a specific item' );
946
947         # Mark it waiting
948         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
949
950         # Revert the waiting status
951         C4::Reserves::RevertWaitingStatus(
952             { itemnumber => $item->itemnumber } );
953
954         $hold = Koha::Holds->find($reserve_id);
955
956         is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should not be removed when the waiting status is revert' );
957
958         $hold->delete;    # cleanup
959     };
960
961     subtest 'biblio level hold' => sub {
962         plan tests => 3;
963         my $reserve_id = AddReserve(
964             {
965                 branchcode     => $item->homebranch,
966                 borrowernumber => $patron->borrowernumber,
967                 biblionumber   => $item->biblionumber,
968                 priority       => 1,
969             }
970         );
971
972         my $hold = Koha::Holds->find($reserve_id);
973         is( $hold->item_level_hold, 0, 'item_level_hold should not be set when AddReserve is called without a specific item' );
974
975         # Mark it waiting
976         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
977
978         $hold = Koha::Holds->find($reserve_id);
979         is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should be set on hold confirmation' );
980
981         # Revert the waiting status
982         C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
983
984         $hold = Koha::Holds->find($reserve_id);
985         is( $hold->itemnumber, undef, 'Itemnumber should be removed when the waiting status is revert' );
986
987         $hold->delete;
988     };
989
990 };
991
992 subtest 'MoveReserve additional test' => sub {
993
994     plan tests => 4;
995
996     # Create the items and patrons we need
997     my $biblio = $builder->build_sample_biblio();
998     my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
999     my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1000     my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, notforloan => 0, itype => $itype->itemtype });
1001     my $patron_1 = $builder->build_object({ class => "Koha::Patrons" });
1002     my $patron_2 = $builder->build_object({ class => "Koha::Patrons" });
1003
1004     # Place a hold on the title for both patrons
1005     my $reserve_1 = AddReserve(
1006         {
1007             branchcode     => $item_1->homebranch,
1008             borrowernumber => $patron_1->borrowernumber,
1009             biblionumber   => $biblio->biblionumber,
1010             priority       => 1,
1011             itemnumber     => $item_1->itemnumber,
1012         }
1013     );
1014     my $reserve_2 = AddReserve(
1015         {
1016             branchcode     => $item_2->homebranch,
1017             borrowernumber => $patron_2->borrowernumber,
1018             biblionumber   => $biblio->biblionumber,
1019             priority       => 1,
1020             itemnumber     => $item_1->itemnumber,
1021         }
1022     );
1023     is($patron_1->holds->next()->reserve_id, $reserve_1, "The 1st patron has a hold");
1024     is($patron_2->holds->next()->reserve_id, $reserve_2, "The 2nd patron has a hold");
1025
1026     # Fake the holds queue
1027     $dbh->do(q{INSERT INTO hold_fill_targets VALUES (?, ?, ?, ?, ?,?)},undef,($patron_1->borrowernumber,$biblio->biblionumber,$item_1->itemnumber,$item_1->homebranch,0,$reserve_1));
1028
1029     # The 2nd hold should be filed even if the item is preselected for the first hold
1030     MoveReserve($item_1->itemnumber,$patron_2->borrowernumber);
1031     is($patron_2->holds->count, 0, "The 2nd patrons no longer has a hold");
1032     is($patron_2->old_holds->next()->reserve_id, $reserve_2, "The 2nd patrons hold was filled and moved to old holds");
1033
1034 };
1035
1036 subtest 'RevertWaitingStatus' => sub {
1037
1038     plan tests => 2;
1039
1040     # Create the items and patrons we need
1041     my $biblio  = $builder->build_sample_biblio();
1042     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1043     my $itype   = $builder->build_object(
1044         { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1045     my $item_1 = $builder->build_sample_item(
1046         {
1047             biblionumber => $biblio->biblionumber,
1048             itype        => $itype->itemtype,
1049             library      => $library->branchcode
1050         }
1051     );
1052     my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1053     my $patron_2 = $builder->build_object( { class => "Koha::Patrons" } );
1054     my $patron_3 = $builder->build_object( { class => "Koha::Patrons" } );
1055     my $patron_4 = $builder->build_object( { class => "Koha::Patrons" } );
1056
1057     # Place a hold on the title for both patrons
1058     my $priority = 1;
1059     my $hold_1 = place_item_hold( $patron_1, $item_1, $library, $priority );
1060     my $hold_2 = place_item_hold( $patron_2, $item_1, $library, $priority );
1061     my $hold_3 = place_item_hold( $patron_3, $item_1, $library, $priority );
1062     my $hold_4 = place_item_hold( $patron_4, $item_1, $library, $priority );
1063
1064     $hold_1->set_waiting;
1065     AddIssue( $patron_3->unblessed, $item_1->barcode, undef, 'revert' );
1066
1067     my $holds = $biblio->holds;
1068     is( $holds->count, 3, 'One hold has been deleted' );
1069     is_deeply(
1070         [
1071             $holds->next->priority, $holds->next->priority,
1072             $holds->next->priority
1073         ],
1074         [ 1, 2, 3 ],
1075         'priorities have been reordered'
1076     );
1077 };
1078
1079 subtest 'CheckReserves additional test' => sub {
1080
1081     plan tests => 3;
1082
1083     my $item = $builder->build_sample_item;
1084     my $reserve1 = $builder->build_object(
1085         {
1086             class => "Koha::Holds",
1087             value => {
1088                 found            => undef,
1089                 priority         => 1,
1090                 itemnumber       => undef,
1091                 biblionumber     => $item->biblionumber,
1092                 waitingdate      => undef,
1093                 cancellationdate => undef,
1094                 item_level_hold  => 0,
1095                 lowestPriority   => 0,
1096                 expirationdate   => undef,
1097                 suspend_until    => undef,
1098                 suspend          => 0,
1099                 itemtype         => undef,
1100             }
1101         }
1102     );
1103     my $reserve2 = $builder->build_object(
1104         {
1105             class => "Koha::Holds",
1106             value => {
1107                 found            => undef,
1108                 priority         => 2,
1109                 biblionumber     => $item->biblionumber,
1110                 borrowernumber   => $reserve1->borrowernumber,
1111                 itemnumber       => undef,
1112                 waitingdate      => undef,
1113                 cancellationdate => undef,
1114                 item_level_hold  => 0,
1115                 lowestPriority   => 0,
1116                 expirationdate   => undef,
1117                 suspend_until    => undef,
1118                 suspend          => 0,
1119                 itemtype         => undef,
1120             }
1121         }
1122     );
1123
1124     my $tmp_holdsqueue = $builder->build(
1125         {
1126             source => 'TmpHoldsqueue',
1127             value  => {
1128                 borrowernumber => $reserve1->borrowernumber,
1129                 biblionumber   => $reserve1->biblionumber,
1130             }
1131         }
1132     );
1133     my $fill_target = $builder->build(
1134         {
1135             source => 'HoldFillTarget',
1136             value  => {
1137                 borrowernumber     => $reserve1->borrowernumber,
1138                 biblionumber       => $reserve1->biblionumber,
1139                 itemnumber         => $item->itemnumber,
1140                 item_level_request => 0,
1141             }
1142         }
1143     );
1144
1145     ModReserveAffect( $item->itemnumber, $reserve1->borrowernumber, 1,
1146         $reserve1->reserve_id );
1147     my ( $status, $matched_reserve, $possible_reserves ) =
1148       CheckReserves( $item->itemnumber );
1149
1150     is( $status, 'Reserved', "We found a reserve" );
1151     is( $matched_reserve->{reserve_id},
1152         $reserve1->reserve_id, "We got the Transit reserve" );
1153     is( scalar @$possible_reserves, 2, 'We do get both reserves' );
1154 };
1155
1156 subtest 'AllowHoldOnPatronPossession test' => sub {
1157
1158     plan tests => 4;
1159
1160     # Create the items and patrons we need
1161     my $biblio = $builder->build_sample_biblio();
1162     my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1163     my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1164     my $patron = $builder->build_object({ class => "Koha::Patrons",
1165                                           value => { branchcode => $item->homebranch }});
1166
1167     C4::Circulation::AddIssue($patron->unblessed,
1168                               $item->barcode);
1169     t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 0);
1170
1171     is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1172                                        $item->biblionumber)->{status},
1173        'alreadypossession',
1174        'Patron cannot place hold on a book loaned to itself');
1175
1176     is(C4::Reserves::CanItemBeReserved($patron->borrowernumber,
1177                                        $item->itemnumber)->{status},
1178        'alreadypossession',
1179        'Patron cannot place hold on an item loaned to itself');
1180
1181     t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 1);
1182
1183     is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1184                                        $item->biblionumber)->{status},
1185        'OK',
1186        'Patron can place hold on a book loaned to itself');
1187
1188     is(C4::Reserves::CanItemBeReserved($patron->borrowernumber,
1189                                        $item->itemnumber)->{status},
1190        'OK',
1191        'Patron can place hold on an item loaned to itself');
1192 };
1193
1194 subtest 'MergeHolds' => sub {
1195
1196     plan tests => 1;
1197
1198     my $biblio_1  = $builder->build_sample_biblio();
1199     my $biblio_2  = $builder->build_sample_biblio();
1200     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1201     my $itype   = $builder->build_object(
1202         { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1203     my $item_1 = $builder->build_sample_item(
1204         {
1205             biblionumber => $biblio_1->biblionumber,
1206             itype        => $itype->itemtype,
1207             library      => $library->branchcode
1208         }
1209     );
1210     my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1211
1212     # Place a hold on $biblio_1
1213     my $priority = 1;
1214     place_item_hold( $patron_1, $item_1, $library, $priority );
1215
1216     # Move and make sure hold is now on $biblio_2
1217     C4::Reserves::MergeHolds($dbh, $biblio_2->biblionumber, $biblio_1->biblionumber);
1218     is( $biblio_2->holds->count, 1, 'Hold has been transferred' );
1219 };
1220
1221 sub count_hold_print_messages {
1222     my $message_count = $dbh->selectall_arrayref(q{
1223         SELECT COUNT(*)
1224         FROM message_queue
1225         WHERE letter_code = 'HOLD' 
1226         AND   message_transport_type = 'print'
1227     });
1228     return $message_count->[0]->[0];
1229 }
1230
1231 sub place_item_hold {
1232     my ($patron,$item,$library,$priority) = @_;
1233
1234     my $hold_id = C4::Reserves::AddReserve(
1235         {
1236             branchcode     => $library->branchcode,
1237             borrowernumber => $patron->borrowernumber,
1238             biblionumber   => $item->biblionumber,
1239             priority       => $priority,
1240             title          => "title for fee",
1241             itemnumber     => $item->itemnumber,
1242         }
1243     );
1244
1245     my $hold = Koha::Holds->find($hold_id);
1246     return $hold;
1247 }
1248
1249 # we reached the finish
1250 $schema->storage->txn_rollback();