Bug 32129: Use patron category when checking if item can fill recall
[koha.git] / t / db_dependent / Koha / Item.t
1 #!/usr/bin/perl
2
3 # Copyright 2019 Koha Development team
4 #
5 # This file is part of Koha
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21 use utf8;
22
23 use Test::More tests => 28;
24 use Test::Exception;
25 use Test::MockModule;
26
27 use C4::Biblio qw( GetMarcSubfieldStructure );
28 use C4::Circulation qw( AddIssue AddReturn );
29
30 use Koha::Caches;
31 use Koha::Items;
32 use Koha::Database;
33 use Koha::DateUtils qw( dt_from_string );
34 use Koha::Old::Items;
35 use Koha::Recalls;
36
37 use List::MoreUtils qw(all);
38
39 use t::lib::TestBuilder;
40 use t::lib::Mocks;
41 use t::lib::Dates;
42
43 my $schema  = Koha::Database->new->schema;
44 my $builder = t::lib::TestBuilder->new;
45
46 subtest 'return_claims relationship' => sub {
47     plan tests => 3;
48
49     $schema->storage->txn_begin;
50
51     my $biblio = $builder->build_sample_biblio();
52     my $item   = $builder->build_sample_item({
53         biblionumber => $biblio->biblionumber,
54     });
55     my $return_claims = $item->return_claims;
56     is( ref($return_claims), 'Koha::Checkouts::ReturnClaims', 'return_claims returns a Koha::Checkouts::ReturnClaims object set' );
57     is($item->return_claims->count, 0, "Empty Koha::Checkouts::ReturnClaims set returned if no return_claims");
58     my $claim1 = $builder->build({ source => 'ReturnClaim', value => { itemnumber => $item->itemnumber }});
59     my $claim2 = $builder->build({ source => 'ReturnClaim', value => { itemnumber => $item->itemnumber }});
60
61     is($item->return_claims()->count,2,"Two ReturnClaims found for item");
62
63     $schema->storage->txn_rollback;
64 };
65
66 subtest 'return_claim accessor' => sub {
67     plan tests => 5;
68
69     $schema->storage->txn_begin;
70
71     my $biblio = $builder->build_sample_biblio();
72     my $item   = $builder->build_sample_item({
73         biblionumber => $biblio->biblionumber,
74     });
75     my $return_claim = $item->return_claim;
76     is( $return_claim, undef, 'return_claim returned undefined if there are no claims for this item' );
77
78     my $claim1 = $builder->build_object(
79         {
80             class => 'Koha::Checkouts::ReturnClaims',
81             value => { itemnumber => $item->itemnumber, resolution => undef, created_on => dt_from_string()->subtract( minutes => 10 ) }
82         }
83     );
84     my $claim2 = $builder->build_object(
85         {
86             class => 'Koha::Checkouts::ReturnClaims',
87             value  => { itemnumber => $item->itemnumber, resolution => undef, created_on => dt_from_string()->subtract( minutes => 5 ) }
88         }
89     );
90
91     $return_claim = $item->return_claim;
92     is( ref($return_claim), 'Koha::Checkouts::ReturnClaim', 'return_claim returned a Koha::Checkouts::ReturnClaim object' );
93     is( $return_claim->id, $claim2->id, 'return_claim returns the most recent unresolved claim');
94
95     $claim2->resolution('test')->store();
96     $return_claim = $item->return_claim;
97     is( $return_claim->id, $claim1->id, 'return_claim returns the only unresolved claim');
98
99     $claim1->resolution('test')->store();
100     $return_claim = $item->return_claim;
101     is( $return_claim, undef, 'return_claim returned undefined if there are no active claims for this item' );
102
103     $schema->storage->txn_rollback;
104 };
105
106 subtest 'tracked_links relationship' => sub {
107     plan tests => 3;
108
109     my $biblio = $builder->build_sample_biblio();
110     my $item   = $builder->build_sample_item({
111         biblionumber => $biblio->biblionumber,
112     });
113     my $tracked_links = $item->tracked_links;
114     is( ref($tracked_links), 'Koha::TrackedLinks', 'tracked_links returns a Koha::TrackedLinks object set' );
115     is($item->tracked_links->count, 0, "Empty Koha::TrackedLinks set returned if no tracked_links");
116     my $link1 = $builder->build({ source => 'Linktracker', value => { itemnumber => $item->itemnumber }});
117     my $link2 = $builder->build({ source => 'Linktracker', value => { itemnumber => $item->itemnumber }});
118
119     is($item->tracked_links()->count,2,"Two tracked links found");
120 };
121
122 subtest 'is_bundle tests' => sub {
123     plan tests => 2;
124
125     $schema->storage->txn_begin;
126
127     my $item   = $builder->build_sample_item();
128
129     my $is_bundle = $item->is_bundle;
130     is($is_bundle, 0, 'is_bundle returns 0 when there are no items attached');
131
132     my $item2 = $builder->build_sample_item();
133     $schema->resultset('ItemBundle')
134       ->create( { host => $item->itemnumber, item => $item2->itemnumber } );
135
136     $is_bundle = $item->is_bundle;
137     is($is_bundle, 1, 'is_bundle returns 1 when there is at least one item attached');
138
139     $schema->storage->txn_rollback;
140 };
141
142 subtest 'in_bundle tests' => sub {
143     plan tests => 2;
144
145     $schema->storage->txn_begin;
146
147     my $item   = $builder->build_sample_item();
148
149     my $in_bundle = $item->in_bundle;
150     is($in_bundle, 0, 'in_bundle returns 0 when the item is not in a bundle');
151
152     my $host_item = $builder->build_sample_item();
153     $schema->resultset('ItemBundle')
154       ->create( { host => $host_item->itemnumber, item => $item->itemnumber } );
155
156     $in_bundle = $item->in_bundle;
157     is($in_bundle, 1, 'in_bundle returns 1 when the item is in a bundle');
158
159     $schema->storage->txn_rollback;
160 };
161
162 subtest 'bundle_items tests' => sub {
163     plan tests => 3;
164
165     $schema->storage->txn_begin;
166
167     my $host_item = $builder->build_sample_item();
168     my $bundle_items = $host_item->bundle_items;
169     is( ref($bundle_items), 'Koha::Items',
170         'bundle_items returns a Koha::Items object set' );
171     is( $bundle_items->count, 0,
172         'bundle_items set is empty when no items are bundled' );
173
174     my $bundle_item1 = $builder->build_sample_item();
175     my $bundle_item2 = $builder->build_sample_item();
176     my $bundle_item3 = $builder->build_sample_item();
177     $schema->resultset('ItemBundle')
178       ->create(
179         { host => $host_item->itemnumber, item => $bundle_item1->itemnumber } );
180     $schema->resultset('ItemBundle')
181       ->create(
182         { host => $host_item->itemnumber, item => $bundle_item2->itemnumber } );
183     $schema->resultset('ItemBundle')
184       ->create(
185         { host => $host_item->itemnumber, item => $bundle_item3->itemnumber } );
186
187     $bundle_items = $host_item->bundle_items;
188     is( $bundle_items->count, 3,
189         'bundle_items returns all the bundled items in the set' );
190
191     $schema->storage->txn_rollback;
192 };
193
194 subtest 'bundle_host tests' => sub {
195     plan tests => 3;
196
197     $schema->storage->txn_begin;
198
199     my $host_item = $builder->build_sample_item();
200     my $bundle_item1 = $builder->build_sample_item();
201     my $bundle_item2 = $builder->build_sample_item();
202     $schema->resultset('ItemBundle')
203       ->create(
204         { host => $host_item->itemnumber, item => $bundle_item2->itemnumber } );
205
206     my $bundle_host = $bundle_item1->bundle_host;
207     is( $bundle_host, undef, 'bundle_host returns undefined when the item it not part of a bundle');
208     $bundle_host = $bundle_item2->bundle_host;
209     is( ref($bundle_host), 'Koha::Item', 'bundle_host returns a Koha::Item object when the item is in a bundle');
210     is( $bundle_host->id, $host_item->id, 'bundle_host returns the host item when called against an item in a bundle');
211
212     $schema->storage->txn_rollback;
213 };
214
215 subtest 'add_to_bundle tests' => sub {
216     plan tests => 10;
217
218     $schema->storage->txn_begin;
219
220     t::lib::Mocks::mock_preference( 'BundleNotLoanValue', 1 );
221
222     my $library = $builder->build_object({ class => 'Koha::Libraries' });
223     t::lib::Mocks::mock_userenv({
224         branchcode => $library->branchcode
225     });
226
227     my $host_item = $builder->build_sample_item();
228     my $bundle_item1 = $builder->build_sample_item();
229     my $bundle_item2 = $builder->build_sample_item();
230
231     throws_ok { $host_item->add_to_bundle($host_item) }
232     'Koha::Exceptions::Item::Bundle::IsBundle',
233       'Exception thrown if you try to add the item to itself';
234
235     ok($host_item->add_to_bundle($bundle_item1), 'bundle_item1 added to bundle');
236     is($bundle_item1->notforloan, 1, 'add_to_bundle sets notforloan to BundleNotLoanValue');
237
238     throws_ok { $host_item->add_to_bundle($bundle_item1) }
239     'Koha::Exceptions::Object::DuplicateID',
240       'Exception thrown if you try to add the same item twice';
241
242     throws_ok { $bundle_item1->add_to_bundle($bundle_item2) }
243     'Koha::Exceptions::Item::Bundle::IsBundle',
244       'Exception thrown if you try to add an item to a bundled item';
245
246     throws_ok { $bundle_item2->add_to_bundle($host_item) }
247     'Koha::Exceptions::Item::Bundle::IsBundle',
248       'Exception thrown if you try to add a bundle host to a bundle item';
249
250     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
251     C4::Circulation::AddIssue( $patron->unblessed, $bundle_item2->barcode );
252     throws_ok { $host_item->add_to_bundle($bundle_item2) }
253     'Koha::Exceptions::Item::Bundle::ItemIsCheckedOut',
254       'Exception thrown if you try to add a checked out item';
255
256     $bundle_item2->withdrawn(1)->store;
257     t::lib::Mocks::mock_preference( 'BlockReturnOfWithdrawnItems', 1 );
258     throws_ok { $host_item->add_to_bundle( $bundle_item2, { force_checkin => 1 } ) }
259     'Koha::Exceptions::Checkin::FailedCheckin',
260       'Exception thrown if you try to add a checked out item using
261       "force_checkin" and the return is not possible';
262
263     $bundle_item2->withdrawn(0)->store;
264     lives_ok { $host_item->add_to_bundle( $bundle_item2, { force_checkin => 1 } ) }
265     'No exception if you try to add a checked out item using "force_checkin" and the return is possible';
266
267     $bundle_item2->discard_changes;
268     ok( !$bundle_item2->checkout, 'Item is not checked out after being added to a bundle' );
269
270     $schema->storage->txn_rollback;
271 };
272
273 subtest 'remove_from_bundle tests' => sub {
274     plan tests => 3;
275
276     $schema->storage->txn_begin;
277
278     my $host_item = $builder->build_sample_item();
279     my $bundle_item1 = $builder->build_sample_item({ notforloan => 1 });
280     $schema->resultset('ItemBundle')
281       ->create(
282         { host => $host_item->itemnumber, item => $bundle_item1->itemnumber } );
283
284     is($bundle_item1->remove_from_bundle(), 1, 'remove_from_bundle returns 1 when item is removed from a bundle');
285     is($bundle_item1->notforloan, 0, 'remove_from_bundle resets notforloan to 0');
286     $bundle_item1 = $bundle_item1->get_from_storage;
287     is($bundle_item1->remove_from_bundle(), 0, 'remove_from_bundle returns 0 when item is not in a bundle');
288
289     $schema->storage->txn_rollback;
290 };
291
292 subtest 'hidden_in_opac() tests' => sub {
293
294     plan tests => 4;
295
296     $schema->storage->txn_begin;
297
298     my $item  = $builder->build_sample_item({ itemlost => 2 });
299     my $rules = {};
300
301     # disable hidelostitems as it interteres with OpachiddenItems for the calculation
302     t::lib::Mocks::mock_preference( 'hidelostitems', 0 );
303
304     ok( !$item->hidden_in_opac, 'No rules passed, shouldn\'t hide' );
305     ok( !$item->hidden_in_opac({ rules => $rules }), 'Empty rules passed, shouldn\'t hide' );
306
307     # enable hidelostitems to verify correct behaviour
308     t::lib::Mocks::mock_preference( 'hidelostitems', 1 );
309     ok( $item->hidden_in_opac, 'Even with no rules, item should hide because of hidelostitems syspref' );
310
311     # disable hidelostitems
312     t::lib::Mocks::mock_preference( 'hidelostitems', 0 );
313     my $withdrawn = $item->withdrawn + 1; # make sure this attribute doesn't match
314
315     $rules = { withdrawn => [$withdrawn], itype => [ $item->itype ] };
316
317     ok( $item->hidden_in_opac({ rules => $rules }), 'Rule matching itype passed, should hide' );
318
319
320
321     $schema->storage->txn_rollback;
322 };
323
324 subtest 'has_pending_hold() tests' => sub {
325
326     plan tests => 2;
327
328     $schema->storage->txn_begin;
329
330     my $dbh = C4::Context->dbh;
331     my $item  = $builder->build_sample_item({ itemlost => 0 });
332     my $itemnumber = $item->itemnumber;
333
334     $dbh->do("INSERT INTO tmp_holdsqueue (surname,borrowernumber,itemnumber) VALUES ('Clamp',42,$itemnumber)");
335     ok( $item->has_pending_hold, "Yes, we have a pending hold");
336     $dbh->do("DELETE FROM tmp_holdsqueue WHERE itemnumber=$itemnumber");
337     ok( !$item->has_pending_hold, "We don't have a pending hold if nothing in the tmp_holdsqueue");
338
339     $schema->storage->txn_rollback;
340 };
341
342 subtest "as_marc_field() tests" => sub {
343
344     my $mss = C4::Biblio::GetMarcSubfieldStructure( '' );
345     my ( $itemtag, $itemtagsubfield) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
346
347     my @schema_columns = $schema->resultset('Item')->result_source->columns;
348     my @mapped_columns = grep { exists $mss->{'items.'.$_} } @schema_columns;
349
350     plan tests => 2 * (scalar @mapped_columns + 1) + 4;
351
352     $schema->storage->txn_begin;
353
354     my $item = $builder->build_sample_item;
355     # Make sure it has at least one undefined attribute
356     $item->set({ replacementprice => undef })->store->discard_changes;
357
358     # Tests with the mss parameter
359     my $marc_field = $item->as_marc_field({ mss => $mss });
360
361     is(
362         $marc_field->tag,
363         $itemtag,
364         'Generated field set the right tag number'
365     );
366
367     foreach my $column ( @mapped_columns ) {
368         my $tagsubfield = $mss->{ 'items.' . $column }[0]->{tagsubfield};
369         is( $marc_field->subfield($tagsubfield),
370             $item->$column, "Value is mapped correctly for column $column" );
371     }
372
373     # Tests without the mss parameter
374     $marc_field = $item->as_marc_field();
375
376     is(
377         $marc_field->tag,
378         $itemtag,
379         'Generated field set the right tag number'
380     );
381
382     foreach my $column (@mapped_columns) {
383         my $tagsubfield = $mss->{ 'items.' . $column }[0]->{tagsubfield};
384         is( $marc_field->subfield($tagsubfield),
385             $item->$column, "Value is mapped correctly for column $column" );
386     }
387
388     my $unmapped_subfield = Koha::MarcSubfieldStructure->new(
389         {
390             frameworkcode => '',
391             tagfield      => $itemtag,
392             tagsubfield   => 'X',
393         }
394     )->store;
395     Koha::MarcSubfieldStructure->new(
396         {
397             frameworkcode => '',
398             tagfield      => $itemtag,
399             tagsubfield   => 'Y',
400             kohafield     => '',
401         }
402     )->store;
403
404     my @unlinked_subfields;
405     push @unlinked_subfields, X => 'Something weird', Y => 'Something else';
406     $item->more_subfields_xml( C4::Items::_get_unlinked_subfields_xml( \@unlinked_subfields ) )->store;
407
408     Koha::Caches->get_instance->clear_from_cache( "MarcStructure-1-" );
409     Koha::MarcSubfieldStructures->search(
410         { frameworkcode => '', tagfield => $itemtag } )
411       ->update( { display_order => \['FLOOR( 1 + RAND( ) * 10 )'] } );
412
413     $marc_field = $item->as_marc_field;
414
415     my $tagslib = C4::Biblio::GetMarcStructure(1, '');
416     my @subfields = $marc_field->subfields;
417     my $result = all { defined $_->[1] } @subfields;
418     ok( $result, 'There are no undef subfields' );
419     my @ordered_subfields = sort {
420             $tagslib->{$itemtag}->{ $a->[0] }->{display_order}
421         <=> $tagslib->{$itemtag}->{ $b->[0] }->{display_order}
422     } @subfields;
423     is_deeply(\@subfields, \@ordered_subfields);
424
425     is( scalar $marc_field->subfield('X'), 'Something weird', 'more_subfield_xml is considered when kohafield is NULL' );
426     is( scalar $marc_field->subfield('Y'), 'Something else', 'more_subfield_xml is considered when kohafield = ""' );
427
428     $schema->storage->txn_rollback;
429     Koha::Caches->get_instance->clear_from_cache( "MarcStructure-1-" );
430 };
431
432 subtest 'pickup_locations() tests' => sub {
433
434     plan tests => 68;
435
436     $schema->storage->txn_begin;
437
438     my $dbh = C4::Context->dbh;
439
440     my $root1 = $builder->build_object( { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1, branchcode => undef } } );
441     my $root2 = $builder->build_object( { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1, branchcode => undef } } );
442     my $library1 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, } } );
443     my $library2 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, } } );
444     my $library3 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 0, } } );
445     my $library4 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, } } );
446     my $group1_1 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library1->branchcode } } );
447     my $group1_2 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library2->branchcode } } );
448
449     my $group2_1 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library3->branchcode } } );
450     my $group2_2 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library4->branchcode } } );
451
452     our @branchcodes = (
453         $library1->branchcode, $library2->branchcode,
454         $library3->branchcode, $library4->branchcode
455     );
456
457     my $item1 = $builder->build_sample_item(
458         {
459             homebranch    => $library1->branchcode,
460             holdingbranch => $library2->branchcode,
461             copynumber    => 1,
462             ccode         => 'Gollum'
463         }
464     )->store;
465
466     my $item3 = $builder->build_sample_item(
467         {
468             homebranch    => $library3->branchcode,
469             holdingbranch => $library4->branchcode,
470             copynumber    => 3,
471             itype         => $item1->itype,
472         }
473     )->store;
474
475     Koha::CirculationRules->set_rules(
476         {
477             categorycode => undef,
478             itemtype     => $item1->itype,
479             branchcode   => undef,
480             rules        => {
481                 reservesallowed => 25,
482             }
483         }
484     );
485
486     throws_ok
487       { $item1->pickup_locations }
488       'Koha::Exceptions::MissingParameter',
489       'Exception thrown on missing parameter';
490
491     is( $@->parameter, 'patron', 'Exception param correctly set' );
492
493     my $patron1 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library1->branchcode, firstname => '1' } } );
494     my $patron4 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library4->branchcode, firstname => '4' } } );
495
496     my $results = {
497         "1-1-from_home_library-any"               => 3,
498         "1-1-from_home_library-holdgroup"         => 2,
499         "1-1-from_home_library-patrongroup"       => 2,
500         "1-1-from_home_library-homebranch"        => 1,
501         "1-1-from_home_library-holdingbranch"     => 1,
502         "1-1-from_any_library-any"                => 3,
503         "1-1-from_any_library-holdgroup"          => 2,
504         "1-1-from_any_library-patrongroup"        => 2,
505         "1-1-from_any_library-homebranch"         => 1,
506         "1-1-from_any_library-holdingbranch"      => 1,
507         "1-1-from_local_hold_group-any"           => 3,
508         "1-1-from_local_hold_group-holdgroup"     => 2,
509         "1-1-from_local_hold_group-patrongroup"   => 2,
510         "1-1-from_local_hold_group-homebranch"    => 1,
511         "1-1-from_local_hold_group-holdingbranch" => 1,
512         "1-4-from_home_library-any"               => 0,
513         "1-4-from_home_library-holdgroup"         => 0,
514         "1-4-from_home_library-patrongroup"       => 0,
515         "1-4-from_home_library-homebranch"        => 0,
516         "1-4-from_home_library-holdingbranch"     => 0,
517         "1-4-from_any_library-any"                => 3,
518         "1-4-from_any_library-holdgroup"          => 2,
519         "1-4-from_any_library-patrongroup"        => 1,
520         "1-4-from_any_library-homebranch"         => 1,
521         "1-4-from_any_library-holdingbranch"      => 1,
522         "1-4-from_local_hold_group-any"           => 0,
523         "1-4-from_local_hold_group-holdgroup"     => 0,
524         "1-4-from_local_hold_group-patrongroup"   => 0,
525         "1-4-from_local_hold_group-homebranch"    => 0,
526         "1-4-from_local_hold_group-holdingbranch" => 0,
527         "3-1-from_home_library-any"               => 0,
528         "3-1-from_home_library-holdgroup"         => 0,
529         "3-1-from_home_library-patrongroup"       => 0,
530         "3-1-from_home_library-homebranch"        => 0,
531         "3-1-from_home_library-holdingbranch"     => 0,
532         "3-1-from_any_library-any"                => 3,
533         "3-1-from_any_library-holdgroup"          => 1,
534         "3-1-from_any_library-patrongroup"        => 2,
535         "3-1-from_any_library-homebranch"         => 0,
536         "3-1-from_any_library-holdingbranch"      => 1,
537         "3-1-from_local_hold_group-any"           => 0,
538         "3-1-from_local_hold_group-holdgroup"     => 0,
539         "3-1-from_local_hold_group-patrongroup"   => 0,
540         "3-1-from_local_hold_group-homebranch"    => 0,
541         "3-1-from_local_hold_group-holdingbranch" => 0,
542         "3-4-from_home_library-any"               => 0,
543         "3-4-from_home_library-holdgroup"         => 0,
544         "3-4-from_home_library-patrongroup"       => 0,
545         "3-4-from_home_library-homebranch"        => 0,
546         "3-4-from_home_library-holdingbranch"     => 0,
547         "3-4-from_any_library-any"                => 3,
548         "3-4-from_any_library-holdgroup"          => 1,
549         "3-4-from_any_library-patrongroup"        => 1,
550         "3-4-from_any_library-homebranch"         => 0,
551         "3-4-from_any_library-holdingbranch"      => 1,
552         "3-4-from_local_hold_group-any"           => 3,
553         "3-4-from_local_hold_group-holdgroup"     => 1,
554         "3-4-from_local_hold_group-patrongroup"   => 1,
555         "3-4-from_local_hold_group-homebranch"    => 0,
556         "3-4-from_local_hold_group-holdingbranch" => 1
557     };
558
559     sub _doTest {
560         my ( $item, $patron, $ha, $hfp, $results ) = @_;
561
562         Koha::CirculationRules->set_rules(
563             {
564                 branchcode => undef,
565                 itemtype   => undef,
566                 rules => {
567                     holdallowed => $ha,
568                     hold_fulfillment_policy => $hfp,
569                     returnbranch => 'any'
570                 }
571             }
572         );
573         my $ha_value =
574           $ha eq 'from_local_hold_group' ? 'holdgroup'
575           : (
576             $ha eq 'from_any_library' ? 'any'
577             : 'homebranch'
578           );
579
580         my @pl = map {
581             my $pickup_location = $_;
582             grep { $pickup_location->branchcode eq $_ } @branchcodes
583         } $item->pickup_locations( { patron => $patron } )->as_list;
584
585         ok(
586             scalar(@pl) eq $results->{
587                     $item->copynumber . '-'
588                   . $patron->firstname . '-'
589                   . $ha . '-'
590                   . $hfp
591             },
592             'item'
593               . $item->copynumber
594               . ', patron'
595               . $patron->firstname
596               . ', holdallowed: '
597               . $ha_value
598               . ', hold_fulfillment_policy: '
599               . $hfp
600               . ' should return '
601               . $results->{
602                     $item->copynumber . '-'
603                   . $patron->firstname . '-'
604                   . $ha . '-'
605                   . $hfp
606               }
607               . ' and returns '
608               . scalar(@pl)
609         );
610
611     }
612
613
614     foreach my $item ($item1, $item3) {
615         foreach my $patron ($patron1, $patron4) {
616             #holdallowed 1: homebranch, 2: any, 3: holdgroup
617             foreach my $ha ('from_home_library', 'from_any_library', 'from_local_hold_group') {
618                 foreach my $hfp ('any', 'holdgroup', 'patrongroup', 'homebranch', 'holdingbranch') {
619                     _doTest($item, $patron, $ha, $hfp, $results);
620                 }
621             }
622         }
623     }
624
625     # Now test that branchtransferlimits will further filter the pickup locations
626
627     my $item_no_ccode = $builder->build_sample_item(
628         {
629             homebranch    => $library1->branchcode,
630             holdingbranch => $library2->branchcode,
631             itype         => $item1->itype,
632         }
633     )->store;
634
635     t::lib::Mocks::mock_preference('UseBranchTransferLimits', 1);
636     t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'itemtype');
637     Koha::CirculationRules->set_rules(
638         {
639             branchcode => undef,
640             itemtype   => $item1->itype,
641             rules      => {
642                 holdallowed             => 'from_home_library',
643                 hold_fulfillment_policy => 1,
644                 returnbranch            => 'any'
645             }
646         }
647     );
648     $builder->build_object(
649         {
650             class => 'Koha::Item::Transfer::Limits',
651             value => {
652                 toBranch   => $library1->branchcode,
653                 fromBranch => $library2->branchcode,
654                 itemtype   => $item1->itype,
655                 ccode      => undef,
656             }
657         }
658     );
659
660     my @pickup_locations = map {
661         my $pickup_location = $_;
662         grep { $pickup_location->branchcode eq $_ } @branchcodes
663     } $item1->pickup_locations( { patron => $patron1 } )->as_list;
664
665     is( scalar @pickup_locations, 3 - 1, "With a transfer limits we get back the libraries that are pickup locations minus 1 limited library");
666
667     $builder->build_object(
668         {
669             class => 'Koha::Item::Transfer::Limits',
670             value => {
671                 toBranch   => $library4->branchcode,
672                 fromBranch => $library2->branchcode,
673                 itemtype   => $item1->itype,
674                 ccode      => undef,
675             }
676         }
677     );
678
679     @pickup_locations = map {
680         my $pickup_location = $_;
681         grep { $pickup_location->branchcode eq $_ } @branchcodes
682     } $item1->pickup_locations( { patron => $patron1 } )->as_list;
683
684     is( scalar @pickup_locations, 3 - 2, "With 2 transfer limits we get back the libraries that are pickup locations minus 2 limited libraries");
685
686     t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'ccode');
687     @pickup_locations = map {
688         my $pickup_location = $_;
689         grep { $pickup_location->branchcode eq $_ } @branchcodes
690     } $item1->pickup_locations( { patron => $patron1 } )->as_list;
691     is( scalar @pickup_locations, 3, "With no transfer limits of type ccode we get back the libraries that are pickup locations");
692
693     @pickup_locations = map {
694         my $pickup_location = $_;
695         grep { $pickup_location->branchcode eq $_ } @branchcodes
696     } $item_no_ccode->pickup_locations( { patron => $patron1 } )->as_list;
697     is( scalar @pickup_locations, 3, "With no transfer limits of type ccode and an item with no ccode we get back the libraries that are pickup locations");
698
699     $builder->build_object(
700         {
701             class => 'Koha::Item::Transfer::Limits',
702             value => {
703                 toBranch   => $library2->branchcode,
704                 fromBranch => $library2->branchcode,
705                 itemtype   => undef,
706                 ccode      => $item1->ccode,
707             }
708         }
709     );
710
711     @pickup_locations = map {
712         my $pickup_location = $_;
713         grep { $pickup_location->branchcode eq $_ } @branchcodes
714     } $item1->pickup_locations( { patron => $patron1 } )->as_list;
715     is( scalar @pickup_locations, 3 - 1, "With a transfer limits we get back the libraries that are pickup locations minus 1 limited library");
716
717     $builder->build_object(
718         {
719             class => 'Koha::Item::Transfer::Limits',
720             value => {
721                 toBranch   => $library4->branchcode,
722                 fromBranch => $library2->branchcode,
723                 itemtype   => undef,
724                 ccode      => $item1->ccode,
725             }
726         }
727     );
728
729     @pickup_locations = map {
730         my $pickup_location = $_;
731         grep { $pickup_location->branchcode eq $_ } @branchcodes
732     } $item1->pickup_locations( { patron => $patron1 } )->as_list;
733     is( scalar @pickup_locations, 3 - 2, "With 2 transfer limits we get back the libraries that are pickup locations minus 2 limited libraries");
734
735     t::lib::Mocks::mock_preference('UseBranchTransferLimits', 0);
736
737     $schema->storage->txn_rollback;
738 };
739
740 subtest 'request_transfer' => sub {
741     plan tests => 13;
742     $schema->storage->txn_begin;
743
744     my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
745     my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
746     my $item     = $builder->build_sample_item(
747         {
748             homebranch    => $library1->branchcode,
749             holdingbranch => $library2->branchcode,
750         }
751     );
752
753     # Mandatory fields tests
754     throws_ok { $item->request_transfer( { to => $library1 } ) }
755     'Koha::Exceptions::MissingParameter',
756       'Exception thrown if `reason` parameter is missing';
757
758     throws_ok { $item->request_transfer( { reason => 'Manual' } ) }
759     'Koha::Exceptions::MissingParameter',
760       'Exception thrown if `to` parameter is missing';
761
762     # Successful request
763     my $transfer = $item->request_transfer({ to => $library1, reason => 'Manual' });
764     is( ref($transfer), 'Koha::Item::Transfer',
765         'Koha::Item->request_transfer should return a Koha::Item::Transfer object'
766     );
767     my $original_transfer = $transfer->get_from_storage;
768
769     # Transfer already in progress
770     throws_ok { $item->request_transfer( { to => $library2, reason => 'Manual' } ) }
771     'Koha::Exceptions::Item::Transfer::InQueue',
772       'Exception thrown if transfer is already in progress';
773
774     my $exception = $@;
775     is( ref( $exception->transfer ),
776         'Koha::Item::Transfer',
777         'The exception contains the found Koha::Item::Transfer' );
778
779     # Queue transfer
780     my $queued_transfer = $item->request_transfer(
781         { to => $library2, reason => 'Manual', enqueue => 1 } );
782     is( ref($queued_transfer), 'Koha::Item::Transfer',
783         'Koha::Item->request_transfer allowed when enqueue is set' );
784     my $transfers = $item->get_transfers;
785     is($transfers->count, 2, "There are now 2 live transfers in the queue");
786     $transfer = $transfer->get_from_storage;
787     is_deeply($transfer->unblessed, $original_transfer->unblessed, "Original transfer unchanged");
788     $queued_transfer->datearrived(dt_from_string)->store();
789
790     # Replace transfer
791     my $replaced_transfer = $item->request_transfer(
792         { to => $library2, reason => 'Manual', replace => 1 } );
793     is( ref($replaced_transfer), 'Koha::Item::Transfer',
794         'Koha::Item->request_transfer allowed when replace is set' );
795     $original_transfer->discard_changes;
796     ok($original_transfer->datecancelled, "Original transfer cancelled");
797     $transfers = $item->get_transfers;
798     is($transfers->count, 1, "There is only 1 live transfer in the queue");
799     $replaced_transfer->datearrived(dt_from_string)->store();
800
801     # BranchTransferLimits
802     t::lib::Mocks::mock_preference('UseBranchTransferLimits', 1);
803     t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'itemtype');
804     my $limit = Koha::Item::Transfer::Limit->new({
805         fromBranch => $library2->branchcode,
806         toBranch => $library1->branchcode,
807         itemtype => $item->effective_itemtype,
808     })->store;
809
810     throws_ok { $item->request_transfer( { to => $library1, reason => 'Manual' } ) }
811     'Koha::Exceptions::Item::Transfer::Limit',
812       'Exception thrown if transfer is prevented by limits';
813
814     my $forced_transfer = $item->request_transfer( { to => $library1, reason => 'Manual', ignore_limits => 1 } );
815     is( ref($forced_transfer), 'Koha::Item::Transfer',
816         'Koha::Item->request_transfer allowed when ignore_limits is set'
817     );
818
819     $schema->storage->txn_rollback;
820 };
821
822 subtest 'deletion' => sub {
823     plan tests => 15;
824
825     $schema->storage->txn_begin;
826
827     my $biblio = $builder->build_sample_biblio();
828
829     my $item = $builder->build_sample_item(
830         {
831             biblionumber => $biblio->biblionumber,
832         }
833     );
834     is( $item->deleted_on, undef, 'deleted_on not set for new item' );
835
836     my $deleted_item = $item->move_to_deleted;
837     is( ref( $deleted_item ), 'Koha::Schema::Result::Deleteditem', 'Koha::Item->move_to_deleted should return the Deleted item' )
838       ;    # FIXME This should be Koha::Deleted::Item
839     is( t::lib::Dates::compare( $deleted_item->deleted_on, dt_from_string() ), 0 );
840
841     is( Koha::Old::Items->search({itemnumber => $item->itemnumber})->count, 1, '->move_to_deleted must have moved the item to deleteditem' );
842     $item = $builder->build_sample_item(
843         {
844             biblionumber => $biblio->biblionumber,
845         }
846     );
847     $item->delete;
848     is( Koha::Old::Items->search({itemnumber => $item->itemnumber})->count, 0, '->move_to_deleted must not have moved the item to deleteditem' );
849
850
851     my $library   = $builder->build_object({ class => 'Koha::Libraries' });
852     my $library_2 = $builder->build_object({ class => 'Koha::Libraries' });
853     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
854
855     my $patron = $builder->build_object({class => 'Koha::Patrons'});
856     $item = $builder->build_sample_item({ library => $library->branchcode });
857
858     # book_on_loan
859     C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
860
861     is(
862         @{$item->safe_to_delete->messages}[0]->message,
863         'book_on_loan',
864         'Koha::Item->safe_to_delete reports item on loan',
865     );
866
867     is(
868         @{$item->safe_to_delete->messages}[0]->message,
869         'book_on_loan',
870         'item that is on loan cannot be deleted',
871     );
872
873     ok(
874         ! $item->safe_to_delete,
875         'Koha::Item->safe_to_delete shows item NOT safe to delete'
876     );
877
878     AddReturn( $item->barcode, $library->branchcode );
879
880     # not_same_branch
881     t::lib::Mocks::mock_preference('IndependentBranches', 1);
882     my $item_2 = $builder->build_sample_item({ library => $library_2->branchcode });
883
884     is(
885         @{$item_2->safe_to_delete->messages}[0]->message,
886         'not_same_branch',
887         'Koha::Item->safe_to_delete reports IndependentBranches restriction',
888     );
889
890     is(
891         @{$item_2->safe_to_delete->messages}[0]->message,
892         'not_same_branch',
893         'IndependentBranches prevents deletion at another branch',
894     );
895
896     # linked_analytics
897
898     { # codeblock to limit scope of $module->mock
899
900         my $module = Test::MockModule->new('C4::Items');
901         $module->mock( GetAnalyticsCount => sub { return 1 } );
902
903         $item->discard_changes;
904         is(
905             @{$item->safe_to_delete->messages}[0]->message,
906             'linked_analytics',
907             'Koha::Item->safe_to_delete reports linked analytics',
908         );
909
910         is(
911             @{$item->safe_to_delete->messages}[0]->message,
912             'linked_analytics',
913             'Linked analytics prevents deletion of item',
914         );
915
916     }
917
918     ok(
919         $item->safe_to_delete,
920         'Koha::Item->safe_to_delete shows item safe to delete'
921     );
922
923     $item->safe_delete,
924
925     my $test_item = Koha::Items->find( $item->itemnumber );
926
927     is( $test_item, undef,
928         "Koha::Item->safe_delete should delete item if safe_to_delete returns true"
929     );
930
931     subtest 'holds tests' => sub {
932
933         plan tests => 9;
934
935         # to avoid noise
936         t::lib::Mocks::mock_preference( 'IndependentBranches', 0 );
937
938         $schema->storage->txn_begin;
939
940         my $item = $builder->build_sample_item;
941
942         my $processing     = $builder->build_object( { class => 'Koha::Holds', value => { itemnumber => $item->id, itemnumber => $item->id, found => 'P' } } );
943         my $safe_to_delete = $item->safe_to_delete;
944
945         ok( !$safe_to_delete, 'Cannot delete' );
946         is(
947             @{ $safe_to_delete->messages }[0]->message,
948             'book_reserved',
949             'Koha::Item->safe_to_delete reports a in processing hold blocks deletion'
950         );
951
952         $processing->delete;
953
954         my $in_transit = $builder->build_object( { class => 'Koha::Holds', value => { itemnumber => $item->id, itemnumber => $item->id, found => 'T' } } );
955         $safe_to_delete = $item->safe_to_delete;
956
957         ok( !$safe_to_delete, 'Cannot delete' );
958         is(
959             @{ $safe_to_delete->messages }[0]->message,
960             'book_reserved',
961             'Koha::Item->safe_to_delete reports a in transit hold blocks deletion'
962         );
963
964         $in_transit->delete;
965
966         my $waiting = $builder->build_object( { class => 'Koha::Holds', value => { itemnumber => $item->id, itemnumber => $item->id, found => 'W' } } );
967         $safe_to_delete = $item->safe_to_delete;
968
969         ok( !$safe_to_delete, 'Cannot delete' );
970         is(
971             @{ $safe_to_delete->messages }[0]->message,
972             'book_reserved',
973             'Koha::Item->safe_to_delete reports a waiting hold blocks deletion'
974         );
975
976         $waiting->delete;
977
978         # Add am unfilled biblio-level hold to catch the 'last_item_for_hold' use case
979         $builder->build_object( { class => 'Koha::Holds', value => { biblionumber => $item->biblionumber, itemnumber => undef, found => undef } } );
980
981         $safe_to_delete = $item->safe_to_delete;
982
983         ok( !$safe_to_delete );
984
985         is(
986             @{ $safe_to_delete->messages}[0]->message,
987             'last_item_for_hold',
988             'Item cannot be deleted if a biblio-level is placed on the biblio and there is only 1 item attached to the biblio'
989         );
990
991         my $extra_item = $builder->build_sample_item({ biblionumber => $item->biblionumber });
992
993         ok( $item->safe_to_delete );
994
995         $schema->storage->txn_rollback;
996     };
997
998     $schema->storage->txn_rollback;
999 };
1000
1001 subtest 'renewal_branchcode' => sub {
1002     plan tests => 13;
1003
1004     $schema->storage->txn_begin;
1005
1006     my $item = $builder->build_sample_item();
1007     my $branch = $builder->build_object({ class => 'Koha::Libraries' });
1008     my $checkout = $builder->build_object({
1009         class => 'Koha::Checkouts',
1010         value => {
1011             itemnumber => $item->itemnumber,
1012         }
1013     });
1014
1015
1016     C4::Context->interface( 'intranet' );
1017     t::lib::Mocks::mock_userenv({ branchcode => $branch->branchcode });
1018
1019     is( $item->renewal_branchcode, $branch->branchcode, "If interface not opac, we get the branch from context");
1020     is( $item->renewal_branchcode({ branch => "PANDA"}), $branch->branchcode, "If interface not opac, we get the branch from context even if we pass one in");
1021     C4::Context->set_userenv(51, 'userid4tests', undef, 'firstname', 'surname', undef, undef, 0, undef, undef, undef ); #mock userenv doesn't let us set null branch
1022     is( $item->renewal_branchcode({ branch => "PANDA"}), "PANDA", "If interface not opac, we get the branch we pass one in if context not set");
1023
1024     C4::Context->interface( 'opac' );
1025
1026     t::lib::Mocks::mock_preference('OpacRenewalBranch', undef);
1027     is( $item->renewal_branchcode, 'OPACRenew', "If interface opac and OpacRenewalBranch undef, we get OPACRenew");
1028     is( $item->renewal_branchcode({branch=>'COW'}), 'OPACRenew', "If interface opac and OpacRenewalBranch undef, we get OPACRenew even if branch passed");
1029
1030     t::lib::Mocks::mock_preference('OpacRenewalBranch', 'none');
1031     is( $item->renewal_branchcode, '', "If interface opac and OpacRenewalBranch is none, we get blank string");
1032     is( $item->renewal_branchcode({branch=>'COW'}), '', "If interface opac and OpacRenewalBranch is none, we get blank string even if branch passed");
1033
1034     t::lib::Mocks::mock_preference('OpacRenewalBranch', 'checkoutbranch');
1035     is( $item->renewal_branchcode, $checkout->branchcode, "If interface opac and OpacRenewalBranch set to checkoutbranch, we get branch of checkout");
1036     is( $item->renewal_branchcode({branch=>'MONKEY'}), $checkout->branchcode, "If interface opac and OpacRenewalBranch set to checkoutbranch, we get branch of checkout even if branch passed");
1037
1038     t::lib::Mocks::mock_preference('OpacRenewalBranch','patronhomebranch');
1039     is( $item->renewal_branchcode, $checkout->patron->branchcode, "If interface opac and OpacRenewalBranch set to patronbranch, we get branch of patron");
1040     is( $item->renewal_branchcode({branch=>'TURKEY'}), $checkout->patron->branchcode, "If interface opac and OpacRenewalBranch set to patronbranch, we get branch of patron even if branch passed");
1041
1042     t::lib::Mocks::mock_preference('OpacRenewalBranch','itemhomebranch');
1043     is( $item->renewal_branchcode, $item->homebranch, "If interface opac and OpacRenewalBranch set to itemhomebranch, we get homebranch of item");
1044     is( $item->renewal_branchcode({branch=>'MANATEE'}), $item->homebranch, "If interface opac and OpacRenewalBranch set to itemhomebranch, we get homebranch of item even if branch passed");
1045
1046     $schema->storage->txn_rollback;
1047 };
1048
1049 subtest 'Tests for itemtype' => sub {
1050     plan tests => 2;
1051     $schema->storage->txn_begin;
1052
1053     my $biblio = $builder->build_sample_biblio;
1054     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' });
1055     my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, itype => $itemtype->itemtype });
1056
1057     t::lib::Mocks::mock_preference('item-level_itypes', 1);
1058     is( $item->itemtype->itemtype, $item->itype, 'Pref enabled' );
1059     t::lib::Mocks::mock_preference('item-level_itypes', 0);
1060     is( $item->itemtype->itemtype, $biblio->biblioitem->itemtype, 'Pref disabled' );
1061
1062     $schema->storage->txn_rollback;
1063 };
1064
1065 subtest 'get_transfers' => sub {
1066     plan tests => 16;
1067     $schema->storage->txn_begin;
1068
1069     my $item = $builder->build_sample_item();
1070
1071     my $transfers = $item->get_transfers();
1072     is(ref($transfers), 'Koha::Item::Transfers', 'Koha::Item->get_transfer should return a Koha::Item::Transfers object' );
1073     is($transfers->count, 0, 'When no transfers exist, the Koha::Item:Transfers object should be empty');
1074
1075     my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
1076
1077     my $transfer_1 = $builder->build_object(
1078         {
1079             class => 'Koha::Item::Transfers',
1080             value => {
1081                 itemnumber    => $item->itemnumber,
1082                 frombranch    => $item->holdingbranch,
1083                 tobranch      => $library_to->branchcode,
1084                 reason        => 'Manual',
1085                 datesent      => undef,
1086                 datearrived   => undef,
1087                 datecancelled => undef,
1088                 daterequested => \'NOW()'
1089             }
1090         }
1091     );
1092
1093     $transfers = $item->get_transfers();
1094     is($transfers->count, 1, 'When one transfer has been requested, the Koha::Item:Transfers object should contain one result');
1095
1096     my $transfer_2 = $builder->build_object(
1097         {
1098             class => 'Koha::Item::Transfers',
1099             value => {
1100                 itemnumber    => $item->itemnumber,
1101                 frombranch    => $item->holdingbranch,
1102                 tobranch      => $library_to->branchcode,
1103                 reason        => 'Manual',
1104                 datesent      => undef,
1105                 datearrived   => undef,
1106                 datecancelled => undef,
1107                 daterequested => \'NOW()'
1108             }
1109         }
1110     );
1111
1112     my $transfer_3 = $builder->build_object(
1113         {
1114             class => 'Koha::Item::Transfers',
1115             value => {
1116                 itemnumber    => $item->itemnumber,
1117                 frombranch    => $item->holdingbranch,
1118                 tobranch      => $library_to->branchcode,
1119                 reason        => 'Manual',
1120                 datesent      => undef,
1121                 datearrived   => undef,
1122                 datecancelled => undef,
1123                 daterequested => \'NOW()'
1124             }
1125         }
1126     );
1127
1128     $transfers = $item->get_transfers();
1129     is($transfers->count, 3, 'When there are multiple open transfer requests, the Koha::Item::Transfers object contains them all');
1130     my $result_1 = $transfers->next;
1131     my $result_2 = $transfers->next;
1132     my $result_3 = $transfers->next;
1133     is( $result_1->branchtransfer_id, $transfer_1->branchtransfer_id, 'Koha::Item->get_transfers returns the oldest transfer request first');
1134     is( $result_2->branchtransfer_id, $transfer_2->branchtransfer_id, 'Koha::Item->get_transfers returns the newer transfer request second');
1135     is( $result_3->branchtransfer_id, $transfer_3->branchtransfer_id, 'Koha::Item->get_transfers returns the newest transfer request last');
1136
1137     $transfer_2->datesent(\'NOW()')->store;
1138     $transfers = $item->get_transfers();
1139     is($transfers->count, 3, 'When one transfer is set to in_transit, the Koha::Item::Transfers object still contains them all');
1140     $result_1 = $transfers->next;
1141     $result_2 = $transfers->next;
1142     $result_3 = $transfers->next;
1143     is( $result_1->branchtransfer_id, $transfer_2->branchtransfer_id, 'Koha::Item->get_transfers returns the active transfer request first');
1144     is( $result_2->branchtransfer_id, $transfer_1->branchtransfer_id, 'Koha::Item->get_transfers returns the other transfers oldest to newest');
1145     is( $result_3->branchtransfer_id, $transfer_3->branchtransfer_id, 'Koha::Item->get_transfers returns the other transfers oldest to newest');
1146
1147     $transfer_2->datearrived(\'NOW()')->store;
1148     $transfers = $item->get_transfers();
1149     is($transfers->count, 2, 'Once a transfer is received, it no longer appears in the list from ->get_transfers()');
1150     $result_1 = $transfers->next;
1151     $result_2 = $transfers->next;
1152     is( $result_1->branchtransfer_id, $transfer_1->branchtransfer_id, 'Koha::Item->get_transfers returns the other transfers oldest to newest');
1153     is( $result_2->branchtransfer_id, $transfer_3->branchtransfer_id, 'Koha::Item->get_transfers returns the other transfers oldest to newest');
1154
1155     $transfer_1->datecancelled(\'NOW()')->store;
1156     $transfers = $item->get_transfers();
1157     is($transfers->count, 1, 'Once a transfer is cancelled, it no longer appears in the list from ->get_transfers()');
1158     $result_1 = $transfers->next;
1159     is( $result_1->branchtransfer_id, $transfer_3->branchtransfer_id, 'Koha::Item->get_transfers returns the only transfer that remains');
1160
1161     $schema->storage->txn_rollback;
1162 };
1163
1164 subtest 'Tests for relationship between item and item_orders via aqorders_item' => sub {
1165     plan tests => 3;
1166
1167     $schema->storage->txn_begin;
1168
1169     my $biblio = $builder->build_sample_biblio();
1170     my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
1171
1172     my $orders = $item->orders;
1173     is ($orders->count, 0, 'No order on this item yet');
1174
1175     my $order_note = 'Order for ' . $item->itemnumber;
1176
1177     my $aq_order1 = $builder->build_object({
1178         class => 'Koha::Acquisition::Orders',
1179         value  => {
1180             biblionumber => $biblio->biblionumber,
1181             order_internalnote => $order_note,
1182         },
1183     });
1184     my $aq_order2 = $builder->build_object({
1185         class => 'Koha::Acquisition::Orders',
1186         value  => {
1187             biblionumber => $biblio->biblionumber,
1188         },
1189     });
1190     my $aq_order_item1 = $builder->build({
1191         source => 'AqordersItem',
1192         value  => {
1193             ordernumber => $aq_order1->ordernumber,
1194             itemnumber => $item->itemnumber,
1195         },
1196     });
1197
1198     $orders = $item->orders;
1199     is ($orders->count, 1, 'One order found by item with the relationship');
1200     is ($orders->next->order_internalnote, $order_note, 'Correct order found by item with the relationship');
1201 };
1202
1203 subtest 'move_to_biblio() tests' => sub {
1204     plan tests => 16;
1205
1206     $schema->storage->txn_begin;
1207
1208     my $dbh = C4::Context->dbh;
1209
1210     my $source_biblio = $builder->build_sample_biblio();
1211     my $target_biblio = $builder->build_sample_biblio();
1212
1213     my $source_biblionumber = $source_biblio->biblionumber;
1214     my $target_biblionumber = $target_biblio->biblionumber;
1215
1216     my $item1 = $builder->build_sample_item({ biblionumber => $source_biblionumber });
1217     my $item2 = $builder->build_sample_item({ biblionumber => $source_biblionumber });
1218     my $item3 = $builder->build_sample_item({ biblionumber => $source_biblionumber });
1219
1220     my $itemnumber1 = $item1->itemnumber;
1221     my $itemnumber2 = $item2->itemnumber;
1222
1223     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1224
1225     my $patron = $builder->build_object({
1226         class => 'Koha::Patrons',
1227         value => { branchcode => $library->branchcode }
1228     });
1229     my $borrowernumber = $patron->borrowernumber;
1230
1231     my $aq_budget = $builder->build({
1232         source => 'Aqbudget',
1233         value  => {
1234             budget_notes => 'test',
1235         },
1236     });
1237
1238     my $aq_order1 = $builder->build_object({
1239         class => 'Koha::Acquisition::Orders',
1240         value  => {
1241             biblionumber => $source_biblionumber,
1242             budget_id => $aq_budget->{budget_id},
1243         },
1244     });
1245     my $aq_order_item1 = $builder->build({
1246         source => 'AqordersItem',
1247         value  => {
1248             ordernumber => $aq_order1->ordernumber,
1249             itemnumber => $itemnumber1,
1250         },
1251     });
1252     my $aq_order2 = $builder->build_object({
1253         class => 'Koha::Acquisition::Orders',
1254         value  => {
1255             biblionumber => $source_biblionumber,
1256             budget_id => $aq_budget->{budget_id},
1257         },
1258     });
1259     my $aq_order_item2 = $builder->build({
1260         source => 'AqordersItem',
1261         value  => {
1262             ordernumber => $aq_order2->ordernumber,
1263             itemnumber => $itemnumber2,
1264         },
1265     });
1266
1267     my $bib_level_hold = $builder->build_object({
1268         class => 'Koha::Holds',
1269         value  => {
1270             biblionumber => $source_biblionumber,
1271             itemnumber => undef,
1272         },
1273     });
1274     my $item_level_hold1 = $builder->build_object({
1275         class => 'Koha::Holds',
1276         value  => {
1277             biblionumber => $source_biblionumber,
1278             itemnumber => $itemnumber1,
1279         },
1280     });
1281     my $item_level_hold2 = $builder->build_object({
1282         class => 'Koha::Holds',
1283         value  => {
1284             biblionumber => $source_biblionumber,
1285             itemnumber => $itemnumber2,
1286         }
1287     });
1288
1289     my $tmp_holdsqueue1 = $builder->build({
1290         source => 'TmpHoldsqueue',
1291         value  => {
1292             borrowernumber => $borrowernumber,
1293             biblionumber   => $source_biblionumber,
1294             itemnumber     => $itemnumber1,
1295         }
1296     });
1297     my $tmp_holdsqueue2 = $builder->build({
1298         source => 'TmpHoldsqueue',
1299         value  => {
1300             borrowernumber => $borrowernumber,
1301             biblionumber   => $source_biblionumber,
1302             itemnumber     => $itemnumber2,
1303         }
1304     });
1305     my $hold_fill_target1 = $builder->build({
1306         source => 'HoldFillTarget',
1307         value  => {
1308             borrowernumber     => $borrowernumber,
1309             biblionumber       => $source_biblionumber,
1310             itemnumber         => $itemnumber1,
1311         }
1312     });
1313     my $hold_fill_target2 = $builder->build({
1314         source => 'HoldFillTarget',
1315         value  => {
1316             borrowernumber     => $borrowernumber,
1317             biblionumber       => $source_biblionumber,
1318             itemnumber         => $itemnumber2,
1319         }
1320     });
1321     my $linktracker1 = $builder->build({
1322         source => 'Linktracker',
1323         value  => {
1324             borrowernumber     => $borrowernumber,
1325             biblionumber       => $source_biblionumber,
1326             itemnumber         => $itemnumber1,
1327         }
1328     });
1329     my $linktracker2 = $builder->build({
1330         source => 'Linktracker',
1331         value  => {
1332             borrowernumber     => $borrowernumber,
1333             biblionumber       => $source_biblionumber,
1334             itemnumber         => $itemnumber2,
1335         }
1336     });
1337
1338     my $to_biblionumber_after_move = $item1->move_to_biblio($target_biblio);
1339     is($to_biblionumber_after_move, $target_biblionumber, 'move_to_biblio returns the target biblionumber if success');
1340
1341     $to_biblionumber_after_move = $item1->move_to_biblio($target_biblio);
1342     is($to_biblionumber_after_move, undef, 'move_to_biblio returns undef if the move has failed. If called twice, the item is not attached to the first biblio anymore');
1343
1344     my $get_item1 = Koha::Items->find( $item1->itemnumber );
1345     is($get_item1->biblionumber, $target_biblionumber, 'item1 is moved');
1346     my $get_item2 = Koha::Items->find( $item2->itemnumber );
1347     is($get_item2->biblionumber, $source_biblionumber, 'item2 is not moved');
1348     my $get_item3 = Koha::Items->find( $item3->itemnumber );
1349     is($get_item3->biblionumber, $source_biblionumber, 'item3 is not moved');
1350
1351     $aq_order1->discard_changes;
1352     $aq_order2->discard_changes;
1353     is($aq_order1->biblionumber, $target_biblionumber, 'move_to_biblio moves aq_orders for item 1');
1354     is($aq_order2->biblionumber, $source_biblionumber, 'move_to_biblio does not move aq_orders for item 2');
1355
1356     $bib_level_hold->discard_changes;
1357     $item_level_hold1->discard_changes;
1358     $item_level_hold2->discard_changes;
1359     is($bib_level_hold->biblionumber,   $source_biblionumber, 'move_to_biblio does not move the biblio-level hold');
1360     is($item_level_hold1->biblionumber, $target_biblionumber, 'move_to_biblio moves the item-level hold placed on item 1');
1361     is($item_level_hold2->biblionumber, $source_biblionumber, 'move_to_biblio does not move the item-level hold placed on item 2');
1362
1363     my $get_tmp_holdsqueue1 = $schema->resultset('TmpHoldsqueue')->search({ itemnumber => $tmp_holdsqueue1->{itemnumber} })->single;
1364     my $get_tmp_holdsqueue2 = $schema->resultset('TmpHoldsqueue')->search({ itemnumber => $tmp_holdsqueue2->{itemnumber} })->single;
1365     is($get_tmp_holdsqueue1->biblionumber->biblionumber, $target_biblionumber, 'move_to_biblio moves tmp_holdsqueue for item 1');
1366     is($get_tmp_holdsqueue2->biblionumber->biblionumber, $source_biblionumber, 'move_to_biblio does not move tmp_holdsqueue for item 2');
1367
1368     my $get_hold_fill_target1 = $schema->resultset('HoldFillTarget')->search({ itemnumber => $hold_fill_target1->{itemnumber} })->single;
1369     my $get_hold_fill_target2 = $schema->resultset('HoldFillTarget')->search({ itemnumber => $hold_fill_target2->{itemnumber} })->single;
1370     # Why does ->biblionumber return a Biblio object???
1371     is($get_hold_fill_target1->biblionumber->biblionumber, $target_biblionumber, 'move_to_biblio moves hold_fill_targets for item 1');
1372     is($get_hold_fill_target2->biblionumber->biblionumber, $source_biblionumber, 'move_to_biblio does not move hold_fill_targets for item 2');
1373
1374     my $get_linktracker1 = $schema->resultset('Linktracker')->search({ itemnumber => $linktracker1->{itemnumber} })->single;
1375     my $get_linktracker2 = $schema->resultset('Linktracker')->search({ itemnumber => $linktracker2->{itemnumber} })->single;
1376     is($get_linktracker1->biblionumber->biblionumber, $target_biblionumber, 'move_to_biblio moves linktracker for item 1');
1377     is($get_linktracker2->biblionumber->biblionumber, $source_biblionumber, 'move_to_biblio does not move linktracker for item 2');
1378
1379     $schema->storage->txn_rollback;
1380 };
1381
1382 subtest 'columns_to_str' => sub {
1383     plan tests => 4;
1384
1385     $schema->storage->txn_begin;
1386
1387     my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
1388
1389     my $cache = Koha::Caches->get_instance();
1390     $cache->clear_from_cache("MarcStructure-0-");
1391     $cache->clear_from_cache("MarcStructure-1-");
1392     $cache->clear_from_cache("MarcSubfieldStructure-");
1393     $cache->clear_from_cache("libraries:name");
1394     $cache->clear_from_cache("itemtype:description:en");
1395     $cache->clear_from_cache("cn_sources:description");
1396     $cache->clear_from_cache("AV_descriptions:LOST");
1397
1398     # Creating subfields 'é', 'è' that are not linked with a kohafield
1399     Koha::MarcSubfieldStructures->search(
1400         {
1401             frameworkcode => '',
1402             tagfield => $itemtag,
1403             tagsubfield => ['é', 'è'],
1404         }
1405     )->delete;    # In case it exist already
1406
1407     # Ã© is not linked with a AV
1408     # Ã¨ is linked with AV branches
1409     Koha::MarcSubfieldStructure->new(
1410         {
1411             frameworkcode => '',
1412             tagfield      => $itemtag,
1413             tagsubfield   => 'é',
1414             kohafield     => undef,
1415             repeatable    => 1,
1416             defaultvalue  => 'ééé',
1417             tab           => 10,
1418         }
1419     )->store;
1420     Koha::MarcSubfieldStructure->new(
1421         {
1422             frameworkcode    => '',
1423             tagfield         => $itemtag,
1424             tagsubfield      => 'è',
1425             kohafield        => undef,
1426             repeatable       => 1,
1427             defaultvalue     => 'èèè',
1428             tab              => 10,
1429             authorised_value => 'branches',
1430         }
1431     )->store;
1432
1433     my $biblio = $builder->build_sample_biblio({ frameworkcode => '' });
1434     my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
1435     my $lost_av = $builder->build_object({ class => 'Koha::AuthorisedValues', value => { category => 'LOST', authorised_value => '42' }});
1436     my $dateaccessioned = '2020-12-15';
1437     my $library = Koha::Libraries->search->next;
1438     my $branchcode = $library->branchcode;
1439
1440     my $some_marc_xml = qq{<?xml version="1.0" encoding="UTF-8"?>
1441 <collection
1442   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1443   xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"
1444   xmlns="http://www.loc.gov/MARC21/slim">
1445
1446 <record>
1447   <leader>         a              </leader>
1448   <datafield tag="999" ind1=" " ind2=" ">
1449     <subfield code="é">value Ã©</subfield>
1450     <subfield code="è">$branchcode</subfield>
1451   </datafield>
1452 </record>
1453
1454 </collection>};
1455
1456     $item->update(
1457         {
1458             itemlost           => $lost_av->authorised_value,
1459             dateaccessioned    => $dateaccessioned,
1460             more_subfields_xml => $some_marc_xml,
1461         }
1462     );
1463
1464     $item = $item->get_from_storage;
1465
1466     my $s = $item->columns_to_str;
1467     is( $s->{itemlost}, $lost_av->lib, 'Attributes linked with AV replaced with description' );
1468     is( $s->{dateaccessioned}, '2020-12-15', 'Date attributes iso formatted');
1469     is( $s->{'é'}, 'value Ã©', 'subfield ok with more than a-Z');
1470     is( $s->{'è'}, $library->branchname );
1471
1472     $cache->clear_from_cache("MarcStructure-0-");
1473     $cache->clear_from_cache("MarcStructure-1-");
1474     $cache->clear_from_cache("MarcSubfieldStructure-");
1475     $cache->clear_from_cache("libraries:name");
1476     $cache->clear_from_cache("itemtype:description:en");
1477     $cache->clear_from_cache("cn_sources:description");
1478     $cache->clear_from_cache("AV_descriptions:LOST");
1479
1480     $schema->storage->txn_rollback;
1481 };
1482
1483 subtest 'strings_map() tests' => sub {
1484
1485     plan tests => 6;
1486
1487     $schema->storage->txn_begin;
1488
1489     my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber");
1490
1491     my $cache = Koha::Caches->get_instance();
1492     $cache->clear_from_cache("MarcStructure-0-");
1493     $cache->clear_from_cache("MarcStructure-1-");
1494     $cache->clear_from_cache("MarcSubfieldStructure-");
1495
1496     # Recreating subfields just to be sure tests will be ok
1497     # 1 => av (LOST)
1498     # 3 => no link
1499     # a => branches
1500     # y => itemtypes
1501     Koha::MarcSubfieldStructures->search(
1502         {
1503             frameworkcode => '',
1504             tagfield      => $itemtag,
1505             tagsubfield   => [ '1', '2', '3', 'a', 'y' ],
1506         }
1507     )->delete;    # In case it exist already
1508
1509     Koha::MarcSubfieldStructure->new(
1510         {
1511             authorised_value => 'LOST',
1512             defaultvalue     => '',
1513             frameworkcode    => '',
1514             kohafield        => 'items.itemlost',
1515             repeatable       => 1,
1516             tab              => 10,
1517             tagfield         => $itemtag,
1518             tagsubfield      => '1',
1519         }
1520     )->store;
1521     Koha::MarcSubfieldStructure->new(
1522         {
1523             authorised_value => 'cn_source',
1524             defaultvalue     => '',
1525             frameworkcode    => '',
1526             kohafield        => 'items.cn_source',
1527             repeatable       => 1,
1528             tab              => 10,
1529             tagfield         => $itemtag,
1530             tagsubfield      => '2',
1531         }
1532     )->store;
1533     Koha::MarcSubfieldStructure->new(
1534         {
1535             authorised_value => '',
1536             defaultvalue     => '',
1537             frameworkcode    => '',
1538             kohafield        => 'items.materials',
1539             repeatable       => 1,
1540             tab              => 10,
1541             tagfield         => $itemtag,
1542             tagsubfield      => '3',
1543         }
1544     )->store;
1545     Koha::MarcSubfieldStructure->new(
1546         {
1547             authorised_value => 'branches',
1548             defaultvalue     => '',
1549             frameworkcode    => '',
1550             kohafield        => 'items.homebranch',
1551             repeatable       => 1,
1552             tab              => 10,
1553             tagfield         => $itemtag,
1554             tagsubfield      => 'a',
1555         }
1556     )->store;
1557     Koha::MarcSubfieldStructure->new(
1558         {
1559             authorised_value => 'itemtypes',
1560             defaultvalue     => '',
1561             frameworkcode    => '',
1562             kohafield        => 'items.itype',
1563             repeatable       => 1,
1564             tab              => 10,
1565             tagfield         => $itemtag,
1566             tagsubfield      => 'y',
1567         }
1568     )->store;
1569
1570     my $itype   = $builder->build_object( { class => 'Koha::ItemTypes' } );
1571     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1572     my $biblio  = $builder->build_sample_biblio( { frameworkcode => '' } );
1573     my $item    = $builder->build_sample_item(
1574         {
1575             biblionumber => $biblio->id,
1576             library      => $library->id
1577         }
1578     );
1579
1580     Koha::AuthorisedValues->search( { authorised_value => 3, category => 'LOST' } )->delete;
1581     my $lost_av = $builder->build_object(
1582         {
1583             class => 'Koha::AuthorisedValues',
1584             value => {
1585                 authorised_value => 3,
1586                 category         => 'LOST',
1587                 lib              => 'internal description',
1588                 lib_opac         => 'public description',
1589             }
1590         }
1591     );
1592
1593     my $class_sort_rule  = $builder->build_object( { class => 'Koha::ClassSortRules', value => { sort_routine => 'Generic' } } );
1594     my $class_split_rule = $builder->build_object( { class => 'Koha::ClassSplitRules' } );
1595     my $class_source     = $builder->build_object(
1596         {
1597             class => 'Koha::ClassSources',
1598             value => {
1599                 class_sort_rule  => $class_sort_rule->class_sort_rule,
1600                 class_split_rule => $class_split_rule->class_split_rule,
1601             }
1602         }
1603     );
1604
1605     $item->set(
1606         {
1607             cn_source => $class_source->id,
1608             itemlost  => $lost_av->authorised_value,
1609             itype     => $itype->itemtype,
1610             materials => 'Suff',
1611         }
1612     )->store->discard_changes;
1613
1614     my $strings = $item->strings_map;
1615
1616     subtest 'unmapped field tests' => sub {
1617
1618         plan tests => 1;
1619
1620         ok( !exists $strings->{materials}, "Unmapped field not present" );
1621     };
1622
1623     subtest 'av handling' => sub {
1624
1625         plan tests => 4;
1626
1627         ok( exists $strings->{itemlost}, "'itemlost' entry exists" );
1628         is( $strings->{itemlost}->{str},      $lost_av->lib, "'str' set to av->lib" );
1629         is( $strings->{itemlost}->{type},     'av',          "'type' is 'av'" );
1630         is( $strings->{itemlost}->{category}, 'LOST',        "'category' exists and set to 'LOST'" );
1631     };
1632
1633     subtest 'cn_source handling' => sub {
1634
1635         plan tests => 3;
1636
1637         ok( exists $strings->{cn_source}, "'cn_source' entry exists" );
1638         is( $strings->{cn_source}->{str},  $class_source->description,    "'str' set to \$class_source->description" );
1639         is( $strings->{cn_source}->{type}, 'call_number_source', "type is 'library'" );
1640     };
1641
1642     subtest 'branches handling' => sub {
1643
1644         plan tests => 3;
1645
1646         ok( exists $strings->{homebranch}, "'homebranch' entry exists" );
1647         is( $strings->{homebranch}->{str},  $library->branchname, "'str' set to 'branchname'" );
1648         is( $strings->{homebranch}->{type}, 'library',            "type is 'library'" );
1649     };
1650
1651     subtest 'itemtype handling' => sub {
1652
1653         plan tests => 3;
1654
1655         ok( exists $strings->{itype}, "'itype' entry exists" );
1656         is( $strings->{itype}->{str},  $itype->description, "'str' correctly set" );
1657         is( $strings->{itype}->{type}, 'item_type',         "'type' is 'item_type'" );
1658     };
1659
1660     subtest 'public flag tests' => sub {
1661
1662         plan tests => 4;
1663
1664         $strings = $item->strings_map( { public => 1 } );
1665
1666         ok( exists $strings->{itemlost}, "'itemlost' entry exists" );
1667         is( $strings->{itemlost}->{str},      $lost_av->lib_opac, "'str' set to av->lib" );
1668         is( $strings->{itemlost}->{type},     'av',               "'type' is 'av'" );
1669         is( $strings->{itemlost}->{category}, 'LOST',             "'category' exists and set to 'LOST'" );
1670     };
1671
1672     $cache->clear_from_cache("MarcStructure-0-");
1673     $cache->clear_from_cache("MarcStructure-1-");
1674     $cache->clear_from_cache("MarcSubfieldStructure-");
1675
1676     $schema->storage->txn_rollback;
1677 };
1678
1679 subtest 'store() tests' => sub {
1680
1681     plan tests => 3;
1682
1683     subtest 'dateaccessioned handling' => sub {
1684
1685         plan tests => 3;
1686
1687         $schema->storage->txn_begin;
1688
1689         my $item = $builder->build_sample_item;
1690
1691         ok( defined $item->dateaccessioned, 'dateaccessioned is set' );
1692
1693         # reset dateaccessioned on the DB
1694         $schema->resultset('Item')->find({ itemnumber => $item->id })->update({ dateaccessioned => undef });
1695         $item->discard_changes;
1696
1697         ok( !defined $item->dateaccessioned );
1698
1699         # update something
1700         $item->replacementprice(100)->store->discard_changes;
1701
1702         ok( !defined $item->dateaccessioned, 'dateaccessioned not set on update if undefined' );
1703
1704         $schema->storage->txn_rollback;
1705     };
1706
1707     subtest '_set_found_trigger() tests' => sub {
1708
1709         plan tests => 9;
1710
1711         $schema->storage->txn_begin;
1712
1713         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1714         my $item   = $builder->build_sample_item({ itemlost => 1, itemlost_on => dt_from_string() });
1715
1716         # Add a lost item debit
1717         my $debit = $patron->account->add_debit(
1718             {
1719                 amount    => 10,
1720                 type      => 'LOST',
1721                 item_id   => $item->id,
1722                 interface => 'intranet',
1723             }
1724         );
1725
1726         # Add a lost item processing fee
1727         my $processing_debit = $patron->account->add_debit(
1728             {
1729                 amount    => 2,
1730                 type      => 'PROCESSING',
1731                 item_id   => $item->id,
1732                 interface => 'intranet',
1733             }
1734         );
1735
1736         my $lostreturn_policy = {
1737             lostreturn       => 'charge',
1738             processingreturn => 'refund'
1739         };
1740
1741         my $mocked_circ_rules = Test::MockModule->new('Koha::CirculationRules');
1742         $mocked_circ_rules->mock( 'get_lostreturn_policy', sub { return $lostreturn_policy; } );
1743
1744         # simulate it was found
1745         $item->set( { itemlost => 0 } )->store;
1746
1747         my $messages = $item->object_messages;
1748
1749         my $message_1 = $messages->[0];
1750
1751         is( $message_1->type,    'info',          'type is correct' );
1752         is( $message_1->message, 'lost_refunded', 'message is correct' );
1753
1754         # Find the refund credit
1755         my $credit = $debit->credits->next;
1756
1757         is_deeply(
1758             $message_1->payload,
1759             { credit_id => $credit->id },
1760             'type is correct'
1761         );
1762
1763         my $message_2 = $messages->[1];
1764
1765         is( $message_2->type,    'info',        'type is correct' );
1766         is( $message_2->message, 'lost_charge', 'message is correct' );
1767         is( $message_2->payload, undef,         'no payload' );
1768
1769         my $message_3 = $messages->[2];
1770         is( $message_3->message, 'processing_refunded', 'message is correct' );
1771
1772         my $processing_credit = $processing_debit->credits->next;
1773         is_deeply(
1774             $message_3->payload,
1775             { credit_id => $processing_credit->id },
1776             'type is correct'
1777         );
1778
1779         # Let's build a new item
1780         $item   = $builder->build_sample_item({ itemlost => 1, itemlost_on => dt_from_string() });
1781         $item->set( { itemlost => 0 } )->store;
1782
1783         $messages = $item->object_messages;
1784         is( scalar @{$messages}, 0, 'This item has no history, no associated lost fines, presumed not lost by patron, no messages returned');
1785
1786         $schema->storage->txn_rollback;
1787     };
1788
1789     subtest 'holds_queue update tests' => sub {
1790
1791         plan tests => 2;
1792
1793         $schema->storage->txn_begin;
1794
1795         my $biblio = $builder->build_sample_biblio;
1796
1797         my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1798         $mock->mock( 'enqueue', sub {
1799             my ( $self, $args ) = @_;
1800             is_deeply(
1801                 $args->{biblio_ids},
1802                 [ $biblio->id ],
1803                 '->store triggers a holds queue update for the related biblio'
1804             );
1805         } );
1806
1807         t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1808
1809         # new item
1810         my $item = $builder->build_sample_item({ biblionumber => $biblio->id });
1811
1812         # updated item
1813         $item->set({ reserves => 1 })->store;
1814
1815         t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1816         # updated item
1817         $item->set({ reserves => 0 })->store;
1818
1819         $schema->storage->txn_rollback;
1820     };
1821 };
1822
1823 subtest 'Recalls tests' => sub {
1824
1825     plan tests => 22;
1826
1827     $schema->storage->txn_begin;
1828
1829     my $item1 = $builder->build_sample_item;
1830     my $biblio = $item1->biblio;
1831     my $branchcode = $item1->holdingbranch;
1832     my $patron1 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $branchcode } });
1833     my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $branchcode } });
1834     my $patron3 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $branchcode } });
1835     my $item2 = $builder->build_object(
1836         {   class => 'Koha::Items',
1837             value => { holdingbranch => $branchcode, homebranch => $branchcode, biblionumber => $biblio->biblionumber, itype => $item1->effective_itemtype }
1838         }
1839     );
1840
1841     t::lib::Mocks::mock_userenv( { patron => $patron1 } );
1842     t::lib::Mocks::mock_preference('UseRecalls', 1);
1843
1844     my $recall1 = Koha::Recall->new(
1845         {   patron_id         => $patron1->borrowernumber,
1846             created_date      => \'NOW()',
1847             biblio_id         => $biblio->biblionumber,
1848             pickup_library_id => $branchcode,
1849             item_id           => $item1->itemnumber,
1850             expiration_date   => undef,
1851             item_level        => 1
1852         }
1853     )->store;
1854     my $recall2 = Koha::Recall->new(
1855         {   patron_id         => $patron2->borrowernumber,
1856             created_date      => \'NOW()',
1857             biblio_id         => $biblio->biblionumber,
1858             pickup_library_id => $branchcode,
1859             item_id           => $item1->itemnumber,
1860             expiration_date   => undef,
1861             item_level        => 1
1862         }
1863     )->store;
1864
1865     is( $item1->recall->patron_id, $patron1->borrowernumber, 'Correctly returns most relevant recall' );
1866
1867     $recall2->set_cancelled;
1868
1869     t::lib::Mocks::mock_preference('UseRecalls', 0);
1870     is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall with UseRecalls disabled" );
1871
1872     t::lib::Mocks::mock_preference("UseRecalls", 1);
1873
1874     $item1->update({ notforloan => 1 });
1875     is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall that is not for loan" );
1876     $item1->update({ notforloan => 0, itemlost => 1 });
1877     is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall that is marked lost" );
1878     $item1->update({ itemlost => 0, withdrawn => 1 });
1879     is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall that is withdrawn" );
1880     is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall item if not checked out" );
1881
1882     $item1->update({ withdrawn => 0 });
1883     C4::Circulation::AddIssue( $patron2->unblessed, $item1->barcode );
1884
1885     Koha::CirculationRules->set_rules({
1886         branchcode => $branchcode,
1887         categorycode => $patron1->categorycode,
1888         itemtype => $item1->effective_itemtype,
1889         rules => {
1890             recalls_allowed => 0,
1891             recalls_per_record => 1,
1892             on_shelf_recalls => 'all',
1893         },
1894     });
1895     is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if recalls_allowed = 0" );
1896
1897     Koha::CirculationRules->set_rules({
1898         branchcode => $branchcode,
1899         categorycode => $patron1->categorycode,
1900         itemtype => $item1->effective_itemtype,
1901         rules => {
1902             recalls_allowed => 1,
1903             recalls_per_record => 1,
1904             on_shelf_recalls => 'all',
1905         },
1906     });
1907     is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if patron has more existing recall(s) than recalls_allowed" );
1908     is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if patron has more existing recall(s) than recalls_per_record" );
1909     is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if patron has already recalled this item" );
1910
1911     my $reserve_id = C4::Reserves::AddReserve({ branchcode => $branchcode, borrowernumber => $patron1->borrowernumber, biblionumber => $item1->biblionumber, itemnumber => $item1->itemnumber });
1912     is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall item if patron has already reserved it" );
1913     C4::Reserves::ModReserve({ rank => 'del', reserve_id => $reserve_id, branchcode => $branchcode, itemnumber => $item1->itemnumber, borrowernumber => $patron1->borrowernumber, biblionumber => $item1->biblionumber });
1914
1915     $recall1->set_cancelled;
1916     is( $item1->can_be_recalled({ patron => $patron2 }), 0, "Can't recall if patron has already checked out an item attached to this biblio" );
1917
1918     is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if on_shelf_recalls = all and items are still available" );
1919
1920     Koha::CirculationRules->set_rules({
1921         branchcode => $branchcode,
1922         categorycode => $patron1->categorycode,
1923         itemtype => $item1->effective_itemtype,
1924         rules => {
1925             recalls_allowed => 1,
1926             recalls_per_record => 1,
1927             on_shelf_recalls => 'any',
1928         },
1929     });
1930     C4::Circulation::AddReturn( $item1->barcode, $branchcode );
1931     is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if no items are checked out" );
1932
1933     C4::Circulation::AddIssue( $patron2->unblessed, $item1->barcode );
1934     is( $item1->can_be_recalled({ patron => $patron1 }), 1, "Can recall item" );
1935
1936     $recall1 = Koha::Recall->new(
1937         {   patron_id         => $patron1->borrowernumber,
1938             created_date      => \'NOW()',
1939             biblio_id         => $biblio->biblionumber,
1940             pickup_library_id => $branchcode,
1941             item_id           => undef,
1942             expiration_date   => undef,
1943             item_level        => 0
1944         }
1945     )->store;
1946
1947     # Patron2 has Item1 checked out. Patron1 has placed a biblio-level recall on Biblio1, so check if Item1 can fulfill Patron1's recall.
1948
1949     Koha::CirculationRules->set_rules({
1950         branchcode => $branchcode,
1951         categorycode => $patron1->categorycode,
1952         itemtype => $item1->effective_itemtype,
1953         rules => {
1954             recalls_allowed => 0,
1955             recalls_per_record => 1,
1956             on_shelf_recalls => 'any',
1957         },
1958     });
1959     is( $item1->can_be_waiting_recall, 0, "Recalls not allowed for this itemtype" );
1960
1961     Koha::CirculationRules->set_rules({
1962         branchcode => $branchcode,
1963         categorycode => $patron1->categorycode,
1964         itemtype => $item1->effective_itemtype,
1965         rules => {
1966             recalls_allowed => 1,
1967             recalls_per_record => 1,
1968             on_shelf_recalls => 'any',
1969         },
1970     });
1971     is( $item1->can_be_waiting_recall, 1, "Recalls are allowed for this itemtype" );
1972
1973     # check_recalls tests
1974
1975     $recall1 = Koha::Recall->new(
1976         {   patron_id         => $patron2->borrowernumber,
1977             created_date      => \'NOW()',
1978             biblio_id         => $biblio->biblionumber,
1979             pickup_library_id => $branchcode,
1980             item_id           => $item1->itemnumber,
1981             expiration_date   => undef,
1982             item_level        => 1
1983         }
1984     )->store;
1985     $recall2 = Koha::Recall->new(
1986         {   patron_id         => $patron1->borrowernumber,
1987             created_date      => \'NOW()',
1988             biblio_id         => $biblio->biblionumber,
1989             pickup_library_id => $branchcode,
1990             item_id           => undef,
1991             expiration_date   => undef,
1992             item_level        => 0
1993         }
1994     )->store;
1995     $recall2->set_waiting( { item => $item1 } );
1996     is( $item1->has_pending_recall, 1, 'Item has pending recall' );
1997
1998     # return a waiting recall
1999     my $check_recall = $item1->check_recalls;
2000     is( $check_recall->patron_id, $patron1->borrowernumber, "Waiting recall is highest priority and returned" );
2001
2002     $recall2->revert_waiting;
2003
2004     is( $item1->has_pending_recall, 0, 'Item does not have pending recall' );
2005
2006     # return recall based on recalldate
2007     $check_recall = $item1->check_recalls;
2008     is( $check_recall->patron_id, $patron1->borrowernumber, "No waiting recall, so oldest recall is returned" );
2009
2010     $recall1->set_cancelled;
2011
2012     # return a biblio-level recall
2013     $check_recall = $item1->check_recalls;
2014     is( $check_recall->patron_id, $patron1->borrowernumber, "Only remaining recall is returned" );
2015
2016     $recall2->set_cancelled;
2017
2018     $schema->storage->txn_rollback;
2019 };
2020
2021 subtest 'Notforloan tests' => sub {
2022
2023     plan tests => 3;
2024
2025     $schema->storage->txn_begin;
2026
2027     my $item1 = $builder->build_sample_item;
2028     $item1->update({ notforloan => 0 });
2029     $item1->itemtype->notforloan(0);
2030     is ( $item1->is_notforloan, 0, 'Notforloan is correctly false by item status and item type');
2031     $item1->update({ notforloan => 1 });
2032     is ( $item1->is_notforloan, 1, 'Notforloan is correctly true by item status');
2033     $item1->update({ notforloan => 0 });
2034     $item1->itemtype->update({ notforloan => 1 });
2035     is ( $item1->is_notforloan, 1, 'Notforloan is correctly true by item type');
2036
2037     $schema->storage->txn_rollback;
2038 };
2039
2040 subtest 'item_group() tests' => sub {
2041
2042     plan tests => 4;
2043
2044     $schema->storage->txn_begin;
2045
2046     my $biblio = $builder->build_sample_biblio();
2047     my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
2048     my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
2049
2050     is( $item_1->item_group, undef, 'Item 1 has no item group');
2051     is( $item_2->item_group, undef, 'Item 2 has no item group');
2052
2053     my $item_group_1 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store();
2054     my $item_group_2 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store();
2055
2056     $item_group_1->add_item({ item_id => $item_1->id });
2057     $item_group_2->add_item({ item_id => $item_2->id });
2058
2059     is( $item_1->item_group->id, $item_group_1->id, 'Got item group 1 correctly' );
2060     is( $item_2->item_group->id, $item_group_2->id, 'Got item group 2 correctly' );
2061
2062     $schema->storage->txn_rollback;
2063 };
2064
2065 subtest 'has_pending_recall() tests' => sub {
2066
2067     plan tests => 2;
2068
2069     $schema->storage->txn_begin;
2070
2071     my $library = $builder->build_object({ class => 'Koha::Libraries' });
2072     my $item    = $builder->build_sample_item;
2073     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
2074
2075     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2076     t::lib::Mocks::mock_preference( 'UseRecalls', 1 );
2077
2078     C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
2079
2080     my ($recall) = Koha::Recalls->add_recall({ biblio => $item->biblio, item => $item, patron => $patron });
2081
2082     ok( !$item->has_pending_recall, 'The item has no pending recalls' );
2083
2084     $recall->status('waiting')->store;
2085
2086     ok( $item->has_pending_recall, 'The item has a pending recall' );
2087
2088     $schema->storage->txn_rollback;
2089 };
2090
2091 subtest 'is_denied_renewal' => sub {
2092     plan tests => 11;
2093
2094     $schema->storage->txn_begin;
2095
2096     my $library = $builder->build_object({ class => 'Koha::Libraries'});
2097
2098     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2099         homebranch => $library->branchcode,
2100         withdrawn => 1,
2101         itype => 'HIDE',
2102         location => 'PROC',
2103         itemcallnumber => undef,
2104         itemnotes => "",
2105         }
2106     });
2107
2108     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2109         homebranch => $library->branchcode,
2110         withdrawn => 0,
2111         itype => 'NOHIDE',
2112         location => 'NOPROC'
2113         }
2114     });
2115
2116     my $idr_rules = "";
2117     C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules);
2118     is( $deny_book->is_denied_renewal, 0, 'Renewal allowed when no rules' );
2119
2120     $idr_rules="withdrawn: [1]";
2121     C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules);
2122     is( $deny_book->is_denied_renewal, 1, 'Renewal blocked when 1 rules (withdrawn)' );
2123     is( $allow_book->is_denied_renewal, 0, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2124
2125     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2126     is( $deny_book->is_denied_renewal, 1, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2127     is( $allow_book->is_denied_renewal, 0, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2128
2129     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2130     C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules);
2131     is( $deny_book->is_denied_renewal, 1, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2132     is( $allow_book->is_denied_renewal, 0, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2133
2134     $idr_rules="itemcallnumber: [NULL]";
2135     C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules);
2136     is( $deny_book->is_denied_renewal, 1, 'Renewal blocked for undef when NULL in pref' );
2137
2138     $idr_rules="itemcallnumber: ['']";
2139     C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules);
2140     is( $deny_book->is_denied_renewal, 0, 'Renewal not blocked for undef when "" in pref' );
2141
2142     $idr_rules="itemnotes: [NULL]";
2143     C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules);
2144     is( $deny_book->is_denied_renewal, 0, 'Renewal not blocked for "" when NULL in pref' );
2145
2146     $idr_rules="itemnotes: ['']";
2147     C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules);
2148     is( $deny_book->is_denied_renewal, 1, 'Renewal blocked for empty string when "" in pref' );
2149
2150     $schema->storage->txn_rollback;
2151 };