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