Bug 14826: Unit Tests
[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
20 use Test::More tests => 103;
21
22 use DateTime;
23
24 use t::lib::Mocks;
25 use t::lib::TestBuilder;
26
27 use C4::Circulation;
28 use C4::Biblio;
29 use C4::Items;
30 use C4::Log;
31 use C4::Members;
32 use C4::Reserves;
33 use C4::Overdues qw(UpdateFine CalcFine);
34 use Koha::DateUtils;
35 use Koha::Database;
36 use Koha::IssuingRules;
37 use Koha::Checkouts;
38 use Koha::Patrons;
39 use Koha::Subscriptions;
40 use Koha::Account::Lines;
41 use Koha::Account::Offsets;
42
43 my $schema = Koha::Database->schema;
44 $schema->storage->txn_begin;
45 my $builder = t::lib::TestBuilder->new;
46 my $dbh = C4::Context->dbh;
47
48 # Start transaction
49 $dbh->{RaiseError} = 1;
50
51 # Start with a clean slate
52 $dbh->do('DELETE FROM issues');
53
54 my $library = $builder->build({
55     source => 'Branch',
56 });
57 my $library2 = $builder->build({
58     source => 'Branch',
59 });
60 my $itemtype = $builder->build(
61     {   source => 'Itemtype',
62         value  => { notforloan => undef, rentalcharge => 0 }
63     }
64 )->{itemtype};
65 my $patron_category = $builder->build({ source => 'Category', value => { categorycode => 'NOT_X', category_type => 'P', enrolmentfee => 0 } });
66
67 my $CircControl = C4::Context->preference('CircControl');
68 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
69
70 my $item = {
71     homebranch => $library2->{branchcode},
72     holdingbranch => $library2->{branchcode}
73 };
74
75 my $borrower = {
76     branchcode => $library2->{branchcode}
77 };
78
79 # No userenv, PickupLibrary
80 t::lib::Mocks::mock_preference('IndependentBranches', '0');
81 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
82 is(
83     C4::Context->preference('CircControl'),
84     'PickupLibrary',
85     'CircControl changed to PickupLibrary'
86 );
87 is(
88     C4::Circulation::_GetCircControlBranch($item, $borrower),
89     $item->{$HomeOrHoldingBranch},
90     '_GetCircControlBranch returned item branch (no userenv defined)'
91 );
92
93 # No userenv, PatronLibrary
94 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
95 is(
96     C4::Context->preference('CircControl'),
97     'PatronLibrary',
98     'CircControl changed to PatronLibrary'
99 );
100 is(
101     C4::Circulation::_GetCircControlBranch($item, $borrower),
102     $borrower->{branchcode},
103     '_GetCircControlBranch returned borrower branch'
104 );
105
106 # No userenv, ItemHomeLibrary
107 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
108 is(
109     C4::Context->preference('CircControl'),
110     'ItemHomeLibrary',
111     'CircControl changed to ItemHomeLibrary'
112 );
113 is(
114     $item->{$HomeOrHoldingBranch},
115     C4::Circulation::_GetCircControlBranch($item, $borrower),
116     '_GetCircControlBranch returned item branch'
117 );
118
119 # Now, set a userenv
120 C4::Context->_new_userenv('xxx');
121 C4::Context->set_userenv(0,0,0,'firstname','surname', $library2->{branchcode}, 'Midway Public Library', '', '', '');
122 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
123
124 # Userenv set, PickupLibrary
125 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
126 is(
127     C4::Context->preference('CircControl'),
128     'PickupLibrary',
129     'CircControl changed to PickupLibrary'
130 );
131 is(
132     C4::Circulation::_GetCircControlBranch($item, $borrower),
133     $library2->{branchcode},
134     '_GetCircControlBranch returned current branch'
135 );
136
137 # Userenv set, PatronLibrary
138 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
139 is(
140     C4::Context->preference('CircControl'),
141     'PatronLibrary',
142     'CircControl changed to PatronLibrary'
143 );
144 is(
145     C4::Circulation::_GetCircControlBranch($item, $borrower),
146     $borrower->{branchcode},
147     '_GetCircControlBranch returned borrower branch'
148 );
149
150 # Userenv set, ItemHomeLibrary
151 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
152 is(
153     C4::Context->preference('CircControl'),
154     'ItemHomeLibrary',
155     'CircControl changed to ItemHomeLibrary'
156 );
157 is(
158     C4::Circulation::_GetCircControlBranch($item, $borrower),
159     $item->{$HomeOrHoldingBranch},
160     '_GetCircControlBranch returned item branch'
161 );
162
163 # Reset initial configuration
164 t::lib::Mocks::mock_preference('CircControl', $CircControl);
165 is(
166     C4::Context->preference('CircControl'),
167     $CircControl,
168     'CircControl reset to its initial value'
169 );
170
171 # Set a simple circ policy
172 $dbh->do('DELETE FROM issuingrules');
173 $dbh->do(
174     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
175                                 maxissueqty, issuelength, lengthunit,
176                                 renewalsallowed, renewalperiod,
177                                 norenewalbefore, auto_renew,
178                                 fine, chargeperiod)
179       VALUES (?, ?, ?, ?,
180               ?, ?, ?,
181               ?, ?,
182               ?, ?,
183               ?, ?
184              )
185     },
186     {},
187     '*', '*', '*', 25,
188     20, 14, 'days',
189     1, 7,
190     undef, 0,
191     .10, 1
192 );
193
194 # Test C4::Circulation::ProcessOfflinePayment
195 my $sth = C4::Context->dbh->prepare("SELECT COUNT(*) FROM accountlines WHERE amount = '-123.45' AND accounttype = 'Pay'");
196 $sth->execute();
197 my ( $original_count ) = $sth->fetchrow_array();
198
199 C4::Context->dbh->do("INSERT INTO borrowers ( cardnumber, surname, firstname, categorycode, branchcode ) VALUES ( '99999999999', 'Hall', 'Kyle', ?, ? )", undef, $patron_category->{categorycode}, $library2->{branchcode} );
200
201 C4::Circulation::ProcessOfflinePayment({ cardnumber => '99999999999', amount => '123.45' });
202
203 $sth->execute();
204 my ( $new_count ) = $sth->fetchrow_array();
205
206 ok( $new_count == $original_count  + 1, 'ProcessOfflinePayment makes payment correctly' );
207
208 C4::Context->dbh->do("DELETE FROM accountlines WHERE borrowernumber IN ( SELECT borrowernumber FROM borrowers WHERE cardnumber = '99999999999' )");
209 C4::Context->dbh->do("DELETE FROM borrowers WHERE cardnumber = '99999999999'");
210 C4::Context->dbh->do("DELETE FROM accountlines");
211 {
212 # CanBookBeRenewed tests
213
214     # Generate test biblio
215     my $biblio = MARC::Record->new();
216     my $title = 'Silence in the library';
217     $biblio->append_fields(
218         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
219         MARC::Field->new('245', ' ', ' ', a => $title),
220     );
221
222     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
223
224     my $barcode = 'R00000342';
225     my $branch = $library2->{branchcode};
226
227     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
228         {
229             homebranch       => $branch,
230             holdingbranch    => $branch,
231             barcode          => $barcode,
232             replacementprice => 12.00,
233             itype            => $itemtype
234         },
235         $biblionumber
236     );
237
238     my $barcode2 = 'R00000343';
239     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
240         {
241             homebranch       => $branch,
242             holdingbranch    => $branch,
243             barcode          => $barcode2,
244             replacementprice => 23.00,
245             itype            => $itemtype
246         },
247         $biblionumber
248     );
249
250     my $barcode3 = 'R00000346';
251     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
252         {
253             homebranch       => $branch,
254             holdingbranch    => $branch,
255             barcode          => $barcode3,
256             replacementprice => 23.00,
257             itype            => $itemtype
258         },
259         $biblionumber
260     );
261
262
263
264
265     # Create borrowers
266     my %renewing_borrower_data = (
267         firstname =>  'John',
268         surname => 'Renewal',
269         categorycode => $patron_category->{categorycode},
270         branchcode => $branch,
271     );
272
273     my %reserving_borrower_data = (
274         firstname =>  'Katrin',
275         surname => 'Reservation',
276         categorycode => $patron_category->{categorycode},
277         branchcode => $branch,
278     );
279
280     my %hold_waiting_borrower_data = (
281         firstname =>  'Kyle',
282         surname => 'Reservation',
283         categorycode => $patron_category->{categorycode},
284         branchcode => $branch,
285     );
286
287     my %restricted_borrower_data = (
288         firstname =>  'Alice',
289         surname => 'Reservation',
290         categorycode => $patron_category->{categorycode},
291         debarred => '3228-01-01',
292         branchcode => $branch,
293     );
294
295     my $renewing_borrowernumber = AddMember(%renewing_borrower_data);
296     my $reserving_borrowernumber = AddMember(%reserving_borrower_data);
297     my $hold_waiting_borrowernumber = AddMember(%hold_waiting_borrower_data);
298     my $restricted_borrowernumber = AddMember(%restricted_borrower_data);
299
300     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
301     my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
302
303     my $bibitems       = '';
304     my $priority       = '1';
305     my $resdate        = undef;
306     my $expdate        = undef;
307     my $notes          = '';
308     my $checkitem      = undef;
309     my $found          = undef;
310
311     my $issue = AddIssue( $renewing_borrower, $barcode);
312     my $datedue = dt_from_string( $issue->date_due() );
313     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
314
315     my $issue2 = AddIssue( $renewing_borrower, $barcode2);
316     $datedue = dt_from_string( $issue->date_due() );
317     is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
318
319
320     my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $itemnumber } )->borrowernumber;
321     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
322
323     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
324     is( $renewokay, 1, 'Can renew, no holds for this title or item');
325
326
327     # Biblio-level hold, renewal test
328     AddReserve(
329         $branch, $reserving_borrowernumber, $biblionumber,
330         $bibitems,  $priority, $resdate, $expdate, $notes,
331         $title, $checkitem, $found
332     );
333
334     # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
335     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
336     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
337     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
338     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
339     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
340     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
341
342     # Now let's add an item level hold, we should no longer be able to renew the item
343     my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
344         {
345             borrowernumber => $hold_waiting_borrowernumber,
346             biblionumber   => $biblionumber,
347             itemnumber     => $itemnumber,
348             branchcode     => $branch,
349             priority       => 3,
350         }
351     );
352     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
353     is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
354     $hold->delete();
355
356     # 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
357     # be able to renew these items
358     $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
359         {
360             borrowernumber => $hold_waiting_borrowernumber,
361             biblionumber   => $biblionumber,
362             itemnumber     => $itemnumber3,
363             branchcode     => $branch,
364             priority       => 0,
365             found          => 'W'
366         }
367     );
368     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
369     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
370     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
371     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
372     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
373
374     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
375     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
376     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
377
378     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
379     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
380     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
381
382     my $reserveid = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
383     my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
384     AddIssue($reserving_borrower, $barcode3);
385     my $reserve = $dbh->selectrow_hashref(
386         'SELECT * FROM old_reserves WHERE reserve_id = ?',
387         { Slice => {} },
388         $reserveid
389     );
390     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
391
392     # Item-level hold, renewal test
393     AddReserve(
394         $branch, $reserving_borrowernumber, $biblionumber,
395         $bibitems,  $priority, $resdate, $expdate, $notes,
396         $title, $itemnumber, $found
397     );
398
399     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
400     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
401     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
402
403     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2, 1);
404     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
405
406     # Items can't fill hold for reasons
407     ModItem({ notforloan => 1 }, $biblionumber, $itemnumber);
408     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
409     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
410     ModItem({ notforloan => 0, itype => $itemtype }, $biblionumber, $itemnumber,1);
411
412     # FIXME: Add more for itemtype not for loan etc.
413
414     # Restricted users cannot renew when RestrictionBlockRenewing is enabled
415     my $barcode5 = 'R00000347';
416     my ( $item_bibnum5, $item_bibitemnum5, $itemnumber5 ) = AddItem(
417         {
418             homebranch       => $branch,
419             holdingbranch    => $branch,
420             barcode          => $barcode5,
421             replacementprice => 23.00,
422             itype            => $itemtype
423         },
424         $biblionumber
425     );
426     my $datedue5 = AddIssue($restricted_borrower, $barcode5);
427     is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
428
429     t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
430     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
431     is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
432     ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $itemnumber5);
433     is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
434
435     # Users cannot renew an overdue item
436     my $barcode6 = 'R00000348';
437     my ( $item_bibnum6, $item_bibitemnum6, $itemnumber6 ) = AddItem(
438         {
439             homebranch       => $branch,
440             holdingbranch    => $branch,
441             barcode          => $barcode6,
442             replacementprice => 23.00,
443             itype            => $itemtype
444         },
445         $biblionumber
446     );
447
448     my $barcode7 = 'R00000349';
449     my ( $item_bibnum7, $item_bibitemnum7, $itemnumber7 ) = AddItem(
450         {
451             homebranch       => $branch,
452             holdingbranch    => $branch,
453             barcode          => $barcode7,
454             replacementprice => 23.00,
455             itype            => $itemtype
456         },
457         $biblionumber
458     );
459     my $datedue6 = AddIssue( $renewing_borrower, $barcode6);
460     is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
461
462     my $now = dt_from_string();
463     my $five_weeks = DateTime::Duration->new(weeks => 5);
464     my $five_weeks_ago = $now - $five_weeks;
465     t::lib::Mocks::mock_preference('finesMode', 'production');
466
467     my $passeddatedue1 = AddIssue($renewing_borrower, $barcode7, $five_weeks_ago);
468     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
469
470     my ( $fine ) = CalcFine( GetItem(undef, $barcode7), $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
471     C4::Overdues::UpdateFine(
472         {
473             issue_id       => $passeddatedue1->id(),
474             itemnumber     => $itemnumber7,
475             borrowernumber => $renewing_borrower->{borrowernumber},
476             amount         => $fine,
477             type           => 'FU',
478             due            => Koha::DateUtils::output_pref($five_weeks_ago)
479         }
480     );
481
482     t::lib::Mocks::mock_preference('RenewalLog', 0);
483     my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
484     my $old_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
485     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
486     my $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
487     is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
488
489     t::lib::Mocks::mock_preference('RenewalLog', 1);
490     $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
491     $old_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
492     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
493     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
494     is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
495
496     my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $itemnumber7 } );
497     is( $fines->count, 2 );
498     is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
499     is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
500     $fines->delete();
501
502
503     my $old_issue_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["ISSUE"]) } );
504     my $old_renew_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
505     AddIssue( $renewing_borrower,$barcode7,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
506     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
507     is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
508     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["ISSUE"]) } );
509     is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
510
511     $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $itemnumber7 } );
512     $fines->delete();
513
514     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
515     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
516     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
517     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
518     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
519
520
521     $hold = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $reserving_borrowernumber })->next;
522     $hold->cancel;
523
524     # Bug 14101
525     # Test automatic renewal before value for "norenewalbefore" in policy is set
526     # In this case automatic renewal is not permitted prior to due date
527     my $barcode4 = '11235813';
528     my ( $item_bibnum4, $item_bibitemnum4, $itemnumber4 ) = AddItem(
529         {
530             homebranch       => $branch,
531             holdingbranch    => $branch,
532             barcode          => $barcode4,
533             replacementprice => 16.00,
534             itype            => $itemtype
535         },
536         $biblionumber
537     );
538
539     $issue = AddIssue( $renewing_borrower, $barcode4, undef, undef, undef, undef, { auto_renew => 1 } );
540     ( $renewokay, $error ) =
541       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
542     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
543     is( $error, 'auto_too_soon',
544         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
545
546     # Bug 7413
547     # Test premature manual renewal
548     $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
549
550     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
551     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
552     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
553
554     # Bug 14395
555     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
556     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
557     is(
558         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
559         $datedue->clone->add( days => -7 ),
560         'Bug 14395: Renewals permitted 7 days before due date, as expected'
561     );
562
563     # Bug 14395
564     # Test 'date' setting for syspref NoRenewalBeforePrecision
565     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
566     is(
567         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
568         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
569         'Bug 14395: Renewals permitted 7 days before due date, as expected'
570     );
571
572     # Bug 14101
573     # Test premature automatic renewal
574     ( $renewokay, $error ) =
575       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
576     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
577     is( $error, 'auto_too_soon',
578         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
579     );
580
581     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
582     # and test automatic renewal again
583     $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
584     ( $renewokay, $error ) =
585       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
586     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
587     is( $error, 'auto_too_soon',
588         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
589     );
590
591     # Change policy so that loans can be renewed 99 days prior to the due date
592     # and test automatic renewal again
593     $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
594     ( $renewokay, $error ) =
595       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
596     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
597     is( $error, 'auto_renew',
598         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
599     );
600
601     subtest "too_late_renewal / no_auto_renewal_after" => sub {
602         plan tests => 14;
603         my $item_to_auto_renew = $builder->build(
604             {   source => 'Item',
605                 value  => {
606                     biblionumber  => $biblionumber,
607                     homebranch    => $branch,
608                     holdingbranch => $branch,
609                 }
610             }
611         );
612
613         my $ten_days_before = dt_from_string->add( days => -10 );
614         my $ten_days_ahead  = dt_from_string->add( days => 10 );
615         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
616
617         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
618         ( $renewokay, $error ) =
619           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
620         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
621         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
622
623         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
624         ( $renewokay, $error ) =
625           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
626         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
627         is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
628
629         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
630         ( $renewokay, $error ) =
631           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
632         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
633         is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
634
635         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
636         ( $renewokay, $error ) =
637           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
638         is( $renewokay, 0,            'Do not renew, renewal is automatic' );
639         is( $error,     'auto_renew', 'Cannot renew, renew is automatic' );
640
641         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => -1 ) );
642         ( $renewokay, $error ) =
643           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
644         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
645         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
646
647         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => -1 ) );
648         ( $renewokay, $error ) =
649           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
650         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
651         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
652
653         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 1 ) );
654         ( $renewokay, $error ) =
655           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
656         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
657         is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
658     };
659
660     subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew" => sub {
661         plan tests => 6;
662         my $item_to_auto_renew = $builder->build({
663             source => 'Item',
664             value => {
665                 biblionumber => $biblionumber,
666                 homebranch       => $branch,
667                 holdingbranch    => $branch,
668             }
669         });
670
671         my $ten_days_before = dt_from_string->add( days => -10 );
672         my $ten_days_ahead = dt_from_string->add( days => 10 );
673         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
674
675         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
676         C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
677         C4::Context->set_preference('OPACFineNoRenewals','10');
678         my $fines_amount = 5;
679         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
680         ( $renewokay, $error ) =
681           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
682         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
683         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
684
685         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
686         ( $renewokay, $error ) =
687           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
688         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
689         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
690
691         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
692         ( $renewokay, $error ) =
693           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
694         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
695         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
696
697         $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
698     };
699
700     subtest "GetLatestAutoRenewDate" => sub {
701         plan tests => 5;
702         my $item_to_auto_renew = $builder->build(
703             {   source => 'Item',
704                 value  => {
705                     biblionumber  => $biblionumber,
706                     homebranch    => $branch,
707                     holdingbranch => $branch,
708                 }
709             }
710         );
711
712         my $ten_days_before = dt_from_string->add( days => -10 );
713         my $ten_days_ahead  = dt_from_string->add( days => 10 );
714         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
715         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = "", no_auto_renewal_after_hard_limit = NULL');
716         my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
717         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' );
718         my $five_days_before = dt_from_string->add( days => -5 );
719         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
720         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
721         is( $latest_auto_renew_date->truncate( to => 'minute' ),
722             $five_days_before->truncate( to => 'minute' ),
723             'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
724         );
725         my $five_days_ahead = dt_from_string->add( days => 5 );
726         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
727         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
728         is( $latest_auto_renew_date->truncate( to => 'minute' ),
729             $five_days_ahead->truncate( to => 'minute' ),
730             'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
731         );
732         my $two_days_ahead = dt_from_string->add( days => 2 );
733         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = "", no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 2 ) );
734         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
735         is( $latest_auto_renew_date->truncate( to => 'day' ),
736             $two_days_ahead->truncate( to => 'day' ),
737             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
738         );
739         $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 ) );
740         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
741         is( $latest_auto_renew_date->truncate( to => 'day' ),
742             $two_days_ahead->truncate( to => 'day' ),
743             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
744         );
745
746     };
747
748     # Too many renewals
749
750     # set policy to forbid renewals
751     $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
752
753     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
754     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
755     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
756
757     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
758     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
759     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
760
761     C4::Overdues::UpdateFine(
762         {
763             issue_id       => $issue->id(),
764             itemnumber     => $itemnumber,
765             borrowernumber => $renewing_borrower->{borrowernumber},
766             amount         => 15.00,
767             type           => q{},
768             due            => Koha::DateUtils::output_pref($datedue)
769         }
770     );
771
772     my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
773     is( $line->accounttype, 'FU', 'Account line type is FU' );
774     is( $line->lastincrement, '15.000000', 'Account line last increment is 15.00' );
775     is( $line->amountoutstanding, '15.000000', 'Account line amount outstanding is 15.00' );
776     is( $line->amount, '15.000000', 'Account line amount is 15.00' );
777     is( $line->issue_id, $issue->id, 'Account line issue id matches' );
778
779     my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
780     is( $offset->type, 'Fine', 'Account offset type is Fine' );
781     is( $offset->amount, '15.000000', 'Account offset amount is 15.00' );
782
783     LostItem( $itemnumber, 1 );
784
785     my $item = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber);
786     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
787
788     my $total_due = $dbh->selectrow_array(
789         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
790         undef, $renewing_borrower->{borrowernumber}
791     );
792
793     ok( $total_due == 12, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
794
795     C4::Context->dbh->do("DELETE FROM accountlines");
796
797     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
798     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
799
800     C4::Overdues::UpdateFine(
801         {
802             issue_id       => $issue2->id(),
803             itemnumber     => $itemnumber2,
804             borrowernumber => $renewing_borrower->{borrowernumber},
805             amount         => 15.00,
806             type           => q{},
807             due            => Koha::DateUtils::output_pref($datedue)
808         }
809     );
810
811     LostItem( $itemnumber2, 0 );
812
813     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
814     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
815
816     $total_due = $dbh->selectrow_array(
817         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
818         undef, $renewing_borrower->{borrowernumber}
819     );
820
821     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
822
823     my $future = dt_from_string();
824     $future->add( days => 7 );
825     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
826     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
827
828     # Users cannot renew any item if there is an overdue item
829     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
830     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
831     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
832     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
833     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
834
835   }
836
837 {
838     # GetUpcomingDueIssues tests
839     my $barcode  = 'R00000342';
840     my $barcode2 = 'R00000343';
841     my $barcode3 = 'R00000344';
842     my $branch   = $library2->{branchcode};
843
844     #Create another record
845     my $biblio2 = MARC::Record->new();
846     my $title2 = 'Something is worng here';
847     $biblio2->append_fields(
848         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
849         MARC::Field->new('245', ' ', ' ', a => $title2),
850     );
851     my ($biblionumber2, $biblioitemnumber2) = AddBiblio($biblio2, '');
852
853     #Create third item
854     AddItem(
855         {
856             homebranch       => $branch,
857             holdingbranch    => $branch,
858             barcode          => $barcode3,
859             itype            => $itemtype
860         },
861         $biblionumber2
862     );
863
864     # Create a borrower
865     my %a_borrower_data = (
866         firstname =>  'Fridolyn',
867         surname => 'SOMERS',
868         categorycode => $patron_category->{categorycode},
869         branchcode => $branch,
870     );
871
872     my $a_borrower_borrowernumber = AddMember(%a_borrower_data);
873     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
874
875     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
876     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
877     my $today = DateTime->today(time_zone => C4::Context->tz());
878
879     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
880     my $datedue = dt_from_string( $issue->date_due() );
881     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
882     my $datedue2 = dt_from_string( $issue->date_due() );
883
884     my $upcoming_dues;
885
886     # GetUpcomingDueIssues tests
887     for my $i(0..1) {
888         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
889         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
890     }
891
892     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
893     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
894     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
895
896     for my $i(3..5) {
897         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
898         is ( scalar( @$upcoming_dues ), 1,
899             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
900     }
901
902     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
903
904     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
905
906     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
907     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
908
909     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
910     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
911
912     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
913     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
914
915     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
916     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
917
918     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
919     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
920
921     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
922     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
923
924 }
925
926 {
927     my $barcode  = '1234567890';
928     my $branch   = $library2->{branchcode};
929
930     my $biblio = MARC::Record->new();
931     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
932
933     #Create third item
934     my ( undef, undef, $itemnumber ) = AddItem(
935         {
936             homebranch       => $branch,
937             holdingbranch    => $branch,
938             barcode          => $barcode,
939             itype            => $itemtype
940         },
941         $biblionumber
942     );
943
944     # Create a borrower
945     my %a_borrower_data = (
946         firstname =>  'Kyle',
947         surname => 'Hall',
948         categorycode => $patron_category->{categorycode},
949         branchcode => $branch,
950     );
951
952     my $borrowernumber = AddMember(%a_borrower_data);
953
954     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
955     my $issue = AddIssue( $borrower, $barcode );
956     UpdateFine(
957         {
958             issue_id       => $issue->id(),
959             itemnumber     => $itemnumber,
960             borrowernumber => $borrowernumber,
961             amount         => 0,
962             type           => q{}
963         }
964     );
965
966     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
967     my $count = $hr->{count};
968
969     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
970 }
971
972 {
973     $dbh->do('DELETE FROM issues');
974     $dbh->do('DELETE FROM items');
975     $dbh->do('DELETE FROM issuingrules');
976     $dbh->do(
977         q{
978         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
979                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
980         },
981         {},
982         '*', '*', '*', 25,
983         20,  14,  'days',
984         1,   7,
985         undef,  0,
986         .10, 1
987     );
988     my $biblio = MARC::Record->new();
989     my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' );
990
991     my $barcode1 = '1234';
992     my ( undef, undef, $itemnumber1 ) = AddItem(
993         {
994             homebranch    => $library2->{branchcode},
995             holdingbranch => $library2->{branchcode},
996             barcode       => $barcode1,
997             itype         => $itemtype
998         },
999         $biblionumber
1000     );
1001     my $barcode2 = '4321';
1002     my ( undef, undef, $itemnumber2 ) = AddItem(
1003         {
1004             homebranch    => $library2->{branchcode},
1005             holdingbranch => $library2->{branchcode},
1006             barcode       => $barcode2,
1007             itype         => $itemtype
1008         },
1009         $biblionumber
1010     );
1011
1012     my $borrowernumber1 = AddMember(
1013         firstname    => 'Kyle',
1014         surname      => 'Hall',
1015         categorycode => $patron_category->{categorycode},
1016         branchcode   => $library2->{branchcode},
1017     );
1018     my $borrowernumber2 = AddMember(
1019         firstname    => 'Chelsea',
1020         surname      => 'Hall',
1021         categorycode => $patron_category->{categorycode},
1022         branchcode   => $library2->{branchcode},
1023     );
1024
1025     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1026     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1027
1028     my $issue = AddIssue( $borrower1, $barcode1 );
1029
1030     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1031     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1032
1033     AddReserve(
1034         $library2->{branchcode}, $borrowernumber2, $biblionumber,
1035         '',  1, undef, undef, '',
1036         undef, undef, undef
1037     );
1038
1039     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1040     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1041     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1042     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1043
1044     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1045     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1046     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1047     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1048
1049     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1050     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1051     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1052     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1053
1054     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1055     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1056     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1057     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1058
1059     # Setting item not checked out to be not for loan but holdable
1060     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
1061
1062     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1063     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' );
1064 }
1065
1066 {
1067     # Don't allow renewing onsite checkout
1068     my $barcode  = 'R00000XXX';
1069     my $branch   = $library->{branchcode};
1070
1071     #Create another record
1072     my $biblio = MARC::Record->new();
1073     $biblio->append_fields(
1074         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
1075         MARC::Field->new('245', ' ', ' ', a => 'A title'),
1076     );
1077     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
1078
1079     my (undef, undef, $itemnumber) = AddItem(
1080         {
1081             homebranch       => $branch,
1082             holdingbranch    => $branch,
1083             barcode          => $barcode,
1084             itype            => $itemtype
1085         },
1086         $biblionumber
1087     );
1088
1089     my $borrowernumber = AddMember(
1090         firstname =>  'fn',
1091         surname => 'dn',
1092         categorycode => $patron_category->{categorycode},
1093         branchcode => $branch,
1094     );
1095
1096     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1097
1098     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1099     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
1100     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1101     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1102 }
1103
1104 {
1105     my $library = $builder->build({ source => 'Branch' });
1106
1107     my $biblio = MARC::Record->new();
1108     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
1109
1110     my $barcode = 'just a barcode';
1111     my ( undef, undef, $itemnumber ) = AddItem(
1112         {
1113             homebranch       => $library->{branchcode},
1114             holdingbranch    => $library->{branchcode},
1115             barcode          => $barcode,
1116             itype            => $itemtype
1117         },
1118         $biblionumber,
1119     );
1120
1121     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1122
1123     my $issue = AddIssue( $patron, $barcode );
1124     UpdateFine(
1125         {
1126             issue_id       => $issue->id(),
1127             itemnumber     => $itemnumber,
1128             borrowernumber => $patron->{borrowernumber},
1129             amount         => 1,
1130             type           => q{}
1131         }
1132     );
1133     UpdateFine(
1134         {
1135             issue_id       => $issue->id(),
1136             itemnumber     => $itemnumber,
1137             borrowernumber => $patron->{borrowernumber},
1138             amount         => 2,
1139             type           => q{}
1140         }
1141     );
1142     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1143 }
1144
1145 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1146     plan tests => 23;
1147
1148     my $homebranch    = $builder->build( { source => 'Branch' } );
1149     my $holdingbranch = $builder->build( { source => 'Branch' } );
1150     my $otherbranch   = $builder->build( { source => 'Branch' } );
1151     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1152     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1153
1154     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1155     my $item = $builder->build(
1156         {   source => 'Item',
1157             value  => {
1158                 homebranch    => $homebranch->{branchcode},
1159                 holdingbranch => $holdingbranch->{branchcode},
1160                 notforloan    => 0,
1161                 itemlost      => 0,
1162                 withdrawn     => 0,
1163                 restricted    => 0,
1164                 biblionumber  => $biblioitem->{biblionumber}
1165             }
1166         }
1167     );
1168
1169     set_userenv($holdingbranch);
1170
1171     my $issue = AddIssue( $patron_1, $item->{barcode} );
1172     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Checkout
1173
1174     my ( $error, $question, $alerts );
1175
1176     # AllowReturnToBranch == anywhere
1177     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1178     ## Can be issued from homebranch
1179     set_userenv($homebranch);
1180     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1181     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1182     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1183     ## Can be issued from holdingbranch
1184     set_userenv($holdingbranch);
1185     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1186     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1187     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1188     ## Can be issued from another branch
1189     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1190     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1191     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1192
1193     # AllowReturnToBranch == holdingbranch
1194     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1195     ## Cannot be issued from homebranch
1196     set_userenv($homebranch);
1197     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1198     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1199     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1200     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1201     ## Can be issued from holdinbranch
1202     set_userenv($holdingbranch);
1203     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1204     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1205     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1206     ## Cannot be issued from another branch
1207     set_userenv($otherbranch);
1208     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1209     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1210     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1211     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1212
1213     # AllowReturnToBranch == homebranch
1214     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1215     ## Can be issued from holdinbranch
1216     set_userenv($homebranch);
1217     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1218     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1219     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1220     ## Cannot be issued from holdinbranch
1221     set_userenv($holdingbranch);
1222     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1223     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1224     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1225     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1226     ## Cannot be issued from holdinbranch
1227     set_userenv($otherbranch);
1228     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1229     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1230     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1231     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1232
1233     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1234 };
1235
1236 subtest 'AddIssue & AllowReturnToBranch' => sub {
1237     plan tests => 9;
1238
1239     my $homebranch    = $builder->build( { source => 'Branch' } );
1240     my $holdingbranch = $builder->build( { source => 'Branch' } );
1241     my $otherbranch   = $builder->build( { source => 'Branch' } );
1242     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1243     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1244
1245     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1246     my $item = $builder->build(
1247         {   source => 'Item',
1248             value  => {
1249                 homebranch    => $homebranch->{branchcode},
1250                 holdingbranch => $holdingbranch->{branchcode},
1251                 notforloan    => 0,
1252                 itemlost      => 0,
1253                 withdrawn     => 0,
1254                 biblionumber  => $biblioitem->{biblionumber}
1255             }
1256         }
1257     );
1258
1259     set_userenv($holdingbranch);
1260
1261     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Checkout
1262     my $issue = AddIssue( $patron_1, $item->{barcode} );
1263
1264     my ( $error, $question, $alerts );
1265
1266     # AllowReturnToBranch == homebranch
1267     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1268     ## Can be issued from homebranch
1269     set_userenv($homebranch);
1270     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1271     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1272     ## Can be issued from holdinbranch
1273     set_userenv($holdingbranch);
1274     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1275     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1276     ## Can be issued from another branch
1277     set_userenv($otherbranch);
1278     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1279     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1280
1281     # AllowReturnToBranch == holdinbranch
1282     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1283     ## Cannot be issued from homebranch
1284     set_userenv($homebranch);
1285     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1286     ## Can be issued from holdingbranch
1287     set_userenv($holdingbranch);
1288     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1289     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1290     ## Cannot be issued from another branch
1291     set_userenv($otherbranch);
1292     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1293
1294     # AllowReturnToBranch == homebranch
1295     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1296     ## Can be issued from homebranch
1297     set_userenv($homebranch);
1298     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1299     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1300     ## Cannot be issued from holdinbranch
1301     set_userenv($holdingbranch);
1302     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1303     ## Cannot be issued from another branch
1304     set_userenv($otherbranch);
1305     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1306     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1307 };
1308
1309 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1310     plan tests => 8;
1311
1312     my $library = $builder->build( { source => 'Branch' } );
1313     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1314
1315     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1316     my $item_1 = $builder->build(
1317         {   source => 'Item',
1318             value  => {
1319                 homebranch    => $library->{branchcode},
1320                 holdingbranch => $library->{branchcode},
1321                 notforloan    => 0,
1322                 itemlost      => 0,
1323                 withdrawn     => 0,
1324                 restricted    => 0,
1325                 biblionumber  => $biblioitem_1->{biblionumber}
1326             }
1327         }
1328     );
1329     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1330     my $item_2 = $builder->build(
1331         {   source => 'Item',
1332             value  => {
1333                 homebranch    => $library->{branchcode},
1334                 holdingbranch => $library->{branchcode},
1335                 notforloan    => 0,
1336                 itemlost      => 0,
1337                 withdrawn     => 0,
1338                 restricted    => 0,
1339                 biblionumber  => $biblioitem_2->{biblionumber}
1340             }
1341         }
1342     );
1343
1344     my ( $error, $question, $alerts );
1345
1346     # Patron cannot issue item_1, they have overdues
1347     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1348     my $issue = AddIssue( $patron, $item_1->{barcode}, $yesterday );    # Add an overdue
1349
1350     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1351     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1352     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
1353     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1354
1355     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1356     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1357     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1358     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1359
1360     # Patron cannot issue item_1, they are debarred
1361     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1362     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber}, expiration => $tomorrow } );
1363     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1364     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1365     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1366
1367     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber} } );
1368     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1369     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1370     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1371 };
1372
1373 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1374     plan tests => 1;
1375
1376     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1377     my $patron_category_x = $builder->build_object(
1378         {
1379             class => 'Koha::Patron::Categories',
1380             value => { category_type => 'X' }
1381         }
1382     );
1383     my $patron = $builder->build_object(
1384         {
1385             class => 'Koha::Patrons',
1386             value => {
1387                 categorycode  => $patron_category_x->categorycode,
1388                 gonenoaddress => undef,
1389                 lost          => undef,
1390                 debarred      => undef,
1391                 borrowernotes => ""
1392             }
1393         }
1394     );
1395     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1396     my $item_1 = $builder->build(
1397         {
1398             source => 'Item',
1399             value  => {
1400                 homebranch    => $library->branchcode,
1401                 holdingbranch => $library->branchcode,
1402                 notforloan    => 0,
1403                 itemlost      => 0,
1404                 withdrawn     => 0,
1405                 restricted    => 0,
1406                 biblionumber  => $biblioitem_1->{biblionumber}
1407             }
1408         }
1409     );
1410
1411     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron->unblessed, $item_1->{barcode} );
1412     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1413
1414     # TODO There are other tests to provide here
1415 };
1416
1417 subtest 'MultipleReserves' => sub {
1418     plan tests => 3;
1419
1420     my $biblio = MARC::Record->new();
1421     my $title = 'Silence in the library';
1422     $biblio->append_fields(
1423         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
1424         MARC::Field->new('245', ' ', ' ', a => $title),
1425     );
1426
1427     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
1428
1429     my $branch = $library2->{branchcode};
1430
1431     my $barcode1 = 'R00110001';
1432     my ( $item_bibnum1, $item_bibitemnum1, $itemnumber1 ) = AddItem(
1433         {
1434             homebranch       => $branch,
1435             holdingbranch    => $branch,
1436             barcode          => $barcode1,
1437             replacementprice => 12.00,
1438             itype            => $itemtype
1439         },
1440         $biblionumber
1441     );
1442
1443     my $barcode2 = 'R00110002';
1444     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
1445         {
1446             homebranch       => $branch,
1447             holdingbranch    => $branch,
1448             barcode          => $barcode2,
1449             replacementprice => 12.00,
1450             itype            => $itemtype
1451         },
1452         $biblionumber
1453     );
1454
1455     my $bibitems       = '';
1456     my $priority       = '1';
1457     my $resdate        = undef;
1458     my $expdate        = undef;
1459     my $notes          = '';
1460     my $checkitem      = undef;
1461     my $found          = undef;
1462
1463     my %renewing_borrower_data = (
1464         firstname =>  'John',
1465         surname => 'Renewal',
1466         categorycode => $patron_category->{categorycode},
1467         branchcode => $branch,
1468     );
1469     my $renewing_borrowernumber = AddMember(%renewing_borrower_data);
1470     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1471     my $issue = AddIssue( $renewing_borrower, $barcode1);
1472     my $datedue = dt_from_string( $issue->date_due() );
1473     is (defined $issue->date_due(), 1, "item 1 checked out");
1474     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $itemnumber1 })->borrowernumber;
1475
1476     my %reserving_borrower_data1 = (
1477         firstname =>  'Katrin',
1478         surname => 'Reservation',
1479         categorycode => $patron_category->{categorycode},
1480         branchcode => $branch,
1481     );
1482     my $reserving_borrowernumber1 = AddMember(%reserving_borrower_data1);
1483     AddReserve(
1484         $branch, $reserving_borrowernumber1, $biblionumber,
1485         $bibitems,  $priority, $resdate, $expdate, $notes,
1486         $title, $checkitem, $found
1487     );
1488
1489     my %reserving_borrower_data2 = (
1490         firstname =>  'Kirk',
1491         surname => 'Reservation',
1492         categorycode => $patron_category->{categorycode},
1493         branchcode => $branch,
1494     );
1495     my $reserving_borrowernumber2 = AddMember(%reserving_borrower_data2);
1496     AddReserve(
1497         $branch, $reserving_borrowernumber2, $biblionumber,
1498         $bibitems,  $priority, $resdate, $expdate, $notes,
1499         $title, $checkitem, $found
1500     );
1501
1502     {
1503         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1504         is($renewokay, 0, 'Bug 17641 - should cover the case where 2 books are both reserved, so failing');
1505     }
1506
1507     my $barcode3 = 'R00110003';
1508     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
1509         {
1510             homebranch       => $branch,
1511             holdingbranch    => $branch,
1512             barcode          => $barcode3,
1513             replacementprice => 12.00,
1514             itype            => $itemtype
1515         },
1516         $biblionumber
1517     );
1518
1519     {
1520         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1521         is($renewokay, 1, 'Bug 17641 - should cover the case where 2 books are reserved, but a third one is available');
1522     }
1523 };
1524
1525 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1526     plan tests => 5;
1527
1528     my $library = $builder->build( { source => 'Branch' } );
1529     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1530
1531     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1532     my $biblionumber = $biblioitem->{biblionumber};
1533     my $item_1 = $builder->build(
1534         {   source => 'Item',
1535             value  => {
1536                 homebranch    => $library->{branchcode},
1537                 holdingbranch => $library->{branchcode},
1538                 notforloan    => 0,
1539                 itemlost      => 0,
1540                 withdrawn     => 0,
1541                 biblionumber  => $biblionumber,
1542             }
1543         }
1544     );
1545     my $item_2 = $builder->build(
1546         {   source => 'Item',
1547             value  => {
1548                 homebranch    => $library->{branchcode},
1549                 holdingbranch => $library->{branchcode},
1550                 notforloan    => 0,
1551                 itemlost      => 0,
1552                 withdrawn     => 0,
1553                 biblionumber  => $biblionumber,
1554             }
1555         }
1556     );
1557
1558     my ( $error, $question, $alerts );
1559     my $issue = AddIssue( $patron, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1560
1561     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1562     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1563     is( keys(%$error) + keys(%$alerts),  0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1564     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) );
1565
1566     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1567     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1568     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1569
1570     # Add a subscription
1571     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1572
1573     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1574     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1575     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) );
1576
1577     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1578     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1579     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) );
1580 };
1581
1582 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1583     plan tests => 8;
1584
1585     my $library = $builder->build( { source => 'Branch' } );
1586     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1587
1588     # Add 2 items
1589     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1590     my $item_1 = $builder->build(
1591         {
1592             source => 'Item',
1593             value  => {
1594                 homebranch    => $library->{branchcode},
1595                 holdingbranch => $library->{branchcode},
1596                 notforloan    => 0,
1597                 itemlost      => 0,
1598                 withdrawn     => 0,
1599                 biblionumber  => $biblioitem_1->{biblionumber}
1600             }
1601         }
1602     );
1603     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1604     my $item_2 = $builder->build(
1605         {
1606             source => 'Item',
1607             value  => {
1608                 homebranch    => $library->{branchcode},
1609                 holdingbranch => $library->{branchcode},
1610                 notforloan    => 0,
1611                 itemlost      => 0,
1612                 withdrawn     => 0,
1613                 biblionumber  => $biblioitem_2->{biblionumber}
1614             }
1615         }
1616     );
1617
1618     # And the issuing rule
1619     Koha::IssuingRules->search->delete;
1620     my $rule = Koha::IssuingRule->new(
1621         {
1622             categorycode => '*',
1623             itemtype     => '*',
1624             branchcode   => '*',
1625             maxissueqty  => 99,
1626             issuelength  => 1,
1627             firstremind  => 1,        # 1 day of grace
1628             finedays     => 2,        # 2 days of fine per day of overdue
1629             lengthunit   => 'days',
1630         }
1631     );
1632     $rule->store();
1633
1634     # Patron cannot issue item_1, they have overdues
1635     my $five_days_ago = dt_from_string->subtract( days => 5 );
1636     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1637     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1638     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1639       ;    # Add another overdue
1640
1641     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1642     AddReturn( $item_1->{barcode}, $library->{branchcode},
1643         undef, undef, dt_from_string );
1644     my $debarments = Koha::Patron::Debarments::GetDebarments(
1645         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1646     is( scalar(@$debarments), 1 );
1647
1648     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1649     # Same for the others
1650     my $expected_expiration = output_pref(
1651         {
1652             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1653             dateformat => 'sql',
1654             dateonly   => 1
1655         }
1656     );
1657     is( $debarments->[0]->{expiration}, $expected_expiration );
1658
1659     AddReturn( $item_2->{barcode}, $library->{branchcode},
1660         undef, undef, dt_from_string );
1661     $debarments = Koha::Patron::Debarments::GetDebarments(
1662         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1663     is( scalar(@$debarments), 1 );
1664     $expected_expiration = output_pref(
1665         {
1666             dt         => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1667             dateformat => 'sql',
1668             dateonly   => 1
1669         }
1670     );
1671     is( $debarments->[0]->{expiration}, $expected_expiration );
1672
1673     Koha::Patron::Debarments::DelUniqueDebarment(
1674         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1675
1676     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1677     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1678     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1679       ;    # Add another overdue
1680     AddReturn( $item_1->{barcode}, $library->{branchcode},
1681         undef, undef, dt_from_string );
1682     $debarments = Koha::Patron::Debarments::GetDebarments(
1683         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1684     is( scalar(@$debarments), 1 );
1685     $expected_expiration = output_pref(
1686         {
1687             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1688             dateformat => 'sql',
1689             dateonly   => 1
1690         }
1691     );
1692     is( $debarments->[0]->{expiration}, $expected_expiration );
1693
1694     AddReturn( $item_2->{barcode}, $library->{branchcode},
1695         undef, undef, dt_from_string );
1696     $debarments = Koha::Patron::Debarments::GetDebarments(
1697         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1698     is( scalar(@$debarments), 1 );
1699     $expected_expiration = output_pref(
1700         {
1701             dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1702             dateformat => 'sql',
1703             dateonly   => 1
1704         }
1705     );
1706     is( $debarments->[0]->{expiration}, $expected_expiration );
1707 };
1708
1709 subtest 'AddReturn | is_overdue' => sub {
1710     plan tests => 5;
1711
1712     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1713     t::lib::Mocks::mock_preference('finesMode', 'production');
1714     t::lib::Mocks::mock_preference('MaxFine', '100');
1715
1716     my $library = $builder->build( { source => 'Branch' } );
1717     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1718
1719     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1720     my $item = $builder->build(
1721         {
1722             source => 'Item',
1723             value  => {
1724                 homebranch    => $library->{branchcode},
1725                 holdingbranch => $library->{branchcode},
1726                 notforloan    => 0,
1727                 itemlost      => 0,
1728                 withdrawn     => 0,
1729                 biblionumber  => $biblioitem->{biblionumber},
1730             }
1731         }
1732     );
1733
1734     Koha::IssuingRules->search->delete;
1735     my $rule = Koha::IssuingRule->new(
1736         {
1737             categorycode => '*',
1738             itemtype     => '*',
1739             branchcode   => '*',
1740             maxissueqty  => 99,
1741             issuelength  => 6,
1742             lengthunit   => 'days',
1743             fine         => 1, # Charge 1 every day of overdue
1744             chargeperiod => 1,
1745         }
1746     );
1747     $rule->store();
1748
1749     my $one_day_ago   = dt_from_string->subtract( days => 1 );
1750     my $five_days_ago = dt_from_string->subtract( days => 5 );
1751     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1752     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1753
1754     # No date specify, today will be used
1755     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1756     AddReturn( $item->{barcode}, $library->{branchcode} );
1757     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
1758     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1759
1760     # specify return date 5 days before => no overdue
1761     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1762     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $ten_days_ago );
1763     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1764     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1765
1766     # specify return date 5 days later => overdue
1767     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1768     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $five_days_ago );
1769     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
1770     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1771
1772     # specify dropbox date 5 days before => no overdue
1773     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1774     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $ten_days_ago );
1775     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1776     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1777
1778     # specify dropbox date 5 days later => overdue, or... not
1779     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1780     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $five_days_ago );
1781     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
1782     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1783
1784 };
1785
1786 subtest 'Set waiting flag' => sub {
1787     plan tests => 4;
1788
1789     my $library_1 = $builder->build( { source => 'Branch' } );
1790     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1791     my $library_2 = $builder->build( { source => 'Branch' } );
1792     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1793
1794     my $biblio = $builder->build( { source => 'Biblio' } );
1795     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
1796
1797     my $item = $builder->build(
1798         {
1799             source => 'Item',
1800             value  => {
1801                 homebranch    => $library_1->{branchcode},
1802                 holdingbranch => $library_1->{branchcode},
1803                 notforloan    => 0,
1804                 itemlost      => 0,
1805                 withdrawn     => 0,
1806                 biblionumber  => $biblioitem->{biblionumber},
1807             }
1808         }
1809     );
1810
1811     set_userenv( $library_2 );
1812     my $reserve_id = AddReserve(
1813         $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
1814         '', 1, undef, undef, '', undef, $item->{itemnumber},
1815     );
1816
1817     set_userenv( $library_1 );
1818     my $do_transfer = 1;
1819     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
1820     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
1821     my $hold = Koha::Holds->find( $reserve_id );
1822     is( $hold->found, 'T', 'Hold is in transit' );
1823
1824     my ( $status ) = CheckReserves($item->{itemnumber});
1825     is( $status, 'Reserved', 'Hold is not waiting yet');
1826
1827     set_userenv( $library_2 );
1828     $do_transfer = 0;
1829     AddReturn( $item->{barcode}, $library_2->{branchcode} );
1830     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
1831     $hold = Koha::Holds->find( $reserve_id );
1832     is( $hold->found, 'W', 'Hold is waiting' );
1833     ( $status ) = CheckReserves($item->{itemnumber});
1834     is( $status, 'Waiting', 'Now the hold is waiting');
1835 };
1836
1837 subtest 'CanBookBeIssued | is_overdue' => sub {
1838     plan tests => 3;
1839
1840     # Set a simple circ policy
1841     $dbh->do('DELETE FROM issuingrules');
1842     $dbh->do(
1843     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
1844                                     maxissueqty, issuelength, lengthunit,
1845                                     renewalsallowed, renewalperiod,
1846                                     norenewalbefore, auto_renew,
1847                                     fine, chargeperiod)
1848           VALUES (?, ?, ?, ?,
1849                   ?, ?, ?,
1850                   ?, ?,
1851                   ?, ?,
1852                   ?, ?
1853                  )
1854         },
1855         {},
1856         '*',   '*', '*', 25,
1857         1,     14,  'days',
1858         1,     7,
1859         undef, 0,
1860         .10,   1
1861     );
1862
1863     my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
1864     my $ten_days_go  = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
1865     my $library = $builder->build( { source => 'Branch' } );
1866     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1867
1868     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1869     my $item = $builder->build(
1870         {
1871             source => 'Item',
1872             value  => {
1873                 homebranch    => $library->{branchcode},
1874                 holdingbranch => $library->{branchcode},
1875                 notforloan    => 0,
1876                 itemlost      => 0,
1877                 withdrawn     => 0,
1878                 biblionumber  => $biblioitem->{biblionumber},
1879             }
1880         }
1881     );
1882
1883     my $issue = AddIssue( $patron, $item->{barcode}, $five_days_go ); # date due was 10d ago
1884     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
1885     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
1886     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
1887     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
1888     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
1889
1890 };
1891
1892 sub set_userenv {
1893     my ( $library ) = @_;
1894     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, $library->{branchname}, '', '', '');
1895 }
1896
1897 sub str {
1898     my ( $error, $question, $alert ) = @_;
1899     my $s;
1900     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
1901     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
1902     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
1903     return $s;
1904 }