+use Koha::Items;
+use Koha::Database;
+use Koha::DateUtils qw( dt_from_string );
+use Koha::Library;
+use Koha::DateUtils;
+use Koha::MarcSubfieldStructures;
+use Koha::Caches;
+use Koha::AuthorisedValues;
+
+use t::lib::Mocks;
+use t::lib::TestBuilder;
+
+use Test::More tests => 15;
+
+use Test::Warn;
+
+my $schema = Koha::Database->new->schema;
+my $location = 'My Location';
+
+subtest 'General Add, Get and Del tests' => sub {
+
+ plan tests => 16;
+
+ $schema->storage->txn_begin;
+
+ my $builder = t::lib::TestBuilder->new;
+ my $library = $builder->build({
+ source => 'Branch',
+ });
+ my $itemtype = $builder->build({
+ source => 'Itemtype',
+ });
+
+ # Create a biblio instance for testing
+ t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
+ my $biblio = $builder->build_sample_biblio();
+
+ # Add an item.
+ my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $library->{branchcode}, holdingbranch => $library->{branchcode}, location => $location, itype => $itemtype->{itemtype} } , $biblio->biblionumber);
+ cmp_ok($item_bibnum, '==', $biblio->biblionumber, "New item is linked to correct biblionumber.");
+ cmp_ok($item_bibitemnum, '==', $biblio->biblioitem->biblioitemnumber, "New item is linked to correct biblioitemnumber.");
+
+ # Get item.
+ my $getitem = Koha::Items->find($itemnumber);
+ cmp_ok($getitem->itemnumber, '==', $itemnumber, "Retrieved item has correct itemnumber.");
+ cmp_ok($getitem->biblioitemnumber, '==', $item_bibitemnum, "Retrieved item has correct biblioitemnumber.");
+ is( $getitem->location, $location, "The location should not have been modified" );
+ is( $getitem->permanent_location, $location, "The permanent_location should have been set to the location value" );
+
+
+ # Do not modify anything, and do not explode!
+ my $dbh = C4::Context->dbh;
+ local $dbh->{RaiseError} = 1;
+ ModItem({}, $biblio->biblionumber, $itemnumber);
+
+ # Modify item; setting barcode.
+ ModItem({ barcode => '987654321' }, $biblio->biblionumber, $itemnumber);
+ my $moditem = Koha::Items->find($itemnumber);
+ cmp_ok($moditem->barcode, '==', '987654321', 'Modified item barcode successfully to: '.$moditem->barcode . '.');
+
+ # Delete item.
+ DelItem({ biblionumber => $biblio->biblionumber, itemnumber => $itemnumber });
+ my $getdeleted = Koha::Items->find($itemnumber);
+ is($getdeleted, undef, "Item deleted as expected.");
+
+ ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $library->{branchcode}, holdingbranch => $library->{branchcode}, location => $location, permanent_location => 'my permanent location', itype => $itemtype->{itemtype} } , $biblio->biblionumber);
+ $getitem = Koha::Items->find($itemnumber);
+ is( $getitem->location, $location, "The location should not have been modified" );
+ is( $getitem->permanent_location, 'my permanent location', "The permanent_location should not have modified" );
+
+ ModItem({ location => $location }, $biblio->biblionumber, $itemnumber);
+ $getitem = Koha::Items->find($itemnumber);
+ is( $getitem->location, $location, "The location should have been set to correct location" );
+ is( $getitem->permanent_location, $location, "The permanent_location should have been set to location" );
+
+ ModItem({ location => 'CART' }, $biblio->biblionumber, $itemnumber);
+ $getitem = Koha::Items->find($itemnumber);
+ is( $getitem->location, 'CART', "The location should have been set to CART" );
+ is( $getitem->permanent_location, $location, "The permanent_location should not have been set to CART" );
+
+ t::lib::Mocks::mock_preference('item-level_itypes', '1');
+ $getitem = Koha::Items->find($itemnumber);
+ is( $getitem->effective_itemtype, $itemtype->{itemtype}, "Itemtype set correctly when using item-level_itypes" );
+ t::lib::Mocks::mock_preference('item-level_itypes', '0');
+ $getitem = Koha::Items->find($itemnumber);
+ is( $getitem->effective_itemtype, $biblio->biblioitem->itemtype, "Itemtype set correctly when not using item-level_itypes" );
+
+ $schema->storage->txn_rollback;
+};
+
+subtest 'ModItem tests' => sub {
+ plan tests => 6;
+
+ $schema->storage->txn_begin;
+
+ my $builder = t::lib::TestBuilder->new;
+ my $item = $builder->build({
+ source => 'Item',
+ value => {
+ itemlost => 0,
+ damaged => 0,
+ withdrawn => 0,
+ itemlost_on => undef,
+ damaged_on => undef,
+ withdrawn_on => undef,
+ }
+ });
+
+ my @fields = qw( itemlost withdrawn damaged );
+ for my $field (@fields) {
+ $item->{$field} = 1;
+ ModItem( $item, $item->{biblionumber}, $item->{itemnumber} );
+ my $post_mod_item = Koha::Items->find({ itemnumber => $item->{itemnumber} })->unblessed;
+ is( output_pref({ str => $post_mod_item->{$field."_on"}, dateonly => 1 }), output_pref({ dt => dt_from_string(), dateonly => 1 }), "When updating $field, $field"."_on is updated" );
+
+ $item->{$field} = 0;
+ ModItem( $item, $item->{biblionumber}, $item->{itemnumber} );
+ $post_mod_item = Koha::Items->find({ itemnumber => $item->{itemnumber} })->unblessed;
+ is( $post_mod_item->{$field."_on"}, undef, "When clearing $field, $field"."_on is cleared" );
+ }
+
+ $schema->storage->txn_rollback;
+
+};
+
+subtest 'GetHiddenItemnumbers tests' => sub {
+
+ plan tests => 11;
+
+ # This sub is controlled by the OpacHiddenItems system preference.
+
+ $schema->storage->txn_begin;
+
+ my $builder = t::lib::TestBuilder->new;
+ my $library1 = $builder->build({
+ source => 'Branch',
+ });
+
+ my $library2 = $builder->build({
+ source => 'Branch',
+ });
+ my $itemtype = $builder->build({
+ source => 'Itemtype',
+ });
+
+ # Create a new biblio
+ t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
+ my $biblio = $builder->build_sample_biblio();
+
+ # Add two items
+ my ( $item1_bibnum, $item1_bibitemnum, $item1_itemnumber ) = AddItem(
+ {
+ homebranch => $library1->{branchcode},
+ holdingbranch => $library1->{branchcode},
+ withdrawn => 1,
+ itype => $itemtype->{itemtype},
+ },
+ $biblio->biblionumber
+ );
+ my ( $item2_bibnum, $item2_bibitemnum, $item2_itemnumber ) = AddItem(
+ {
+ homebranch => $library2->{branchcode},
+ holdingbranch => $library2->{branchcode},
+ withdrawn => 0,
+ itype => $itemtype->{itemtype},
+ },
+ $biblio->biblionumber
+ );
+
+ my $opachiddenitems;
+ my @itemnumbers = ($item1_itemnumber,$item2_itemnumber);
+ my @hidden;
+ my @items;
+ push @items, Koha::Items->find( $item1_itemnumber )->unblessed;
+ push @items, Koha::Items->find( $item2_itemnumber )->unblessed;
+
+ # Empty OpacHiddenItems
+ t::lib::Mocks::mock_preference('OpacHiddenItems','');
+ ok( !defined( GetHiddenItemnumbers( { items => \@items } ) ),
+ "Hidden items list undef if OpacHiddenItems empty");
+
+ # Blank spaces
+ t::lib::Mocks::mock_preference('OpacHiddenItems',' ');
+ ok( scalar GetHiddenItemnumbers( { items => \@items } ) == 0,
+ "Hidden items list empty if OpacHiddenItems only contains blanks");
+
+ # One variable / value
+ $opachiddenitems = "
+ withdrawn: [1]";
+ t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
+ @hidden = GetHiddenItemnumbers( { items => \@items } );
+ ok( scalar @hidden == 1, "Only one hidden item");
+ is( $hidden[0], $item1_itemnumber, "withdrawn=1 is hidden");
+
+ # One variable, two values
+ $opachiddenitems = "
+ withdrawn: [1,0]";
+ t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
+ @hidden = GetHiddenItemnumbers( { items => \@items } );
+ ok( scalar @hidden == 2, "Two items hidden");
+ is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and withdrawn=0 hidden");
+
+ # Two variables, a value each
+ $opachiddenitems = "
+ withdrawn: [1]
+ homebranch: [$library2->{branchcode}]
+ ";
+ t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
+ @hidden = GetHiddenItemnumbers( { items => \@items } );
+ ok( scalar @hidden == 2, "Two items hidden");
+ is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and homebranch library2 hidden");
+
+ # Override hidden with patron category
+ t::lib::Mocks::mock_preference( 'OpacHiddenItemsExceptions', 'S' );
+ @hidden = GetHiddenItemnumbers( { items => \@items, borcat => 'PT' } );
+ ok( scalar @hidden == 2, "Two items still hidden");
+ @hidden = GetHiddenItemnumbers( { items => \@items, borcat => 'S' } );
+ ok( scalar @hidden == 0, "Two items not hidden");
+
+ # Valid OpacHiddenItems, empty list
+ @items = ();
+ @hidden = GetHiddenItemnumbers( { items => \@items } );
+ ok( scalar @hidden == 0, "Empty items list, no item hidden");
+
+ $schema->storage->txn_rollback;
+};
+
+subtest 'GetItemsInfo tests' => sub {
+
+ plan tests => 9;
+
+ $schema->storage->txn_begin;
+
+ my $builder = t::lib::TestBuilder->new;
+ my $library1 = $builder->build({
+ source => 'Branch',
+ });
+ my $library2 = $builder->build({
+ source => 'Branch',
+ });
+ my $itemtype = $builder->build({
+ source => 'Itemtype',
+ });
+
+ Koha::AuthorisedValues->delete;
+ my $av1 = Koha::AuthorisedValue->new(
+ {
+ category => 'RESTRICTED',
+ authorised_value => '1',
+ lib => 'Restricted Access',
+ lib_opac => 'Restricted Access OPAC',
+ }
+ )->store();
+
+ # Add a biblio
+ my $biblio = $builder->build_sample_biblio();
+ # Add an item
+ my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
+ {
+ homebranch => $library1->{branchcode},
+ holdingbranch => $library2->{branchcode},
+ itype => $itemtype->{itemtype},
+ restricted => 1,
+ },
+ $biblio->biblionumber
+ );
+
+ my $library = Koha::Libraries->find( $library1->{branchcode} );
+ $library->opac_info("homebranch OPAC info");
+ $library->store;
+
+ $library = Koha::Libraries->find( $library2->{branchcode} );
+ $library->opac_info("holdingbranch OPAC info");
+ $library->store;
+
+ my @results = GetItemsInfo( $biblio->biblionumber );
+ ok( @results, 'GetItemsInfo returns results');
+
+ is( $results[0]->{ home_branch_opac_info }, "homebranch OPAC info",
+ 'GetItemsInfo returns the correct home branch OPAC info notice' );
+ is( $results[0]->{ holding_branch_opac_info }, "holdingbranch OPAC info",
+ 'GetItemsInfo returns the correct holding branch OPAC info notice' );
+ is( exists( $results[0]->{ onsite_checkout } ), 1,
+ 'GetItemsInfo returns a onsite_checkout key' );
+ is( $results[0]->{ restricted }, 1,
+ 'GetItemsInfo returns a restricted value code' );
+ is( $results[0]->{ restrictedvalue }, "Restricted Access",
+ 'GetItemsInfo returns a restricted value description (staff)' );
+ is( $results[0]->{ restrictedvalueopac }, "Restricted Access OPAC",
+ 'GetItemsInfo returns a restricted value description (OPAC)' );
+
+ #place item into holds queue
+ my $dbh = C4::Context->dbh;
+ @results = GetItemsInfo( $biblio->biblionumber );
+ is( $results[0]->{ has_pending_hold }, "0",
+ 'Hold not marked as pending/unavailable if nothing in tmp_holdsqueue for item' );
+
+ $dbh->do(q{INSERT INTO tmp_holdsqueue (biblionumber, itemnumber, surname, borrowernumber ) VALUES (?, ?, "Zorro", 42)}, undef, $item_bibnum, $itemnumber);
+ @results = GetItemsInfo( $biblio->biblionumber );
+ is( $results[0]->{ has_pending_hold }, "1",
+ 'Hold marked as pending/unavailable if tmp_holdsqueue is not empty for item' );
+
+ $schema->storage->txn_rollback;
+};
+
+subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub {
+
+ plan tests => 4;
+
+ $schema->storage->txn_begin;
+
+ my $biblio = $schema->resultset('Biblio')->create({
+ title => "Test title",
+ datecreated => dt_from_string,
+ biblioitems => [ { itemtype => 'BIB_LEVEL' } ],
+ });
+ my $biblioitem = $biblio->biblioitems->first;
+ my $item = $schema->resultset('Item')->create({
+ biblioitemnumber => $biblioitem->biblioitemnumber,
+ biblionumber => $biblio->biblionumber,
+ itype => "ITEM_LEVEL",
+ });
+
+ t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
+ is( $item->effective_itemtype(), 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' );
+
+ t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
+ is( $item->effective_itemtype(), 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' );
+
+ # If itemtype is not defined and item-level_level item types are set
+ # fallback to biblio-level itemtype (Bug 14651) and warn
+ $item->itype( undef );
+ $item->update();
+ my $effective_itemtype;
+ warning_is { $effective_itemtype = $item->effective_itemtype() }
+ "item-level_itypes set but no itemtype set for item (".$item->itemnumber.")",
+ '->effective_itemtype() raises a warning when falling back to bib-level';
+
+ ok( defined $effective_itemtype &&
+ $effective_itemtype eq 'BIB_LEVEL',
+ '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' );
+
+ $schema->storage->txn_rollback;
+};
+
+subtest 'SearchItems test' => sub {
+ plan tests => 15;
+
+ $schema->storage->txn_begin;
+ my $dbh = C4::Context->dbh;
+ my $builder = t::lib::TestBuilder->new;
+
+ my $library1 = $builder->build({
+ source => 'Branch',
+ });
+ my $library2 = $builder->build({
+ source => 'Branch',
+ });
+ my $itemtype = $builder->build({
+ source => 'Itemtype',
+ });
+
+ t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
+ my $cpl_items_before = SearchItemsByField( 'homebranch', $library1->{branchcode});
+
+ my $biblio = $builder->build_sample_biblio({ title => 'Silence in the library' });
+ $builder->build_sample_biblio({ title => 'Silence in the shadow' });
+
+ my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
+
+ # Add two items
+ my (undef, undef, $item1_itemnumber) = AddItem({
+ homebranch => $library1->{branchcode},
+ holdingbranch => $library1->{branchcode},
+ itype => $itemtype->{itemtype},
+ }, $biblio->biblionumber);
+ my (undef, undef, $item2_itemnumber) = AddItem({
+ homebranch => $library2->{branchcode},
+ holdingbranch => $library2->{branchcode},
+ itype => $itemtype->{itemtype},
+ issues => 3,
+ }, $biblio->biblionumber);
+
+ my ($items, $total_results);
+
+ ($items, $total_results) = SearchItems();
+ is($total_results, $initial_items_count + 2, "Created 2 new items");
+ is(scalar @$items, $total_results, "SearchItems() returns all items");
+
+ ($items, $total_results) = SearchItems(undef, {rows => 1});
+ is($total_results, $initial_items_count + 2);
+ is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item");
+
+ # Search all items where homebranch = 'CPL'
+ my $filter = {
+ field => 'homebranch',
+ query => $library1->{branchcode},
+ operator => '=',
+ };
+ ($items, $total_results) = SearchItems($filter);
+ ok($total_results > 0, "There is at least one CPL item");
+ my $all_items_are_CPL = 1;
+ foreach my $item (@$items) {
+ if ($item->{homebranch} ne $library1->{branchcode}) {
+ $all_items_are_CPL = 0;
+ last;
+ }
+ }
+ ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
+
+ # Search all items where homebranch != 'CPL'
+ $filter = {
+ field => 'homebranch',
+ query => $library1->{branchcode},
+ operator => '!=',
+ };
+ ($items, $total_results) = SearchItems($filter);
+ ok($total_results > 0, "There is at least one non-CPL item");
+ my $all_items_are_not_CPL = 1;
+ foreach my $item (@$items) {
+ if ($item->{homebranch} eq $library1->{branchcode}) {
+ $all_items_are_not_CPL = 0;
+ last;
+ }
+ }
+ ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
+
+ # Search all items where biblio title (245$a) is like 'Silence in the %'
+ $filter = {
+ field => 'marc:245$a',
+ query => 'Silence in the %',
+ operator => 'like',
+ };
+ ($items, $total_results) = SearchItems($filter);
+ ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'");
+
+ # Search all items where biblio title is 'Silence in the library'
+ # and homebranch is 'CPL'
+ $filter = {
+ conjunction => 'AND',
+ filters => [
+ {
+ field => 'marc:245$a',
+ query => 'Silence in the %',
+ operator => 'like',
+ },
+ {
+ field => 'homebranch',
+ query => $library1->{branchcode},
+ operator => '=',
+ },
+ ],
+ };
+ ($items, $total_results) = SearchItems($filter);
+ my $found = 0;
+ foreach my $item (@$items) {
+ if ($item->{itemnumber} == $item1_itemnumber) {
+ $found = 1;
+ last;
+ }
+ }
+ ok($found, "item1 found");
+
+ my $frameworkcode = q||;
+ my ($itemfield) = GetMarcFromKohaField( 'items.itemnumber' );
+
+ # Create item subfield 'z' without link
+ $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
+ $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", ?)', undef, $itemfield, $frameworkcode);
+
+ # Clear cache
+ my $cache = Koha::Caches->get_instance();
+ $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
+ $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
+ $cache->clear_from_cache("default_value_for_mod_marc-");
+ $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
+
+ my $item3_record = new MARC::Record;
+ $item3_record->append_fields(
+ new MARC::Field(
+ $itemfield, '', '',
+ 'z' => 'foobar',
+ 'y' => $itemtype->{itemtype}
+ )
+ );
+ my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
+ $biblio->biblionumber);
+
+ # Search item where item subfield z is "foobar"
+ $filter = {
+ field => 'marc:' . $itemfield . '$z',
+ query => 'foobar',
+ operator => 'like',
+ };
+ ($items, $total_results) = SearchItems($filter);
+ ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
+
+ # Link $z to items.itemnotes (and make sure there is no other subfields
+ # linked to it)
+ $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
+ $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
+
+ # Clear cache
+ $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
+ $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
+ $cache->clear_from_cache("default_value_for_mod_marc-");
+ $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
+
+ ModItemFromMarc($item3_record, $biblio->biblionumber, $item3_itemnumber);
+
+ # Make sure the link is used
+ my $item3 = Koha::Items->find($item3_itemnumber);
+ ok($item3->itemnotes eq 'foobar', 'itemnotes eq "foobar"');
+
+ # Do the same search again.
+ # This time it will search in items.itemnotes
+ ($items, $total_results) = SearchItems($filter);
+ ok(scalar @$items == 1, 'found 1 item with itemnotes = "foobar"');
+
+ my $cpl_items_after = SearchItemsByField( 'homebranch', $library1->{branchcode});
+ is( ( scalar( @$cpl_items_after ) - scalar ( @$cpl_items_before ) ), 1, 'SearchItemsByField should return something' );
+
+ # Issues count may be NULL
+ $filter = {
+ conjunction => 'AND',
+ filters => [
+ {
+ field => 'issues',
+ query => 0,
+ operator => '=',
+ },
+ {
+ field => 'homebranch',
+ query => $library1->{branchcode},
+ operator => '=',
+ },
+ ],
+ };
+ ($items, $total_results) = SearchItems($filter);
+ is($total_results, 1, "Search items.issues is NULL with filter issues = 0");