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