Bug 19974: Make MarkLostItemsAsReturned multiple
[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 => 116;
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, 'test', 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     my $checkout = Koha::Checkouts->find({ itemnumber => $itemnumber });
854     is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
855
856     my $total_due = $dbh->selectrow_array(
857         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
858         undef, $renewing_borrower->{borrowernumber}
859     );
860
861     is( $total_due, '15.000000', 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
862
863     C4::Context->dbh->do("DELETE FROM accountlines");
864
865     C4::Overdues::UpdateFine(
866         {
867             issue_id       => $issue2->id(),
868             itemnumber     => $itemnumber2,
869             borrowernumber => $renewing_borrower->{borrowernumber},
870             amount         => 15.00,
871             type           => q{},
872             due            => Koha::DateUtils::output_pref($datedue)
873         }
874     );
875
876     LostItem( $itemnumber2, 'test', 0 );
877
878     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
879     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
880     ok( Koha::Checkouts->find({ itemnumber => $itemnumber2 }), 'LostItem called without forced return has checked in the item' );
881
882     $total_due = $dbh->selectrow_array(
883         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
884         undef, $renewing_borrower->{borrowernumber}
885     );
886
887     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
888
889     my $future = dt_from_string();
890     $future->add( days => 7 );
891     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
892     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
893
894     # Users cannot renew any item if there is an overdue item
895     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
896     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
897     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
898     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
899     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
900
901   }
902
903 {
904     # GetUpcomingDueIssues tests
905     my $barcode  = 'R00000342';
906     my $barcode2 = 'R00000343';
907     my $barcode3 = 'R00000344';
908     my $branch   = $library2->{branchcode};
909
910     #Create another record
911     my $title2 = 'Something is worng here';
912     my ($biblionumber2, $biblioitemnumber2) = add_biblio($title2, 'Anonymous');
913
914     #Create third item
915     AddItem(
916         {
917             homebranch       => $branch,
918             holdingbranch    => $branch,
919             barcode          => $barcode3,
920             itype            => $itemtype
921         },
922         $biblionumber2
923     );
924
925     # Create a borrower
926     my %a_borrower_data = (
927         firstname =>  'Fridolyn',
928         surname => 'SOMERS',
929         categorycode => $patron_category->{categorycode},
930         branchcode => $branch,
931     );
932
933     my $a_borrower_borrowernumber = AddMember(%a_borrower_data);
934     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
935
936     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
937     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
938     my $today = DateTime->today(time_zone => C4::Context->tz());
939
940     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
941     my $datedue = dt_from_string( $issue->date_due() );
942     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
943     my $datedue2 = dt_from_string( $issue->date_due() );
944
945     my $upcoming_dues;
946
947     # GetUpcomingDueIssues tests
948     for my $i(0..1) {
949         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
950         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
951     }
952
953     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
954     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
955     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
956
957     for my $i(3..5) {
958         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
959         is ( scalar( @$upcoming_dues ), 1,
960             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
961     }
962
963     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
964
965     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
966
967     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
968     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
969
970     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
971     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
972
973     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
974     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
975
976     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
977     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
978
979     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
980     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
981
982     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
983     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
984
985 }
986
987 {
988     my $barcode  = '1234567890';
989     my $branch   = $library2->{branchcode};
990
991     my ($biblionumber, $biblioitemnumber) = add_biblio();
992
993     #Create third item
994     my ( undef, undef, $itemnumber ) = AddItem(
995         {
996             homebranch       => $branch,
997             holdingbranch    => $branch,
998             barcode          => $barcode,
999             itype            => $itemtype
1000         },
1001         $biblionumber
1002     );
1003
1004     # Create a borrower
1005     my %a_borrower_data = (
1006         firstname =>  'Kyle',
1007         surname => 'Hall',
1008         categorycode => $patron_category->{categorycode},
1009         branchcode => $branch,
1010     );
1011
1012     my $borrowernumber = AddMember(%a_borrower_data);
1013
1014     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1015     my $issue = AddIssue( $borrower, $barcode );
1016     UpdateFine(
1017         {
1018             issue_id       => $issue->id(),
1019             itemnumber     => $itemnumber,
1020             borrowernumber => $borrowernumber,
1021             amount         => 0,
1022             type           => q{}
1023         }
1024     );
1025
1026     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
1027     my $count = $hr->{count};
1028
1029     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1030 }
1031
1032 {
1033     $dbh->do('DELETE FROM issues');
1034     $dbh->do('DELETE FROM items');
1035     $dbh->do('DELETE FROM issuingrules');
1036     $dbh->do(
1037         q{
1038         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
1039                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1040         },
1041         {},
1042         '*', '*', '*', 25,
1043         20,  14,  'days',
1044         1,   7,
1045         undef,  0,
1046         .10, 1
1047     );
1048     my ( $biblionumber, $biblioitemnumber ) = add_biblio();
1049
1050     my $barcode1 = '1234';
1051     my ( undef, undef, $itemnumber1 ) = AddItem(
1052         {
1053             homebranch    => $library2->{branchcode},
1054             holdingbranch => $library2->{branchcode},
1055             barcode       => $barcode1,
1056             itype         => $itemtype
1057         },
1058         $biblionumber
1059     );
1060     my $barcode2 = '4321';
1061     my ( undef, undef, $itemnumber2 ) = AddItem(
1062         {
1063             homebranch    => $library2->{branchcode},
1064             holdingbranch => $library2->{branchcode},
1065             barcode       => $barcode2,
1066             itype         => $itemtype
1067         },
1068         $biblionumber
1069     );
1070
1071     my $borrowernumber1 = AddMember(
1072         firstname    => 'Kyle',
1073         surname      => 'Hall',
1074         categorycode => $patron_category->{categorycode},
1075         branchcode   => $library2->{branchcode},
1076     );
1077     my $borrowernumber2 = AddMember(
1078         firstname    => 'Chelsea',
1079         surname      => 'Hall',
1080         categorycode => $patron_category->{categorycode},
1081         branchcode   => $library2->{branchcode},
1082     );
1083
1084     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1085     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1086
1087     my $issue = AddIssue( $borrower1, $barcode1 );
1088
1089     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1090     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1091
1092     AddReserve(
1093         $library2->{branchcode}, $borrowernumber2, $biblionumber,
1094         '',  1, undef, undef, '',
1095         undef, undef, undef
1096     );
1097
1098     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1099     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1100     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1101     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1102
1103     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1104     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1105     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1106     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1107
1108     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1109     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1110     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1111     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1112
1113     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1114     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1115     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1116     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1117
1118     # Setting item not checked out to be not for loan but holdable
1119     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
1120
1121     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1122     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' );
1123 }
1124
1125 {
1126     # Don't allow renewing onsite checkout
1127     my $barcode  = 'R00000XXX';
1128     my $branch   = $library->{branchcode};
1129
1130     #Create another record
1131     my ($biblionumber, $biblioitemnumber) = add_biblio('A title', 'Anonymous');
1132
1133     my (undef, undef, $itemnumber) = AddItem(
1134         {
1135             homebranch       => $branch,
1136             holdingbranch    => $branch,
1137             barcode          => $barcode,
1138             itype            => $itemtype
1139         },
1140         $biblionumber
1141     );
1142
1143     my $borrowernumber = AddMember(
1144         firstname =>  'fn',
1145         surname => 'dn',
1146         categorycode => $patron_category->{categorycode},
1147         branchcode => $branch,
1148     );
1149
1150     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1151
1152     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1153     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
1154     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1155     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1156 }
1157
1158 {
1159     my $library = $builder->build({ source => 'Branch' });
1160
1161     my ($biblionumber, $biblioitemnumber) = add_biblio();
1162
1163     my $barcode = 'just a barcode';
1164     my ( undef, undef, $itemnumber ) = AddItem(
1165         {
1166             homebranch       => $library->{branchcode},
1167             holdingbranch    => $library->{branchcode},
1168             barcode          => $barcode,
1169             itype            => $itemtype
1170         },
1171         $biblionumber,
1172     );
1173
1174     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1175
1176     my $issue = AddIssue( $patron, $barcode );
1177     UpdateFine(
1178         {
1179             issue_id       => $issue->id(),
1180             itemnumber     => $itemnumber,
1181             borrowernumber => $patron->{borrowernumber},
1182             amount         => 1,
1183             type           => q{}
1184         }
1185     );
1186     UpdateFine(
1187         {
1188             issue_id       => $issue->id(),
1189             itemnumber     => $itemnumber,
1190             borrowernumber => $patron->{borrowernumber},
1191             amount         => 2,
1192             type           => q{}
1193         }
1194     );
1195     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1196 }
1197
1198 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1199     plan tests => 24;
1200
1201     my $homebranch    = $builder->build( { source => 'Branch' } );
1202     my $holdingbranch = $builder->build( { source => 'Branch' } );
1203     my $otherbranch   = $builder->build( { source => 'Branch' } );
1204     my $patron_1      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1205     my $patron_2      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1206
1207     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1208     my $item = $builder->build(
1209         {   source => 'Item',
1210             value  => {
1211                 homebranch    => $homebranch->{branchcode},
1212                 holdingbranch => $holdingbranch->{branchcode},
1213                 notforloan    => 0,
1214                 itemlost      => 0,
1215                 withdrawn     => 0,
1216                 restricted    => 0,
1217                 biblionumber  => $biblioitem->{biblionumber}
1218             }
1219         }
1220     );
1221
1222     set_userenv($holdingbranch);
1223
1224     my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1225     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Checkout
1226
1227     my ( $error, $question, $alerts );
1228
1229     # AllowReturnToBranch == anywhere
1230     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1231     ## Test that unknown barcodes don't generate internal server errors
1232     set_userenv($homebranch);
1233     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1234     ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1235     ## Can be issued from homebranch
1236     set_userenv($homebranch);
1237     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1238     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1239     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1240     ## Can be issued from holdingbranch
1241     set_userenv($holdingbranch);
1242     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1243     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1244     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1245     ## Can be issued from another branch
1246     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1247     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1248     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1249
1250     # AllowReturnToBranch == holdingbranch
1251     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1252     ## Cannot be issued from homebranch
1253     set_userenv($homebranch);
1254     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1255     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1256     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1257     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1258     ## Can be issued from holdinbranch
1259     set_userenv($holdingbranch);
1260     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1261     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1262     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1263     ## Cannot be issued from another branch
1264     set_userenv($otherbranch);
1265     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1266     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1267     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1268     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1269
1270     # AllowReturnToBranch == homebranch
1271     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1272     ## Can be issued from holdinbranch
1273     set_userenv($homebranch);
1274     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1275     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1276     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1277     ## Cannot be issued from holdinbranch
1278     set_userenv($holdingbranch);
1279     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1280     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1281     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1282     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1283     ## Cannot be issued from holdinbranch
1284     set_userenv($otherbranch);
1285     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1286     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1287     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1288     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1289
1290     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1291 };
1292
1293 subtest 'AddIssue & AllowReturnToBranch' => sub {
1294     plan tests => 9;
1295
1296     my $homebranch    = $builder->build( { source => 'Branch' } );
1297     my $holdingbranch = $builder->build( { source => 'Branch' } );
1298     my $otherbranch   = $builder->build( { source => 'Branch' } );
1299     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1300     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1301
1302     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1303     my $item = $builder->build(
1304         {   source => 'Item',
1305             value  => {
1306                 homebranch    => $homebranch->{branchcode},
1307                 holdingbranch => $holdingbranch->{branchcode},
1308                 notforloan    => 0,
1309                 itemlost      => 0,
1310                 withdrawn     => 0,
1311                 biblionumber  => $biblioitem->{biblionumber}
1312             }
1313         }
1314     );
1315
1316     set_userenv($holdingbranch);
1317
1318     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Checkout
1319     my $issue = AddIssue( $patron_1, $item->{barcode} );
1320
1321     my ( $error, $question, $alerts );
1322
1323     # AllowReturnToBranch == homebranch
1324     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1325     ## Can be issued from homebranch
1326     set_userenv($homebranch);
1327     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1328     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1329     ## Can be issued from holdinbranch
1330     set_userenv($holdingbranch);
1331     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1332     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1333     ## Can be issued from another branch
1334     set_userenv($otherbranch);
1335     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1336     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1337
1338     # AllowReturnToBranch == holdinbranch
1339     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1340     ## Cannot be issued from homebranch
1341     set_userenv($homebranch);
1342     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1343     ## Can be issued from holdingbranch
1344     set_userenv($holdingbranch);
1345     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1346     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1347     ## Cannot be issued from another branch
1348     set_userenv($otherbranch);
1349     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1350
1351     # AllowReturnToBranch == homebranch
1352     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1353     ## Can be issued from homebranch
1354     set_userenv($homebranch);
1355     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1356     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1357     ## Cannot be issued from holdinbranch
1358     set_userenv($holdingbranch);
1359     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1360     ## Cannot be issued from another branch
1361     set_userenv($otherbranch);
1362     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1363     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1364 };
1365
1366 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1367     plan tests => 8;
1368
1369     my $library = $builder->build( { source => 'Branch' } );
1370     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1371
1372     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1373     my $item_1 = $builder->build(
1374         {   source => 'Item',
1375             value  => {
1376                 homebranch    => $library->{branchcode},
1377                 holdingbranch => $library->{branchcode},
1378                 notforloan    => 0,
1379                 itemlost      => 0,
1380                 withdrawn     => 0,
1381                 restricted    => 0,
1382                 biblionumber  => $biblioitem_1->{biblionumber}
1383             }
1384         }
1385     );
1386     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1387     my $item_2 = $builder->build(
1388         {   source => 'Item',
1389             value  => {
1390                 homebranch    => $library->{branchcode},
1391                 holdingbranch => $library->{branchcode},
1392                 notforloan    => 0,
1393                 itemlost      => 0,
1394                 withdrawn     => 0,
1395                 restricted    => 0,
1396                 biblionumber  => $biblioitem_2->{biblionumber}
1397             }
1398         }
1399     );
1400
1401     my ( $error, $question, $alerts );
1402
1403     # Patron cannot issue item_1, they have overdues
1404     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1405     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday );    # Add an overdue
1406
1407     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1408     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1409     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
1410     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1411
1412     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1413     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1414     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1415     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1416
1417     # Patron cannot issue item_1, they are debarred
1418     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1419     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1420     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1421     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1422     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1423
1424     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1425     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1426     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1427     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1428 };
1429
1430 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1431     plan tests => 1;
1432
1433     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1434     my $patron_category_x = $builder->build_object(
1435         {
1436             class => 'Koha::Patron::Categories',
1437             value => { category_type => 'X' }
1438         }
1439     );
1440     my $patron = $builder->build_object(
1441         {
1442             class => 'Koha::Patrons',
1443             value => {
1444                 categorycode  => $patron_category_x->categorycode,
1445                 gonenoaddress => undef,
1446                 lost          => undef,
1447                 debarred      => undef,
1448                 borrowernotes => ""
1449             }
1450         }
1451     );
1452     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1453     my $item_1 = $builder->build(
1454         {
1455             source => 'Item',
1456             value  => {
1457                 homebranch    => $library->branchcode,
1458                 holdingbranch => $library->branchcode,
1459                 notforloan    => 0,
1460                 itemlost      => 0,
1461                 withdrawn     => 0,
1462                 restricted    => 0,
1463                 biblionumber  => $biblioitem_1->{biblionumber}
1464             }
1465         }
1466     );
1467
1468     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1469     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1470
1471     # TODO There are other tests to provide here
1472 };
1473
1474 subtest 'MultipleReserves' => sub {
1475     plan tests => 3;
1476
1477     my $title = 'Silence in the library';
1478     my ($biblionumber, $biblioitemnumber) = add_biblio($title, 'Moffat, Steven');
1479
1480     my $branch = $library2->{branchcode};
1481
1482     my $barcode1 = 'R00110001';
1483     my ( $item_bibnum1, $item_bibitemnum1, $itemnumber1 ) = AddItem(
1484         {
1485             homebranch       => $branch,
1486             holdingbranch    => $branch,
1487             barcode          => $barcode1,
1488             replacementprice => 12.00,
1489             itype            => $itemtype
1490         },
1491         $biblionumber
1492     );
1493
1494     my $barcode2 = 'R00110002';
1495     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
1496         {
1497             homebranch       => $branch,
1498             holdingbranch    => $branch,
1499             barcode          => $barcode2,
1500             replacementprice => 12.00,
1501             itype            => $itemtype
1502         },
1503         $biblionumber
1504     );
1505
1506     my $bibitems       = '';
1507     my $priority       = '1';
1508     my $resdate        = undef;
1509     my $expdate        = undef;
1510     my $notes          = '';
1511     my $checkitem      = undef;
1512     my $found          = undef;
1513
1514     my %renewing_borrower_data = (
1515         firstname =>  'John',
1516         surname => 'Renewal',
1517         categorycode => $patron_category->{categorycode},
1518         branchcode => $branch,
1519     );
1520     my $renewing_borrowernumber = AddMember(%renewing_borrower_data);
1521     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1522     my $issue = AddIssue( $renewing_borrower, $barcode1);
1523     my $datedue = dt_from_string( $issue->date_due() );
1524     is (defined $issue->date_due(), 1, "item 1 checked out");
1525     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $itemnumber1 })->borrowernumber;
1526
1527     my %reserving_borrower_data1 = (
1528         firstname =>  'Katrin',
1529         surname => 'Reservation',
1530         categorycode => $patron_category->{categorycode},
1531         branchcode => $branch,
1532     );
1533     my $reserving_borrowernumber1 = AddMember(%reserving_borrower_data1);
1534     AddReserve(
1535         $branch, $reserving_borrowernumber1, $biblionumber,
1536         $bibitems,  $priority, $resdate, $expdate, $notes,
1537         $title, $checkitem, $found
1538     );
1539
1540     my %reserving_borrower_data2 = (
1541         firstname =>  'Kirk',
1542         surname => 'Reservation',
1543         categorycode => $patron_category->{categorycode},
1544         branchcode => $branch,
1545     );
1546     my $reserving_borrowernumber2 = AddMember(%reserving_borrower_data2);
1547     AddReserve(
1548         $branch, $reserving_borrowernumber2, $biblionumber,
1549         $bibitems,  $priority, $resdate, $expdate, $notes,
1550         $title, $checkitem, $found
1551     );
1552
1553     {
1554         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1555         is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1556     }
1557
1558     my $barcode3 = 'R00110003';
1559     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
1560         {
1561             homebranch       => $branch,
1562             holdingbranch    => $branch,
1563             barcode          => $barcode3,
1564             replacementprice => 12.00,
1565             itype            => $itemtype
1566         },
1567         $biblionumber
1568     );
1569
1570     {
1571         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1572         is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1573     }
1574 };
1575
1576 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1577     plan tests => 5;
1578
1579     my $library = $builder->build( { source => 'Branch' } );
1580     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1581
1582     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1583     my $biblionumber = $biblioitem->{biblionumber};
1584     my $item_1 = $builder->build(
1585         {   source => 'Item',
1586             value  => {
1587                 homebranch    => $library->{branchcode},
1588                 holdingbranch => $library->{branchcode},
1589                 notforloan    => 0,
1590                 itemlost      => 0,
1591                 withdrawn     => 0,
1592                 biblionumber  => $biblionumber,
1593             }
1594         }
1595     );
1596     my $item_2 = $builder->build(
1597         {   source => 'Item',
1598             value  => {
1599                 homebranch    => $library->{branchcode},
1600                 holdingbranch => $library->{branchcode},
1601                 notforloan    => 0,
1602                 itemlost      => 0,
1603                 withdrawn     => 0,
1604                 biblionumber  => $biblionumber,
1605             }
1606         }
1607     );
1608
1609     my ( $error, $question, $alerts );
1610     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1611
1612     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1613     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1614     is( keys(%$error) + keys(%$alerts),  0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1615     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) );
1616
1617     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1618     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1619     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1620
1621     # Add a subscription
1622     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1623
1624     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1625     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1626     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) );
1627
1628     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1629     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1630     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) );
1631 };
1632
1633 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1634     plan tests => 8;
1635
1636     my $library = $builder->build( { source => 'Branch' } );
1637     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1638
1639     # Add 2 items
1640     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1641     my $item_1 = $builder->build(
1642         {
1643             source => 'Item',
1644             value  => {
1645                 homebranch    => $library->{branchcode},
1646                 holdingbranch => $library->{branchcode},
1647                 notforloan    => 0,
1648                 itemlost      => 0,
1649                 withdrawn     => 0,
1650                 biblionumber  => $biblioitem_1->{biblionumber}
1651             }
1652         }
1653     );
1654     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1655     my $item_2 = $builder->build(
1656         {
1657             source => 'Item',
1658             value  => {
1659                 homebranch    => $library->{branchcode},
1660                 holdingbranch => $library->{branchcode},
1661                 notforloan    => 0,
1662                 itemlost      => 0,
1663                 withdrawn     => 0,
1664                 biblionumber  => $biblioitem_2->{biblionumber}
1665             }
1666         }
1667     );
1668
1669     # And the issuing rule
1670     Koha::IssuingRules->search->delete;
1671     my $rule = Koha::IssuingRule->new(
1672         {
1673             categorycode => '*',
1674             itemtype     => '*',
1675             branchcode   => '*',
1676             maxissueqty  => 99,
1677             issuelength  => 1,
1678             firstremind  => 1,        # 1 day of grace
1679             finedays     => 2,        # 2 days of fine per day of overdue
1680             lengthunit   => 'days',
1681         }
1682     );
1683     $rule->store();
1684
1685     # Patron cannot issue item_1, they have overdues
1686     my $five_days_ago = dt_from_string->subtract( days => 5 );
1687     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1688     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1689     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1690       ;    # Add another overdue
1691
1692     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1693     AddReturn( $item_1->{barcode}, $library->{branchcode},
1694         undef, undef, dt_from_string );
1695     my $debarments = Koha::Patron::Debarments::GetDebarments(
1696         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1697     is( scalar(@$debarments), 1 );
1698
1699     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1700     # Same for the others
1701     my $expected_expiration = output_pref(
1702         {
1703             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1704             dateformat => 'sql',
1705             dateonly   => 1
1706         }
1707     );
1708     is( $debarments->[0]->{expiration}, $expected_expiration );
1709
1710     AddReturn( $item_2->{barcode}, $library->{branchcode},
1711         undef, undef, dt_from_string );
1712     $debarments = Koha::Patron::Debarments::GetDebarments(
1713         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1714     is( scalar(@$debarments), 1 );
1715     $expected_expiration = output_pref(
1716         {
1717             dt         => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1718             dateformat => 'sql',
1719             dateonly   => 1
1720         }
1721     );
1722     is( $debarments->[0]->{expiration}, $expected_expiration );
1723
1724     Koha::Patron::Debarments::DelUniqueDebarment(
1725         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1726
1727     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1728     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1729     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1730       ;    # Add another overdue
1731     AddReturn( $item_1->{barcode}, $library->{branchcode},
1732         undef, undef, dt_from_string );
1733     $debarments = Koha::Patron::Debarments::GetDebarments(
1734         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1735     is( scalar(@$debarments), 1 );
1736     $expected_expiration = output_pref(
1737         {
1738             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1739             dateformat => 'sql',
1740             dateonly   => 1
1741         }
1742     );
1743     is( $debarments->[0]->{expiration}, $expected_expiration );
1744
1745     AddReturn( $item_2->{barcode}, $library->{branchcode},
1746         undef, undef, dt_from_string );
1747     $debarments = Koha::Patron::Debarments::GetDebarments(
1748         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1749     is( scalar(@$debarments), 1 );
1750     $expected_expiration = output_pref(
1751         {
1752             dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1753             dateformat => 'sql',
1754             dateonly   => 1
1755         }
1756     );
1757     is( $debarments->[0]->{expiration}, $expected_expiration );
1758 };
1759
1760 subtest 'AddReturn + suspension_chargeperiod' => sub {
1761     plan tests => 6;
1762
1763     my $library = $builder->build( { source => 'Branch' } );
1764     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1765
1766     # Add 2 items
1767     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1768     my $item_1 = $builder->build(
1769         {
1770             source => 'Item',
1771             value  => {
1772                 homebranch    => $library->{branchcode},
1773                 holdingbranch => $library->{branchcode},
1774                 notforloan    => 0,
1775                 itemlost      => 0,
1776                 withdrawn     => 0,
1777                 biblionumber  => $biblioitem_1->{biblionumber}
1778             }
1779         }
1780     );
1781
1782     # And the issuing rule
1783     Koha::IssuingRules->search->delete;
1784     my $rule = Koha::IssuingRule->new(
1785         {
1786             categorycode => '*',
1787             itemtype     => '*',
1788             branchcode   => '*',
1789             maxissueqty  => 99,
1790             issuelength  => 1,
1791             firstremind  => 0,        # 0 day of grace
1792             finedays     => 2,        # 2 days of fine per day of overdue
1793             suspension_chargeperiod => 1,
1794             lengthunit   => 'days',
1795         }
1796     );
1797     $rule->store();
1798
1799     my $five_days_ago = dt_from_string->subtract( days => 5 );
1800     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1801
1802     # We want to charge 2 days every day, without grace
1803     # With 5 days of overdue: 5 * Z
1804     AddReturn( $item_1->{barcode}, $library->{branchcode},
1805         undef, undef, dt_from_string );
1806     my $debarments = Koha::Patron::Debarments::GetDebarments(
1807         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1808     is( scalar(@$debarments), 1 );
1809
1810     my $expected_expiration = output_pref(
1811         {
1812             dt         => dt_from_string->add( days => ( 5 * 2 ) / 1 ),
1813             dateformat => 'sql',
1814             dateonly   => 1
1815         }
1816     );
1817     is( $debarments->[0]->{expiration}, $expected_expiration );
1818     Koha::Patron::Debarments::DelUniqueDebarment(
1819         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1820
1821     # We want to charge 2 days every 2 days, without grace
1822     # With 5 days of overdue: (5 * 2) / 2
1823     $rule->suspension_chargeperiod(2)->store;
1824     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1825
1826     AddReturn( $item_1->{barcode}, $library->{branchcode},
1827         undef, undef, dt_from_string );
1828     $debarments = Koha::Patron::Debarments::GetDebarments(
1829         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1830     is( scalar(@$debarments), 1 );
1831
1832     $expected_expiration = output_pref(
1833         {
1834             dt         => dt_from_string->add( days => floor( 5 * 2 ) / 2 ),
1835             dateformat => 'sql',
1836             dateonly   => 1
1837         }
1838     );
1839     is( $debarments->[0]->{expiration}, $expected_expiration );
1840     Koha::Patron::Debarments::DelUniqueDebarment(
1841         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1842
1843     # We want to charge 2 days every 3 days, with 1 day of grace
1844     # With 5 days of overdue: ((5-1) / 3 ) * 2
1845     $rule->suspension_chargeperiod(3)->store;
1846     $rule->firstremind(1)->store;
1847     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1848
1849     AddReturn( $item_1->{barcode}, $library->{branchcode},
1850         undef, undef, dt_from_string );
1851     $debarments = Koha::Patron::Debarments::GetDebarments(
1852         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1853     is( scalar(@$debarments), 1 );
1854
1855     $expected_expiration = output_pref(
1856         {
1857             dt         => dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) ),
1858             dateformat => 'sql',
1859             dateonly   => 1
1860         }
1861     );
1862     is( $debarments->[0]->{expiration}, $expected_expiration );
1863     Koha::Patron::Debarments::DelUniqueDebarment(
1864         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1865
1866 };
1867
1868
1869 subtest 'AddReturn | is_overdue' => sub {
1870     plan tests => 5;
1871
1872     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1873     t::lib::Mocks::mock_preference('finesMode', 'production');
1874     t::lib::Mocks::mock_preference('MaxFine', '100');
1875
1876     my $library = $builder->build( { source => 'Branch' } );
1877     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1878
1879     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1880     my $item = $builder->build(
1881         {
1882             source => 'Item',
1883             value  => {
1884                 homebranch    => $library->{branchcode},
1885                 holdingbranch => $library->{branchcode},
1886                 notforloan    => 0,
1887                 itemlost      => 0,
1888                 withdrawn     => 0,
1889                 biblionumber  => $biblioitem->{biblionumber},
1890             }
1891         }
1892     );
1893
1894     Koha::IssuingRules->search->delete;
1895     my $rule = Koha::IssuingRule->new(
1896         {
1897             categorycode => '*',
1898             itemtype     => '*',
1899             branchcode   => '*',
1900             maxissueqty  => 99,
1901             issuelength  => 6,
1902             lengthunit   => 'days',
1903             fine         => 1, # Charge 1 every day of overdue
1904             chargeperiod => 1,
1905         }
1906     );
1907     $rule->store();
1908
1909     my $one_day_ago   = dt_from_string->subtract( days => 1 );
1910     my $five_days_ago = dt_from_string->subtract( days => 5 );
1911     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1912     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1913
1914     # No date specify, today will be used
1915     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1916     AddReturn( $item->{barcode}, $library->{branchcode} );
1917     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
1918     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1919
1920     # specify return date 5 days before => no overdue
1921     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1922     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $ten_days_ago );
1923     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1924     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1925
1926     # specify return date 5 days later => overdue
1927     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1928     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $five_days_ago );
1929     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
1930     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1931
1932     # specify dropbox date 5 days before => no overdue
1933     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1934     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $ten_days_ago );
1935     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1936     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1937
1938     # specify dropbox date 5 days later => overdue, or... not
1939     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1940     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $five_days_ago );
1941     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
1942     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1943 };
1944
1945 subtest '_FixAccountForLostAndReturned' => sub {
1946     plan tests => 2;
1947
1948     # Generate test biblio
1949     my $title  = 'Koha for Dummies';
1950     my ( $biblionumber, $biblioitemnumber ) = add_biblio($title, 'Hall, Daria');
1951
1952     my $barcode = 'KD123456789';
1953     my $branchcode  = $library2->{branchcode};
1954
1955     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
1956         {
1957             homebranch       => $branchcode,
1958             holdingbranch    => $branchcode,
1959             barcode          => $barcode,
1960             replacementprice => 99.00,
1961             itype            => $itemtype
1962         },
1963         $biblionumber
1964     );
1965
1966     my $patron = $builder->build( { source => 'Borrower' } );
1967
1968     my $accountline = Koha::Account::Line->new(
1969         {
1970             borrowernumber => $patron->{borrowernumber},
1971             accounttype    => 'L',
1972             itemnumber     => $itemnumber,
1973             amount => 99.00,
1974             amountoutstanding => 99.00,
1975         }
1976     )->store();
1977
1978     C4::Circulation::_FixAccountForLostAndReturned( $itemnumber, $patron->{borrowernumber} );
1979
1980     $accountline->_result()->discard_changes();
1981
1982     is( $accountline->amountoutstanding, '0.000000', 'Lost fee has no outstanding amount' );
1983     is( $accountline->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )');
1984 };
1985
1986 subtest '_FixOverduesOnReturn' => sub {
1987     plan tests => 6;
1988
1989     # Generate test biblio
1990     my $title  = 'Koha for Dummies';
1991     my ( $biblionumber, $biblioitemnumber ) = add_biblio($title, 'Hall, Kylie');
1992
1993     my $barcode = 'KD987654321';
1994     my $branchcode  = $library2->{branchcode};
1995
1996     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
1997         {
1998             homebranch       => $branchcode,
1999             holdingbranch    => $branchcode,
2000             barcode          => $barcode,
2001             replacementprice => 99.00,
2002             itype            => $itemtype
2003         },
2004         $biblionumber
2005     );
2006
2007     my $patron = $builder->build( { source => 'Borrower' } );
2008
2009     ## Start with basic call, should just close out the open fine
2010     my $accountline = Koha::Account::Line->new(
2011         {
2012             borrowernumber => $patron->{borrowernumber},
2013             accounttype    => 'FU',
2014             itemnumber     => $itemnumber,
2015             amount => 99.00,
2016             amountoutstanding => 99.00,
2017             lastincrement => 9.00,
2018         }
2019     )->store();
2020
2021     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber );
2022
2023     $accountline->_result()->discard_changes();
2024
2025     is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2026     is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2027
2028
2029     ## Run again, with exemptfine enabled
2030     $accountline->set(
2031         {
2032             accounttype    => 'FU',
2033             amountoutstanding => 99.00,
2034         }
2035     )->store();
2036
2037     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber, 1 );
2038
2039     $accountline->_result()->discard_changes();
2040
2041     is( $accountline->amountoutstanding, '0.000000', 'Fine has been reduced to 0' );
2042     is( $accountline->accounttype, 'FFOR', 'Open fine ( account type FU ) has been set to fine forgiven ( account type FFOR )');
2043
2044     ## Run again, with dropbox mode enabled
2045     $accountline->set(
2046         {
2047             accounttype    => 'FU',
2048             amountoutstanding => 99.00,
2049         }
2050     )->store();
2051
2052     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber, 0, 1 );
2053
2054     $accountline->_result()->discard_changes();
2055
2056     is( $accountline->amountoutstanding, '90.000000', 'Fine has been reduced to 90' );
2057     is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2058 };
2059
2060 subtest 'Set waiting flag' => sub {
2061     plan tests => 4;
2062
2063     my $library_1 = $builder->build( { source => 'Branch' } );
2064     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2065     my $library_2 = $builder->build( { source => 'Branch' } );
2066     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2067
2068     my $biblio = $builder->build( { source => 'Biblio' } );
2069     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2070
2071     my $item = $builder->build(
2072         {
2073             source => 'Item',
2074             value  => {
2075                 homebranch    => $library_1->{branchcode},
2076                 holdingbranch => $library_1->{branchcode},
2077                 notforloan    => 0,
2078                 itemlost      => 0,
2079                 withdrawn     => 0,
2080                 biblionumber  => $biblioitem->{biblionumber},
2081             }
2082         }
2083     );
2084
2085     set_userenv( $library_2 );
2086     my $reserve_id = AddReserve(
2087         $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
2088         '', 1, undef, undef, '', undef, $item->{itemnumber},
2089     );
2090
2091     set_userenv( $library_1 );
2092     my $do_transfer = 1;
2093     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2094     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2095     my $hold = Koha::Holds->find( $reserve_id );
2096     is( $hold->found, 'T', 'Hold is in transit' );
2097
2098     my ( $status ) = CheckReserves($item->{itemnumber});
2099     is( $status, 'Reserved', 'Hold is not waiting yet');
2100
2101     set_userenv( $library_2 );
2102     $do_transfer = 0;
2103     AddReturn( $item->{barcode}, $library_2->{branchcode} );
2104     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2105     $hold = Koha::Holds->find( $reserve_id );
2106     is( $hold->found, 'W', 'Hold is waiting' );
2107     ( $status ) = CheckReserves($item->{itemnumber});
2108     is( $status, 'Waiting', 'Now the hold is waiting');
2109 };
2110
2111 subtest 'CanBookBeIssued | is_overdue' => sub {
2112     plan tests => 3;
2113
2114     # Set a simple circ policy
2115     $dbh->do('DELETE FROM issuingrules');
2116     $dbh->do(
2117     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2118                                     maxissueqty, issuelength, lengthunit,
2119                                     renewalsallowed, renewalperiod,
2120                                     norenewalbefore, auto_renew,
2121                                     fine, chargeperiod)
2122           VALUES (?, ?, ?, ?,
2123                   ?, ?, ?,
2124                   ?, ?,
2125                   ?, ?,
2126                   ?, ?
2127                  )
2128         },
2129         {},
2130         '*',   '*', '*', 25,
2131         1,     14,  'days',
2132         1,     7,
2133         undef, 0,
2134         .10,   1
2135     );
2136
2137     my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2138     my $ten_days_go  = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2139     my $library = $builder->build( { source => 'Branch' } );
2140     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2141
2142     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2143     my $item = $builder->build(
2144         {
2145             source => 'Item',
2146             value  => {
2147                 homebranch    => $library->{branchcode},
2148                 holdingbranch => $library->{branchcode},
2149                 notforloan    => 0,
2150                 itemlost      => 0,
2151                 withdrawn     => 0,
2152                 biblionumber  => $biblioitem->{biblionumber},
2153             }
2154         }
2155     );
2156
2157     my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2158     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2159     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2160     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2161     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2162     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2163
2164 };
2165
2166 sub set_userenv {
2167     my ( $library ) = @_;
2168     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, $library->{branchname}, '', '', '');
2169 }
2170
2171 sub str {
2172     my ( $error, $question, $alert ) = @_;
2173     my $s;
2174     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
2175     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
2176     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
2177     return $s;
2178 }
2179
2180 sub add_biblio {
2181     my ($title, $author) = @_;
2182
2183     my $marcflavour = C4::Context->preference('marcflavour');
2184
2185     my $biblio = MARC::Record->new();
2186     if ($title) {
2187         my $tag = $marcflavour eq 'UNIMARC' ? '200' : '245';
2188         $biblio->append_fields(
2189             MARC::Field->new($tag, ' ', ' ', a => $title),
2190         );
2191     }
2192
2193     if ($author) {
2194         my ($tag, $code) = $marcflavour eq 'UNIMARC' ? (200, 'f') : (100, 'a');
2195         $biblio->append_fields(
2196             MARC::Field->new($tag, ' ', ' ', $code => $author),
2197         );
2198     }
2199
2200     return AddBiblio($biblio, '');
2201 }