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