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