Bug 21800: (RM follow-up) Fix unit tests
[koha.git] / t / db_dependent / Items.t
1 #!/usr/bin/perl
2 #
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 use Data::Dumper;
20
21 use MARC::Record;
22 use C4::Items;
23 use C4::Biblio;
24 use Koha::Items;
25 use Koha::Database;
26 use Koha::DateUtils qw( dt_from_string );
27 use Koha::Library;
28 use Koha::DateUtils;
29 use Koha::MarcSubfieldStructures;
30 use Koha::Caches;
31 use Koha::AuthorisedValues;
32
33 use t::lib::Mocks;
34 use t::lib::TestBuilder;
35
36 use Test::More tests => 15;
37
38 use Test::Warn;
39
40 my $schema = Koha::Database->new->schema;
41 my $location = 'My Location';
42
43 subtest 'General Add, Get and Del tests' => sub {
44
45     plan tests => 16;
46
47     $schema->storage->txn_begin;
48
49     my $builder = t::lib::TestBuilder->new;
50     my $library = $builder->build({
51         source => 'Branch',
52     });
53     my $itemtype = $builder->build({
54         source => 'Itemtype',
55     });
56
57     # Create a biblio instance for testing
58     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
59     my $biblio = $builder->build_sample_biblio();
60
61     # Add an item.
62     my $item = $builder->build_sample_item(
63         {
64             biblionumber => $biblio->biblionumber,
65             library      => $library->{branchcode},
66             location     => $location,
67             itype        => $itemtype->{itemtype}
68         }
69     );
70     my $itemnumber = $item->itemnumber;
71     cmp_ok($item->biblionumber, '==', $biblio->biblionumber, "New item is linked to correct biblionumber.");
72     cmp_ok($item->biblioitemnumber, '==', $biblio->biblioitem->biblioitemnumber, "New item is linked to correct biblioitemnumber.");
73
74     # Get item.
75     my $getitem = Koha::Items->find($itemnumber);
76     cmp_ok($getitem->itemnumber, '==', $itemnumber, "Retrieved item has correct itemnumber.");
77     cmp_ok($getitem->biblioitemnumber, '==', $item->biblioitemnumber, "Retrieved item has correct biblioitemnumber."); # We are not testing anything useful here
78     is( $getitem->location, $location, "The location should not have been modified" );
79     is( $getitem->permanent_location, $location, "The permanent_location should have been set to the location value" );
80
81
82     # Do not modify anything, and do not explode!
83     my $dbh = C4::Context->dbh;
84     local $dbh->{RaiseError} = 1;
85     $getitem->set({})->store;
86
87     # Modify item; setting barcode.
88     $getitem->barcode('987654321')->store;
89     my $moditem = Koha::Items->find($itemnumber);
90     cmp_ok($moditem->barcode, '==', '987654321', 'Modified item barcode successfully to: '.$moditem->barcode . '.');
91
92     # Delete item.
93     $moditem->delete;
94     my $getdeleted = Koha::Items->find($itemnumber);
95     is($getdeleted, undef, "Item deleted as expected.");
96
97     $itemnumber = $builder->build_sample_item(
98         {
99             biblionumber => $biblio->biblionumber,
100             library      => $library->{branchcode},
101             location     => $location,
102             permanent_location => 'my permanent location',
103             itype        => $itemtype->{itemtype}
104         }
105     )->itemnumber;
106     $getitem = Koha::Items->find($itemnumber);
107     is( $getitem->location, $location, "The location should not have been modified" );
108     is( $getitem->permanent_location, 'my permanent location', "The permanent_location should not have modified" );
109
110     my $new_location = "New location";
111     $getitem->location($new_location)->store;
112     $getitem = Koha::Items->find($itemnumber);
113     is( $getitem->location, $new_location, "The location should have been set to correct location" );
114     is( $getitem->permanent_location, $new_location, "The permanent_location should have been set to location" );
115
116     $getitem->location('CART')->store;
117     $getitem = Koha::Items->find($itemnumber);
118     is( $getitem->location, 'CART', "The location should have been set to CART" );
119     is( $getitem->permanent_location, $new_location, "The permanent_location should not have been set to CART" );
120
121     t::lib::Mocks::mock_preference('item-level_itypes', '1');
122     $getitem = Koha::Items->find($itemnumber);
123     is( $getitem->effective_itemtype, $itemtype->{itemtype}, "Itemtype set correctly when using item-level_itypes" );
124     t::lib::Mocks::mock_preference('item-level_itypes', '0');
125     $getitem = Koha::Items->find($itemnumber);
126     is( $getitem->effective_itemtype, $biblio->biblioitem->itemtype, "Itemtype set correctly when not using item-level_itypes" );
127
128     $schema->storage->txn_rollback;
129 };
130
131 subtest 'ModItem tests' => sub {
132     plan tests => 6;
133
134     $schema->storage->txn_begin;
135
136     my $builder = t::lib::TestBuilder->new;
137     my $item    = $builder->build_sample_item();
138
139     my @fields = qw( itemlost withdrawn damaged );
140     for my $field (@fields) {
141         my $field_on = $field."_on";
142
143         $item->$field(1)->store;
144         $item->discard_changes;
145         is( output_pref({ str => $item->$field_on, dateonly => 1 }), output_pref({ dt => dt_from_string(), dateonly => 1 }), "When updating $field, $field_on is updated" );
146
147         $item->$field(0)->store;
148         $item->discard_changes;
149         is( $item->$field_on, undef, "When clearing $field, $field_on is cleared" );
150     }
151
152     $schema->storage->txn_rollback;
153
154 };
155
156 subtest 'ModItemTransfer tests' => sub {
157     plan tests => 8;
158
159     $schema->storage->txn_begin;
160
161     my $builder = t::lib::TestBuilder->new;
162     my $item    = $builder->build_sample_item();
163
164     my $library1 = $builder->build(
165         {
166             source => 'Branch',
167         }
168     );
169     my $library2 = $builder->build(
170         {
171             source => 'Branch',
172         }
173     );
174
175     ModItemTransfer( $item->itemnumber, $library1->{branchcode},
176         $library2->{branchcode} );
177
178     my $transfers = Koha::Item::Transfers->search(
179         {
180             itemnumber => $item->itemnumber
181         }
182     );
183
184     is( $transfers->count, 1, "One transfer created with ModItemTransfer" );
185     $item->discard_changes;
186     is($item->holdingbranch, $library1->{branchcode}, "Items holding branch was updated to frombranch");
187
188     ModItemTransfer( $item->itemnumber, $library2->{branchcode},
189         $library1->{branchcode} );
190     $transfers = Koha::Item::Transfers->search(
191         { itemnumber => $item->itemnumber, },
192         { order_by   => { '-asc' => 'branchtransfer_id' } }
193     );
194
195     is($transfers->count, 2, "Second transfer recorded on second call of ModItemTransfer");
196     my $transfer1 = $transfers->next;
197     my $transfer2 = $transfers->next;
198     isnt($transfer1->datearrived, undef, "First transfer marked as completed by ModItemTransfer");
199     like($transfer1->comments,qr/^Canceled/, "First transfer contains 'Canceled' comment");
200     is($transfer2->datearrived, undef, "Second transfer is now the active transfer");
201     $item->discard_changes;
202     is($item->holdingbranch, $library2->{branchcode}, "Items holding branch was updated to frombranch");
203
204     # Check 'reason' is populated when passed
205     ModItemTransfer( $item->itemnumber, $library2->{branchcode},
206         $library1->{branchcode}, "Manual" );
207
208     $transfers = Koha::Item::Transfers->search(
209         { itemnumber => $item->itemnumber, },
210         { order_by   => { '-desc' => 'branchtransfer_id' } }
211     );
212
213     my $transfer3 = $transfers->next;
214     is($transfer3->reason, 'Manual', "Reason set via ModItemTransfer");
215
216     $schema->storage->txn_rollback;
217 };
218
219 subtest 'GetHiddenItemnumbers tests' => sub {
220
221     plan tests => 11;
222
223     # This sub is controlled by the OpacHiddenItems system preference.
224
225     $schema->storage->txn_begin;
226
227     my $builder = t::lib::TestBuilder->new;
228     my $library1 = $builder->build({
229         source => 'Branch',
230     });
231
232     my $library2 = $builder->build({
233         source => 'Branch',
234     });
235     my $itemtype = $builder->build({
236         source => 'Itemtype',
237     });
238
239     # Create a new biblio
240     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
241     my $biblio = $builder->build_sample_biblio();
242
243     # Add two items
244     my $item1_itemnumber = $builder->build_sample_item(
245         {
246             biblionumber => $biblio->biblionumber,
247             library      => $library1->{branchcode},
248             withdrawn    => 1,
249             itype        => $itemtype->{itemtype}
250         }
251     )->itemnumber;
252     my $item2_itemnumber = $builder->build_sample_item(
253         {
254             biblionumber => $biblio->biblionumber,
255             library      => $library2->{branchcode},
256             withdrawn    => 0,
257             itype        => $itemtype->{itemtype}
258         }
259     )->itemnumber;
260     my $opachiddenitems;
261     my @itemnumbers = ($item1_itemnumber,$item2_itemnumber);
262     my @hidden;
263     my @items;
264     push @items, Koha::Items->find( $item1_itemnumber )->unblessed;
265     push @items, Koha::Items->find( $item2_itemnumber )->unblessed;
266
267     # Empty OpacHiddenItems
268     t::lib::Mocks::mock_preference('OpacHiddenItems','');
269     ok( !defined( GetHiddenItemnumbers( { items => \@items } ) ),
270         "Hidden items list undef if OpacHiddenItems empty");
271
272     # Blank spaces
273     t::lib::Mocks::mock_preference('OpacHiddenItems','  ');
274     ok( scalar GetHiddenItemnumbers( { items => \@items } ) == 0,
275         "Hidden items list empty if OpacHiddenItems only contains blanks");
276
277     # One variable / value
278     $opachiddenitems = "
279         withdrawn: [1]";
280     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
281     @hidden = GetHiddenItemnumbers( { items => \@items } );
282     ok( scalar @hidden == 1, "Only one hidden item");
283     is( $hidden[0], $item1_itemnumber, "withdrawn=1 is hidden");
284
285     # One variable, two values
286     $opachiddenitems = "
287         withdrawn: [1,0]";
288     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
289     @hidden = GetHiddenItemnumbers( { items => \@items } );
290     ok( scalar @hidden == 2, "Two items hidden");
291     is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and withdrawn=0 hidden");
292
293     # Two variables, a value each
294     $opachiddenitems = "
295         withdrawn: [1]
296         homebranch: [$library2->{branchcode}]
297     ";
298     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
299     @hidden = GetHiddenItemnumbers( { items => \@items } );
300     ok( scalar @hidden == 2, "Two items hidden");
301     is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and homebranch library2 hidden");
302
303     # Override hidden with patron category
304     t::lib::Mocks::mock_preference( 'OpacHiddenItemsExceptions', 'S' );
305     @hidden = GetHiddenItemnumbers( { items => \@items, borcat => 'PT' } );
306     ok( scalar @hidden == 2, "Two items still hidden");
307     @hidden = GetHiddenItemnumbers( { items => \@items, borcat => 'S' } );
308     ok( scalar @hidden == 0, "Two items not hidden");
309
310     # Valid OpacHiddenItems, empty list
311     @items = ();
312     @hidden = GetHiddenItemnumbers( { items => \@items } );
313     ok( scalar @hidden == 0, "Empty items list, no item hidden");
314
315     $schema->storage->txn_rollback;
316 };
317
318 subtest 'GetItemsInfo tests' => sub {
319
320     plan tests => 9;
321
322     $schema->storage->txn_begin;
323
324     my $builder = t::lib::TestBuilder->new;
325     my $library1 = $builder->build({
326         source => 'Branch',
327     });
328     my $library2 = $builder->build({
329         source => 'Branch',
330     });
331     my $itemtype = $builder->build({
332         source => 'Itemtype',
333     });
334
335     Koha::AuthorisedValues->delete;
336     my $av1 = Koha::AuthorisedValue->new(
337         {
338             category         => 'RESTRICTED',
339             authorised_value => '1',
340             lib              => 'Restricted Access',
341             lib_opac         => 'Restricted Access OPAC',
342         }
343     )->store();
344
345     # Add a biblio
346     my $biblio = $builder->build_sample_biblio();
347     # Add an item
348     my $itemnumber = $builder->build_sample_item(
349         {
350             biblionumber  => $biblio->biblionumber,
351             homebranch    => $library1->{branchcode},
352             holdingbranch => $library2->{branchcode},
353             itype         => $itemtype->{itemtype},
354             restricted    => 1,
355         }
356     )->itemnumber;
357
358     my $library = Koha::Libraries->find( $library1->{branchcode} );
359     $library->opac_info("homebranch OPAC info");
360     $library->store;
361
362     $library = Koha::Libraries->find( $library2->{branchcode} );
363     $library->opac_info("holdingbranch OPAC info");
364     $library->store;
365
366     my @results = GetItemsInfo( $biblio->biblionumber );
367     ok( @results, 'GetItemsInfo returns results');
368
369     is( $results[0]->{ home_branch_opac_info }, "homebranch OPAC info",
370         'GetItemsInfo returns the correct home branch OPAC info notice' );
371     is( $results[0]->{ holding_branch_opac_info }, "holdingbranch OPAC info",
372         'GetItemsInfo returns the correct holding branch OPAC info notice' );
373     is( exists( $results[0]->{ onsite_checkout } ), 1,
374         'GetItemsInfo returns a onsite_checkout key' );
375     is( $results[0]->{ restricted }, 1,
376         'GetItemsInfo returns a restricted value code' );
377     is( $results[0]->{ restrictedvalue }, "Restricted Access",
378         'GetItemsInfo returns a restricted value description (staff)' );
379     is( $results[0]->{ restrictedvalueopac }, "Restricted Access OPAC",
380         'GetItemsInfo returns a restricted value description (OPAC)' );
381
382     #place item into holds queue
383     my $dbh = C4::Context->dbh;
384     @results = GetItemsInfo( $biblio->biblionumber );
385     is( $results[0]->{ has_pending_hold }, "0",
386         'Hold not marked as pending/unavailable if nothing in tmp_holdsqueue for item' );
387
388     $dbh->do(q{INSERT INTO tmp_holdsqueue (biblionumber, itemnumber, surname, borrowernumber ) VALUES (?, ?, "Zorro", 42)}, undef, $biblio->biblionumber, $itemnumber);
389     @results = GetItemsInfo( $biblio->biblionumber );
390     is( $results[0]->{ has_pending_hold }, "1",
391         'Hold marked as pending/unavailable if tmp_holdsqueue is not empty for item' );
392
393     $schema->storage->txn_rollback;
394 };
395
396 subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub {
397
398     plan tests => 4;
399
400     $schema->storage->txn_begin;
401
402     my $biblio = $schema->resultset('Biblio')->create({
403         title       => "Test title",
404         datecreated => dt_from_string,
405         biblioitems => [ { itemtype => 'BIB_LEVEL' } ],
406     });
407     my $biblioitem = $biblio->biblioitems->first;
408     my $item = $schema->resultset('Item')->create({
409         biblioitemnumber => $biblioitem->biblioitemnumber,
410         biblionumber     => $biblio->biblionumber,
411         itype            => "ITEM_LEVEL",
412     });
413
414     t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
415     is( $item->effective_itemtype(), 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' );
416
417     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
418     is( $item->effective_itemtype(), 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' );
419
420     # If itemtype is not defined and item-level_level item types are set
421     # fallback to biblio-level itemtype (Bug 14651) and warn
422     $item->itype( undef );
423     $item->update();
424     my $effective_itemtype;
425     warning_is { $effective_itemtype = $item->effective_itemtype() }
426                 "item-level_itypes set but no itemtype set for item (".$item->itemnumber.")",
427                 '->effective_itemtype() raises a warning when falling back to bib-level';
428
429     ok( defined $effective_itemtype &&
430                 $effective_itemtype eq 'BIB_LEVEL',
431         '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' );
432
433     $schema->storage->txn_rollback;
434 };
435
436 subtest 'SearchItems test' => sub {
437     plan tests => 15;
438
439     $schema->storage->txn_begin;
440     my $dbh = C4::Context->dbh;
441     my $builder = t::lib::TestBuilder->new;
442
443     my $library1 = $builder->build({
444         source => 'Branch',
445     });
446     my $library2 = $builder->build({
447         source => 'Branch',
448     });
449     my $itemtype = $builder->build({
450         source => 'Itemtype',
451     });
452
453     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
454     my ($cpl_items_before) = SearchItems( { field => 'homebranch', query => $library1->{branchcode} } );
455
456     my $biblio = $builder->build_sample_biblio({ title => 'Silence in the library' });
457     $builder->build_sample_biblio({ title => 'Silence in the shadow' });
458
459     my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
460
461     # Add two items
462     my $item1_itemnumber = $builder->build_sample_item(
463         {
464             biblionumber => $biblio->biblionumber,
465             library      => $library1->{branchcode},
466             itype        => $itemtype->{itemtype}
467         }
468     )->itemnumber;
469     my $item2_itemnumber = $builder->build_sample_item(
470         {
471             biblionumber => $biblio->biblionumber,
472             library      => $library2->{branchcode},
473             itype        => $itemtype->{itemtype}
474         }
475     )->itemnumber;
476
477     my ($items, $total_results);
478
479     ($items, $total_results) = SearchItems();
480     is($total_results, $initial_items_count + 2, "Created 2 new items");
481     is(scalar @$items, $total_results, "SearchItems() returns all items");
482
483     ($items, $total_results) = SearchItems(undef, {rows => 1});
484     is($total_results, $initial_items_count + 2);
485     is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item");
486
487     # Search all items where homebranch = 'CPL'
488     my $filter = {
489         field => 'homebranch',
490         query => $library1->{branchcode},
491         operator => '=',
492     };
493     ($items, $total_results) = SearchItems($filter);
494     ok($total_results > 0, "There is at least one CPL item");
495     my $all_items_are_CPL = 1;
496     foreach my $item (@$items) {
497         if ($item->{homebranch} ne $library1->{branchcode}) {
498             $all_items_are_CPL = 0;
499             last;
500         }
501     }
502     ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
503
504     # Search all items where homebranch != 'CPL'
505     $filter = {
506         field => 'homebranch',
507         query => $library1->{branchcode},
508         operator => '!=',
509     };
510     ($items, $total_results) = SearchItems($filter);
511     ok($total_results > 0, "There is at least one non-CPL item");
512     my $all_items_are_not_CPL = 1;
513     foreach my $item (@$items) {
514         if ($item->{homebranch} eq $library1->{branchcode}) {
515             $all_items_are_not_CPL = 0;
516             last;
517         }
518     }
519     ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
520
521     # Search all items where biblio title (245$a) is like 'Silence in the %'
522     $filter = {
523         field => 'marc:245$a',
524         query => 'Silence in the %',
525         operator => 'like',
526     };
527     ($items, $total_results) = SearchItems($filter);
528     ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'");
529
530     # Search all items where biblio title is 'Silence in the library'
531     # and homebranch is 'CPL'
532     $filter = {
533         conjunction => 'AND',
534         filters => [
535             {
536                 field => 'marc:245$a',
537                 query => 'Silence in the %',
538                 operator => 'like',
539             },
540             {
541                 field => 'homebranch',
542                 query => $library1->{branchcode},
543                 operator => '=',
544             },
545         ],
546     };
547     ($items, $total_results) = SearchItems($filter);
548     my $found = 0;
549     foreach my $item (@$items) {
550         if ($item->{itemnumber} == $item1_itemnumber) {
551             $found = 1;
552             last;
553         }
554     }
555     ok($found, "item1 found");
556
557     my $frameworkcode = q||;
558     my ($itemfield) = GetMarcFromKohaField( 'items.itemnumber' );
559
560     # Create item subfield 'z' without link
561     $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
562     $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", ?)', undef, $itemfield, $frameworkcode);
563
564     # Clear cache
565     my $cache = Koha::Caches->get_instance();
566     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
567     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
568     $cache->clear_from_cache("default_value_for_mod_marc-");
569     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
570
571     my $item3_record = new MARC::Record;
572     $item3_record->append_fields(
573         new MARC::Field(
574             $itemfield, '', '',
575             'z' => 'foobar',
576             'y' => $itemtype->{itemtype}
577         )
578     );
579     my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
580         $biblio->biblionumber);
581
582     # Search item where item subfield z is "foobar"
583     $filter = {
584         field => 'marc:' . $itemfield . '$z',
585         query => 'foobar',
586         operator => 'like',
587     };
588     ($items, $total_results) = SearchItems($filter);
589     ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
590
591     # Link $z to items.itemnotes (and make sure there is no other subfields
592     # linked to it)
593     $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
594     $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
595
596     # Clear cache
597     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
598     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
599     $cache->clear_from_cache("default_value_for_mod_marc-");
600     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
601
602     ModItemFromMarc($item3_record, $biblio->biblionumber, $item3_itemnumber);
603
604     # Make sure the link is used
605     my $item3 = Koha::Items->find($item3_itemnumber);
606     ok($item3->itemnotes eq 'foobar', 'itemnotes eq "foobar"');
607
608     # Do the same search again.
609     # This time it will search in items.itemnotes
610     ($items, $total_results) = SearchItems($filter);
611     ok(scalar @$items == 1, 'found 1 item with itemnotes = "foobar"');
612
613     my ($cpl_items_after) = SearchItems( { field => 'homebranch', query => $library1->{branchcode} } );
614     is( ( scalar( @$cpl_items_after ) - scalar ( @$cpl_items_before ) ), 1, 'SearchItems should return something' );
615
616     # Issues count may be NULL
617     $filter = {
618         conjunction => 'AND',
619         filters => [
620             {
621                 field => 'issues',
622                 query => 0,
623                 operator => '=',
624             },
625             {
626                 field => 'homebranch',
627                 query => $library1->{branchcode},
628                 operator => '=',
629             },
630         ],
631     };
632     ($items, $total_results) = SearchItems($filter);
633     is($total_results, 1, "Search items.issues is NULL with filter issues = 0");
634
635     $schema->storage->txn_rollback;
636 };
637
638 subtest 'Koha::Item(s) tests' => sub {
639
640     plan tests => 7;
641
642     $schema->storage->txn_begin();
643
644     my $builder = t::lib::TestBuilder->new;
645     my $library1 = $builder->build({
646         source => 'Branch',
647     });
648     my $library2 = $builder->build({
649         source => 'Branch',
650     });
651     my $itemtype = $builder->build({
652         source => 'Itemtype',
653     });
654
655     # Create a biblio and item for testing
656     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
657     my $biblio = $builder->build_sample_biblio();
658     my $itemnumber = $builder->build_sample_item(
659         {
660             biblionumber  => $biblio->biblionumber,
661             homebranch    => $library1->{branchcode},
662             holdingbranch => $library2->{branchcode},
663             itype         => $itemtype->{itemtype}
664         }
665     )->itemnumber;
666
667     # Get item.
668     my $item = Koha::Items->find( $itemnumber );
669     is( ref($item), 'Koha::Item', "Got Koha::Item" );
670
671     my $homebranch = $item->home_branch();
672     is( ref($homebranch), 'Koha::Library', "Got Koha::Library from home_branch method" );
673     is( $homebranch->branchcode(), $library1->{branchcode}, "Home branch code matches homebranch" );
674
675     my $holdingbranch = $item->holding_branch();
676     is( ref($holdingbranch), 'Koha::Library', "Got Koha::Library from holding_branch method" );
677     is( $holdingbranch->branchcode(), $library2->{branchcode}, "Home branch code matches holdingbranch" );
678
679     $biblio = $item->biblio();
680     is( ref($item->biblio), 'Koha::Biblio', "Got Koha::Biblio from biblio method" );
681     is( $item->biblio->title(), $biblio->title, 'Title matches biblio title' );
682
683     $schema->storage->txn_rollback;
684 };
685
686 subtest 'C4::Biblio::EmbedItemsInMarcBiblio' => sub {
687     plan tests => 8;
688
689     $schema->storage->txn_begin();
690
691     my $builder = t::lib::TestBuilder->new;
692     my $library1 = $builder->build({
693         source => 'Branch',
694     });
695     my $library2 = $builder->build({
696         source => 'Branch',
697     });
698     my $itemtype = $builder->build({
699         source => 'Itemtype',
700     });
701
702     my $biblio = $builder->build_sample_biblio();
703     my $item_infos = [
704         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
705         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
706         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
707         { homebranch => $library2->{branchcode}, holdingbranch => $library2->{branchcode} },
708         { homebranch => $library2->{branchcode}, holdingbranch => $library2->{branchcode} },
709         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
710         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
711         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
712     ];
713     my $number_of_items = scalar @$item_infos;
714     my $number_of_items_with_homebranch_is_CPL =
715       grep { $_->{homebranch} eq $library1->{branchcode} } @$item_infos;
716
717     my @itemnumbers;
718     for my $item_info (@$item_infos) {
719         my $itemnumber = $builder->build_sample_item(
720             {
721                 biblionumber  => $biblio->biblionumber,
722                 homebranch    => $item_info->{homebranch},
723                 holdingbranch => $item_info->{holdingbranch},
724                 itype         => $itemtype->{itemtype}
725             }
726         )->itemnumber;
727
728         push @itemnumbers, $itemnumber;
729     }
730
731     # Emptied the OpacHiddenItems pref
732     t::lib::Mocks::mock_preference( 'OpacHiddenItems', '' );
733
734     my ($itemfield) =
735       C4::Biblio::GetMarcFromKohaField( 'items.itemnumber' );
736     my $record = C4::Biblio::GetMarcBiblio({ biblionumber => $biblio->biblionumber });
737     warning_is { C4::Biblio::EmbedItemsInMarcBiblio() }
738     { carped => 'EmbedItemsInMarcBiblio: No MARC record passed' },
739       'Should carp is no record passed.';
740
741     C4::Biblio::EmbedItemsInMarcBiblio({
742         marc_record  => $record,
743         biblionumber => $biblio->biblionumber });
744     my @items = $record->field($itemfield);
745     is( scalar @items, $number_of_items, 'Should return all items' );
746
747     my $marc_with_items = C4::Biblio::GetMarcBiblio({
748         biblionumber => $biblio->biblionumber,
749         embed_items  => 1 });
750     is_deeply( $record, $marc_with_items, 'A direct call to GetMarcBiblio with items matches');
751
752     C4::Biblio::EmbedItemsInMarcBiblio({
753         marc_record  => $record,
754         biblionumber => $biblio->biblionumber,
755         item_numbers => [ $itemnumbers[1], $itemnumbers[3] ] });
756     @items = $record->field($itemfield);
757     is( scalar @items, 2, 'Should return all items present in the list' );
758
759     C4::Biblio::EmbedItemsInMarcBiblio({
760         marc_record  => $record,
761         biblionumber => $biblio->biblionumber,
762         opac         => 1 });
763     @items = $record->field($itemfield);
764     is( scalar @items, $number_of_items, 'Should return all items for opac' );
765
766     my $opachiddenitems = "
767         homebranch: ['$library1->{branchcode}']";
768     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
769
770     C4::Biblio::EmbedItemsInMarcBiblio({
771         marc_record  => $record,
772         biblionumber => $biblio->biblionumber });
773     @items = $record->field($itemfield);
774     is( scalar @items,
775         $number_of_items,
776         'Even with OpacHiddenItems set, all items should have been embedded' );
777
778     C4::Biblio::EmbedItemsInMarcBiblio({
779         marc_record  => $record,
780         biblionumber => $biblio->biblionumber,
781         opac         => 1 });
782     @items = $record->field($itemfield);
783     is(
784         scalar @items,
785         $number_of_items - $number_of_items_with_homebranch_is_CPL,
786 'For OPAC, the pref OpacHiddenItems should have been take into account. Only items with homebranch ne CPL should have been embedded'
787     );
788
789     $opachiddenitems = "
790         homebranch: ['$library1->{branchcode}', '$library2->{branchcode}']";
791     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
792     C4::Biblio::EmbedItemsInMarcBiblio({
793         marc_record  => $record,
794         biblionumber => $biblio->biblionumber,
795         opac         => 1 });
796     @items = $record->field($itemfield);
797     is(
798         scalar @items,
799         0,
800 'For OPAC, If all items are hidden, no item should have been embedded'
801     );
802
803     $schema->storage->txn_rollback;
804 };
805
806
807 subtest 'get_hostitemnumbers_of' => sub {
808     plan tests => 3;
809
810     $schema->storage->txn_begin;
811     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
812     my $builder = t::lib::TestBuilder->new;
813
814     # Host item field without 0 or 9
815     my $bib1 = MARC::Record->new();
816     $bib1->append_fields(
817         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
818         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
819         MARC::Field->new('773', ' ', ' ', b => 'b without 0 or 9'),
820     );
821     my ($biblionumber1, $bibitemnum1) = AddBiblio($bib1, '');
822     my @itemnumbers1 = C4::Items::get_hostitemnumbers_of( $biblionumber1 );
823     is( scalar @itemnumbers1, 0, '773 without 0 or 9');
824
825     # Correct host item field, analytical records on
826     t::lib::Mocks::mock_preference('EasyAnalyticalRecords', 1);
827     my $hostitem = $builder->build_sample_item();
828     my $bib2 = MARC::Record->new();
829     $bib2->append_fields(
830         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
831         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
832         MARC::Field->new('773', ' ', ' ', 0 => $hostitem->biblionumber , 9 => $hostitem->itemnumber, b => 'b' ),
833     );
834     my ($biblionumber2, $bibitemnum2) = AddBiblio($bib2, '');
835     my @itemnumbers2 = C4::Items::get_hostitemnumbers_of( $biblionumber2 );
836     is( scalar @itemnumbers2, 1, '773 with 0 and 9, EasyAnalyticalRecords on');
837
838     # Correct host item field, analytical records off
839     t::lib::Mocks::mock_preference('EasyAnalyticalRecords', 0);
840     @itemnumbers2 = C4::Items::get_hostitemnumbers_of( $biblionumber2 );
841     is( scalar @itemnumbers2, 0, '773 with 0 and 9, EasyAnalyticalRecords off');
842
843     $schema->storage->txn_rollback;
844 };
845
846 subtest 'Test logging for ModItem' => sub {
847
848     plan tests => 3;
849
850     t::lib::Mocks::mock_preference('CataloguingLog', 1);
851
852     $schema->storage->txn_begin;
853
854     my $builder = t::lib::TestBuilder->new;
855     my $library = $builder->build({
856         source => 'Branch',
857     });
858     my $itemtype = $builder->build({
859         source => 'Itemtype',
860     });
861
862     # Create a biblio instance for testing
863     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
864     my $biblio = $builder->build_sample_biblio();
865
866     # Add an item.
867     my $item = $builder->build_sample_item(
868         {
869             biblionumber => $biblio->biblionumber,
870             library      => $library->{homebranch},
871             location     => $location,
872             itype        => $itemtype->{itemtype}
873         }
874     );
875
876     # False means no logging
877     $schema->resultset('ActionLog')->search()->delete();
878     $item->location($location)->store({ log_action => 0 });
879     is( $schema->resultset('ActionLog')->count(), 0, 'False value does not trigger logging' );
880
881     # True means logging
882     $schema->resultset('ActionLog')->search()->delete();
883     $item->location('new location')->store({ log_action => 1 });
884     is( $schema->resultset('ActionLog')->count(), 1, 'True value does trigger logging' );
885
886     # Undefined defaults to true
887     $schema->resultset('ActionLog')->search()->delete();
888     $item->location($location)->store();
889     is( $schema->resultset('ActionLog')->count(), 1, 'Undefined value defaults to true, triggers logging' );
890
891     $schema->storage->txn_rollback;
892 };
893
894 subtest 'Check stockrotationitem relationship' => sub {
895     plan tests => 1;
896
897     $schema->storage->txn_begin();
898
899     my $builder = t::lib::TestBuilder->new;
900     my $item = $builder->build({ source => 'Item' });
901
902     $builder->build({
903         source => 'Stockrotationitem',
904         value  => { itemnumber_id => $item->{itemnumber} }
905     });
906
907     my $sritem = Koha::Items->find($item->{itemnumber})->stockrotationitem;
908     isa_ok( $sritem, 'Koha::StockRotationItem', "Relationship works and correctly creates Koha::Object." );
909
910     $schema->storage->txn_rollback;
911 };
912
913 subtest 'Check add_to_rota method' => sub {
914     plan tests => 2;
915
916     $schema->storage->txn_begin();
917
918     my $builder = t::lib::TestBuilder->new;
919     my $item = $builder->build({ source => 'Item' });
920     my $rota = $builder->build({ source => 'Stockrotationrota' });
921     my $srrota = Koha::StockRotationRotas->find($rota->{rota_id});
922
923     $builder->build({
924         source => 'Stockrotationstage',
925         value  => { rota_id => $rota->{rota_id} },
926     });
927
928     my $sritem = Koha::Items->find($item->{itemnumber});
929     $sritem->add_to_rota($rota->{rota_id});
930
931     is(
932         Koha::StockRotationItems->find($item->{itemnumber})->stage_id,
933         $srrota->stockrotationstages->next->stage_id,
934         "Adding to a rota a new sritem item being assigned to its first stage."
935     );
936
937     my $newrota = $builder->build({ source => 'Stockrotationrota' });
938
939     my $srnewrota = Koha::StockRotationRotas->find($newrota->{rota_id});
940
941     $builder->build({
942         source => 'Stockrotationstage',
943         value  => { rota_id => $newrota->{rota_id} },
944     });
945
946     $sritem->add_to_rota($newrota->{rota_id});
947
948     is(
949         Koha::StockRotationItems->find($item->{itemnumber})->stage_id,
950         $srnewrota->stockrotationstages->next->stage_id,
951         "Moving an item results in that sritem being assigned to the new first stage."
952     );
953
954     $schema->storage->txn_rollback;
955 };
956
957 subtest 'Split subfields in Item2Marc (Bug 21774)' => sub {
958     plan tests => 3;
959     $schema->storage->txn_begin;
960
961     my $builder = t::lib::TestBuilder->new;
962     my $biblio = $builder->build({ source => 'Biblio', value => { frameworkcode => q{} } });
963     my $item = $builder->build({ source => 'Item', value => { biblionumber => $biblio->{biblionumber}, ccode => 'A|B' } });
964
965     Koha::MarcSubfieldStructures->search({ tagfield => '952', tagsubfield => '8' })->delete; # theoretical precaution
966     Koha::MarcSubfieldStructures->search({ kohafield => 'items.ccode' })->delete;
967     my $mapping = Koha::MarcSubfieldStructure->new(
968         {
969             frameworkcode => q{},
970             tagfield      => '952',
971             tagsubfield   => '8',
972             kohafield     => 'items.ccode',
973             repeatable    => 1
974         }
975     )->store;
976     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
977
978     # Start testing
979     my $marc = C4::Items::Item2Marc( $item, $biblio->{biblionumber} );
980     my @subs = $marc->subfield( $mapping->tagfield, $mapping->tagsubfield );
981     is( @subs, 2, 'Expect two subfields' );
982     is( $subs[0], 'A', 'First subfield matches' );
983     is( $subs[1], 'B', 'Second subfield matches' );
984
985     $schema->storage->txn_rollback;
986 };
987
988 subtest 'ModItemFromMarc' => sub {
989     plan tests => 2;
990     $schema->storage->txn_begin;
991
992     my $builder = t::lib::TestBuilder->new;
993     my ($itemfield) = GetMarcFromKohaField( 'items.itemnumber' );
994     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' });
995     my $biblio = $builder->build_sample_biblio;
996     my ( $lost_tag, $lost_sf ) = GetMarcFromKohaField( 'items.itemlost' );
997     my $item_record = new MARC::Record;
998     $item_record->append_fields(
999         MARC::Field->new(
1000             $itemfield, '', '',
1001             'y' => $itemtype->itemtype,
1002         ),
1003         MARC::Field->new(
1004             $itemfield, '', '',
1005             $lost_sf => '1',
1006         ),
1007     );
1008     my (undef, undef, $itemnumber) = AddItemFromMarc($item_record,
1009         $biblio->biblionumber);
1010
1011     my $item = Koha::Items->find($itemnumber);
1012     is( $item->itemlost, 1, 'itemlost picked from the item marc');
1013
1014     my $updated_item_record = new MARC::Record;
1015     $updated_item_record->append_fields(
1016         MARC::Field->new(
1017             $itemfield, '', '',
1018             'y' => $itemtype->itemtype,
1019         )
1020     );
1021
1022     my $updated_item = ModItemFromMarc($updated_item_record, $biblio->biblionumber, $itemnumber);
1023     is( $updated_item->{itemlost}, 0, 'itemlost should have been reset to the default value in DB' );
1024
1025     $schema->storage->txn_rollback;
1026 };