Bug 11439: (follow up) add missing rollback call
[koha.git] / t / db_dependent / Reserves.t
1 #!/usr/bin/perl
2
3 use Modern::Perl;
4
5 use Test::More tests => 20;
6 use MARC::Record;
7 use DateTime::Duration;
8
9 use C4::Branch;
10 use C4::Biblio;
11 use C4::Items;
12 use C4::Members;
13 use C4::Circulation;
14 use t::lib::Mocks;
15
16 use Koha::DateUtils;
17
18 BEGIN {
19     use_ok('C4::Reserves');
20 }
21
22 # a very minimal mack of userenv for use by the test of DelItemCheck
23 *C4::Context::userenv = sub {
24     return {};
25 };
26
27 my $dbh = C4::Context->dbh;
28
29 # Start transaction
30 $dbh->{AutoCommit} = 0;
31 $dbh->{RaiseError} = 1;
32
33 # Setup Test------------------------
34
35 # Add branches if not existing
36 foreach my $addbra ('CPL', 'FPL', 'RPL') {
37     $dbh->do("INSERT INTO branches (branchcode,branchname) VALUES (?,?)", undef, ($addbra,"$addbra branch")) unless GetBranchName($addbra);
38 }
39
40 # Add categories if not existing
41 foreach my $addcat ('S', 'PT') {
42     $dbh->do("INSERT INTO categories (categorycode,hidelostitems,category_type) VALUES (?,?,?)",undef,($addcat, 0, $addcat eq 'S'? 'S': 'A')) unless GetBorrowercategory($addcat);
43 }
44
45 # Helper biblio.
46 diag("\nCreating biblio instance for testing.");
47 my $bib = MARC::Record->new();
48 my $title = 'Silence in the library';
49 $bib->append_fields(
50     MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
51     MARC::Field->new('245', ' ', ' ', a => $title),
52 );
53 my ($bibnum, $bibitemnum);
54 ($bibnum, $title, $bibitemnum) = AddBiblio($bib, '');
55
56 # Helper item for that biblio.
57 diag("Creating item instance for testing.");
58 my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => 'CPL', holdingbranch => 'CPL' } , $bibnum);
59
60 # Modify item; setting barcode.
61 my $testbarcode = '97531';
62 ModItem({ barcode => $testbarcode }, $bibnum, $itemnumber);
63
64 # Create a borrower
65 my %data = (
66     firstname =>  'my firstname',
67     surname => 'my surname',
68     categorycode => 'S',
69     branchcode => 'CPL',
70 );
71 my $borrowernumber = AddMember(%data);
72 my $borrower = GetMember( borrowernumber => $borrowernumber );
73 my $biblionumber   = $bibnum;
74 my $barcode        = $testbarcode;
75
76 my $constraint     = 'a';
77 my $bibitems       = '';
78 my $priority       = '1';
79 my $resdate        = undef;
80 my $expdate        = undef;
81 my $notes          = '';
82 my $checkitem      = undef;
83 my $found          = undef;
84
85 my @branches = GetBranchesLoop();
86 my $branch = $branches[0][0]{value};
87
88 AddReserve($branch,    $borrowernumber, $biblionumber,
89         $constraint, $bibitems,  $priority, $resdate, $expdate, $notes,
90         $title,      $checkitem, $found);
91
92 my ($status, $reserve, $all_reserves) = CheckReserves($itemnumber, $barcode);
93
94 is($status, "Reserved", "CheckReserves Test 1");
95
96 ($status, $reserve, $all_reserves) = CheckReserves($itemnumber);
97 is($status, "Reserved", "CheckReserves Test 2");
98
99 ($status, $reserve, $all_reserves) = CheckReserves(undef, $barcode);
100 is($status, "Reserved", "CheckReserves Test 3");
101
102 my $ReservesControlBranch = C4::Context->preference('ReservesControlBranch');
103 C4::Context->set_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
104 ok(
105     'ItemHomeLib' eq GetReservesControlBranch(
106         { homebranch => 'ItemHomeLib' },
107         { branchcode => 'PatronHomeLib' }
108     ), "GetReservesControlBranch returns item home branch when set to ItemHomeLibrary"
109 );
110 C4::Context->set_preference( 'ReservesControlBranch', 'PatronLibrary' );
111 ok(
112     'PatronHomeLib' eq GetReservesControlBranch(
113         { homebranch => 'ItemHomeLib' },
114         { branchcode => 'PatronHomeLib' }
115     ), "GetReservesControlBranch returns patron home branch when set to PatronLibrary"
116 );
117 C4::Context->set_preference( 'ReservesControlBranch', $ReservesControlBranch );
118
119 ###
120 ### Regression test for bug 10272
121 ###
122 my %requesters = ();
123 $requesters{'CPL'} = AddMember(
124     branchcode   => 'CPL',
125     categorycode => 'PT',
126     surname      => 'borrower from CPL',
127 );
128 $requesters{'FPL'} = AddMember(
129     branchcode   => 'FPL',
130     categorycode => 'PT',
131     surname      => 'borrower from FPL',
132 );
133 $requesters{'RPL'} = AddMember(
134     branchcode   => 'RPL',
135     categorycode => 'PT',
136     surname      => 'borrower from RPL',
137 );
138
139 # Configure rules so that CPL allows only CPL patrons
140 # to request its items, while FPL will allow its items
141 # to fill holds from anywhere.
142
143 $dbh->do('DELETE FROM issuingrules');
144 $dbh->do('DELETE FROM branch_item_rules');
145 $dbh->do('DELETE FROM branch_borrower_circ_rules');
146 $dbh->do('DELETE FROM default_borrower_circ_rules');
147 $dbh->do('DELETE FROM default_branch_item_rules');
148 $dbh->do('DELETE FROM default_branch_circ_rules');
149 $dbh->do('DELETE FROM default_circ_rules');
150 $dbh->do(
151     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed)
152       VALUES (?, ?, ?, ?)},
153     {},
154     '*', '*', '*', 25
155 );
156
157 # CPL allows only its own patrons to request its items
158 $dbh->do(
159     q{INSERT INTO default_branch_circ_rules (branchcode, maxissueqty, holdallowed, returnbranch)
160       VALUES (?, ?, ?, ?)},
161     {},
162     'CPL', 10, 1, 'homebranch',
163 );
164
165 # ... while FPL allows anybody to request its items
166 $dbh->do(
167     q{INSERT INTO default_branch_circ_rules (branchcode, maxissueqty, holdallowed, returnbranch)
168       VALUES (?, ?, ?, ?)},
169     {},
170     'FPL', 10, 2, 'homebranch',
171 );
172
173 # helper biblio for the bug 10272 regression test
174 my $bib2 = MARC::Record->new();
175 $bib2->append_fields(
176     MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
177     MARC::Field->new('245', ' ', ' ', a => $title),
178 );
179
180 # create one item belonging to FPL and one belonging to CPL
181 my ($bibnum2, $bibitemnum2) = AddBiblio($bib, '');
182 my ($itemnum_cpl, $itemnum_fpl);
183 (undef, undef, $itemnum_cpl) = AddItem({
184         homebranch => 'CPL',
185         holdingbranch => 'CPL',
186         barcode => 'bug10272_CPL'
187     } , $bibnum2);
188 (undef, undef, $itemnum_fpl) = AddItem({
189         homebranch => 'FPL',
190         holdingbranch => 'FPL',
191         barcode => 'bug10272_FPL'
192     } , $bibnum2);
193
194 AddReserve('RPL',  $requesters{'RPL'}, $bibnum2,
195            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
196            $title,      $checkitem, $found);
197 AddReserve('FPL',  $requesters{'FPL'}, $bibnum2,
198            $constraint, $bibitems,  2, $resdate, $expdate, $notes,
199            $title,      $checkitem, $found);
200 AddReserve('CPL',  $requesters{'CPL'}, $bibnum2,
201            $constraint, $bibitems,  3, $resdate, $expdate, $notes,
202            $title,      $checkitem, $found);
203
204 # Ensure that the item's home library controls hold policy lookup
205 C4::Context->set_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
206
207 my $messages;
208 # Return the CPL item at FPL.  The hold that should be triggered is
209 # the one placed by the CPL patron, as the other two patron's hold
210 # requests cannot be filled by that item per policy.
211 (undef, $messages, undef, undef) = AddReturn('bug10272_CPL', 'FPL');
212 is( $messages->{ResFound}->{borrowernumber},
213     $requesters{'CPL'},
214     'restrictive library\'s items only fill requests by own patrons (bug 10272)');
215
216 # Return the FPL item at FPL.  The hold that should be triggered is
217 # the one placed by the RPL patron, as that patron is first in line
218 # and RPL imposes no restrictions on whose holds its items can fill.
219 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', 'FPL');
220 is( $messages->{ResFound}->{borrowernumber},
221     $requesters{'RPL'},
222     'for generous library, its items fill first hold request in line (bug 10272)');
223
224 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
225 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
226 # Test 9761a: Add a reserve without date, CheckReserve should return it
227 $resdate= undef; #defaults to today in AddReserve
228 $expdate= undef; #no expdate
229 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
230 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
231            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
232            $title,      $checkitem, $found);
233 ($status)=CheckReserves($itemnumber,undef,undef);
234 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
235 ($status)=CheckReserves($itemnumber,undef,7);
236 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
237
238 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
239 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
240 C4::Context->set_preference('AllowHoldDateInFuture', 1);
241 $resdate= dt_from_string();
242 $resdate->add_duration(DateTime::Duration->new(days => 4));
243 $resdate=output_pref($resdate);
244 $expdate= undef; #no expdate
245 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
246            $constraint, $bibitems,  1, $resdate, $expdate, $notes,
247            $title,      $checkitem, $found);
248 ($status)=CheckReserves($itemnumber,undef,undef);
249 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
250
251 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
252 ($status)=CheckReserves($itemnumber,undef,3);
253 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
254 ($status)=CheckReserves($itemnumber,undef,4);
255 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
256
257 # Test 9761d: Check ResFound message of AddReturn for future hold
258 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
259 # In this test we do not need an issued item; it is just a 'checkin'
260 C4::Context->set_preference('ConfirmFutureHolds', 0);
261 (my $doreturn, $messages)= AddReturn('97531','CPL');
262 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
263 C4::Context->set_preference('ConfirmFutureHolds', 3);
264 ($doreturn, $messages)= AddReturn('97531','CPL');
265 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
266 C4::Context->set_preference('ConfirmFutureHolds', 7);
267 ($doreturn, $messages)= AddReturn('97531','CPL');
268 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
269
270 # End of tests for bug 9761 (ConfirmFutureHolds)
271
272 # test marking a hold as captured
273 my $hold_notice_count = count_hold_print_messages();
274 ModReserveAffect($itemnumber, $requesters{'CPL'}, 0);
275 my $new_count = count_hold_print_messages();
276 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
277
278 # test that duplicate notices aren't generated
279 ModReserveAffect($itemnumber, $requesters{'CPL'}, 0);
280 $new_count = count_hold_print_messages();
281 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
282
283 # avoiding the not_same_branch error
284 t::lib::Mocks::mock_preference('IndependentBranches', 0);
285 is(
286     DelItemCheck($dbh, $bibnum, $itemnumber),
287     'book_reserved',
288     'item that is captured to fill a hold cannot be deleted',
289 );
290
291 my $letter = ReserveSlip('CPL', $requesters{'CPL'}, $bibnum);
292 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
293
294 $dbh->rollback;
295
296 sub count_hold_print_messages {
297     my $message_count = $dbh->selectall_arrayref(q{
298         SELECT COUNT(*) FROM message_queue WHERE letter_code = 'HOLD_PRINT'
299     });
300     return $message_count->[0]->[0];
301 }