Bug 19403: Prevent Circulation.t to fail randomly
[koha-equinox.git] / t / db_dependent / Circulation.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 => 102;
21
22 use DateTime;
23
24 use t::lib::Mocks;
25 use t::lib::TestBuilder;
26
27 use C4::Circulation;
28 use C4::Biblio;
29 use C4::Items;
30 use C4::Log;
31 use C4::Members;
32 use C4::Reserves;
33 use C4::Overdues qw(UpdateFine CalcFine);
34 use Koha::DateUtils;
35 use Koha::Database;
36 use Koha::IssuingRules;
37 use Koha::Checkouts;
38 use Koha::Patrons;
39 use Koha::Subscriptions;
40
41 my $schema = Koha::Database->schema;
42 $schema->storage->txn_begin;
43 my $builder = t::lib::TestBuilder->new;
44 my $dbh = C4::Context->dbh;
45
46 # Start transaction
47 $dbh->{RaiseError} = 1;
48
49 # Start with a clean slate
50 $dbh->do('DELETE FROM issues');
51
52 my $library = $builder->build({
53     source => 'Branch',
54 });
55 my $library2 = $builder->build({
56     source => 'Branch',
57 });
58 my $itemtype = $builder->build(
59     {   source => 'Itemtype',
60         value  => { notforloan => undef, rentalcharge => 0 }
61     }
62 )->{itemtype};
63 my $patron_category = $builder->build({ source => 'Category', value => { categorycode => 'NOT_X', category_type => 'P', enrolmentfee => 0 } });
64
65 my $CircControl = C4::Context->preference('CircControl');
66 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
67
68 my $item = {
69     homebranch => $library2->{branchcode},
70     holdingbranch => $library2->{branchcode}
71 };
72
73 my $borrower = {
74     branchcode => $library2->{branchcode}
75 };
76
77 # No userenv, PickupLibrary
78 t::lib::Mocks::mock_preference('IndependentBranches', '0');
79 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
80 is(
81     C4::Context->preference('CircControl'),
82     'PickupLibrary',
83     'CircControl changed to PickupLibrary'
84 );
85 is(
86     C4::Circulation::_GetCircControlBranch($item, $borrower),
87     $item->{$HomeOrHoldingBranch},
88     '_GetCircControlBranch returned item branch (no userenv defined)'
89 );
90
91 # No userenv, PatronLibrary
92 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
93 is(
94     C4::Context->preference('CircControl'),
95     'PatronLibrary',
96     'CircControl changed to PatronLibrary'
97 );
98 is(
99     C4::Circulation::_GetCircControlBranch($item, $borrower),
100     $borrower->{branchcode},
101     '_GetCircControlBranch returned borrower branch'
102 );
103
104 # No userenv, ItemHomeLibrary
105 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
106 is(
107     C4::Context->preference('CircControl'),
108     'ItemHomeLibrary',
109     'CircControl changed to ItemHomeLibrary'
110 );
111 is(
112     $item->{$HomeOrHoldingBranch},
113     C4::Circulation::_GetCircControlBranch($item, $borrower),
114     '_GetCircControlBranch returned item branch'
115 );
116
117 # Now, set a userenv
118 C4::Context->_new_userenv('xxx');
119 C4::Context->set_userenv(0,0,0,'firstname','surname', $library2->{branchcode}, 'Midway Public Library', '', '', '');
120 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
121
122 # Userenv set, PickupLibrary
123 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
124 is(
125     C4::Context->preference('CircControl'),
126     'PickupLibrary',
127     'CircControl changed to PickupLibrary'
128 );
129 is(
130     C4::Circulation::_GetCircControlBranch($item, $borrower),
131     $library2->{branchcode},
132     '_GetCircControlBranch returned current branch'
133 );
134
135 # Userenv set, PatronLibrary
136 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
137 is(
138     C4::Context->preference('CircControl'),
139     'PatronLibrary',
140     'CircControl changed to PatronLibrary'
141 );
142 is(
143     C4::Circulation::_GetCircControlBranch($item, $borrower),
144     $borrower->{branchcode},
145     '_GetCircControlBranch returned borrower branch'
146 );
147
148 # Userenv set, ItemHomeLibrary
149 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
150 is(
151     C4::Context->preference('CircControl'),
152     'ItemHomeLibrary',
153     'CircControl changed to ItemHomeLibrary'
154 );
155 is(
156     C4::Circulation::_GetCircControlBranch($item, $borrower),
157     $item->{$HomeOrHoldingBranch},
158     '_GetCircControlBranch returned item branch'
159 );
160
161 # Reset initial configuration
162 t::lib::Mocks::mock_preference('CircControl', $CircControl);
163 is(
164     C4::Context->preference('CircControl'),
165     $CircControl,
166     'CircControl reset to its initial value'
167 );
168
169 # Set a simple circ policy
170 $dbh->do('DELETE FROM issuingrules');
171 $dbh->do(
172     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
173                                 maxissueqty, issuelength, lengthunit,
174                                 renewalsallowed, renewalperiod,
175                                 norenewalbefore, auto_renew,
176                                 fine, chargeperiod)
177       VALUES (?, ?, ?, ?,
178               ?, ?, ?,
179               ?, ?,
180               ?, ?,
181               ?, ?
182              )
183     },
184     {},
185     '*', '*', '*', 25,
186     20, 14, 'days',
187     1, 7,
188     undef, 0,
189     .10, 1
190 );
191
192 # Test C4::Circulation::ProcessOfflinePayment
193 my $sth = C4::Context->dbh->prepare("SELECT COUNT(*) FROM accountlines WHERE amount = '-123.45' AND accounttype = 'Pay'");
194 $sth->execute();
195 my ( $original_count ) = $sth->fetchrow_array();
196
197 C4::Context->dbh->do("INSERT INTO borrowers ( cardnumber, surname, firstname, categorycode, branchcode ) VALUES ( '99999999999', 'Hall', 'Kyle', ?, ? )", undef, $patron_category->{categorycode}, $library2->{branchcode} );
198
199 C4::Circulation::ProcessOfflinePayment({ cardnumber => '99999999999', amount => '123.45' });
200
201 $sth->execute();
202 my ( $new_count ) = $sth->fetchrow_array();
203
204 ok( $new_count == $original_count  + 1, 'ProcessOfflinePayment makes payment correctly' );
205
206 C4::Context->dbh->do("DELETE FROM accountlines WHERE borrowernumber IN ( SELECT borrowernumber FROM borrowers WHERE cardnumber = '99999999999' )");
207 C4::Context->dbh->do("DELETE FROM borrowers WHERE cardnumber = '99999999999'");
208 C4::Context->dbh->do("DELETE FROM accountlines");
209 {
210 # CanBookBeRenewed tests
211
212     # Generate test biblio
213     my $biblio = MARC::Record->new();
214     my $title = 'Silence in the library';
215     $biblio->append_fields(
216         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
217         MARC::Field->new('245', ' ', ' ', a => $title),
218     );
219
220     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
221
222     my $barcode = 'R00000342';
223     my $branch = $library2->{branchcode};
224
225     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
226         {
227             homebranch       => $branch,
228             holdingbranch    => $branch,
229             barcode          => $barcode,
230             replacementprice => 12.00,
231             itype            => $itemtype
232         },
233         $biblionumber
234     );
235
236     my $barcode2 = 'R00000343';
237     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
238         {
239             homebranch       => $branch,
240             holdingbranch    => $branch,
241             barcode          => $barcode2,
242             replacementprice => 23.00,
243             itype            => $itemtype
244         },
245         $biblionumber
246     );
247
248     my $barcode3 = 'R00000346';
249     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
250         {
251             homebranch       => $branch,
252             holdingbranch    => $branch,
253             barcode          => $barcode3,
254             replacementprice => 23.00,
255             itype            => $itemtype
256         },
257         $biblionumber
258     );
259
260
261
262
263     # Create borrowers
264     my %renewing_borrower_data = (
265         firstname =>  'John',
266         surname => 'Renewal',
267         categorycode => $patron_category->{categorycode},
268         branchcode => $branch,
269     );
270
271     my %reserving_borrower_data = (
272         firstname =>  'Katrin',
273         surname => 'Reservation',
274         categorycode => $patron_category->{categorycode},
275         branchcode => $branch,
276     );
277
278     my %hold_waiting_borrower_data = (
279         firstname =>  'Kyle',
280         surname => 'Reservation',
281         categorycode => $patron_category->{categorycode},
282         branchcode => $branch,
283     );
284
285     my %restricted_borrower_data = (
286         firstname =>  'Alice',
287         surname => 'Reservation',
288         categorycode => $patron_category->{categorycode},
289         debarred => '3228-01-01',
290         branchcode => $branch,
291     );
292
293     my $renewing_borrowernumber = AddMember(%renewing_borrower_data);
294     my $reserving_borrowernumber = AddMember(%reserving_borrower_data);
295     my $hold_waiting_borrowernumber = AddMember(%hold_waiting_borrower_data);
296     my $restricted_borrowernumber = AddMember(%restricted_borrower_data);
297
298     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
299     my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
300
301     my $bibitems       = '';
302     my $priority       = '1';
303     my $resdate        = undef;
304     my $expdate        = undef;
305     my $notes          = '';
306     my $checkitem      = undef;
307     my $found          = undef;
308
309     my $issue = AddIssue( $renewing_borrower, $barcode);
310     my $datedue = dt_from_string( $issue->date_due() );
311     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
312
313     my $issue2 = AddIssue( $renewing_borrower, $barcode2);
314     $datedue = dt_from_string( $issue->date_due() );
315     is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
316
317
318     my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $itemnumber } )->borrowernumber;
319     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
320
321     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
322     is( $renewokay, 1, 'Can renew, no holds for this title or item');
323
324
325     # Biblio-level hold, renewal test
326     AddReserve(
327         $branch, $reserving_borrowernumber, $biblionumber,
328         $bibitems,  $priority, $resdate, $expdate, $notes,
329         $title, $checkitem, $found
330     );
331
332     # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
333     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
334     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
335     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
336     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
337     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
338     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
339
340     # Now let's add an item level hold, we should no longer be able to renew the item
341     my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
342         {
343             borrowernumber => $hold_waiting_borrowernumber,
344             biblionumber   => $biblionumber,
345             itemnumber     => $itemnumber,
346             branchcode     => $branch,
347             priority       => 3,
348         }
349     );
350     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
351     is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
352     $hold->delete();
353
354     # Now let's add a waiting hold on the 3rd item, it's no longer available tp check out by just anyone, so we should no longer
355     # be able to renew these items
356     $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
357         {
358             borrowernumber => $hold_waiting_borrowernumber,
359             biblionumber   => $biblionumber,
360             itemnumber     => $itemnumber3,
361             branchcode     => $branch,
362             priority       => 0,
363             found          => 'W'
364         }
365     );
366     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
367     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
368     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
369     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
370     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
371
372     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
373     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
374     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
375
376     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
377     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
378     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
379
380     my $reserveid = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
381     my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
382     AddIssue($reserving_borrower, $barcode3);
383     my $reserve = $dbh->selectrow_hashref(
384         'SELECT * FROM old_reserves WHERE reserve_id = ?',
385         { Slice => {} },
386         $reserveid
387     );
388     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
389
390     # Item-level hold, renewal test
391     AddReserve(
392         $branch, $reserving_borrowernumber, $biblionumber,
393         $bibitems,  $priority, $resdate, $expdate, $notes,
394         $title, $itemnumber, $found
395     );
396
397     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
398     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
399     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
400
401     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2, 1);
402     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
403
404     # Items can't fill hold for reasons
405     ModItem({ notforloan => 1 }, $biblionumber, $itemnumber);
406     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
407     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
408     ModItem({ notforloan => 0, itype => $itemtype }, $biblionumber, $itemnumber,1);
409
410     # FIXME: Add more for itemtype not for loan etc.
411
412     # Restricted users cannot renew when RestrictionBlockRenewing is enabled
413     my $barcode5 = 'R00000347';
414     my ( $item_bibnum5, $item_bibitemnum5, $itemnumber5 ) = AddItem(
415         {
416             homebranch       => $branch,
417             holdingbranch    => $branch,
418             barcode          => $barcode5,
419             replacementprice => 23.00,
420             itype            => $itemtype
421         },
422         $biblionumber
423     );
424     my $datedue5 = AddIssue($restricted_borrower, $barcode5);
425     is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
426
427     t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
428     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
429     is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
430     ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $itemnumber5);
431     is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
432
433     # Users cannot renew an overdue item
434     my $barcode6 = 'R00000348';
435     my ( $item_bibnum6, $item_bibitemnum6, $itemnumber6 ) = AddItem(
436         {
437             homebranch       => $branch,
438             holdingbranch    => $branch,
439             barcode          => $barcode6,
440             replacementprice => 23.00,
441             itype            => $itemtype
442         },
443         $biblionumber
444     );
445
446     my $barcode7 = 'R00000349';
447     my ( $item_bibnum7, $item_bibitemnum7, $itemnumber7 ) = AddItem(
448         {
449             homebranch       => $branch,
450             holdingbranch    => $branch,
451             barcode          => $barcode7,
452             replacementprice => 23.00,
453             itype            => $itemtype
454         },
455         $biblionumber
456     );
457     my $datedue6 = AddIssue( $renewing_borrower, $barcode6);
458     is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
459
460     my $now = dt_from_string();
461     my $five_weeks = DateTime::Duration->new(weeks => 5);
462     my $five_weeks_ago = $now - $five_weeks;
463     t::lib::Mocks::mock_preference('finesMode', 'production');
464
465     my $passeddatedue1 = AddIssue($renewing_borrower, $barcode7, $five_weeks_ago);
466     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
467
468     my ( $fine ) = CalcFine( GetItem(undef, $barcode7), $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
469     C4::Overdues::UpdateFine(
470         {
471             issue_id       => $passeddatedue1->id(),
472             itemnumber     => $itemnumber7,
473             borrowernumber => $renewing_borrower->{borrowernumber},
474             amount         => $fine,
475             type           => 'FU',
476             due            => Koha::DateUtils::output_pref($five_weeks_ago)
477         }
478     );
479
480     t::lib::Mocks::mock_preference('RenewalLog', 0);
481     my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
482     my $old_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
483     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
484     my $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
485     is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
486
487     t::lib::Mocks::mock_preference('RenewalLog', 1);
488     $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
489     $old_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
490     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
491     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
492     is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
493
494     my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $itemnumber7 } );
495     is( $fines->count, 2 );
496     is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
497     is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
498     $fines->delete();
499
500
501     my $old_issue_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["ISSUE"]) } );
502     my $old_renew_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
503     AddIssue( $renewing_borrower,$barcode7,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
504     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
505     is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
506     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["ISSUE"]) } );
507     is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
508
509     $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $itemnumber7 } );
510     $fines->delete();
511
512     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
513     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
514     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
515     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
516     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
517
518
519     $hold = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $reserving_borrowernumber })->next;
520     $hold->cancel;
521
522     # Bug 14101
523     # Test automatic renewal before value for "norenewalbefore" in policy is set
524     # In this case automatic renewal is not permitted prior to due date
525     my $barcode4 = '11235813';
526     my ( $item_bibnum4, $item_bibitemnum4, $itemnumber4 ) = AddItem(
527         {
528             homebranch       => $branch,
529             holdingbranch    => $branch,
530             barcode          => $barcode4,
531             replacementprice => 16.00,
532             itype            => $itemtype
533         },
534         $biblionumber
535     );
536
537     $issue = AddIssue( $renewing_borrower, $barcode4, undef, undef, undef, undef, { auto_renew => 1 } );
538     ( $renewokay, $error ) =
539       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
540     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
541     is( $error, 'auto_too_soon',
542         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
543
544     # Bug 7413
545     # Test premature manual renewal
546     $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
547
548     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
549     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
550     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
551
552     # Bug 14395
553     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
554     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
555     is(
556         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
557         $datedue->clone->add( days => -7 ),
558         'Bug 14395: Renewals permitted 7 days before due date, as expected'
559     );
560
561     # Bug 14395
562     # Test 'date' setting for syspref NoRenewalBeforePrecision
563     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
564     is(
565         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
566         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
567         'Bug 14395: Renewals permitted 7 days before due date, as expected'
568     );
569
570     # Bug 14101
571     # Test premature automatic renewal
572     ( $renewokay, $error ) =
573       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
574     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
575     is( $error, 'auto_too_soon',
576         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
577     );
578
579     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
580     # and test automatic renewal again
581     $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
582     ( $renewokay, $error ) =
583       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
584     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
585     is( $error, 'auto_too_soon',
586         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
587     );
588
589     # Change policy so that loans can be renewed 99 days prior to the due date
590     # and test automatic renewal again
591     $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
592     ( $renewokay, $error ) =
593       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
594     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
595     is( $error, 'auto_renew',
596         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
597     );
598
599     subtest "too_late_renewal / no_auto_renewal_after" => sub {
600         plan tests => 14;
601         my $item_to_auto_renew = $builder->build(
602             {   source => 'Item',
603                 value  => {
604                     biblionumber  => $biblionumber,
605                     homebranch    => $branch,
606                     holdingbranch => $branch,
607                 }
608             }
609         );
610
611         my $ten_days_before = dt_from_string->add( days => -10 );
612         my $ten_days_ahead  = dt_from_string->add( days => 10 );
613         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
614
615         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
616         ( $renewokay, $error ) =
617           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
618         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
619         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
620
621         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
622         ( $renewokay, $error ) =
623           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
624         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
625         is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
626
627         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
628         ( $renewokay, $error ) =
629           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
630         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
631         is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
632
633         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
634         ( $renewokay, $error ) =
635           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
636         is( $renewokay, 0,            'Do not renew, renewal is automatic' );
637         is( $error,     'auto_renew', 'Cannot renew, renew is automatic' );
638
639         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => -1 ) );
640         ( $renewokay, $error ) =
641           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
642         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
643         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
644
645         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => -1 ) );
646         ( $renewokay, $error ) =
647           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
648         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
649         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
650
651         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 1 ) );
652         ( $renewokay, $error ) =
653           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
654         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
655         is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
656     };
657
658     subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew" => sub {
659         plan tests => 6;
660         my $item_to_auto_renew = $builder->build({
661             source => 'Item',
662             value => {
663                 biblionumber => $biblionumber,
664                 homebranch       => $branch,
665                 holdingbranch    => $branch,
666             }
667         });
668
669         my $ten_days_before = dt_from_string->add( days => -10 );
670         my $ten_days_ahead = dt_from_string->add( days => 10 );
671         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
672
673         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
674         C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
675         C4::Context->set_preference('OPACFineNoRenewals','10');
676         my $fines_amount = 5;
677         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
678         ( $renewokay, $error ) =
679           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
680         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
681         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
682
683         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
684         ( $renewokay, $error ) =
685           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
686         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
687         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
688
689         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
690         ( $renewokay, $error ) =
691           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
692         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
693         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
694
695         $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
696     };
697
698     subtest "GetLatestAutoRenewDate" => sub {
699         plan tests => 5;
700         my $item_to_auto_renew = $builder->build(
701             {   source => 'Item',
702                 value  => {
703                     biblionumber  => $biblionumber,
704                     homebranch    => $branch,
705                     holdingbranch => $branch,
706                 }
707             }
708         );
709
710         my $ten_days_before = dt_from_string->add( days => -10 );
711         my $ten_days_ahead  = dt_from_string->add( days => 10 );
712         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
713         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = "", no_auto_renewal_after_hard_limit = NULL');
714         my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
715         is( $latest_auto_renew_date, undef, 'GetLatestAutoRenewDate should return undef if no_auto_renewal_after or no_auto_renewal_after_hard_limit are not defined' );
716         my $five_days_before = dt_from_string->add( days => -5 );
717         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
718         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
719         is( $latest_auto_renew_date->truncate( to => 'minute' ),
720             $five_days_before->truncate( to => 'minute' ),
721             'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
722         );
723         my $five_days_ahead = dt_from_string->add( days => 5 );
724         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
725         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
726         is( $latest_auto_renew_date->truncate( to => 'minute' ),
727             $five_days_ahead->truncate( to => 'minute' ),
728             'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
729         );
730         my $two_days_ahead = dt_from_string->add( days => 2 );
731         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = "", no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 2 ) );
732         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
733         is( $latest_auto_renew_date->truncate( to => 'day' ),
734             $two_days_ahead->truncate( to => 'day' ),
735             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
736         );
737         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 2 ) );
738         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
739         is( $latest_auto_renew_date->truncate( to => 'day' ),
740             $two_days_ahead->truncate( to => 'day' ),
741             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
742         );
743
744     };
745
746     # Too many renewals
747
748     # set policy to forbid renewals
749     $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
750
751     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
752     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
753     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
754
755     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
756     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
757     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
758
759     C4::Overdues::UpdateFine(
760         {
761             issue_id       => $issue->id(),
762             itemnumber     => $itemnumber,
763             borrowernumber => $renewing_borrower->{borrowernumber},
764             amount         => 15.00,
765             type           => q{},
766             due            => Koha::DateUtils::output_pref($datedue)
767         }
768     );
769
770     LostItem( $itemnumber, 1 );
771
772     my $item = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber);
773     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
774
775     my $total_due = $dbh->selectrow_array(
776         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
777         undef, $renewing_borrower->{borrowernumber}
778     );
779
780     ok( $total_due == 12, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
781
782     C4::Context->dbh->do("DELETE FROM accountlines");
783
784     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
785     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
786
787     C4::Overdues::UpdateFine(
788         {
789             issue_id       => $issue2->id(),
790             itemnumber     => $itemnumber2,
791             borrowernumber => $renewing_borrower->{borrowernumber},
792             amount         => 15.00,
793             type           => q{},
794             due            => Koha::DateUtils::output_pref($datedue)
795         }
796     );
797
798     LostItem( $itemnumber2, 0 );
799
800     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
801     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
802
803     $total_due = $dbh->selectrow_array(
804         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
805         undef, $renewing_borrower->{borrowernumber}
806     );
807
808     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
809
810     my $future = dt_from_string();
811     $future->add( days => 7 );
812     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
813     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
814
815     # Users cannot renew any item if there is an overdue item
816     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
817     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
818     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
819     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
820     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
821
822   }
823
824 {
825     # GetUpcomingDueIssues tests
826     my $barcode  = 'R00000342';
827     my $barcode2 = 'R00000343';
828     my $barcode3 = 'R00000344';
829     my $branch   = $library2->{branchcode};
830
831     #Create another record
832     my $biblio2 = MARC::Record->new();
833     my $title2 = 'Something is worng here';
834     $biblio2->append_fields(
835         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
836         MARC::Field->new('245', ' ', ' ', a => $title2),
837     );
838     my ($biblionumber2, $biblioitemnumber2) = AddBiblio($biblio2, '');
839
840     #Create third item
841     AddItem(
842         {
843             homebranch       => $branch,
844             holdingbranch    => $branch,
845             barcode          => $barcode3,
846             itype            => $itemtype
847         },
848         $biblionumber2
849     );
850
851     # Create a borrower
852     my %a_borrower_data = (
853         firstname =>  'Fridolyn',
854         surname => 'SOMERS',
855         categorycode => $patron_category->{categorycode},
856         branchcode => $branch,
857     );
858
859     my $a_borrower_borrowernumber = AddMember(%a_borrower_data);
860     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
861
862     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
863     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
864     my $today = DateTime->today(time_zone => C4::Context->tz());
865
866     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
867     my $datedue = dt_from_string( $issue->date_due() );
868     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
869     my $datedue2 = dt_from_string( $issue->date_due() );
870
871     my $upcoming_dues;
872
873     # GetUpcomingDueIssues tests
874     for my $i(0..1) {
875         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
876         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
877     }
878
879     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
880     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
881     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
882
883     for my $i(3..5) {
884         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
885         is ( scalar( @$upcoming_dues ), 1,
886             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
887     }
888
889     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
890
891     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
892
893     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
894     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
895
896     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
897     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
898
899     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
900     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
901
902     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
903     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
904
905     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
906     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
907
908     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
909     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
910
911 }
912
913 {
914     my $barcode  = '1234567890';
915     my $branch   = $library2->{branchcode};
916
917     my $biblio = MARC::Record->new();
918     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
919
920     #Create third item
921     my ( undef, undef, $itemnumber ) = AddItem(
922         {
923             homebranch       => $branch,
924             holdingbranch    => $branch,
925             barcode          => $barcode,
926             itype            => $itemtype
927         },
928         $biblionumber
929     );
930
931     # Create a borrower
932     my %a_borrower_data = (
933         firstname =>  'Kyle',
934         surname => 'Hall',
935         categorycode => $patron_category->{categorycode},
936         branchcode => $branch,
937     );
938
939     my $borrowernumber = AddMember(%a_borrower_data);
940
941     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
942     my $issue = AddIssue( $borrower, $barcode );
943     UpdateFine(
944         {
945             issue_id       => $issue->id(),
946             itemnumber     => $itemnumber,
947             borrowernumber => $borrowernumber,
948             amount         => 0,
949             type           => q{}
950         }
951     );
952
953     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
954     my $count = $hr->{count};
955
956     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
957 }
958
959 {
960     $dbh->do('DELETE FROM issues');
961     $dbh->do('DELETE FROM items');
962     $dbh->do('DELETE FROM issuingrules');
963     $dbh->do(
964         q{
965         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
966                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
967         },
968         {},
969         '*', '*', '*', 25,
970         20,  14,  'days',
971         1,   7,
972         undef,  0,
973         .10, 1
974     );
975     my $biblio = MARC::Record->new();
976     my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' );
977
978     my $barcode1 = '1234';
979     my ( undef, undef, $itemnumber1 ) = AddItem(
980         {
981             homebranch    => $library2->{branchcode},
982             holdingbranch => $library2->{branchcode},
983             barcode       => $barcode1,
984             itype         => $itemtype
985         },
986         $biblionumber
987     );
988     my $barcode2 = '4321';
989     my ( undef, undef, $itemnumber2 ) = AddItem(
990         {
991             homebranch    => $library2->{branchcode},
992             holdingbranch => $library2->{branchcode},
993             barcode       => $barcode2,
994             itype         => $itemtype
995         },
996         $biblionumber
997     );
998
999     my $borrowernumber1 = AddMember(
1000         firstname    => 'Kyle',
1001         surname      => 'Hall',
1002         categorycode => $patron_category->{categorycode},
1003         branchcode   => $library2->{branchcode},
1004     );
1005     my $borrowernumber2 = AddMember(
1006         firstname    => 'Chelsea',
1007         surname      => 'Hall',
1008         categorycode => $patron_category->{categorycode},
1009         branchcode   => $library2->{branchcode},
1010     );
1011
1012     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1013     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1014
1015     my $issue = AddIssue( $borrower1, $barcode1 );
1016
1017     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1018     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1019
1020     AddReserve(
1021         $library2->{branchcode}, $borrowernumber2, $biblionumber,
1022         '',  1, undef, undef, '',
1023         undef, undef, undef
1024     );
1025
1026     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1027     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1028     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1029     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1030
1031     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1032     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1033     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1034     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1035
1036     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1037     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1038     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1039     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1040
1041     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1042     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1043     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1044     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1045
1046     # Setting item not checked out to be not for loan but holdable
1047     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
1048
1049     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1050     is( $renewokay, 0, 'Bug 14337 - Verify the borrower can not renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled but the only available item is notforloan' );
1051 }
1052
1053 {
1054     # Don't allow renewing onsite checkout
1055     my $barcode  = 'R00000XXX';
1056     my $branch   = $library->{branchcode};
1057
1058     #Create another record
1059     my $biblio = MARC::Record->new();
1060     $biblio->append_fields(
1061         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
1062         MARC::Field->new('245', ' ', ' ', a => 'A title'),
1063     );
1064     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
1065
1066     my (undef, undef, $itemnumber) = AddItem(
1067         {
1068             homebranch       => $branch,
1069             holdingbranch    => $branch,
1070             barcode          => $barcode,
1071             itype            => $itemtype
1072         },
1073         $biblionumber
1074     );
1075
1076     my $borrowernumber = AddMember(
1077         firstname =>  'fn',
1078         surname => 'dn',
1079         categorycode => $patron_category->{categorycode},
1080         branchcode => $branch,
1081     );
1082
1083     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1084
1085     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1086     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
1087     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1088     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1089 }
1090
1091 {
1092     my $library = $builder->build({ source => 'Branch' });
1093
1094     my $biblio = MARC::Record->new();
1095     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
1096
1097     my $barcode = 'just a barcode';
1098     my ( undef, undef, $itemnumber ) = AddItem(
1099         {
1100             homebranch       => $library->{branchcode},
1101             holdingbranch    => $library->{branchcode},
1102             barcode          => $barcode,
1103             itype            => $itemtype
1104         },
1105         $biblionumber,
1106     );
1107
1108     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1109
1110     my $issue = AddIssue( $patron, $barcode );
1111     UpdateFine(
1112         {
1113             issue_id       => $issue->id(),
1114             itemnumber     => $itemnumber,
1115             borrowernumber => $patron->{borrowernumber},
1116             amount         => 1,
1117             type           => q{}
1118         }
1119     );
1120     UpdateFine(
1121         {
1122             issue_id       => $issue->id(),
1123             itemnumber     => $itemnumber,
1124             borrowernumber => $patron->{borrowernumber},
1125             amount         => 2,
1126             type           => q{}
1127         }
1128     );
1129     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1130 }
1131
1132 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1133     plan tests => 23;
1134
1135     my $homebranch    = $builder->build( { source => 'Branch' } );
1136     my $holdingbranch = $builder->build( { source => 'Branch' } );
1137     my $otherbranch   = $builder->build( { source => 'Branch' } );
1138     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1139     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1140
1141     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1142     my $item = $builder->build(
1143         {   source => 'Item',
1144             value  => {
1145                 homebranch    => $homebranch->{branchcode},
1146                 holdingbranch => $holdingbranch->{branchcode},
1147                 notforloan    => 0,
1148                 itemlost      => 0,
1149                 withdrawn     => 0,
1150                 restricted    => 0,
1151                 biblionumber  => $biblioitem->{biblionumber}
1152             }
1153         }
1154     );
1155
1156     set_userenv($holdingbranch);
1157
1158     my $issue = AddIssue( $patron_1, $item->{barcode} );
1159     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Checkout
1160
1161     my ( $error, $question, $alerts );
1162
1163     # AllowReturnToBranch == anywhere
1164     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1165     ## Can be issued from homebranch
1166     set_userenv($homebranch);
1167     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1168     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1169     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1170     ## Can be issued from holdingbranch
1171     set_userenv($holdingbranch);
1172     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1173     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1174     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1175     ## Can be issued from another branch
1176     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1177     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1178     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1179
1180     # AllowReturnToBranch == holdingbranch
1181     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1182     ## Cannot be issued from homebranch
1183     set_userenv($homebranch);
1184     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1185     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1186     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1187     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1188     ## Can be issued from holdinbranch
1189     set_userenv($holdingbranch);
1190     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1191     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1192     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1193     ## Cannot be issued from another branch
1194     set_userenv($otherbranch);
1195     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1196     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1197     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1198     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1199
1200     # AllowReturnToBranch == homebranch
1201     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1202     ## Can be issued from holdinbranch
1203     set_userenv($homebranch);
1204     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1205     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1206     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1207     ## Cannot be issued from holdinbranch
1208     set_userenv($holdingbranch);
1209     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1210     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1211     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1212     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1213     ## Cannot be issued from holdinbranch
1214     set_userenv($otherbranch);
1215     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1216     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1217     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1218     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1219
1220     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1221 };
1222
1223 subtest 'AddIssue & AllowReturnToBranch' => sub {
1224     plan tests => 9;
1225
1226     my $homebranch    = $builder->build( { source => 'Branch' } );
1227     my $holdingbranch = $builder->build( { source => 'Branch' } );
1228     my $otherbranch   = $builder->build( { source => 'Branch' } );
1229     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1230     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1231
1232     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1233     my $item = $builder->build(
1234         {   source => 'Item',
1235             value  => {
1236                 homebranch    => $homebranch->{branchcode},
1237                 holdingbranch => $holdingbranch->{branchcode},
1238                 notforloan    => 0,
1239                 itemlost      => 0,
1240                 withdrawn     => 0,
1241                 biblionumber  => $biblioitem->{biblionumber}
1242             }
1243         }
1244     );
1245
1246     set_userenv($holdingbranch);
1247
1248     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Checkout
1249     my $issue = AddIssue( $patron_1, $item->{barcode} );
1250
1251     my ( $error, $question, $alerts );
1252
1253     # AllowReturnToBranch == homebranch
1254     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1255     ## Can be issued from homebranch
1256     set_userenv($homebranch);
1257     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1258     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1259     ## Can be issued from holdinbranch
1260     set_userenv($holdingbranch);
1261     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1262     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1263     ## Can be issued from another branch
1264     set_userenv($otherbranch);
1265     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1266     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1267
1268     # AllowReturnToBranch == holdinbranch
1269     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1270     ## Cannot be issued from homebranch
1271     set_userenv($homebranch);
1272     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1273     ## Can be issued from holdingbranch
1274     set_userenv($holdingbranch);
1275     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1276     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1277     ## Cannot be issued from another branch
1278     set_userenv($otherbranch);
1279     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1280
1281     # AllowReturnToBranch == homebranch
1282     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1283     ## Can be issued from homebranch
1284     set_userenv($homebranch);
1285     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1286     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1287     ## Cannot be issued from holdinbranch
1288     set_userenv($holdingbranch);
1289     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1290     ## Cannot be issued from another branch
1291     set_userenv($otherbranch);
1292     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1293     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1294 };
1295
1296 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1297     plan tests => 8;
1298
1299     my $library = $builder->build( { source => 'Branch' } );
1300     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1301
1302     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1303     my $item_1 = $builder->build(
1304         {   source => 'Item',
1305             value  => {
1306                 homebranch    => $library->{branchcode},
1307                 holdingbranch => $library->{branchcode},
1308                 notforloan    => 0,
1309                 itemlost      => 0,
1310                 withdrawn     => 0,
1311                 restricted    => 0,
1312                 biblionumber  => $biblioitem_1->{biblionumber}
1313             }
1314         }
1315     );
1316     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1317     my $item_2 = $builder->build(
1318         {   source => 'Item',
1319             value  => {
1320                 homebranch    => $library->{branchcode},
1321                 holdingbranch => $library->{branchcode},
1322                 notforloan    => 0,
1323                 itemlost      => 0,
1324                 withdrawn     => 0,
1325                 restricted    => 0,
1326                 biblionumber  => $biblioitem_2->{biblionumber}
1327             }
1328         }
1329     );
1330
1331     my ( $error, $question, $alerts );
1332
1333     # Patron cannot issue item_1, they have overdues
1334     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1335     my $issue = AddIssue( $patron, $item_1->{barcode}, $yesterday );    # Add an overdue
1336
1337     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1338     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1339     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
1340     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1341
1342     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1343     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1344     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1345     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1346
1347     # Patron cannot issue item_1, they are debarred
1348     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1349     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber}, expiration => $tomorrow } );
1350     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1351     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1352     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1353
1354     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber} } );
1355     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1356     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1357     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1358 };
1359
1360 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1361     plan tests => 1;
1362
1363     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1364     my $patron_category_x = $builder->build_object(
1365         {
1366             class => 'Koha::Patron::Categories',
1367             value => { category_type => 'X' }
1368         }
1369     );
1370     my $patron = $builder->build_object(
1371         {
1372             class => 'Koha::Patrons',
1373             value => {
1374                 categorycode  => $patron_category_x->categorycode,
1375                 gonenoaddress => undef,
1376                 lost          => undef,
1377                 debarred      => undef,
1378                 borrowernotes => ""
1379             }
1380         }
1381     );
1382     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1383     my $item_1 = $builder->build(
1384         {
1385             source => 'Item',
1386             value  => {
1387                 homebranch    => $library->branchcode,
1388                 holdingbranch => $library->branchcode,
1389                 notforloan    => 0,
1390                 itemlost      => 0,
1391                 withdrawn     => 0,
1392                 restricted    => 0,
1393                 biblionumber  => $biblioitem_1->{biblionumber}
1394             }
1395         }
1396     );
1397
1398     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron->unblessed, $item_1->{barcode} );
1399     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1400
1401     # TODO There are other tests to provide here
1402 };
1403
1404 subtest 'MultipleReserves' => sub {
1405     plan tests => 3;
1406
1407     my $biblio = MARC::Record->new();
1408     my $title = 'Silence in the library';
1409     $biblio->append_fields(
1410         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
1411         MARC::Field->new('245', ' ', ' ', a => $title),
1412     );
1413
1414     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
1415
1416     my $branch = $library2->{branchcode};
1417
1418     my $barcode1 = 'R00110001';
1419     my ( $item_bibnum1, $item_bibitemnum1, $itemnumber1 ) = AddItem(
1420         {
1421             homebranch       => $branch,
1422             holdingbranch    => $branch,
1423             barcode          => $barcode1,
1424             replacementprice => 12.00,
1425             itype            => $itemtype
1426         },
1427         $biblionumber
1428     );
1429
1430     my $barcode2 = 'R00110002';
1431     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
1432         {
1433             homebranch       => $branch,
1434             holdingbranch    => $branch,
1435             barcode          => $barcode2,
1436             replacementprice => 12.00,
1437             itype            => $itemtype
1438         },
1439         $biblionumber
1440     );
1441
1442     my $bibitems       = '';
1443     my $priority       = '1';
1444     my $resdate        = undef;
1445     my $expdate        = undef;
1446     my $notes          = '';
1447     my $checkitem      = undef;
1448     my $found          = undef;
1449
1450     my %renewing_borrower_data = (
1451         firstname =>  'John',
1452         surname => 'Renewal',
1453         categorycode => $patron_category->{categorycode},
1454         branchcode => $branch,
1455     );
1456     my $renewing_borrowernumber = AddMember(%renewing_borrower_data);
1457     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1458     my $issue = AddIssue( $renewing_borrower, $barcode1);
1459     my $datedue = dt_from_string( $issue->date_due() );
1460     is (defined $issue->date_due(), 1, "item 1 checked out");
1461     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $itemnumber1 })->borrowernumber;
1462
1463     my %reserving_borrower_data1 = (
1464         firstname =>  'Katrin',
1465         surname => 'Reservation',
1466         categorycode => $patron_category->{categorycode},
1467         branchcode => $branch,
1468     );
1469     my $reserving_borrowernumber1 = AddMember(%reserving_borrower_data1);
1470     AddReserve(
1471         $branch, $reserving_borrowernumber1, $biblionumber,
1472         $bibitems,  $priority, $resdate, $expdate, $notes,
1473         $title, $checkitem, $found
1474     );
1475
1476     my %reserving_borrower_data2 = (
1477         firstname =>  'Kirk',
1478         surname => 'Reservation',
1479         categorycode => $patron_category->{categorycode},
1480         branchcode => $branch,
1481     );
1482     my $reserving_borrowernumber2 = AddMember(%reserving_borrower_data2);
1483     AddReserve(
1484         $branch, $reserving_borrowernumber2, $biblionumber,
1485         $bibitems,  $priority, $resdate, $expdate, $notes,
1486         $title, $checkitem, $found
1487     );
1488
1489     {
1490         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1491         is($renewokay, 0, 'Bug 17641 - should cover the case where 2 books are both reserved, so failing');
1492     }
1493
1494     my $barcode3 = 'R00110003';
1495     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
1496         {
1497             homebranch       => $branch,
1498             holdingbranch    => $branch,
1499             barcode          => $barcode3,
1500             replacementprice => 12.00,
1501             itype            => $itemtype
1502         },
1503         $biblionumber
1504     );
1505
1506     {
1507         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1508         is($renewokay, 1, 'Bug 17641 - should cover the case where 2 books are reserved, but a third one is available');
1509     }
1510 };
1511
1512 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1513     plan tests => 5;
1514
1515     my $library = $builder->build( { source => 'Branch' } );
1516     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1517
1518     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1519     my $biblionumber = $biblioitem->{biblionumber};
1520     my $item_1 = $builder->build(
1521         {   source => 'Item',
1522             value  => {
1523                 homebranch    => $library->{branchcode},
1524                 holdingbranch => $library->{branchcode},
1525                 notforloan    => 0,
1526                 itemlost      => 0,
1527                 withdrawn     => 0,
1528                 biblionumber  => $biblionumber,
1529             }
1530         }
1531     );
1532     my $item_2 = $builder->build(
1533         {   source => 'Item',
1534             value  => {
1535                 homebranch    => $library->{branchcode},
1536                 holdingbranch => $library->{branchcode},
1537                 notforloan    => 0,
1538                 itemlost      => 0,
1539                 withdrawn     => 0,
1540                 biblionumber  => $biblionumber,
1541             }
1542         }
1543     );
1544
1545     my ( $error, $question, $alerts );
1546     my $issue = AddIssue( $patron, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1547
1548     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1549     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1550     is( keys(%$error) + keys(%$alerts),  0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1551     is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' . str($error, $question, $alerts) );
1552
1553     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1554     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1555     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1556
1557     # Add a subscription
1558     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1559
1560     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1561     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1562     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription' . str($error, $question, $alerts) );
1563
1564     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1565     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1566     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription' . str($error, $question, $alerts) );
1567 };
1568
1569 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1570     plan tests => 8;
1571
1572     my $library = $builder->build( { source => 'Branch' } );
1573     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1574
1575     # Add 2 items
1576     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1577     my $item_1 = $builder->build(
1578         {
1579             source => 'Item',
1580             value  => {
1581                 homebranch    => $library->{branchcode},
1582                 holdingbranch => $library->{branchcode},
1583                 notforloan    => 0,
1584                 itemlost      => 0,
1585                 withdrawn     => 0,
1586                 biblionumber  => $biblioitem_1->{biblionumber}
1587             }
1588         }
1589     );
1590     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1591     my $item_2 = $builder->build(
1592         {
1593             source => 'Item',
1594             value  => {
1595                 homebranch    => $library->{branchcode},
1596                 holdingbranch => $library->{branchcode},
1597                 notforloan    => 0,
1598                 itemlost      => 0,
1599                 withdrawn     => 0,
1600                 biblionumber  => $biblioitem_2->{biblionumber}
1601             }
1602         }
1603     );
1604
1605     # And the issuing rule
1606     Koha::IssuingRules->search->delete;
1607     my $rule = Koha::IssuingRule->new(
1608         {
1609             categorycode => '*',
1610             itemtype     => '*',
1611             branchcode   => '*',
1612             maxissueqty  => 99,
1613             issuelength  => 1,
1614             firstremind  => 1,        # 1 day of grace
1615             finedays     => 2,        # 2 days of fine per day of overdue
1616             lengthunit   => 'days',
1617         }
1618     );
1619     $rule->store();
1620
1621     # Patron cannot issue item_1, they have overdues
1622     my $five_days_ago = dt_from_string->subtract( days => 5 );
1623     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1624     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1625     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1626       ;    # Add another overdue
1627
1628     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1629     AddReturn( $item_1->{barcode}, $library->{branchcode},
1630         undef, undef, dt_from_string );
1631     my $debarments = Koha::Patron::Debarments::GetDebarments(
1632         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1633     is( scalar(@$debarments), 1 );
1634
1635     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1636     # Same for the others
1637     my $expected_expiration = output_pref(
1638         {
1639             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1640             dateformat => 'sql',
1641             dateonly   => 1
1642         }
1643     );
1644     is( $debarments->[0]->{expiration}, $expected_expiration );
1645
1646     AddReturn( $item_2->{barcode}, $library->{branchcode},
1647         undef, undef, dt_from_string );
1648     $debarments = Koha::Patron::Debarments::GetDebarments(
1649         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1650     is( scalar(@$debarments), 1 );
1651     $expected_expiration = output_pref(
1652         {
1653             dt         => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1654             dateformat => 'sql',
1655             dateonly   => 1
1656         }
1657     );
1658     is( $debarments->[0]->{expiration}, $expected_expiration );
1659
1660     Koha::Patron::Debarments::DelUniqueDebarment(
1661         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1662
1663     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1664     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1665     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1666       ;    # Add another overdue
1667     AddReturn( $item_1->{barcode}, $library->{branchcode},
1668         undef, undef, dt_from_string );
1669     $debarments = Koha::Patron::Debarments::GetDebarments(
1670         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1671     is( scalar(@$debarments), 1 );
1672     $expected_expiration = output_pref(
1673         {
1674             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1675             dateformat => 'sql',
1676             dateonly   => 1
1677         }
1678     );
1679     is( $debarments->[0]->{expiration}, $expected_expiration );
1680
1681     AddReturn( $item_2->{barcode}, $library->{branchcode},
1682         undef, undef, dt_from_string );
1683     $debarments = Koha::Patron::Debarments::GetDebarments(
1684         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1685     is( scalar(@$debarments), 1 );
1686     $expected_expiration = output_pref(
1687         {
1688             dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1689             dateformat => 'sql',
1690             dateonly   => 1
1691         }
1692     );
1693     is( $debarments->[0]->{expiration}, $expected_expiration );
1694 };
1695
1696 subtest 'AddReturn | is_overdue' => sub {
1697     plan tests => 5;
1698
1699     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1700     t::lib::Mocks::mock_preference('finesMode', 'production');
1701     t::lib::Mocks::mock_preference('MaxFine', '100');
1702
1703     my $library = $builder->build( { source => 'Branch' } );
1704     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1705
1706     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1707     my $item = $builder->build(
1708         {
1709             source => 'Item',
1710             value  => {
1711                 homebranch    => $library->{branchcode},
1712                 holdingbranch => $library->{branchcode},
1713                 notforloan    => 0,
1714                 itemlost      => 0,
1715                 withdrawn     => 0,
1716                 biblionumber  => $biblioitem->{biblionumber},
1717             }
1718         }
1719     );
1720
1721     Koha::IssuingRules->search->delete;
1722     my $rule = Koha::IssuingRule->new(
1723         {
1724             categorycode => '*',
1725             itemtype     => '*',
1726             branchcode   => '*',
1727             maxissueqty  => 99,
1728             issuelength  => 6,
1729             lengthunit   => 'days',
1730             fine         => 1, # Charge 1 every day of overdue
1731             chargeperiod => 1,
1732         }
1733     );
1734     $rule->store();
1735
1736     my $one_day_ago   = dt_from_string->subtract( days => 1 );
1737     my $five_days_ago = dt_from_string->subtract( days => 5 );
1738     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1739     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1740
1741     # No date specify, today will be used
1742     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1743     AddReturn( $item->{barcode}, $library->{branchcode} );
1744     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
1745     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1746
1747     # specify return date 5 days before => no overdue
1748     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1749     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $ten_days_ago );
1750     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1751     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1752
1753     # specify return date 5 days later => overdue
1754     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1755     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $five_days_ago );
1756     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
1757     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1758
1759     # specify dropbox date 5 days before => no overdue
1760     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1761     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $ten_days_ago );
1762     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1763     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1764
1765     # specify dropbox date 5 days later => overdue, or... not
1766     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1767     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $five_days_ago );
1768     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue in dropbox mode' ); # FIXME? This is weird, the FU fine is created ( _CalculateAndUpdateFine > C4::Overdues::UpdateFine ) then remove later (in _FixOverduesOnReturn). Looks like it is a feature
1769     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1770
1771 };
1772
1773 subtest 'Set waiting flag' => sub {
1774     plan tests => 4;
1775
1776     my $library_1 = $builder->build( { source => 'Branch' } );
1777     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1778     my $library_2 = $builder->build( { source => 'Branch' } );
1779     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1780
1781     my $biblio = $builder->build( { source => 'Biblio' } );
1782     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
1783     my $item = $builder->build(
1784         {
1785             source => 'Item',
1786             value  => {
1787                 homebranch    => $library_1->{branchcode},
1788                 holdingbranch => $library_1->{branchcode},
1789                 notforloan    => 0,
1790                 itemlost      => 0,
1791                 withdrawn     => 0,
1792                 biblionumber  => $biblioitem->{biblionumber},
1793             }
1794         }
1795     );
1796
1797
1798
1799     set_userenv( $library_2 );
1800     my $reserve_id = AddReserve(
1801         $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
1802         '', 1, undef, undef, '', undef, $item->{itemnumber},
1803     );
1804
1805     set_userenv( $library_1 );
1806     my $do_transfer = 1;
1807     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
1808     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
1809     my $hold = Koha::Holds->find( $reserve_id );
1810     is( $hold->found, 'T', 'Hold is in transit' );
1811
1812     my ( $status ) = CheckReserves($item->{itemnumber});
1813     is( $status, 'Reserved', 'Hold is not waiting yet');
1814
1815     set_userenv( $library_2 );
1816     $do_transfer = 0;
1817     AddReturn( $item->{barcode}, $library_2->{branchcode} );
1818     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
1819     $hold = Koha::Holds->find( $reserve_id );
1820     is( $hold->found, 'W', 'Hold is waiting' );
1821     ( $status ) = CheckReserves($item->{itemnumber});
1822     is( $status, 'Waiting', 'Now the hold is waiting');
1823 };
1824
1825 sub set_userenv {
1826     my ( $library ) = @_;
1827     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, $library->{branchname}, '', '', '');
1828 }
1829
1830 sub str {
1831     my ( $error, $question, $alert ) = @_;
1832     my $s;
1833     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
1834     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
1835     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
1836     return $s;
1837 }