Bug 16889: Add Koha::Objects->columns
[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 DateTime;
21 use t::lib::Mocks;
22 use C4::Biblio;
23 use C4::Branch;
24 use C4::Items;
25 use C4::Members;
26 use C4::Reserves;
27 use C4::Overdues qw(UpdateFine);
28 use Koha::DateUtils;
29 use Koha::Database;
30
31 use t::lib::TestBuilder;
32
33 use Test::More tests => 86;
34
35 BEGIN {
36     use_ok('C4::Circulation');
37 }
38
39 my $schema = Koha::Database->schema;
40 $schema->storage->txn_begin;
41 my $builder = t::lib::TestBuilder->new;
42 my $dbh = C4::Context->dbh;
43
44 # Start transaction
45 $dbh->{RaiseError} = 1;
46
47 # Start with a clean slate
48 $dbh->do('DELETE FROM issues');
49
50 my $library = $builder->build({
51     source => 'Branch',
52 });
53 my $library2 = $builder->build({
54     source => 'Branch',
55 });
56
57 my $CircControl = C4::Context->preference('CircControl');
58 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
59
60 my $item = {
61     homebranch => $library2->{branchcode},
62     holdingbranch => $library2->{branchcode}
63 };
64
65 my $borrower = {
66     branchcode => $library2->{branchcode}
67 };
68
69 # No userenv, PickupLibrary
70 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
71 is(
72     C4::Context->preference('CircControl'),
73     'PickupLibrary',
74     'CircControl changed to PickupLibrary'
75 );
76 is(
77     C4::Circulation::_GetCircControlBranch($item, $borrower),
78     $item->{$HomeOrHoldingBranch},
79     '_GetCircControlBranch returned item branch (no userenv defined)'
80 );
81
82 # No userenv, PatronLibrary
83 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
84 is(
85     C4::Context->preference('CircControl'),
86     'PatronLibrary',
87     'CircControl changed to PatronLibrary'
88 );
89 is(
90     C4::Circulation::_GetCircControlBranch($item, $borrower),
91     $borrower->{branchcode},
92     '_GetCircControlBranch returned borrower branch'
93 );
94
95 # No userenv, ItemHomeLibrary
96 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
97 is(
98     C4::Context->preference('CircControl'),
99     'ItemHomeLibrary',
100     'CircControl changed to ItemHomeLibrary'
101 );
102 is(
103     $item->{$HomeOrHoldingBranch},
104     C4::Circulation::_GetCircControlBranch($item, $borrower),
105     '_GetCircControlBranch returned item branch'
106 );
107
108 # Now, set a userenv
109 C4::Context->_new_userenv('xxx');
110 C4::Context->set_userenv(0,0,0,'firstname','surname', $library2->{branchcode}, 'Midway Public Library', '', '', '');
111 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
112
113 # Userenv set, PickupLibrary
114 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
115 is(
116     C4::Context->preference('CircControl'),
117     'PickupLibrary',
118     'CircControl changed to PickupLibrary'
119 );
120 is(
121     C4::Circulation::_GetCircControlBranch($item, $borrower),
122     $library2->{branchcode},
123     '_GetCircControlBranch returned current branch'
124 );
125
126 # Userenv set, PatronLibrary
127 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
128 is(
129     C4::Context->preference('CircControl'),
130     'PatronLibrary',
131     'CircControl changed to PatronLibrary'
132 );
133 is(
134     C4::Circulation::_GetCircControlBranch($item, $borrower),
135     $borrower->{branchcode},
136     '_GetCircControlBranch returned borrower branch'
137 );
138
139 # Userenv set, ItemHomeLibrary
140 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
141 is(
142     C4::Context->preference('CircControl'),
143     'ItemHomeLibrary',
144     'CircControl changed to ItemHomeLibrary'
145 );
146 is(
147     C4::Circulation::_GetCircControlBranch($item, $borrower),
148     $item->{$HomeOrHoldingBranch},
149     '_GetCircControlBranch returned item branch'
150 );
151
152 # Reset initial configuration
153 t::lib::Mocks::mock_preference('CircControl', $CircControl);
154 is(
155     C4::Context->preference('CircControl'),
156     $CircControl,
157     'CircControl reset to its initial value'
158 );
159
160 # Set a simple circ policy
161 $dbh->do('DELETE FROM issuingrules');
162 $dbh->do(
163     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
164                                 maxissueqty, issuelength, lengthunit,
165                                 renewalsallowed, renewalperiod,
166                                 norenewalbefore, auto_renew,
167                                 fine, chargeperiod)
168       VALUES (?, ?, ?, ?,
169               ?, ?, ?,
170               ?, ?,
171               ?, ?,
172               ?, ?
173              )
174     },
175     {},
176     '*', '*', '*', 25,
177     20, 14, 'days',
178     1, 7,
179     undef, 0,
180     .10, 1
181 );
182
183 # Test C4::Circulation::ProcessOfflinePayment
184 my $sth = C4::Context->dbh->prepare("SELECT COUNT(*) FROM accountlines WHERE amount = '-123.45' AND accounttype = 'Pay'");
185 $sth->execute();
186 my ( $original_count ) = $sth->fetchrow_array();
187
188 C4::Context->dbh->do("INSERT INTO borrowers ( cardnumber, surname, firstname, categorycode, branchcode ) VALUES ( '99999999999', 'Hall', 'Kyle', 'S', ? )", undef, $library2->{branchcode} );
189
190 C4::Circulation::ProcessOfflinePayment({ cardnumber => '99999999999', amount => '123.45' });
191
192 $sth->execute();
193 my ( $new_count ) = $sth->fetchrow_array();
194
195 ok( $new_count == $original_count  + 1, 'ProcessOfflinePayment makes payment correctly' );
196
197 C4::Context->dbh->do("DELETE FROM accountlines WHERE borrowernumber IN ( SELECT borrowernumber FROM borrowers WHERE cardnumber = '99999999999' )");
198 C4::Context->dbh->do("DELETE FROM borrowers WHERE cardnumber = '99999999999'");
199 C4::Context->dbh->do("DELETE FROM accountlines");
200 {
201 # CanBookBeRenewed tests
202
203     # Generate test biblio
204     my $biblio = MARC::Record->new();
205     my $title = 'Silence in the library';
206     $biblio->append_fields(
207         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
208         MARC::Field->new('245', ' ', ' ', a => $title),
209     );
210
211     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
212
213     my $barcode = 'R00000342';
214     my $branch = $library2->{branchcode};
215
216     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
217         {
218             homebranch       => $branch,
219             holdingbranch    => $branch,
220             barcode          => $barcode,
221             replacementprice => 12.00
222         },
223         $biblionumber
224     );
225
226     my $barcode2 = 'R00000343';
227     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
228         {
229             homebranch       => $branch,
230             holdingbranch    => $branch,
231             barcode          => $barcode2,
232             replacementprice => 23.00
233         },
234         $biblionumber
235     );
236
237     my $barcode3 = 'R00000346';
238     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
239         {
240             homebranch       => $branch,
241             holdingbranch    => $branch,
242             barcode          => $barcode3,
243             replacementprice => 23.00
244         },
245         $biblionumber
246     );
247
248
249
250
251     # Create borrowers
252     my %renewing_borrower_data = (
253         firstname =>  'John',
254         surname => 'Renewal',
255         categorycode => 'S',
256         branchcode => $branch,
257     );
258
259     my %reserving_borrower_data = (
260         firstname =>  'Katrin',
261         surname => 'Reservation',
262         categorycode => 'S',
263         branchcode => $branch,
264     );
265
266     my %hold_waiting_borrower_data = (
267         firstname =>  'Kyle',
268         surname => 'Reservation',
269         categorycode => 'S',
270         branchcode => $branch,
271     );
272
273     my %restricted_borrower_data = (
274         firstname =>  'Alice',
275         surname => 'Reservation',
276         categorycode => 'S',
277         debarred => '3228-01-01',
278         branchcode => $branch,
279     );
280
281     my $renewing_borrowernumber = AddMember(%renewing_borrower_data);
282     my $reserving_borrowernumber = AddMember(%reserving_borrower_data);
283     my $hold_waiting_borrowernumber = AddMember(%hold_waiting_borrower_data);
284     my $restricted_borrowernumber = AddMember(%restricted_borrower_data);
285
286     my $renewing_borrower = GetMember( borrowernumber => $renewing_borrowernumber );
287     my $restricted_borrower = GetMember( borrowernumber => $restricted_borrowernumber );
288
289     my $bibitems       = '';
290     my $priority       = '1';
291     my $resdate        = undef;
292     my $expdate        = undef;
293     my $notes          = '';
294     my $checkitem      = undef;
295     my $found          = undef;
296
297     my $issue = AddIssue( $renewing_borrower, $barcode);
298     my $datedue = dt_from_string( $issue->date_due() );
299     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
300
301     my $issue2 = AddIssue( $renewing_borrower, $barcode2);
302     $datedue = dt_from_string( $issue->date_due() );
303     is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
304
305
306     my $borrowing_borrowernumber = GetItemIssue($itemnumber)->{borrowernumber};
307     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
308
309     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
310     is( $renewokay, 1, 'Can renew, no holds for this title or item');
311
312
313     # Biblio-level hold, renewal test
314     AddReserve(
315         $branch, $reserving_borrowernumber, $biblionumber,
316         $bibitems,  $priority, $resdate, $expdate, $notes,
317         $title, $checkitem, $found
318     );
319
320     # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
321     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
322     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
323     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
324     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
325     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
326     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
327
328     # Now let's add an item level hold, we should no longer be able to renew the item
329     my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
330         {
331             borrowernumber => $hold_waiting_borrowernumber,
332             biblionumber   => $biblionumber,
333             itemnumber     => $itemnumber,
334             branchcode     => $branch,
335             priority       => 3,
336         }
337     );
338     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
339     is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
340     $hold->delete();
341
342     # 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
343     # be able to renew these items
344     $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
345         {
346             borrowernumber => $hold_waiting_borrowernumber,
347             biblionumber   => $biblionumber,
348             itemnumber     => $itemnumber3,
349             branchcode     => $branch,
350             priority       => 0,
351             found          => 'W'
352         }
353     );
354     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
355     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
356     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
357     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
358     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
359
360     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
361     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
362     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
363
364     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
365     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
366     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
367
368     my $reserveid = C4::Reserves::GetReserveId({ biblionumber => $biblionumber, borrowernumber => $reserving_borrowernumber});
369     my $reserving_borrower = GetMember( borrowernumber => $reserving_borrowernumber );
370     AddIssue($reserving_borrower, $barcode3);
371     my $reserve = $dbh->selectrow_hashref(
372         'SELECT * FROM old_reserves WHERE reserve_id = ?',
373         { Slice => {} },
374         $reserveid
375     );
376     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
377
378     # Item-level hold, renewal test
379     AddReserve(
380         $branch, $reserving_borrowernumber, $biblionumber,
381         $bibitems,  $priority, $resdate, $expdate, $notes,
382         $title, $itemnumber, $found
383     );
384
385     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
386     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
387     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
388
389     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2, 1);
390     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
391
392     # Items can't fill hold for reasons
393     ModItem({ notforloan => 1 }, $biblionumber, $itemnumber);
394     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
395     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
396     ModItem({ notforloan => 0, itype => '' }, $biblionumber, $itemnumber,1);
397
398     # FIXME: Add more for itemtype not for loan etc.
399
400     # Restricted users cannot renew when RestrictionBlockRenewing is enabled
401     my $barcode5 = 'R00000347';
402     my ( $item_bibnum5, $item_bibitemnum5, $itemnumber5 ) = AddItem(
403         {
404             homebranch       => $branch,
405             holdingbranch    => $branch,
406             barcode          => $barcode5,
407             replacementprice => 23.00
408         },
409         $biblionumber
410     );
411     my $datedue5 = AddIssue($restricted_borrower, $barcode5);
412     is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
413
414     t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
415     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
416     is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
417     ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $itemnumber5);
418     is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
419
420     # Users cannot renew an overdue item
421     my $barcode6 = 'R00000348';
422     my ( $item_bibnum6, $item_bibitemnum6, $itemnumber6 ) = AddItem(
423         {
424             homebranch       => $branch,
425             holdingbranch    => $branch,
426             barcode          => $barcode6,
427             replacementprice => 23.00
428         },
429         $biblionumber
430     );
431
432     my $barcode7 = 'R00000349';
433     my ( $item_bibnum7, $item_bibitemnum7, $itemnumber7 ) = AddItem(
434         {
435             homebranch       => $branch,
436             holdingbranch    => $branch,
437             barcode          => $barcode7,
438             replacementprice => 23.00
439         },
440         $biblionumber
441     );
442     my $datedue6 = AddIssue( $renewing_borrower, $barcode6);
443     is (defined $datedue6, 1, "Item 2 checked out, due date: $datedue6");
444
445     my $passeddatedue1 = AddIssue($renewing_borrower, $barcode7, DateTime->from_epoch(epoch => 1));
446     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: $passeddatedue1");
447
448
449     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
450     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
451     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
452     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
453     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
454
455
456     $reserveid = C4::Reserves::GetReserveId({ biblionumber => $biblionumber, itemnumber => $itemnumber, borrowernumber => $reserving_borrowernumber});
457     CancelReserve({ reserve_id => $reserveid });
458
459     # Bug 14101
460     # Test automatic renewal before value for "norenewalbefore" in policy is set
461     # In this case automatic renewal is not permitted prior to due date
462     my $barcode4 = '11235813';
463     my ( $item_bibnum4, $item_bibitemnum4, $itemnumber4 ) = AddItem(
464         {
465             homebranch       => $branch,
466             holdingbranch    => $branch,
467             barcode          => $barcode4,
468             replacementprice => 16.00
469         },
470         $biblionumber
471     );
472
473     $issue = AddIssue( $renewing_borrower, $barcode4, undef, undef, undef, undef, { auto_renew => 1 } );
474     ( $renewokay, $error ) =
475       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
476     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
477     is( $error, 'auto_too_soon',
478         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
479
480     # Bug 7413
481     # Test premature manual renewal
482     $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
483
484     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
485     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
486     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
487
488     # Bug 14395
489     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
490     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
491     is(
492         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
493         $datedue->clone->add( days => -7 ),
494         'Bug 14395: Renewals permitted 7 days before due date, as expected'
495     );
496
497     # Bug 14395
498     # Test 'date' setting for syspref NoRenewalBeforePrecision
499     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
500     is(
501         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
502         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
503         'Bug 14395: Renewals permitted 7 days before due date, as expected'
504     );
505
506     # Bug 14101
507     # Test premature automatic renewal
508     ( $renewokay, $error ) =
509       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
510     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
511     is( $error, 'auto_too_soon',
512         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
513     );
514
515     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
516     # and test automatic renewal again
517     $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
518     ( $renewokay, $error ) =
519       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
520     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
521     is( $error, 'auto_too_soon',
522         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
523     );
524
525     # Change policy so that loans can be renewed 99 days prior to the due date
526     # and test automatic renewal again
527     $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
528     ( $renewokay, $error ) =
529       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
530     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
531     is( $error, 'auto_renew',
532         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
533     );
534
535     # Too many renewals
536
537     # set policy to forbid renewals
538     $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
539
540     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
541     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
542     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
543
544     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
545     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
546     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
547
548     C4::Overdues::UpdateFine(
549         {
550             issue_id       => $issue->id(),
551             itemnumber     => $itemnumber,
552             borrowernumber => $renewing_borrower->{borrowernumber},
553             amount         => 15.00,
554             type           => q{},
555             due            => Koha::DateUtils::output_pref($datedue)
556         }
557     );
558
559     LostItem( $itemnumber, 1 );
560
561     my $item = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber);
562     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
563
564     my $total_due = $dbh->selectrow_array(
565         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
566         undef, $renewing_borrower->{borrowernumber}
567     );
568
569     ok( $total_due == 12, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
570
571     C4::Context->dbh->do("DELETE FROM accountlines");
572
573     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
574     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
575
576     C4::Overdues::UpdateFine(
577         {
578             issue_id       => $issue2->id(),
579             itemnumber     => $itemnumber2,
580             borrowernumber => $renewing_borrower->{borrowernumber},
581             amount         => 15.00,
582             type           => q{},
583             due            => Koha::DateUtils::output_pref($datedue)
584         }
585     );
586
587     LostItem( $itemnumber2, 0 );
588
589     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
590     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
591
592     $total_due = $dbh->selectrow_array(
593         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
594         undef, $renewing_borrower->{borrowernumber}
595     );
596
597     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
598
599     my $now = dt_from_string();
600     my $future = dt_from_string();
601     $future->add( days => 7 );
602     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
603     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
604
605     # Users cannot renew any item if there is an overdue item
606     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
607     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
608     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
609     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
610     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
611
612   }
613
614 {
615     # GetUpcomingDueIssues tests
616     my $barcode  = 'R00000342';
617     my $barcode2 = 'R00000343';
618     my $barcode3 = 'R00000344';
619     my $branch   = $library2->{branchcode};
620
621     #Create another record
622     my $biblio2 = MARC::Record->new();
623     my $title2 = 'Something is worng here';
624     $biblio2->append_fields(
625         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
626         MARC::Field->new('245', ' ', ' ', a => $title2),
627     );
628     my ($biblionumber2, $biblioitemnumber2) = AddBiblio($biblio2, '');
629
630     #Create third item
631     AddItem(
632         {
633             homebranch       => $branch,
634             holdingbranch    => $branch,
635             barcode          => $barcode3
636         },
637         $biblionumber2
638     );
639
640     # Create a borrower
641     my %a_borrower_data = (
642         firstname =>  'Fridolyn',
643         surname => 'SOMERS',
644         categorycode => 'S',
645         branchcode => $branch,
646     );
647
648     my $a_borrower_borrowernumber = AddMember(%a_borrower_data);
649     my $a_borrower = GetMember( borrowernumber => $a_borrower_borrowernumber );
650
651     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
652     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
653     my $today = DateTime->today(time_zone => C4::Context->tz());
654
655     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
656     my $datedue = dt_from_string( $issue->date_due() );
657     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
658     my $datedue2 = dt_from_string( $issue->date_due() );
659
660     my $upcoming_dues;
661
662     # GetUpcomingDueIssues tests
663     for my $i(0..1) {
664         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
665         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
666     }
667
668     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
669     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
670     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
671
672     for my $i(3..5) {
673         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
674         is ( scalar( @$upcoming_dues ), 1,
675             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
676     }
677
678     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
679
680     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
681
682     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
683     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
684
685     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
686     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
687
688     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
689     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
690
691     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
692     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
693
694     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
695     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
696
697     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
698     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
699
700 }
701
702 {
703     my $barcode  = '1234567890';
704     my $branch   = $library2->{branchcode};
705
706     my $biblio = MARC::Record->new();
707     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
708
709     #Create third item
710     my ( undef, undef, $itemnumber ) = AddItem(
711         {
712             homebranch       => $branch,
713             holdingbranch    => $branch,
714             barcode          => $barcode
715         },
716         $biblionumber
717     );
718
719     # Create a borrower
720     my %a_borrower_data = (
721         firstname =>  'Kyle',
722         surname => 'Hall',
723         categorycode => 'S',
724         branchcode => $branch,
725     );
726
727     my $borrowernumber = AddMember(%a_borrower_data);
728
729     my $issue = AddIssue( GetMember( borrowernumber => $borrowernumber ), $barcode );
730     UpdateFine(
731         {
732             issue_id       => $issue->id(),
733             itemnumber     => $itemnumber,
734             borrowernumber => $borrowernumber,
735             amount         => 0
736         }
737     );
738
739     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
740     my $count = $hr->{count};
741
742     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
743 }
744
745 {
746     $dbh->do('DELETE FROM issues');
747     $dbh->do('DELETE FROM items');
748     $dbh->do('DELETE FROM issuingrules');
749     $dbh->do(
750         q{
751         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
752                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
753         },
754         {},
755         '*', '*', '*', 25,
756         20,  14,  'days',
757         1,   7,
758         undef,  0,
759         .10, 1
760     );
761     my $biblio = MARC::Record->new();
762     my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' );
763
764     my $barcode1 = '1234';
765     my ( undef, undef, $itemnumber1 ) = AddItem(
766         {
767             homebranch    => $library2->{branchcode},
768             holdingbranch => $library2->{branchcode},
769             barcode       => $barcode1,
770         },
771         $biblionumber
772     );
773     my $barcode2 = '4321';
774     my ( undef, undef, $itemnumber2 ) = AddItem(
775         {
776             homebranch    => $library2->{branchcode},
777             holdingbranch => $library2->{branchcode},
778             barcode       => $barcode2,
779         },
780         $biblionumber
781     );
782
783     my $borrowernumber1 = AddMember(
784         firstname    => 'Kyle',
785         surname      => 'Hall',
786         categorycode => 'S',
787         branchcode   => $library2->{branchcode},
788     );
789     my $borrowernumber2 = AddMember(
790         firstname    => 'Chelsea',
791         surname      => 'Hall',
792         categorycode => 'S',
793         branchcode   => $library2->{branchcode},
794     );
795
796     my $borrower1 = GetMember( borrowernumber => $borrowernumber1 );
797     my $borrower2 = GetMember( borrowernumber => $borrowernumber2 );
798
799     my $issue = AddIssue( $borrower1, $barcode1 );
800
801     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
802     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
803
804     AddReserve(
805         $library2->{branchcode}, $borrowernumber2, $biblionumber,
806         '',  1, undef, undef, '',
807         undef, undef, undef
808     );
809
810     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
811     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
812     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
813     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
814
815     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
816     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
817     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
818     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
819
820     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
821     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
822     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
823     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
824
825     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
826     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
827     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
828     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
829
830     # Setting item not checked out to be not for loan but holdable
831     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
832
833     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
834     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' );
835 }
836
837 {
838     # Don't allow renewing onsite checkout
839     my $barcode  = 'R00000XXX';
840     my $branch   = $library->{branchcode};
841
842     #Create another record
843     my $biblio = MARC::Record->new();
844     $biblio->append_fields(
845         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
846         MARC::Field->new('245', ' ', ' ', a => 'A title'),
847     );
848     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
849
850     my (undef, undef, $itemnumber) = AddItem(
851         {
852             homebranch       => $branch,
853             holdingbranch    => $branch,
854             barcode          => $barcode,
855         },
856         $biblionumber
857     );
858
859     my $borrowernumber = AddMember(
860         firstname =>  'fn',
861         surname => 'dn',
862         categorycode => 'S',
863         branchcode => $branch,
864     );
865
866     my $borrower = GetMember( borrowernumber => $borrowernumber );
867     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
868     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
869     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
870     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
871 }
872
873 {
874     my $library = $builder->build({ source => 'Branch' });
875
876     my $biblio = MARC::Record->new();
877     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
878
879     my $barcode = 'just a barcode';
880     my ( undef, undef, $itemnumber ) = AddItem(
881         {
882             homebranch       => $library->{branchcode},
883             holdingbranch    => $library->{branchcode},
884             barcode          => $barcode,
885         },
886         $biblionumber,
887     );
888
889     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode} } } );
890
891     my $issue = AddIssue( GetMember( borrowernumber => $patron->{borrowernumber} ), $barcode );
892     UpdateFine(
893         {
894             issue_id       => $issue->id(),
895             itemnumber     => $itemnumber,
896             borrowernumber => $patron->{borrowernumber},
897             amount         => 1,
898         }
899     );
900     UpdateFine(
901         {
902             issue_id       => $issue->id(),
903             itemnumber     => $itemnumber,
904             borrowernumber => $patron->{borrowernumber},
905             amount         => 2,
906         }
907     );
908     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
909 }
910
911 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
912     plan tests => 23;
913
914     my $homebranch    = $builder->build( { source => 'Branch' } );
915     my $holdingbranch = $builder->build( { source => 'Branch' } );
916     my $otherbranch   = $builder->build( { source => 'Branch' } );
917     my $patron_1      = $builder->build( { source => 'Borrower' } );
918     my $patron_2      = $builder->build( { source => 'Borrower' } );
919
920     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
921     my $item = $builder->build(
922         {   source => 'Item',
923             value  => {
924                 homebranch    => $homebranch->{branchcode},
925                 holdingbranch => $holdingbranch->{branchcode},
926                 notforloan    => 0,
927                 itemlost      => 0,
928                 withdrawn     => 0,
929                 biblionumber  => $biblioitem->{biblionumber}
930             }
931         }
932     );
933
934     set_userenv($holdingbranch);
935
936     my $issue = AddIssue( $patron_1, $item->{barcode} );
937     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Issue
938
939     my ( $error, $question, $alerts );
940
941     # AllowReturnToBranch == anywhere
942     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
943     ## Can be issued from homebranch
944     set_userenv($homebranch);
945     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
946     is( keys(%$error) + keys(%$alerts),        0 );
947     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
948     ## Can be issued from holdingbranch
949     set_userenv($holdingbranch);
950     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
951     is( keys(%$error) + keys(%$alerts),        0 );
952     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
953     ## Can be issued from another branch
954     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
955     is( keys(%$error) + keys(%$alerts),        0 );
956     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
957
958     # AllowReturnToBranch == holdingbranch
959     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
960     ## Cannot be issued from homebranch
961     set_userenv($homebranch);
962     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
963     is( keys(%$question) + keys(%$alerts),  0 );
964     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
965     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
966     ## Can be issued from holdinbranch
967     set_userenv($holdingbranch);
968     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
969     is( keys(%$error) + keys(%$alerts),        0 );
970     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
971     ## Cannot be issued from another branch
972     set_userenv($otherbranch);
973     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
974     is( keys(%$question) + keys(%$alerts),  0 );
975     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
976     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
977
978     # AllowReturnToBranch == homebranch
979     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
980     ## Can be issued from holdinbranch
981     set_userenv($homebranch);
982     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
983     is( keys(%$error) + keys(%$alerts),        0 );
984     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
985     ## Cannot be issued from holdinbranch
986     set_userenv($holdingbranch);
987     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
988     is( keys(%$question) + keys(%$alerts),  0 );
989     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
990     is( $error->{branch_to_return},         $homebranch->{branchcode} );
991     ## Cannot be issued from holdinbranch
992     set_userenv($otherbranch);
993     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
994     is( keys(%$question) + keys(%$alerts),  0 );
995     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
996     is( $error->{branch_to_return},         $homebranch->{branchcode} );
997
998     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
999 };
1000
1001 subtest 'AddIssue & AllowReturnToBranch' => sub {
1002     plan tests => 9;
1003
1004     my $homebranch    = $builder->build( { source => 'Branch' } );
1005     my $holdingbranch = $builder->build( { source => 'Branch' } );
1006     my $otherbranch   = $builder->build( { source => 'Branch' } );
1007     my $patron_1      = $builder->build( { source => 'Borrower' } );
1008     my $patron_2      = $builder->build( { source => 'Borrower' } );
1009
1010     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1011     my $item = $builder->build(
1012         {   source => 'Item',
1013             value  => {
1014                 homebranch    => $homebranch->{branchcode},
1015                 holdingbranch => $holdingbranch->{branchcode},
1016                 notforloan    => 0,
1017                 itemlost      => 0,
1018                 withdrawn     => 0,
1019                 biblionumber  => $biblioitem->{biblionumber}
1020             }
1021         }
1022     );
1023
1024     set_userenv($holdingbranch);
1025
1026     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Issue
1027     my $issue = AddIssue( $patron_1, $item->{barcode} );
1028
1029     my ( $error, $question, $alerts );
1030
1031     # AllowReturnToBranch == homebranch
1032     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1033     ## Can be issued from homebranch
1034     set_userenv($homebranch);
1035     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1036     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1037     ## Can be issued from holdinbranch
1038     set_userenv($holdingbranch);
1039     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1040     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1041     ## Can be issued from another branch
1042     set_userenv($otherbranch);
1043     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1044     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1045
1046     # AllowReturnToBranch == holdinbranch
1047     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1048     ## Cannot be issued from homebranch
1049     set_userenv($homebranch);
1050     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1051     ## Can be issued from holdingbranch
1052     set_userenv($holdingbranch);
1053     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1054     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1055     ## Cannot be issued from another branch
1056     set_userenv($otherbranch);
1057     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1058
1059     # AllowReturnToBranch == homebranch
1060     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1061     ## Can be issued from homebranch
1062     set_userenv($homebranch);
1063     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1064     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1065     ## Cannot be issued from holdinbranch
1066     set_userenv($holdingbranch);
1067     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1068     ## Cannot be issued from another branch
1069     set_userenv($otherbranch);
1070     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1071     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1072 };
1073
1074
1075 sub set_userenv {
1076     my ( $library ) = @_;
1077     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, $library->{branchname}, '', '', '');
1078 }
1079
1080 1;