Bug 19066: (RM follow-up) Fix test count and structure error
[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 use utf8;
20
21 use Test::More tests => 124;
22 use Test::MockModule;
23
24 use Data::Dumper;
25 use DateTime;
26 use POSIX qw( floor );
27 use t::lib::Mocks;
28 use t::lib::TestBuilder;
29
30 use C4::Calendar;
31 use C4::Circulation;
32 use C4::Biblio;
33 use C4::Items;
34 use C4::Log;
35 use C4::Reserves;
36 use C4::Overdues qw(UpdateFine CalcFine);
37 use Koha::DateUtils;
38 use Koha::Database;
39 use Koha::IssuingRules;
40 use Koha::Checkouts;
41 use Koha::Patrons;
42 use Koha::Subscriptions;
43 use Koha::Account::Lines;
44 use Koha::Account::Offsets;
45
46 my $schema = Koha::Database->schema;
47 $schema->storage->txn_begin;
48 my $builder = t::lib::TestBuilder->new;
49 my $dbh = C4::Context->dbh;
50
51 # Start transaction
52 $dbh->{RaiseError} = 1;
53
54 my $cache = Koha::Caches->get_instance();
55 $dbh->do(q|DELETE FROM special_holidays|);
56 $dbh->do(q|DELETE FROM repeatable_holidays|);
57 $cache->clear_from_cache('single_holidays');
58
59 # Start with a clean slate
60 $dbh->do('DELETE FROM issues');
61 $dbh->do('DELETE FROM borrowers');
62
63 my $library = $builder->build({
64     source => 'Branch',
65 });
66 my $library2 = $builder->build({
67     source => 'Branch',
68 });
69 my $itemtype = $builder->build(
70     {   source => 'Itemtype',
71         value  => { notforloan => undef, rentalcharge => 0, defaultreplacecost => undef, processfee => undef }
72     }
73 )->{itemtype};
74 my $patron_category = $builder->build(
75     {
76         source => 'Category',
77         value  => {
78             category_type                 => 'P',
79             enrolmentfee                  => 0,
80             BlockExpiredPatronOpacActions => -1, # Pick the pref value
81         }
82     }
83 );
84
85 my $CircControl = C4::Context->preference('CircControl');
86 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
87
88 my $item = {
89     homebranch => $library2->{branchcode},
90     holdingbranch => $library2->{branchcode}
91 };
92
93 my $borrower = {
94     branchcode => $library2->{branchcode}
95 };
96
97 # No userenv, PickupLibrary
98 t::lib::Mocks::mock_preference('IndependentBranches', '0');
99 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
100 is(
101     C4::Context->preference('CircControl'),
102     'PickupLibrary',
103     'CircControl changed to PickupLibrary'
104 );
105 is(
106     C4::Circulation::_GetCircControlBranch($item, $borrower),
107     $item->{$HomeOrHoldingBranch},
108     '_GetCircControlBranch returned item branch (no userenv defined)'
109 );
110
111 # No userenv, PatronLibrary
112 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
113 is(
114     C4::Context->preference('CircControl'),
115     'PatronLibrary',
116     'CircControl changed to PatronLibrary'
117 );
118 is(
119     C4::Circulation::_GetCircControlBranch($item, $borrower),
120     $borrower->{branchcode},
121     '_GetCircControlBranch returned borrower branch'
122 );
123
124 # No userenv, ItemHomeLibrary
125 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
126 is(
127     C4::Context->preference('CircControl'),
128     'ItemHomeLibrary',
129     'CircControl changed to ItemHomeLibrary'
130 );
131 is(
132     $item->{$HomeOrHoldingBranch},
133     C4::Circulation::_GetCircControlBranch($item, $borrower),
134     '_GetCircControlBranch returned item branch'
135 );
136
137 # Now, set a userenv
138 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
139 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
140
141 # Userenv set, PickupLibrary
142 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
143 is(
144     C4::Context->preference('CircControl'),
145     'PickupLibrary',
146     'CircControl changed to PickupLibrary'
147 );
148 is(
149     C4::Circulation::_GetCircControlBranch($item, $borrower),
150     $library2->{branchcode},
151     '_GetCircControlBranch returned current branch'
152 );
153
154 # Userenv set, PatronLibrary
155 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
156 is(
157     C4::Context->preference('CircControl'),
158     'PatronLibrary',
159     'CircControl changed to PatronLibrary'
160 );
161 is(
162     C4::Circulation::_GetCircControlBranch($item, $borrower),
163     $borrower->{branchcode},
164     '_GetCircControlBranch returned borrower branch'
165 );
166
167 # Userenv set, ItemHomeLibrary
168 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
169 is(
170     C4::Context->preference('CircControl'),
171     'ItemHomeLibrary',
172     'CircControl changed to ItemHomeLibrary'
173 );
174 is(
175     C4::Circulation::_GetCircControlBranch($item, $borrower),
176     $item->{$HomeOrHoldingBranch},
177     '_GetCircControlBranch returned item branch'
178 );
179
180 # Reset initial configuration
181 t::lib::Mocks::mock_preference('CircControl', $CircControl);
182 is(
183     C4::Context->preference('CircControl'),
184     $CircControl,
185     'CircControl reset to its initial value'
186 );
187
188 # Set a simple circ policy
189 $dbh->do('DELETE FROM issuingrules');
190 $dbh->do(
191     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
192                                 maxissueqty, issuelength, lengthunit,
193                                 renewalsallowed, renewalperiod,
194                                 norenewalbefore, auto_renew,
195                                 fine, chargeperiod)
196       VALUES (?, ?, ?, ?,
197               ?, ?, ?,
198               ?, ?,
199               ?, ?,
200               ?, ?
201              )
202     },
203     {},
204     '*', '*', '*', 25,
205     20, 14, 'days',
206     1, 7,
207     undef, 0,
208     .10, 1
209 );
210
211 # Test C4::Circulation::ProcessOfflinePayment
212 my $sth = C4::Context->dbh->prepare("SELECT COUNT(*) FROM accountlines WHERE amount = '-123.45' AND accounttype = 'Pay'");
213 $sth->execute();
214 my ( $original_count ) = $sth->fetchrow_array();
215
216 C4::Context->dbh->do("INSERT INTO borrowers ( cardnumber, surname, firstname, categorycode, branchcode ) VALUES ( '99999999999', 'Hall', 'Kyle', ?, ? )", undef, $patron_category->{categorycode}, $library2->{branchcode} );
217
218 C4::Circulation::ProcessOfflinePayment({ cardnumber => '99999999999', amount => '123.45' });
219
220 $sth->execute();
221 my ( $new_count ) = $sth->fetchrow_array();
222
223 ok( $new_count == $original_count  + 1, 'ProcessOfflinePayment makes payment correctly' );
224
225 C4::Context->dbh->do("DELETE FROM accountlines WHERE borrowernumber IN ( SELECT borrowernumber FROM borrowers WHERE cardnumber = '99999999999' )");
226 C4::Context->dbh->do("DELETE FROM borrowers WHERE cardnumber = '99999999999'");
227 C4::Context->dbh->do("DELETE FROM accountlines");
228 {
229 # CanBookBeRenewed tests
230     C4::Context->set_preference('ItemsDeniedRenewal','');
231     # Generate test biblio
232     my $title = 'Silence in the library';
233     my ($biblionumber, $biblioitemnumber) = add_biblio($title, 'Moffat, Steven');
234
235     my $barcode = 'R00000342';
236     my $branch = $library2->{branchcode};
237
238     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
239         {
240             homebranch       => $branch,
241             holdingbranch    => $branch,
242             barcode          => $barcode,
243             replacementprice => 12.00,
244             itype            => $itemtype
245         },
246         $biblionumber
247     );
248
249     my $barcode2 = 'R00000343';
250     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
251         {
252             homebranch       => $branch,
253             holdingbranch    => $branch,
254             barcode          => $barcode2,
255             replacementprice => 23.00,
256             itype            => $itemtype
257         },
258         $biblionumber
259     );
260
261     my $barcode3 = 'R00000346';
262     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
263         {
264             homebranch       => $branch,
265             holdingbranch    => $branch,
266             barcode          => $barcode3,
267             replacementprice => 23.00,
268             itype            => $itemtype
269         },
270         $biblionumber
271     );
272
273     # Create borrowers
274     my %renewing_borrower_data = (
275         firstname =>  'John',
276         surname => 'Renewal',
277         categorycode => $patron_category->{categorycode},
278         branchcode => $branch,
279     );
280
281     my %reserving_borrower_data = (
282         firstname =>  'Katrin',
283         surname => 'Reservation',
284         categorycode => $patron_category->{categorycode},
285         branchcode => $branch,
286     );
287
288     my %hold_waiting_borrower_data = (
289         firstname =>  'Kyle',
290         surname => 'Reservation',
291         categorycode => $patron_category->{categorycode},
292         branchcode => $branch,
293     );
294
295     my %restricted_borrower_data = (
296         firstname =>  'Alice',
297         surname => 'Reservation',
298         categorycode => $patron_category->{categorycode},
299         debarred => '3228-01-01',
300         branchcode => $branch,
301     );
302
303     my %expired_borrower_data = (
304         firstname =>  'Ça',
305         surname => 'Glisse',
306         categorycode => $patron_category->{categorycode},
307         branchcode => $branch,
308         dateexpiry => dt_from_string->subtract( months => 1 ),
309     );
310
311     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
312     my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
313     my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
314     my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
315     my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
316
317     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
318     my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
319     my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
320
321     my $bibitems       = '';
322     my $priority       = '1';
323     my $resdate        = undef;
324     my $expdate        = undef;
325     my $notes          = '';
326     my $checkitem      = undef;
327     my $found          = undef;
328
329     my $issue = AddIssue( $renewing_borrower, $barcode);
330     my $datedue = dt_from_string( $issue->date_due() );
331     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
332
333     my $issue2 = AddIssue( $renewing_borrower, $barcode2);
334     $datedue = dt_from_string( $issue->date_due() );
335     is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
336
337
338     my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $itemnumber } )->borrowernumber;
339     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
340
341     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
342     is( $renewokay, 1, 'Can renew, no holds for this title or item');
343
344
345     # Biblio-level hold, renewal test
346     AddReserve(
347         $branch, $reserving_borrowernumber, $biblionumber,
348         $bibitems,  $priority, $resdate, $expdate, $notes,
349         $title, $checkitem, $found
350     );
351
352     # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
353     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
354     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
355     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
356     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
357     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
358     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
359
360     # Now let's add an item level hold, we should no longer be able to renew the item
361     my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
362         {
363             borrowernumber => $hold_waiting_borrowernumber,
364             biblionumber   => $biblionumber,
365             itemnumber     => $itemnumber,
366             branchcode     => $branch,
367             priority       => 3,
368         }
369     );
370     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
371     is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
372     $hold->delete();
373
374     # 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
375     # be able to renew these items
376     $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
377         {
378             borrowernumber => $hold_waiting_borrowernumber,
379             biblionumber   => $biblionumber,
380             itemnumber     => $itemnumber3,
381             branchcode     => $branch,
382             priority       => 0,
383             found          => 'W'
384         }
385     );
386     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
387     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
388     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
389     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
390     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
391
392     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
393     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
394     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
395
396     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
397     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
398     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
399
400     my $reserveid = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
401     my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
402     AddIssue($reserving_borrower, $barcode3);
403     my $reserve = $dbh->selectrow_hashref(
404         'SELECT * FROM old_reserves WHERE reserve_id = ?',
405         { Slice => {} },
406         $reserveid
407     );
408     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
409
410     # Item-level hold, renewal test
411     AddReserve(
412         $branch, $reserving_borrowernumber, $biblionumber,
413         $bibitems,  $priority, $resdate, $expdate, $notes,
414         $title, $itemnumber, $found
415     );
416
417     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
418     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
419     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
420
421     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2, 1);
422     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
423
424     # Items can't fill hold for reasons
425     ModItem({ notforloan => 1 }, $biblionumber, $itemnumber);
426     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
427     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
428     ModItem({ notforloan => 0, itype => $itemtype }, $biblionumber, $itemnumber);
429
430     # FIXME: Add more for itemtype not for loan etc.
431
432     # Restricted users cannot renew when RestrictionBlockRenewing is enabled
433     my $barcode5 = 'R00000347';
434     my ( $item_bibnum5, $item_bibitemnum5, $itemnumber5 ) = AddItem(
435         {
436             homebranch       => $branch,
437             holdingbranch    => $branch,
438             barcode          => $barcode5,
439             replacementprice => 23.00,
440             itype            => $itemtype
441         },
442         $biblionumber
443     );
444     my $datedue5 = AddIssue($restricted_borrower, $barcode5);
445     is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
446
447     t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
448     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
449     is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
450     ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $itemnumber5);
451     is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
452
453     # Users cannot renew an overdue item
454     my $barcode6 = 'R00000348';
455     my ( $item_bibnum6, $item_bibitemnum6, $itemnumber6 ) = AddItem(
456         {
457             homebranch       => $branch,
458             holdingbranch    => $branch,
459             barcode          => $barcode6,
460             replacementprice => 23.00,
461             itype            => $itemtype
462         },
463         $biblionumber
464     );
465
466     my $barcode7 = 'R00000349';
467     my ( $item_bibnum7, $item_bibitemnum7, $itemnumber7 ) = AddItem(
468         {
469             homebranch       => $branch,
470             holdingbranch    => $branch,
471             barcode          => $barcode7,
472             replacementprice => 23.00,
473             itype            => $itemtype
474         },
475         $biblionumber
476     );
477     my $datedue6 = AddIssue( $renewing_borrower, $barcode6);
478     is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
479
480     my $now = dt_from_string();
481     my $five_weeks = DateTime::Duration->new(weeks => 5);
482     my $five_weeks_ago = $now - $five_weeks;
483     t::lib::Mocks::mock_preference('finesMode', 'production');
484
485     my $passeddatedue1 = AddIssue($renewing_borrower, $barcode7, $five_weeks_ago);
486     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
487
488     my ( $fine ) = CalcFine( GetItem(undef, $barcode7), $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
489     C4::Overdues::UpdateFine(
490         {
491             issue_id       => $passeddatedue1->id(),
492             itemnumber     => $itemnumber7,
493             borrowernumber => $renewing_borrower->{borrowernumber},
494             amount         => $fine,
495             type           => 'FU',
496             due            => Koha::DateUtils::output_pref($five_weeks_ago)
497         }
498     );
499
500     t::lib::Mocks::mock_preference('RenewalLog', 0);
501     my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
502     my $old_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
503     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
504     my $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
505     is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
506
507     t::lib::Mocks::mock_preference('RenewalLog', 1);
508     $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
509     $old_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
510     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
511     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
512     is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
513
514     my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $itemnumber7 } );
515     is( $fines->count, 2 );
516     is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
517     is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
518     $fines->delete();
519
520
521     my $old_issue_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["ISSUE"]) } );
522     my $old_renew_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
523     AddIssue( $renewing_borrower,$barcode7,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
524     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
525     is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
526     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["ISSUE"]) } );
527     is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
528
529     $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $itemnumber7 } );
530     $fines->delete();
531
532     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
533     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
534     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
535     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
536     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
537
538
539     $hold = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $reserving_borrowernumber })->next;
540     $hold->cancel;
541
542     # Bug 14101
543     # Test automatic renewal before value for "norenewalbefore" in policy is set
544     # In this case automatic renewal is not permitted prior to due date
545     my $barcode4 = '11235813';
546     my ( $item_bibnum4, $item_bibitemnum4, $itemnumber4 ) = AddItem(
547         {
548             homebranch       => $branch,
549             holdingbranch    => $branch,
550             barcode          => $barcode4,
551             replacementprice => 16.00,
552             itype            => $itemtype
553         },
554         $biblionumber
555     );
556
557     $issue = AddIssue( $renewing_borrower, $barcode4, undef, undef, undef, undef, { auto_renew => 1 } );
558     ( $renewokay, $error ) =
559       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
560     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
561     is( $error, 'auto_too_soon',
562         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
563
564     # Bug 7413
565     # Test premature manual renewal
566     $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
567
568     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
569     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
570     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
571
572     # Bug 14395
573     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
574     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
575     is(
576         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
577         $datedue->clone->add( days => -7 ),
578         'Bug 14395: Renewals permitted 7 days before due date, as expected'
579     );
580
581     # Bug 14395
582     # Test 'date' setting for syspref NoRenewalBeforePrecision
583     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
584     is(
585         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
586         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
587         'Bug 14395: Renewals permitted 7 days before due date, as expected'
588     );
589
590     # Bug 14101
591     # Test premature automatic renewal
592     ( $renewokay, $error ) =
593       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
594     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
595     is( $error, 'auto_too_soon',
596         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
597     );
598
599     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
600     # and test automatic renewal again
601     $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
602     ( $renewokay, $error ) =
603       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
604     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
605     is( $error, 'auto_too_soon',
606         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
607     );
608
609     # Change policy so that loans can be renewed 99 days prior to the due date
610     # and test automatic renewal again
611     $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
612     ( $renewokay, $error ) =
613       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
614     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
615     is( $error, 'auto_renew',
616         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
617     );
618
619     subtest "too_late_renewal / no_auto_renewal_after" => sub {
620         plan tests => 14;
621         my $item_to_auto_renew = $builder->build(
622             {   source => 'Item',
623                 value  => {
624                     biblionumber  => $biblionumber,
625                     homebranch    => $branch,
626                     holdingbranch => $branch,
627                 }
628             }
629         );
630
631         my $ten_days_before = dt_from_string->add( days => -10 );
632         my $ten_days_ahead  = dt_from_string->add( days => 10 );
633         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
634
635         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
636         ( $renewokay, $error ) =
637           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
638         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
639         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
640
641         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
642         ( $renewokay, $error ) =
643           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
644         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
645         is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
646
647         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
648         ( $renewokay, $error ) =
649           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
650         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
651         is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
652
653         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
654         ( $renewokay, $error ) =
655           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
656         is( $renewokay, 0,            'Do not renew, renewal is automatic' );
657         is( $error,     'auto_renew', 'Cannot renew, renew is automatic' );
658
659         $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 ) );
660         ( $renewokay, $error ) =
661           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
662         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
663         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
664
665         $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 ) );
666         ( $renewokay, $error ) =
667           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
668         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
669         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
670
671         $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 ) );
672         ( $renewokay, $error ) =
673           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
674         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
675         is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
676     };
677
678     subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew" => sub {
679         plan tests => 6;
680         my $item_to_auto_renew = $builder->build({
681             source => 'Item',
682             value => {
683                 biblionumber => $biblionumber,
684                 homebranch       => $branch,
685                 holdingbranch    => $branch,
686             }
687         });
688
689         my $ten_days_before = dt_from_string->add( days => -10 );
690         my $ten_days_ahead = dt_from_string->add( days => 10 );
691         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
692
693         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
694         C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
695         C4::Context->set_preference('OPACFineNoRenewals','10');
696         my $fines_amount = 5;
697         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
698         ( $renewokay, $error ) =
699           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
700         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
701         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
702
703         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
704         ( $renewokay, $error ) =
705           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
706         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
707         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
708
709         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
710         ( $renewokay, $error ) =
711           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
712         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
713         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
714
715         $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
716     };
717
718     subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
719         plan tests => 6;
720         my $item_to_auto_renew = $builder->build({
721             source => 'Item',
722             value => {
723                 biblionumber => $biblionumber,
724                 homebranch       => $branch,
725                 holdingbranch    => $branch,
726             }
727         });
728
729         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
730
731         my $ten_days_before = dt_from_string->add( days => -10 );
732         my $ten_days_ahead = dt_from_string->add( days => 10 );
733
734         # Patron is expired and BlockExpiredPatronOpacActions=0
735         # => auto renew is allowed
736         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
737         my $patron = $expired_borrower;
738         my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
739         ( $renewokay, $error ) =
740           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
741         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
742         is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
743         Koha::Checkouts->find( $checkout->issue_id )->delete;
744
745
746         # Patron is expired and BlockExpiredPatronOpacActions=1
747         # => auto renew is not allowed
748         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
749         $patron = $expired_borrower;
750         $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
751         ( $renewokay, $error ) =
752           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
753         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
754         is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
755         Koha::Checkouts->find( $checkout->issue_id )->delete;
756
757
758         # Patron is not expired and BlockExpiredPatronOpacActions=1
759         # => auto renew is allowed
760         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
761         $patron = $renewing_borrower;
762         $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
763         ( $renewokay, $error ) =
764           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
765         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
766         is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
767         Koha::Checkouts->find( $checkout->issue_id )->delete;
768     };
769
770     subtest "GetLatestAutoRenewDate" => sub {
771         plan tests => 5;
772         my $item_to_auto_renew = $builder->build(
773             {   source => 'Item',
774                 value  => {
775                     biblionumber  => $biblionumber,
776                     homebranch    => $branch,
777                     holdingbranch => $branch,
778                 }
779             }
780         );
781
782         my $ten_days_before = dt_from_string->add( days => -10 );
783         my $ten_days_ahead  = dt_from_string->add( days => 10 );
784         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
785         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = NULL');
786         my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
787         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' );
788         my $five_days_before = dt_from_string->add( days => -5 );
789         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, 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_before->truncate( to => 'minute' ),
793             'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
794         );
795         my $five_days_ahead = dt_from_string->add( days => 5 );
796         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
797         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
798         is( $latest_auto_renew_date->truncate( to => 'minute' ),
799             $five_days_ahead->truncate( to => 'minute' ),
800             'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
801         );
802         my $two_days_ahead = dt_from_string->add( days => 2 );
803         $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 ) );
804         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
805         is( $latest_auto_renew_date->truncate( to => 'day' ),
806             $two_days_ahead->truncate( to => 'day' ),
807             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
808         );
809         $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 ) );
810         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
811         is( $latest_auto_renew_date->truncate( to => 'day' ),
812             $two_days_ahead->truncate( to => 'day' ),
813             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
814         );
815
816     };
817
818     # Too many renewals
819
820     # set policy to forbid renewals
821     $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
822
823     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
824     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
825     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
826
827     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
828     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
829     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
830
831     C4::Overdues::UpdateFine(
832         {
833             issue_id       => $issue->id(),
834             itemnumber     => $itemnumber,
835             borrowernumber => $renewing_borrower->{borrowernumber},
836             amount         => 15.00,
837             type           => q{},
838             due            => Koha::DateUtils::output_pref($datedue)
839         }
840     );
841
842     my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
843     is( $line->accounttype, 'FU', 'Account line type is FU' );
844     is( $line->lastincrement, '15.000000', 'Account line last increment is 15.00' );
845     is( $line->amountoutstanding, '15.000000', 'Account line amount outstanding is 15.00' );
846     is( $line->amount, '15.000000', 'Account line amount is 15.00' );
847     is( $line->issue_id, $issue->id, 'Account line issue id matches' );
848
849     my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
850     is( $offset->type, 'Fine', 'Account offset type is Fine' );
851     is( $offset->amount, '15.000000', 'Account offset amount is 15.00' );
852
853     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
854     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
855
856     LostItem( $itemnumber, 'test', 1 );
857
858     $line = Koha::Account::Lines->find($line->id);
859     is( $line->accounttype, 'F', 'Account type correctly changed from FU to F' );
860
861     my $item = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber);
862     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
863     my $checkout = Koha::Checkouts->find({ itemnumber => $itemnumber });
864     is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
865
866     my $total_due = $dbh->selectrow_array(
867         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
868         undef, $renewing_borrower->{borrowernumber}
869     );
870
871     is( $total_due, '15.000000', 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
872
873     C4::Context->dbh->do("DELETE FROM accountlines");
874
875     C4::Overdues::UpdateFine(
876         {
877             issue_id       => $issue2->id(),
878             itemnumber     => $itemnumber2,
879             borrowernumber => $renewing_borrower->{borrowernumber},
880             amount         => 15.00,
881             type           => q{},
882             due            => Koha::DateUtils::output_pref($datedue)
883         }
884     );
885
886     LostItem( $itemnumber2, 'test', 0 );
887
888     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
889     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
890     ok( Koha::Checkouts->find({ itemnumber => $itemnumber2 }), 'LostItem called without forced return has checked in the item' );
891
892     $total_due = $dbh->selectrow_array(
893         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
894         undef, $renewing_borrower->{borrowernumber}
895     );
896
897     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
898
899     my $future = dt_from_string();
900     $future->add( days => 7 );
901     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
902     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
903
904     # Users cannot renew any item if there is an overdue item
905     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
906     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
907     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
908     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
909     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
910
911     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
912     $checkout = Koha::Checkouts->find( { itemnumber => $itemnumber3 } );
913     LostItem( $itemnumber3, 'test', 0 );
914     my $accountline = Koha::Account::Lines->find( { itemnumber => $itemnumber3 } );
915     is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
916
917   }
918
919 {
920     # GetUpcomingDueIssues tests
921     my $barcode  = 'R00000342';
922     my $barcode2 = 'R00000343';
923     my $barcode3 = 'R00000344';
924     my $branch   = $library2->{branchcode};
925
926     #Create another record
927     my $title2 = 'Something is worng here';
928     my ($biblionumber2, $biblioitemnumber2) = add_biblio($title2, 'Anonymous');
929
930     #Create third item
931     AddItem(
932         {
933             homebranch       => $branch,
934             holdingbranch    => $branch,
935             barcode          => $barcode3,
936             itype            => $itemtype
937         },
938         $biblionumber2
939     );
940
941     # Create a borrower
942     my %a_borrower_data = (
943         firstname =>  'Fridolyn',
944         surname => 'SOMERS',
945         categorycode => $patron_category->{categorycode},
946         branchcode => $branch,
947     );
948
949     my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
950     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
951
952     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
953     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
954     my $today = DateTime->today(time_zone => C4::Context->tz());
955
956     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
957     my $datedue = dt_from_string( $issue->date_due() );
958     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
959     my $datedue2 = dt_from_string( $issue->date_due() );
960
961     my $upcoming_dues;
962
963     # GetUpcomingDueIssues tests
964     for my $i(0..1) {
965         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
966         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
967     }
968
969     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
970     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
971     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
972
973     for my $i(3..5) {
974         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
975         is ( scalar( @$upcoming_dues ), 1,
976             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
977     }
978
979     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
980
981     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
982
983     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
984     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
985
986     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
987     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
988
989     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
990     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
991
992     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
993     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
994
995     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
996     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
997
998     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
999     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1000
1001 }
1002
1003 {
1004     my $barcode  = '1234567890';
1005     my $branch   = $library2->{branchcode};
1006
1007     my ($biblionumber, $biblioitemnumber) = add_biblio();
1008
1009     #Create third item
1010     my ( undef, undef, $itemnumber ) = AddItem(
1011         {
1012             homebranch       => $branch,
1013             holdingbranch    => $branch,
1014             barcode          => $barcode,
1015             itype            => $itemtype
1016         },
1017         $biblionumber
1018     );
1019
1020     # Create a borrower
1021     my %a_borrower_data = (
1022         firstname =>  'Kyle',
1023         surname => 'Hall',
1024         categorycode => $patron_category->{categorycode},
1025         branchcode => $branch,
1026     );
1027
1028     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1029
1030     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1031     my $issue = AddIssue( $borrower, $barcode );
1032     UpdateFine(
1033         {
1034             issue_id       => $issue->id(),
1035             itemnumber     => $itemnumber,
1036             borrowernumber => $borrowernumber,
1037             amount         => 0,
1038             type           => q{}
1039         }
1040     );
1041
1042     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
1043     my $count = $hr->{count};
1044
1045     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1046 }
1047
1048 {
1049     $dbh->do('DELETE FROM issues');
1050     $dbh->do('DELETE FROM items');
1051     $dbh->do('DELETE FROM issuingrules');
1052     $dbh->do(
1053         q{
1054         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
1055                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1056         },
1057         {},
1058         '*', '*', '*', 25,
1059         20,  14,  'days',
1060         1,   7,
1061         undef,  0,
1062         .10, 1
1063     );
1064     my ( $biblionumber, $biblioitemnumber ) = add_biblio();
1065
1066     my $barcode1 = '1234';
1067     my ( undef, undef, $itemnumber1 ) = AddItem(
1068         {
1069             homebranch    => $library2->{branchcode},
1070             holdingbranch => $library2->{branchcode},
1071             barcode       => $barcode1,
1072             itype         => $itemtype
1073         },
1074         $biblionumber
1075     );
1076     my $barcode2 = '4321';
1077     my ( undef, undef, $itemnumber2 ) = AddItem(
1078         {
1079             homebranch    => $library2->{branchcode},
1080             holdingbranch => $library2->{branchcode},
1081             barcode       => $barcode2,
1082             itype         => $itemtype
1083         },
1084         $biblionumber
1085     );
1086
1087     my $borrowernumber1 = Koha::Patron->new({
1088         firstname    => 'Kyle',
1089         surname      => 'Hall',
1090         categorycode => $patron_category->{categorycode},
1091         branchcode   => $library2->{branchcode},
1092     })->store->borrowernumber;
1093     my $borrowernumber2 = Koha::Patron->new({
1094         firstname    => 'Chelsea',
1095         surname      => 'Hall',
1096         categorycode => $patron_category->{categorycode},
1097         branchcode   => $library2->{branchcode},
1098     })->store->borrowernumber;
1099
1100     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1101     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1102
1103     my $issue = AddIssue( $borrower1, $barcode1 );
1104
1105     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1106     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1107
1108     AddReserve(
1109         $library2->{branchcode}, $borrowernumber2, $biblionumber,
1110         '',  1, undef, undef, '',
1111         undef, undef, undef
1112     );
1113
1114     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1115     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1116     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1117     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1118
1119     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1120     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1121     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1122     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1123
1124     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1125     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1126     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1127     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1128
1129     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1130     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1131     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1132     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1133
1134     # Setting item not checked out to be not for loan but holdable
1135     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
1136
1137     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1138     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' );
1139 }
1140
1141 {
1142     # Don't allow renewing onsite checkout
1143     my $barcode  = 'R00000XXX';
1144     my $branch   = $library->{branchcode};
1145
1146     #Create another record
1147     my ($biblionumber, $biblioitemnumber) = add_biblio('A title', 'Anonymous');
1148
1149     my (undef, undef, $itemnumber) = AddItem(
1150         {
1151             homebranch       => $branch,
1152             holdingbranch    => $branch,
1153             barcode          => $barcode,
1154             itype            => $itemtype
1155         },
1156         $biblionumber
1157     );
1158
1159     my $borrowernumber = Koha::Patron->new({
1160         firstname =>  'fn',
1161         surname => 'dn',
1162         categorycode => $patron_category->{categorycode},
1163         branchcode => $branch,
1164     })->store->borrowernumber;
1165
1166     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1167
1168     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1169     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
1170     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1171     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1172 }
1173
1174 {
1175     my $library = $builder->build({ source => 'Branch' });
1176
1177     my ($biblionumber, $biblioitemnumber) = add_biblio();
1178
1179     my $barcode = 'just a barcode';
1180     my ( undef, undef, $itemnumber ) = AddItem(
1181         {
1182             homebranch       => $library->{branchcode},
1183             holdingbranch    => $library->{branchcode},
1184             barcode          => $barcode,
1185             itype            => $itemtype
1186         },
1187         $biblionumber,
1188     );
1189
1190     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1191
1192     my $issue = AddIssue( $patron, $barcode );
1193     UpdateFine(
1194         {
1195             issue_id       => $issue->id(),
1196             itemnumber     => $itemnumber,
1197             borrowernumber => $patron->{borrowernumber},
1198             amount         => 1,
1199             type           => q{}
1200         }
1201     );
1202     UpdateFine(
1203         {
1204             issue_id       => $issue->id(),
1205             itemnumber     => $itemnumber,
1206             borrowernumber => $patron->{borrowernumber},
1207             amount         => 2,
1208             type           => q{}
1209         }
1210     );
1211     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1212 }
1213
1214 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1215     plan tests => 24;
1216
1217     my $homebranch    = $builder->build( { source => 'Branch' } );
1218     my $holdingbranch = $builder->build( { source => 'Branch' } );
1219     my $otherbranch   = $builder->build( { source => 'Branch' } );
1220     my $patron_1      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1221     my $patron_2      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1222
1223     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1224     my $item = $builder->build(
1225         {   source => 'Item',
1226             value  => {
1227                 homebranch    => $homebranch->{branchcode},
1228                 holdingbranch => $holdingbranch->{branchcode},
1229                 biblionumber  => $biblioitem->{biblionumber}
1230             }
1231         }
1232     );
1233
1234     set_userenv($holdingbranch);
1235
1236     my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1237     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Checkout
1238
1239     my ( $error, $question, $alerts );
1240
1241     # AllowReturnToBranch == anywhere
1242     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1243     ## Test that unknown barcodes don't generate internal server errors
1244     set_userenv($homebranch);
1245     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1246     ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1247     ## Can be issued from homebranch
1248     set_userenv($homebranch);
1249     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1250     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1251     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1252     ## Can be issued from holdingbranch
1253     set_userenv($holdingbranch);
1254     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1255     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1256     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1257     ## Can be issued from another branch
1258     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1259     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1260     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1261
1262     # AllowReturnToBranch == holdingbranch
1263     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1264     ## Cannot be issued from homebranch
1265     set_userenv($homebranch);
1266     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1267     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1268     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1269     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1270     ## Can be issued from holdinbranch
1271     set_userenv($holdingbranch);
1272     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1273     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1274     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1275     ## Cannot be issued from another branch
1276     set_userenv($otherbranch);
1277     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1278     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1279     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1280     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1281
1282     # AllowReturnToBranch == homebranch
1283     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1284     ## Can be issued from holdinbranch
1285     set_userenv($homebranch);
1286     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1287     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1288     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1289     ## Cannot be issued from holdinbranch
1290     set_userenv($holdingbranch);
1291     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1292     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1293     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1294     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1295     ## Cannot be issued from holdinbranch
1296     set_userenv($otherbranch);
1297     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1298     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1299     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1300     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1301
1302     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1303 };
1304
1305 subtest 'AddIssue & AllowReturnToBranch' => sub {
1306     plan tests => 9;
1307
1308     my $homebranch    = $builder->build( { source => 'Branch' } );
1309     my $holdingbranch = $builder->build( { source => 'Branch' } );
1310     my $otherbranch   = $builder->build( { source => 'Branch' } );
1311     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1312     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1313
1314     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1315     my $item = $builder->build(
1316         {   source => 'Item',
1317             value  => {
1318                 homebranch    => $homebranch->{branchcode},
1319                 holdingbranch => $holdingbranch->{branchcode},
1320                 notforloan    => 0,
1321                 itemlost      => 0,
1322                 withdrawn     => 0,
1323                 biblionumber  => $biblioitem->{biblionumber}
1324             }
1325         }
1326     );
1327
1328     set_userenv($holdingbranch);
1329
1330     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Checkout
1331     my $issue = AddIssue( $patron_1, $item->{barcode} );
1332
1333     my ( $error, $question, $alerts );
1334
1335     # AllowReturnToBranch == homebranch
1336     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1337     ## Can be issued from homebranch
1338     set_userenv($homebranch);
1339     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1340     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1341     ## Can be issued from holdinbranch
1342     set_userenv($holdingbranch);
1343     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1344     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1345     ## Can be issued from another branch
1346     set_userenv($otherbranch);
1347     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1348     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1349
1350     # AllowReturnToBranch == holdinbranch
1351     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1352     ## Cannot be issued from homebranch
1353     set_userenv($homebranch);
1354     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1355     ## Can be issued from holdingbranch
1356     set_userenv($holdingbranch);
1357     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1358     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1359     ## Cannot be issued from another branch
1360     set_userenv($otherbranch);
1361     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1362
1363     # AllowReturnToBranch == homebranch
1364     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1365     ## Can be issued from homebranch
1366     set_userenv($homebranch);
1367     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1368     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1369     ## Cannot be issued from holdinbranch
1370     set_userenv($holdingbranch);
1371     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1372     ## Cannot be issued from another branch
1373     set_userenv($otherbranch);
1374     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1375     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1376 };
1377
1378 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1379     plan tests => 8;
1380
1381     my $library = $builder->build( { source => 'Branch' } );
1382     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1383
1384     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1385     my $item_1 = $builder->build(
1386         {   source => 'Item',
1387             value  => {
1388                 homebranch    => $library->{branchcode},
1389                 holdingbranch => $library->{branchcode},
1390                 biblionumber  => $biblioitem_1->{biblionumber}
1391             }
1392         }
1393     );
1394     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1395     my $item_2 = $builder->build(
1396         {   source => 'Item',
1397             value  => {
1398                 homebranch    => $library->{branchcode},
1399                 holdingbranch => $library->{branchcode},
1400                 biblionumber  => $biblioitem_2->{biblionumber}
1401             }
1402         }
1403     );
1404
1405     my ( $error, $question, $alerts );
1406
1407     # Patron cannot issue item_1, they have overdues
1408     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1409     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday );    # Add an overdue
1410
1411     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1412     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1413     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
1414     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1415
1416     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1417     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1418     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1419     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1420
1421     # Patron cannot issue item_1, they are debarred
1422     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1423     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1424     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1425     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1426     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1427
1428     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1429     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1430     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1431     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1432 };
1433
1434 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1435     plan tests => 1;
1436
1437     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1438     my $patron_category_x = $builder->build_object(
1439         {
1440             class => 'Koha::Patron::Categories',
1441             value => { category_type => 'X' }
1442         }
1443     );
1444     my $patron = $builder->build_object(
1445         {
1446             class => 'Koha::Patrons',
1447             value => {
1448                 categorycode  => $patron_category_x->categorycode,
1449                 gonenoaddress => undef,
1450                 lost          => undef,
1451                 debarred      => undef,
1452                 borrowernotes => ""
1453             }
1454         }
1455     );
1456     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1457     my $item_1 = $builder->build(
1458         {
1459             source => 'Item',
1460             value  => {
1461                 homebranch    => $library->branchcode,
1462                 holdingbranch => $library->branchcode,
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 = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
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 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
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 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
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                 biblionumber  => $biblionumber,
1590             }
1591         }
1592     );
1593     my $item_2 = $builder->build(
1594         {   source => 'Item',
1595             value  => {
1596                 homebranch    => $library->{branchcode},
1597                 holdingbranch => $library->{branchcode},
1598                 biblionumber  => $biblionumber,
1599             }
1600         }
1601     );
1602
1603     my ( $error, $question, $alerts );
1604     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1605
1606     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1607     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1608     is( keys(%$error) + keys(%$alerts),  0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1609     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) );
1610
1611     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1612     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1613     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1614
1615     # Add a subscription
1616     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1617
1618     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1619     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1620     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) );
1621
1622     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1623     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1624     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) );
1625 };
1626
1627 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1628     plan tests => 8;
1629
1630     my $library = $builder->build( { source => 'Branch' } );
1631     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1632
1633     # Add 2 items
1634     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1635     my $item_1 = $builder->build(
1636         {
1637             source => 'Item',
1638             value  => {
1639                 homebranch    => $library->{branchcode},
1640                 holdingbranch => $library->{branchcode},
1641                 notforloan    => 0,
1642                 itemlost      => 0,
1643                 withdrawn     => 0,
1644                 biblionumber  => $biblioitem_1->{biblionumber}
1645             }
1646         }
1647     );
1648     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1649     my $item_2 = $builder->build(
1650         {
1651             source => 'Item',
1652             value  => {
1653                 homebranch    => $library->{branchcode},
1654                 holdingbranch => $library->{branchcode},
1655                 notforloan    => 0,
1656                 itemlost      => 0,
1657                 withdrawn     => 0,
1658                 biblionumber  => $biblioitem_2->{biblionumber}
1659             }
1660         }
1661     );
1662
1663     # And the issuing rule
1664     Koha::IssuingRules->search->delete;
1665     my $rule = Koha::IssuingRule->new(
1666         {
1667             categorycode => '*',
1668             itemtype     => '*',
1669             branchcode   => '*',
1670             maxissueqty  => 99,
1671             issuelength  => 1,
1672             firstremind  => 1,        # 1 day of grace
1673             finedays     => 2,        # 2 days of fine per day of overdue
1674             lengthunit   => 'days',
1675         }
1676     );
1677     $rule->store();
1678
1679     # Patron cannot issue item_1, they have overdues
1680     my $five_days_ago = dt_from_string->subtract( days => 5 );
1681     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1682     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1683     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1684       ;    # Add another overdue
1685
1686     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1687     AddReturn( $item_1->{barcode}, $library->{branchcode},
1688         undef, undef, dt_from_string );
1689     my $debarments = Koha::Patron::Debarments::GetDebarments(
1690         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1691     is( scalar(@$debarments), 1 );
1692
1693     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1694     # Same for the others
1695     my $expected_expiration = output_pref(
1696         {
1697             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1698             dateformat => 'sql',
1699             dateonly   => 1
1700         }
1701     );
1702     is( $debarments->[0]->{expiration}, $expected_expiration );
1703
1704     AddReturn( $item_2->{barcode}, $library->{branchcode},
1705         undef, undef, dt_from_string );
1706     $debarments = Koha::Patron::Debarments::GetDebarments(
1707         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1708     is( scalar(@$debarments), 1 );
1709     $expected_expiration = output_pref(
1710         {
1711             dt         => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1712             dateformat => 'sql',
1713             dateonly   => 1
1714         }
1715     );
1716     is( $debarments->[0]->{expiration}, $expected_expiration );
1717
1718     Koha::Patron::Debarments::DelUniqueDebarment(
1719         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1720
1721     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1722     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1723     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1724       ;    # Add another overdue
1725     AddReturn( $item_1->{barcode}, $library->{branchcode},
1726         undef, undef, dt_from_string );
1727     $debarments = Koha::Patron::Debarments::GetDebarments(
1728         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1729     is( scalar(@$debarments), 1 );
1730     $expected_expiration = output_pref(
1731         {
1732             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1733             dateformat => 'sql',
1734             dateonly   => 1
1735         }
1736     );
1737     is( $debarments->[0]->{expiration}, $expected_expiration );
1738
1739     AddReturn( $item_2->{barcode}, $library->{branchcode},
1740         undef, undef, dt_from_string );
1741     $debarments = Koha::Patron::Debarments::GetDebarments(
1742         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1743     is( scalar(@$debarments), 1 );
1744     $expected_expiration = output_pref(
1745         {
1746             dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1747             dateformat => 'sql',
1748             dateonly   => 1
1749         }
1750     );
1751     is( $debarments->[0]->{expiration}, $expected_expiration );
1752 };
1753
1754 subtest 'AddReturn + suspension_chargeperiod' => sub {
1755     plan tests => 21;
1756
1757     my $library = $builder->build( { source => 'Branch' } );
1758     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1759
1760     # Add 2 items
1761     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1762     my $item_1 = $builder->build(
1763         {
1764             source => 'Item',
1765             value  => {
1766                 homebranch    => $library->{branchcode},
1767                 holdingbranch => $library->{branchcode},
1768                 notforloan    => 0,
1769                 itemlost      => 0,
1770                 withdrawn     => 0,
1771                 biblionumber  => $biblioitem_1->{biblionumber}
1772             }
1773         }
1774     );
1775
1776     # And the issuing rule
1777     Koha::IssuingRules->search->delete;
1778     my $rule = Koha::IssuingRule->new(
1779         {
1780             categorycode => '*',
1781             itemtype     => '*',
1782             branchcode   => '*',
1783             maxissueqty  => 99,
1784             issuelength  => 1,
1785             firstremind  => 0,        # 0 day of grace
1786             finedays     => 2,        # 2 days of fine per day of overdue
1787             suspension_chargeperiod => 1,
1788             lengthunit   => 'days',
1789         }
1790     );
1791     $rule->store();
1792
1793     my $five_days_ago = dt_from_string->subtract( days => 5 );
1794     # We want to charge 2 days every day, without grace
1795     # With 5 days of overdue: 5 * Z
1796     my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
1797     test_debarment_on_checkout(
1798         {
1799             item            => $item_1,
1800             library         => $library,
1801             patron          => $patron,
1802             due_date        => $five_days_ago,
1803             expiration_date => $expected_expiration,
1804         }
1805     );
1806
1807     # We want to charge 2 days every 2 days, without grace
1808     # With 5 days of overdue: (5 * 2) / 2
1809     $rule->suspension_chargeperiod(2)->store;
1810     $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
1811     test_debarment_on_checkout(
1812         {
1813             item            => $item_1,
1814             library         => $library,
1815             patron          => $patron,
1816             due_date        => $five_days_ago,
1817             expiration_date => $expected_expiration,
1818         }
1819     );
1820
1821     # We want to charge 2 days every 3 days, with 1 day of grace
1822     # With 5 days of overdue: ((5-1) / 3 ) * 2
1823     $rule->suspension_chargeperiod(3)->store;
1824     $rule->firstremind(1)->store;
1825     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1826     test_debarment_on_checkout(
1827         {
1828             item            => $item_1,
1829             library         => $library,
1830             patron          => $patron,
1831             due_date        => $five_days_ago,
1832             expiration_date => $expected_expiration,
1833         }
1834     );
1835
1836     # Use finesCalendar to know if holiday must be skipped to calculate the due date
1837     # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
1838     $rule->finedays(2)->store;
1839     $rule->suspension_chargeperiod(1)->store;
1840     $rule->firstremind(0)->store;
1841     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
1842
1843     # Adding a holiday 2 days ago
1844     my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
1845     my $two_days_ago = dt_from_string->subtract( days => 2 );
1846     $calendar->insert_single_holiday(
1847         day             => $two_days_ago->day,
1848         month           => $two_days_ago->month,
1849         year            => $two_days_ago->year,
1850         title           => 'holidayTest-2d',
1851         description     => 'holidayDesc 2 days ago'
1852     );
1853     # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
1854     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
1855     test_debarment_on_checkout(
1856         {
1857             item            => $item_1,
1858             library         => $library,
1859             patron          => $patron,
1860             due_date        => $five_days_ago,
1861             expiration_date => $expected_expiration,
1862         }
1863     );
1864
1865     # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
1866     my $two_days_ahead = dt_from_string->add( days => 2 );
1867     $calendar->insert_single_holiday(
1868         day             => $two_days_ahead->day,
1869         month           => $two_days_ahead->month,
1870         year            => $two_days_ahead->year,
1871         title           => 'holidayTest+2d',
1872         description     => 'holidayDesc 2 days ahead'
1873     );
1874
1875     # Same as above, but we should skip D+2
1876     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
1877     test_debarment_on_checkout(
1878         {
1879             item            => $item_1,
1880             library         => $library,
1881             patron          => $patron,
1882             due_date        => $five_days_ago,
1883             expiration_date => $expected_expiration,
1884         }
1885     );
1886
1887     # Adding another holiday, day of expiration date
1888     my $expected_expiration_dt = dt_from_string($expected_expiration);
1889     $calendar->insert_single_holiday(
1890         day             => $expected_expiration_dt->day,
1891         month           => $expected_expiration_dt->month,
1892         year            => $expected_expiration_dt->year,
1893         title           => 'holidayTest_exp',
1894         description     => 'holidayDesc on expiration date'
1895     );
1896     # Expiration date will be the day after
1897     test_debarment_on_checkout(
1898         {
1899             item            => $item_1,
1900             library         => $library,
1901             patron          => $patron,
1902             due_date        => $five_days_ago,
1903             expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
1904         }
1905     );
1906
1907     test_debarment_on_checkout(
1908         {
1909             item            => $item_1,
1910             library         => $library,
1911             patron          => $patron,
1912             return_date     => dt_from_string->add(days => 5),
1913             expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
1914         }
1915     );
1916 };
1917
1918 subtest 'AddReturn | is_overdue' => sub {
1919     plan tests => 5;
1920
1921     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1922     t::lib::Mocks::mock_preference('finesMode', 'production');
1923     t::lib::Mocks::mock_preference('MaxFine', '100');
1924
1925     my $library = $builder->build( { source => 'Branch' } );
1926     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1927
1928     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1929     my $item = $builder->build(
1930         {
1931             source => 'Item',
1932             value  => {
1933                 homebranch    => $library->{branchcode},
1934                 holdingbranch => $library->{branchcode},
1935                 notforloan    => 0,
1936                 itemlost      => 0,
1937                 withdrawn     => 0,
1938                 biblionumber  => $biblioitem->{biblionumber},
1939             }
1940         }
1941     );
1942
1943     Koha::IssuingRules->search->delete;
1944     my $rule = Koha::IssuingRule->new(
1945         {
1946             categorycode => '*',
1947             itemtype     => '*',
1948             branchcode   => '*',
1949             maxissueqty  => 99,
1950             issuelength  => 6,
1951             lengthunit   => 'days',
1952             fine         => 1, # Charge 1 every day of overdue
1953             chargeperiod => 1,
1954         }
1955     );
1956     $rule->store();
1957
1958     my $one_day_ago   = dt_from_string->subtract( days => 1 );
1959     my $five_days_ago = dt_from_string->subtract( days => 5 );
1960     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1961     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1962
1963     # No date specify, today will be used
1964     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1965     AddReturn( $item->{barcode}, $library->{branchcode} );
1966     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
1967     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1968
1969     # specify return date 5 days before => no overdue
1970     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1971     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $ten_days_ago );
1972     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1973     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1974
1975     # specify return date 5 days later => overdue
1976     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1977     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $five_days_ago );
1978     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
1979     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1980
1981     # specify dropbox date 5 days before => no overdue
1982     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1983     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $ten_days_ago );
1984     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1985     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1986
1987     # specify dropbox date 5 days later => overdue, or... not
1988     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1989     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $five_days_ago );
1990     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
1991     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1992 };
1993
1994 subtest '_FixAccountForLostAndReturned' => sub {
1995
1996     plan tests => 4;
1997
1998     t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
1999     t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
2000
2001     my $processfee_amount  = 20;
2002     my $replacement_amount = 99.00;
2003     my $item_type          = $builder->build_object(
2004         {   class => 'Koha::ItemTypes',
2005             value => {
2006                 notforloan         => undef,
2007                 rentalcharge       => 0,
2008                 defaultreplacecost => undef,
2009                 processfee         => $processfee_amount
2010             }
2011         }
2012     );
2013     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2014
2015     # Generate test biblio
2016     my $title = 'Koha for Dummies';
2017     my ( $biblionumber, $biblioitemnumber ) = add_biblio( $title, 'Hall, Daria' );
2018
2019     subtest 'Full write-off tests' => sub {
2020
2021         plan tests => 10;
2022
2023         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2024         my $barcode = 'KD123456789';
2025
2026         my ( undef, undef, $item_id ) = AddItem(
2027             {   homebranch       => $library->branchcode,
2028                 holdingbranch    => $library->branchcode,
2029                 barcode          => $barcode,
2030                 replacementprice => $replacement_amount,
2031                 itype            => $item_type->itemtype
2032             },
2033             $biblionumber
2034         );
2035
2036         AddIssue( $patron->unblessed, $barcode );
2037
2038         # Simulate item marked as lost
2039         ModItem( { itemlost => 3 }, $biblionumber, $item_id );
2040         LostItem( $item_id, 1 );
2041
2042         my $processing_fee_lines = Koha::Account::Lines->search(
2043             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'PF' } );
2044         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2045         my $processing_fee_line = $processing_fee_lines->next;
2046         is( $processing_fee_line->amount + 0,
2047             $processfee_amount, 'The right PF amount is generated' );
2048         is( $processing_fee_line->amountoutstanding + 0,
2049             $processfee_amount, 'The right PF amountoutstanding is generated' );
2050
2051         my $lost_fee_lines = Koha::Account::Lines->search(
2052             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2053         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2054         my $lost_fee_line = $lost_fee_lines->next;
2055         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2056         is( $lost_fee_line->amountoutstanding + 0,
2057             $replacement_amount, 'The right L amountoutstanding is generated' );
2058
2059         my $account = $patron->account;
2060         my $debts   = $account->outstanding_debits;
2061
2062         # Write off the debt
2063         my $credit = $account->add_credit(
2064             {   amount => $account->balance,
2065                 type   => 'writeoff'
2066             }
2067         );
2068         $credit->apply( { debits => $debts, offset_type => 'Writeoff' } );
2069
2070         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2071         is( $credit_return_id, undef, 'No CR account line added' );
2072
2073         $lost_fee_line->discard_changes; # reload from DB
2074         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2075         is( $lost_fee_line->accounttype,
2076             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2077
2078         is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2079     };
2080
2081     subtest 'Full payment tests' => sub {
2082
2083         plan tests => 12;
2084
2085         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2086         my $barcode = 'KD123456790';
2087
2088         my ( undef, undef, $item_id ) = AddItem(
2089             {   homebranch       => $library->branchcode,
2090                 holdingbranch    => $library->branchcode,
2091                 barcode          => $barcode,
2092                 replacementprice => $replacement_amount,
2093                 itype            => $item_type->itemtype
2094             },
2095             $biblionumber
2096         );
2097
2098         AddIssue( $patron->unblessed, $barcode );
2099
2100         # Simulate item marked as lost
2101         ModItem( { itemlost => 1 }, $biblionumber, $item_id );
2102         LostItem( $item_id, 1 );
2103
2104         my $processing_fee_lines = Koha::Account::Lines->search(
2105             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'PF' } );
2106         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2107         my $processing_fee_line = $processing_fee_lines->next;
2108         is( $processing_fee_line->amount + 0,
2109             $processfee_amount, 'The right PF amount is generated' );
2110         is( $processing_fee_line->amountoutstanding + 0,
2111             $processfee_amount, 'The right PF amountoutstanding is generated' );
2112
2113         my $lost_fee_lines = Koha::Account::Lines->search(
2114             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2115         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2116         my $lost_fee_line = $lost_fee_lines->next;
2117         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2118         is( $lost_fee_line->amountoutstanding + 0,
2119             $replacement_amount, 'The right L amountountstanding is generated' );
2120
2121         my $account = $patron->account;
2122         my $debts   = $account->outstanding_debits;
2123
2124         # Write off the debt
2125         my $credit = $account->add_credit(
2126             {   amount => $account->balance,
2127                 type   => 'payment'
2128             }
2129         );
2130         $credit->apply( { debits => $debts, offset_type => 'Payment' } );
2131
2132         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2133         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2134
2135         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2136         is( $credit_return->amount + 0,
2137             -99.00, 'The account line of type CR has an amount of -99' );
2138         is( $credit_return->amountoutstanding + 0,
2139             -99.00, 'The account line of type CR has an amountoutstanding of -99' );
2140
2141         $lost_fee_line->discard_changes;
2142         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2143         is( $lost_fee_line->accounttype,
2144             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2145
2146         is( $patron->account->balance,
2147             -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2148     };
2149
2150     subtest 'Test without payment or write off' => sub {
2151
2152         plan tests => 12;
2153
2154         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2155         my $barcode = 'KD123456791';
2156
2157         my ( undef, undef, $item_id ) = AddItem(
2158             {   homebranch       => $library->branchcode,
2159                 holdingbranch    => $library->branchcode,
2160                 barcode          => $barcode,
2161                 replacementprice => $replacement_amount,
2162                 itype            => $item_type->itemtype
2163             },
2164             $biblionumber
2165         );
2166
2167         AddIssue( $patron->unblessed, $barcode );
2168
2169         # Simulate item marked as lost
2170         ModItem( { itemlost => 3 }, $biblionumber, $item_id );
2171         LostItem( $item_id, 1 );
2172
2173         my $processing_fee_lines = Koha::Account::Lines->search(
2174             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'PF' } );
2175         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2176         my $processing_fee_line = $processing_fee_lines->next;
2177         is( $processing_fee_line->amount + 0,
2178             $processfee_amount, 'The right PF amount is generated' );
2179         is( $processing_fee_line->amountoutstanding + 0,
2180             $processfee_amount, 'The right PF amountoutstanding is generated' );
2181
2182         my $lost_fee_lines = Koha::Account::Lines->search(
2183             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2184         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2185         my $lost_fee_line = $lost_fee_lines->next;
2186         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2187         is( $lost_fee_line->amountoutstanding + 0,
2188             $replacement_amount, 'The right L amountountstanding is generated' );
2189
2190         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2191         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2192
2193         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2194         is( $credit_return->amount + 0, -99.00, 'The account line of type CR has an amount of -99' );
2195         is( $credit_return->amountoutstanding + 0, 0, 'The account line of type CR has an amountoutstanding of 0' );
2196
2197         $lost_fee_line->discard_changes;
2198         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2199         is( $lost_fee_line->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2200
2201         is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2202     };
2203
2204     subtest 'Test with partial payement and write off, and remaining debt' => sub {
2205
2206         plan tests => 15;
2207
2208         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2209         my $barcode = 'KD123456792';
2210
2211         my ( undef, undef, $item_id ) = AddItem(
2212             {   homebranch       => $library->branchcode,
2213                 holdingbranch    => $library->branchcode,
2214                 barcode          => $barcode,
2215                 replacementprice => $replacement_amount,
2216                 itype            => $item_type->itemtype
2217             },
2218             $biblionumber
2219         );
2220
2221         AddIssue( $patron->unblessed, $barcode );
2222
2223         # Simulate item marked as lost
2224         ModItem( { itemlost => 1 }, $biblionumber, $item_id );
2225         LostItem( $item_id, 1 );
2226
2227         my $processing_fee_lines = Koha::Account::Lines->search(
2228             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'PF' } );
2229         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2230         my $processing_fee_line = $processing_fee_lines->next;
2231         is( $processing_fee_line->amount + 0,
2232             $processfee_amount, 'The right PF amount is generated' );
2233         is( $processing_fee_line->amountoutstanding + 0,
2234             $processfee_amount, 'The right PF amountoutstanding is generated' );
2235
2236         my $lost_fee_lines = Koha::Account::Lines->search(
2237             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2238         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2239         my $lost_fee_line = $lost_fee_lines->next;
2240         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2241         is( $lost_fee_line->amountoutstanding + 0,
2242             $replacement_amount, 'The right L amountountstanding is generated' );
2243
2244         my $account = $patron->account;
2245         is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PF + L' );
2246
2247         # Partially pay fee
2248         my $payment_amount = 27;
2249         my $payment        = $account->add_credit(
2250             {   amount => $payment_amount,
2251                 type   => 'payment'
2252             }
2253         );
2254
2255         $payment->apply( { debits => $lost_fee_lines->reset, offset_type => 'Payment' } );
2256
2257         # Partially write off fee
2258         my $write_off_amount = 25;
2259         my $write_off        = $account->add_credit(
2260             {   amount => $write_off_amount,
2261                 type   => 'writeoff'
2262             }
2263         );
2264         $write_off->apply( { debits => $lost_fee_lines->reset, offset_type => 'Writeoff' } );
2265
2266         is( $account->balance,
2267             $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2268             'Payment and write off applied'
2269         );
2270
2271         # Store the amountoutstanding value
2272         $lost_fee_line->discard_changes;
2273         my $outstanding = $lost_fee_line->amountoutstanding;
2274
2275         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2276         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2277
2278         is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2279
2280         $lost_fee_line->discard_changes;
2281         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2282         is( $lost_fee_line->accounttype,
2283             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2284
2285         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2286         is( $credit_return->amount + 0,
2287             ($payment_amount + $outstanding ) * -1,
2288             'The account line of type CR has an amount equal to the payment + outstanding'
2289         );
2290         is( $credit_return->amountoutstanding + 0,
2291             $payment_amount * -1,
2292             'The account line of type CR has an amountoutstanding equal to the payment'
2293         );
2294
2295         is( $account->balance,
2296             $processfee_amount - $payment_amount,
2297             'The patron balance is the difference between the PF and the credit'
2298         );
2299     };
2300 };
2301
2302 subtest '_FixOverduesOnReturn' => sub {
2303     plan tests => 10;
2304
2305     # Generate test biblio
2306     my $title  = 'Koha for Dummies';
2307     my ( $biblionumber, $biblioitemnumber ) = add_biblio($title, 'Hall, Kylie');
2308
2309     my $barcode = 'KD987654321';
2310     my $branchcode  = $library2->{branchcode};
2311
2312     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
2313         {
2314             homebranch       => $branchcode,
2315             holdingbranch    => $branchcode,
2316             barcode          => $barcode,
2317             replacementprice => 99.00,
2318             itype            => $itemtype
2319         },
2320         $biblionumber
2321     );
2322
2323     my $patron = $builder->build( { source => 'Borrower' } );
2324
2325     ## Start with basic call, should just close out the open fine
2326     my $accountline = Koha::Account::Line->new(
2327         {
2328             borrowernumber => $patron->{borrowernumber},
2329             accounttype    => 'FU',
2330             itemnumber     => $itemnumber,
2331             amount => 99.00,
2332             amountoutstanding => 99.00,
2333             lastincrement => 9.00,
2334         }
2335     )->store();
2336
2337     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber );
2338
2339     $accountline->_result()->discard_changes();
2340
2341     is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2342     is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2343
2344
2345     ## Run again, with exemptfine enabled
2346     $accountline->set(
2347         {
2348             accounttype    => 'FU',
2349             amountoutstanding => 99.00,
2350         }
2351     )->store();
2352
2353     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber, 1 );
2354
2355     $accountline->_result()->discard_changes();
2356     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2357
2358     is( $accountline->amountoutstanding + 0, 0, 'Fine has been reduced to 0' );
2359     is( $accountline->accounttype, 'FFOR', 'Open fine ( account type FU ) has been set to fine forgiven ( account type FFOR )');
2360     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2361     is( $offset->amount, '-99.000000', "Amount of offset is correct" );
2362
2363     ## Run again, with dropbox mode enabled
2364     $accountline->set(
2365         {
2366             accounttype    => 'FU',
2367             amountoutstanding => 99.00,
2368         }
2369     )->store();
2370
2371     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber, 0, 1 );
2372
2373     $accountline->_result()->discard_changes();
2374     $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Dropbox' })->next();
2375
2376     is( $accountline->amountoutstanding + 0, 90, 'Fine has been reduced to 90' );
2377     is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2378     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via dropbox" );
2379     is( $offset->amount, '-9.000000', "Amount of offset is correct" );
2380 };
2381
2382 subtest 'Set waiting flag' => sub {
2383     plan tests => 4;
2384
2385     my $library_1 = $builder->build( { source => 'Branch' } );
2386     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2387     my $library_2 = $builder->build( { source => 'Branch' } );
2388     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2389
2390     my $biblio = $builder->build( { source => 'Biblio' } );
2391     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2392
2393     my $item = $builder->build(
2394         {
2395             source => 'Item',
2396             value  => {
2397                 homebranch    => $library_1->{branchcode},
2398                 holdingbranch => $library_1->{branchcode},
2399                 notforloan    => 0,
2400                 itemlost      => 0,
2401                 withdrawn     => 0,
2402                 biblionumber  => $biblioitem->{biblionumber},
2403             }
2404         }
2405     );
2406
2407     set_userenv( $library_2 );
2408     my $reserve_id = AddReserve(
2409         $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
2410         '', 1, undef, undef, '', undef, $item->{itemnumber},
2411     );
2412
2413     set_userenv( $library_1 );
2414     my $do_transfer = 1;
2415     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2416     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2417     my $hold = Koha::Holds->find( $reserve_id );
2418     is( $hold->found, 'T', 'Hold is in transit' );
2419
2420     my ( $status ) = CheckReserves($item->{itemnumber});
2421     is( $status, 'Reserved', 'Hold is not waiting yet');
2422
2423     set_userenv( $library_2 );
2424     $do_transfer = 0;
2425     AddReturn( $item->{barcode}, $library_2->{branchcode} );
2426     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2427     $hold = Koha::Holds->find( $reserve_id );
2428     is( $hold->found, 'W', 'Hold is waiting' );
2429     ( $status ) = CheckReserves($item->{itemnumber});
2430     is( $status, 'Waiting', 'Now the hold is waiting');
2431 };
2432
2433 subtest 'Cancel transfers on lost items' => sub {
2434     plan tests => 5;
2435     my $library_1 = $builder->build( { source => 'Branch' } );
2436     my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2437     my $library_2 = $builder->build( { source => 'Branch' } );
2438     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2439     my $biblio = $builder->build( { source => 'Biblio' } );
2440     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2441     my $item = $builder->build(
2442         {
2443             source => 'Item',
2444             value => {
2445                 homebranch => $library_1->{branchcode},
2446                 holdingbranch => $library_1->{branchcode},
2447                 notforloan => 0,
2448                 itemlost => 0,
2449                 withdrawn => 0,
2450                 biblionumber => $biblioitem->{biblionumber},
2451             }
2452         }
2453     );
2454
2455     set_userenv( $library_2 );
2456     my $reserve_id = AddReserve(
2457         $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber}, '', 1, undef, undef, '', undef, $item->{itemnumber},
2458     );
2459
2460     #Return book and add transfer
2461     set_userenv( $library_1 );
2462     my $do_transfer = 1;
2463     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2464     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2465     C4::Circulation::transferbook( $library_2->{branchcode}, $item->{barcode} );
2466     my $hold = Koha::Holds->find( $reserve_id );
2467     is( $hold->found, 'T', 'Hold is in transit' );
2468
2469     #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2470     my ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2471     is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2472     my $itemcheck = GetItem($item->{itemnumber});
2473     is( $itemcheck->{holdingbranch}, $library_2->{branchcode}, 'Items holding branch is the transfers destination branch before it is marked as lost' );
2474
2475     #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2476     ModItem( { itemlost => 1 }, $biblio->{biblionumber}, $item->{itemnumber} );
2477     LostItem( $item->{itemnumber}, 'test', 1 );
2478     ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2479     is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2480     $itemcheck = GetItem($item->{itemnumber});
2481     is( $itemcheck->{holdingbranch}, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2482 };
2483
2484 subtest 'CanBookBeIssued | is_overdue' => sub {
2485     plan tests => 3;
2486
2487     # Set a simple circ policy
2488     $dbh->do('DELETE FROM issuingrules');
2489     $dbh->do(
2490     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2491                                     maxissueqty, issuelength, lengthunit,
2492                                     renewalsallowed, renewalperiod,
2493                                     norenewalbefore, auto_renew,
2494                                     fine, chargeperiod)
2495           VALUES (?, ?, ?, ?,
2496                   ?, ?, ?,
2497                   ?, ?,
2498                   ?, ?,
2499                   ?, ?
2500                  )
2501         },
2502         {},
2503         '*',   '*', '*', 25,
2504         1,     14,  'days',
2505         1,     7,
2506         undef, 0,
2507         .10,   1
2508     );
2509
2510     my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2511     my $ten_days_go  = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2512     my $library = $builder->build( { source => 'Branch' } );
2513     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2514
2515     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2516     my $item = $builder->build(
2517         {
2518             source => 'Item',
2519             value  => {
2520                 homebranch    => $library->{branchcode},
2521                 holdingbranch => $library->{branchcode},
2522                 notforloan    => 0,
2523                 itemlost      => 0,
2524                 withdrawn     => 0,
2525                 biblionumber  => $biblioitem->{biblionumber},
2526             }
2527         }
2528     );
2529
2530     my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2531     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2532     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2533     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2534     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2535     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2536 };
2537
2538 subtest 'ItemsDeniedRenewal preference' => sub {
2539     plan tests => 18;
2540
2541     C4::Context->set_preference('ItemsDeniedRenewal','');
2542
2543     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2544     $dbh->do(
2545         q{
2546         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
2547                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2548         },
2549         {},
2550         '*', $idr_lib->branchcode, '*', 25,
2551         20,  14,  'days',
2552         10,   7,
2553         undef,  0,
2554         .10, 1
2555     );
2556
2557     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2558         homebranch => $idr_lib->branchcode,
2559         withdrawn => 1,
2560         itype => 'HIDE',
2561         location => 'PROC',
2562         itemcallnumber => undef,
2563         itemnotes => "",
2564         }
2565     });
2566     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2567         homebranch => $idr_lib->branchcode,
2568         withdrawn => 0,
2569         itype => 'NOHIDE',
2570         location => 'NOPROC'
2571         }
2572     });
2573
2574     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2575         branchcode => $idr_lib->branchcode,
2576         }
2577     });
2578     my $future = dt_from_string->add( days => 1 );
2579     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2580         returndate => undef,
2581         renewals => 0,
2582         auto_renew => 0,
2583         borrowernumber => $idr_borrower->borrowernumber,
2584         itemnumber => $deny_book->itemnumber,
2585         onsite_checkout => 0,
2586         date_due => $future,
2587         }
2588     });
2589     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2590         returndate => undef,
2591         renewals => 0,
2592         auto_renew => 0,
2593         borrowernumber => $idr_borrower->borrowernumber,
2594         itemnumber => $allow_book->itemnumber,
2595         onsite_checkout => 0,
2596         date_due => $future,
2597         }
2598     });
2599
2600     my $idr_rules;
2601
2602     my ( $idr_mayrenew, $idr_error ) =
2603     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2604     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2605     is( $idr_error, undef, 'Renewal allowed when no rules' );
2606
2607     $idr_rules="withdrawn: [1]";
2608
2609     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2610     ( $idr_mayrenew, $idr_error ) =
2611     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2612     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2613     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2614     ( $idr_mayrenew, $idr_error ) =
2615     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2616     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2617     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2618
2619     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2620
2621     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2622     ( $idr_mayrenew, $idr_error ) =
2623     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2624     is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2625     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2626     ( $idr_mayrenew, $idr_error ) =
2627     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2628     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2629     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2630
2631     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2632
2633     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2634     ( $idr_mayrenew, $idr_error ) =
2635     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2636     is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2637     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2638     ( $idr_mayrenew, $idr_error ) =
2639     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2640     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2641     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2642
2643     $idr_rules="itemcallnumber: [NULL]";
2644     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2645     ( $idr_mayrenew, $idr_error ) =
2646     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2647     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2648     $idr_rules="itemcallnumber: ['']";
2649     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2650     ( $idr_mayrenew, $idr_error ) =
2651     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2652     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2653
2654     $idr_rules="itemnotes: [NULL]";
2655     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2656     ( $idr_mayrenew, $idr_error ) =
2657     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2658     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2659     $idr_rules="itemnotes: ['']";
2660     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2661     ( $idr_mayrenew, $idr_error ) =
2662     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2663     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2664 };
2665
2666 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2667     plan tests => 2;
2668
2669     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2670     my $library = $builder->build( { source => 'Branch' } );
2671     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2672
2673     my $itemtype = $builder->build(
2674         {
2675             source => 'Itemtype',
2676             value  => { notforloan => undef, }
2677         }
2678     );
2679
2680     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { itemtype => $itemtype->{itemtype} } } );
2681     my $item = $builder->build_object(
2682         {
2683             class => 'Koha::Items',
2684             value  => {
2685                 homebranch    => $library->{branchcode},
2686                 holdingbranch => $library->{branchcode},
2687                 notforloan    => 0,
2688                 itemlost      => 0,
2689                 withdrawn     => 0,
2690                 biblionumber  => $biblioitem->{biblionumber},
2691                 biblioitemnumber => $biblioitem->{biblioitemnumber},
2692             }
2693         }
2694     )->store;
2695
2696     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2697     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2698     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2699 };
2700
2701 subtest 'CanBookBeIssued | notforloan' => sub {
2702     plan tests => 2;
2703
2704     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2705
2706     my $library = $builder->build( { source => 'Branch' } );
2707     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2708
2709     my $itemtype = $builder->build(
2710         {
2711             source => 'Itemtype',
2712             value  => { notforloan => undef, }
2713         }
2714     );
2715
2716     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2717     my $item = $builder->build_object(
2718         {
2719             class => 'Koha::Items',
2720             value  => {
2721                 homebranch    => $library->{branchcode},
2722                 holdingbranch => $library->{branchcode},
2723                 notforloan    => 0,
2724                 itemlost      => 0,
2725                 withdrawn     => 0,
2726                 itype         => $itemtype->{itemtype},
2727                 biblionumber  => $biblioitem->{biblionumber},
2728                 biblioitemnumber => $biblioitem->{biblioitemnumber},
2729             }
2730         }
2731     )->store;
2732
2733     my ( $issuingimpossible, $needsconfirmation );
2734
2735
2736     subtest 'item-level_itypes = 1' => sub {
2737         plan tests => 6;
2738
2739         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
2740         # Is for loan at item type and item level
2741         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2742         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2743         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2744
2745         # not for loan at item type level
2746         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2747         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2748         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2749         is_deeply(
2750             $issuingimpossible,
2751             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2752             'Item can not be issued, not for loan at item type level'
2753         );
2754
2755         # not for loan at item level
2756         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2757         $item->notforloan( 1 )->store;
2758         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2759         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2760         is_deeply(
2761             $issuingimpossible,
2762             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2763             'Item can not be issued, not for loan at item type level'
2764         );
2765     };
2766
2767     subtest 'item-level_itypes = 0' => sub {
2768         plan tests => 6;
2769
2770         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2771
2772         # We set another itemtype for biblioitem
2773         my $itemtype = $builder->build(
2774             {
2775                 source => 'Itemtype',
2776                 value  => { notforloan => undef, }
2777             }
2778         );
2779
2780         # for loan at item type and item level
2781         $item->notforloan(0)->store;
2782         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2783         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2784         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2785         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2786
2787         # not for loan at item type level
2788         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2789         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2790         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2791         is_deeply(
2792             $issuingimpossible,
2793             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2794             'Item can not be issued, not for loan at item type level'
2795         );
2796
2797         # not for loan at item level
2798         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2799         $item->notforloan( 1 )->store;
2800         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2801         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2802         is_deeply(
2803             $issuingimpossible,
2804             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2805             'Item can not be issued, not for loan at item type level'
2806         );
2807     };
2808
2809     # TODO test with AllowNotForLoanOverride = 1
2810 };
2811
2812 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
2813     plan tests => 1;
2814
2815     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
2816     my $item = $builder->build_object({ class => 'Koha::Items', value  => { onloan => '2018-01-01' }});
2817     AddReturn( $item->barcode, $item->homebranch );
2818     $item->discard_changes; # refresh
2819     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
2820 };
2821
2822 $schema->storage->txn_rollback;
2823 C4::Context->clear_syspref_cache();
2824 $cache->clear_from_cache('single_holidays');
2825
2826 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
2827
2828     plan tests => 12;
2829
2830     $schema->storage->txn_begin;
2831
2832     my $issuing_charges = 15;
2833     my $title   = 'A title';
2834     my $author  = 'Author, An';
2835     my $barcode = 'WHATARETHEODDS';
2836
2837     my $circ = Test::MockModule->new('C4::Circulation');
2838     $circ->mock(
2839         'GetIssuingCharges',
2840         sub {
2841             return $issuing_charges;
2842         }
2843     );
2844
2845     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
2846     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' });
2847     my $patron   = $builder->build_object({
2848         class => 'Koha::Patrons',
2849         value => { branchcode => $library->id }
2850     });
2851
2852     my ( $biblionumber, $biblioitemnumber ) = add_biblio( $title, $author );
2853     my ( undef, undef, $item_id ) = AddItem(
2854         {
2855             homebranch       => $library->id,
2856             holdingbranch    => $library->id,
2857             barcode          => $barcode,
2858             replacementprice => 23.00,
2859             itype            => $itemtype->id
2860         },
2861         $biblionumber
2862     );
2863     my $item = Koha::Items->find( $item_id );
2864
2865     my $items = Test::MockModule->new('C4::Items');
2866     $items->mock( GetItem => $item->unblessed );
2867     my $context = Test::MockModule->new('C4::Context');
2868     $context->mock( userenv => { branch => $library->id } );
2869
2870     # Check the item out
2871     AddIssue( $patron->unblessed, $item->barcode );
2872
2873     t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
2874     my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
2875     my $old_log_size = scalar( @{ GetLogs( $date, $date, undef, ["CIRCULATION"], ["RENEWAL"] ) } );
2876     AddRenewal( $patron->id, $item->id, $library->id );
2877     my $new_log_size = scalar( @{ GetLogs( $date, $date, undef, ["CIRCULATION"], ["RENEWAL"] ) } );
2878     is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
2879
2880     t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
2881     $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
2882     $old_log_size = scalar( @{ GetLogs( $date, $date, undef, ["CIRCULATION"], ["RENEWAL"] ) } );
2883     AddRenewal( $patron->id, $item->id, $library->id );
2884     $new_log_size = scalar( @{ GetLogs( $date, $date, undef, ["CIRCULATION"], ["RENEWAL"] ) } );
2885     is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
2886
2887     my $lines = Koha::Account::Lines->search({
2888         borrowernumber => $patron->id,
2889         itemnumber     => $item->id
2890     });
2891
2892     is( $lines->count, 3 );
2893
2894     my $line = $lines->next;
2895     is( $line->accounttype, 'Rent',       'The issuing charge generates an accountline' );
2896     is( $line->branchcode,  $library->id, 'AddIssuingCharge correctly sets branchcode' );
2897     is( $line->description, 'Rental',     'AddIssuingCharge set a hardcoded description for the accountline' );
2898
2899     $line = $lines->next;
2900     is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
2901     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
2902     is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
2903
2904     $line = $lines->next;
2905     is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
2906     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
2907     is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
2908
2909     $schema->storage->txn_rollback;
2910 };
2911
2912
2913 sub set_userenv {
2914     my ( $library ) = @_;
2915     t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
2916 }
2917
2918 sub str {
2919     my ( $error, $question, $alert ) = @_;
2920     my $s;
2921     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
2922     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
2923     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
2924     return $s;
2925 }
2926
2927 sub add_biblio {
2928     my ($title, $author) = @_;
2929
2930     my $marcflavour = C4::Context->preference('marcflavour');
2931
2932     my $biblio = MARC::Record->new();
2933     if ($title) {
2934         my $tag = $marcflavour eq 'UNIMARC' ? '200' : '245';
2935         $biblio->append_fields(
2936             MARC::Field->new($tag, ' ', ' ', a => $title),
2937         );
2938     }
2939
2940     if ($author) {
2941         my ($tag, $code) = $marcflavour eq 'UNIMARC' ? (200, 'f') : (100, 'a');
2942         $biblio->append_fields(
2943             MARC::Field->new($tag, ' ', ' ', $code => $author),
2944         );
2945     }
2946
2947     return AddBiblio($biblio, '');
2948 }
2949
2950 sub test_debarment_on_checkout {
2951     my ($params) = @_;
2952     my $item     = $params->{item};
2953     my $library  = $params->{library};
2954     my $patron   = $params->{patron};
2955     my $due_date = $params->{due_date} || dt_from_string;
2956     my $return_date = $params->{return_date} || dt_from_string;
2957     my $expected_expiration_date = $params->{expiration_date};
2958
2959     $expected_expiration_date = output_pref(
2960         {
2961             dt         => $expected_expiration_date,
2962             dateformat => 'sql',
2963             dateonly   => 1,
2964         }
2965     );
2966     my @caller      = caller;
2967     my $line_number = $caller[2];
2968     AddIssue( $patron, $item->{barcode}, $due_date );
2969
2970     my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode},
2971         undef, undef, $return_date );
2972     is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
2973         or diag('AddReturn returned message ' . Dumper $message );
2974     my $debarments = Koha::Patron::Debarments::GetDebarments(
2975         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2976     is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
2977
2978     is( $debarments->[0]->{expiration},
2979         $expected_expiration_date, 'Test at line ' . $line_number );
2980     Koha::Patron::Debarments::DelUniqueDebarment(
2981         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2982 }