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