3 # This file is part of Koha.
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.
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.
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>.
22 use C4::Items qw( ModItemTransfer SearchItems AddItemFromMarc ModItemFromMarc get_hostitemnumbers_of Item2Marc ModDateLastSeen CartToShelf );
23 use C4::Biblio qw( GetMarcFromKohaField AddBiblio );
24 use C4::Circulation qw( AddIssue );
25 use Koha::BackgroundJobs;
28 use Koha::DateUtils qw( dt_from_string );
31 use Koha::MarcSubfieldStructures;
33 use Koha::AuthorisedValues;
36 use t::lib::TestBuilder;
38 use Test::More tests => 13;
42 my $schema = Koha::Database->new->schema;
43 my $location = 'My Location';
45 subtest 'General Add, Get and Del tests' => sub {
49 $schema->storage->txn_begin;
51 my $builder = t::lib::TestBuilder->new;
52 my $library = $builder->build({
55 my $itemtype = $builder->build({
59 # Create a biblio instance for testing
60 t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
61 my $biblio = $builder->build_sample_biblio();
64 my $item = $builder->build_sample_item(
66 biblionumber => $biblio->biblionumber,
67 library => $library->{branchcode},
68 location => $location,
69 itype => $itemtype->{itemtype}
72 my $itemnumber = $item->itemnumber;
73 cmp_ok($item->biblionumber, '==', $biblio->biblionumber, "New item is linked to correct biblionumber.");
74 cmp_ok($item->biblioitemnumber, '==', $biblio->biblioitem->biblioitemnumber, "New item is linked to correct biblioitemnumber.");
77 my $getitem = Koha::Items->find($itemnumber);
78 cmp_ok($getitem->itemnumber, '==', $itemnumber, "Retrieved item has correct itemnumber.");
79 cmp_ok($getitem->biblioitemnumber, '==', $item->biblioitemnumber, "Retrieved item has correct biblioitemnumber."); # We are not testing anything useful here
80 is( $getitem->location, $location, "The location should not have been modified" );
81 is( $getitem->permanent_location, $location, "The permanent_location should have been set to the location value" );
84 # Do not modify anything, and do not explode!
85 $getitem->set({})->store;
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 . '.');
94 my $getdeleted = Koha::Items->find($itemnumber);
95 is($getdeleted, undef, "Item deleted as expected.");
97 $itemnumber = $builder->build_sample_item(
99 biblionumber => $biblio->biblionumber,
100 library => $library->{branchcode},
101 location => $location,
102 permanent_location => 'my permanent location',
103 itype => $itemtype->{itemtype}
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" );
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" );
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" );
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" );
128 $schema->storage->txn_rollback;
131 subtest 'ModItemTransfer tests' => sub {
134 $schema->storage->txn_begin;
136 my $builder = t::lib::TestBuilder->new;
137 my $item = $builder->build_sample_item();
139 my $library1 = $builder->build(
144 my $library2 = $builder->build(
150 ModItemTransfer( $item->itemnumber, $library1->{branchcode},
151 $library2->{branchcode}, 'Manual' );
153 my $transfers = Koha::Item::Transfers->search(
155 itemnumber => $item->itemnumber
159 is( $transfers->count, 1, "One transfer created with ModItemTransfer" );
160 $item->discard_changes;
161 is($item->holdingbranch, $library1->{branchcode}, "Items holding branch was updated to frombranch");
163 ModItemTransfer( $item->itemnumber, $library2->{branchcode},
164 $library1->{branchcode}, 'Manual' );
165 $transfers = Koha::Item::Transfers->search(
166 { itemnumber => $item->itemnumber, },
167 { order_by => { '-asc' => 'branchtransfer_id' } }
170 is($transfers->count, 2, "Second transfer recorded on second call of ModItemTransfer");
171 my $transfer1 = $transfers->next;
172 my $transfer2 = $transfers->next;
173 isnt($transfer1->datecancelled, undef, "First transfer marked as cancelled by ModItemTransfer");
174 like($transfer1->cancellation_reason,qr/^Manual/, "First transfer contains cancellation_reason 'Manual'");
175 is($transfer2->datearrived, undef, "Second transfer is now the active transfer");
176 $item->discard_changes;
177 is($item->holdingbranch, $library2->{branchcode}, "Items holding branch was updated to frombranch");
179 # Check 'reason' is populated when passed
180 ModItemTransfer( $item->itemnumber, $library2->{branchcode},
181 $library1->{branchcode}, "Manual" );
183 $transfers = Koha::Item::Transfers->search(
184 { itemnumber => $item->itemnumber, },
185 { order_by => { '-desc' => 'branchtransfer_id' } }
188 my $transfer3 = $transfers->next;
189 is($transfer3->reason, 'Manual', "Reason set via ModItemTransfer");
191 $schema->storage->txn_rollback;
194 subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub {
198 $schema->storage->txn_begin;
200 my $biblio = $schema->resultset('Biblio')->create({
201 title => "Test title",
202 datecreated => dt_from_string,
203 biblioitems => [ { itemtype => 'BIB_LEVEL' } ],
205 my $biblioitem = $biblio->biblioitems->first;
206 my $item = $schema->resultset('Item')->create({
207 biblioitemnumber => $biblioitem->biblioitemnumber,
208 biblionumber => $biblio->biblionumber,
209 itype => "ITEM_LEVEL",
212 t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
213 is( $item->effective_itemtype(), 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' );
215 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
216 is( $item->effective_itemtype(), 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' );
218 # If itemtype is not defined and item-level_level item types are set
219 # fallback to biblio-level itemtype (Bug 14651) and warn
220 $item->itype( undef );
222 my $effective_itemtype;
223 warning_is { $effective_itemtype = $item->effective_itemtype() }
224 "item-level_itypes set but no itemtype set for item (".$item->itemnumber.")",
225 '->effective_itemtype() raises a warning when falling back to bib-level';
227 ok( defined $effective_itemtype &&
228 $effective_itemtype eq 'BIB_LEVEL',
229 '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' );
231 $schema->storage->txn_rollback;
234 subtest 'SearchItems test' => sub {
237 $schema->storage->txn_begin;
238 my $dbh = C4::Context->dbh;
239 my $builder = t::lib::TestBuilder->new;
241 my $library1 = $builder->build({
244 my $library2 = $builder->build({
247 my $itemtype = $builder->build({
248 source => 'Itemtype',
251 t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
252 my ($cpl_items_before) = SearchItems( { field => 'homebranch', query => $library1->{branchcode} } );
254 my $biblio = $builder->build_sample_biblio({ title => 'Silence in the library' });
255 $builder->build_sample_biblio({ title => 'Silence in the shadow' });
257 my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
260 my $item1 = $builder->build_sample_item(
262 biblionumber => $biblio->biblionumber,
263 library => $library1->{branchcode},
264 itype => $itemtype->{itemtype}
267 my $item1_itemnumber = $item1->itemnumber;
268 my $item2_itemnumber = $builder->build_sample_item(
270 biblionumber => $biblio->biblionumber,
271 library => $library2->{branchcode},
272 itype => $itemtype->{itemtype}
276 my ($items, $total_results);
278 ($items, $total_results) = SearchItems();
280 is($total_results, $initial_items_count + 2, "Created 2 new items");
281 is(scalar @$items, $total_results, "SearchItems() returns all items");
283 ($items, $total_results) = SearchItems(undef, {rows => 1});
284 is($total_results, $initial_items_count + 2);
285 is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item");
287 # Search all items where homebranch = 'CPL'
289 field => 'homebranch',
290 query => $library1->{branchcode},
293 ($items, $total_results) = SearchItems($filter);
294 ok($total_results > 0, "There is at least one CPL item");
295 my $all_items_are_CPL = 1;
296 foreach my $item (@$items) {
297 if ($item->{homebranch} ne $library1->{branchcode}) {
298 $all_items_are_CPL = 0;
302 ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
304 # Search all items where homebranch != 'CPL'
306 field => 'homebranch',
307 query => $library1->{branchcode},
310 ($items, $total_results) = SearchItems($filter);
311 ok($total_results > 0, "There is at least one non-CPL item");
312 my $all_items_are_not_CPL = 1;
313 foreach my $item (@$items) {
314 if ($item->{homebranch} eq $library1->{branchcode}) {
315 $all_items_are_not_CPL = 0;
319 ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
321 # Search all items where biblio title (245$a) is like 'Silence in the %'
323 field => 'marc:245$a',
324 query => 'Silence in the %',
327 ($items, $total_results) = SearchItems($filter);
328 ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'");
330 # Search all items where biblio title is 'Silence in the library'
331 # and homebranch is 'CPL'
333 conjunction => 'AND',
336 field => 'marc:245$a',
337 query => 'Silence in the %',
341 field => 'homebranch',
342 query => $library1->{branchcode},
347 ($items, $total_results) = SearchItems($filter);
349 foreach my $item (@$items) {
350 if ($item->{itemnumber} == $item1_itemnumber) {
355 ok($found, "item1 found");
357 my $frameworkcode = q||;
358 my ($itemfield) = GetMarcFromKohaField( 'items.itemnumber' );
360 # Create item subfield 'z' without link
361 $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
362 $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", ?)', undef, $itemfield, $frameworkcode);
365 my $cache = Koha::Caches->get_instance();
366 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
367 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
368 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
370 my $item3_record = MARC::Record->new;
371 $item3_record->append_fields(
375 'y' => $itemtype->{itemtype}
378 my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
379 $biblio->biblionumber);
381 # Search item where item subfield z is "foobar"
383 field => 'marc:' . $itemfield . '$z',
387 ($items, $total_results) = SearchItems($filter);
388 ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
390 # Link $z to items.itemnotes (and make sure there is no other subfields
392 $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
393 $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
396 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
397 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
398 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
400 ModItemFromMarc($item3_record, $biblio->biblionumber, $item3_itemnumber);
402 # Make sure the link is used
403 my $item3 = Koha::Items->find($item3_itemnumber);
404 is($item3->itemnotes, 'foobar', 'itemnotes eq "foobar"');
406 # Do the same search again.
407 # This time it will search in items.itemnotes
408 ($items, $total_results) = SearchItems($filter);
409 is(scalar(@$items), 1, 'found 1 item with itemnotes = "foobar"');
411 my ($cpl_items_after) = SearchItems( { field => 'homebranch', query => $library1->{branchcode} } );
412 is( ( scalar( @$cpl_items_after ) - scalar ( @$cpl_items_before ) ), 1, 'SearchItems should return something' );
416 conjunction => 'AND',
424 field => 'homebranch',
425 query => $library1->{branchcode},
430 ($items, $total_results) = SearchItems($filter);
431 is($total_results, 1, "Search items.issues issues = 0 returns result (items.issues defaults to 0)");
435 conjunction => 'AND',
438 field => 'new_status',
443 field => 'homebranch',
444 query => $library1->{branchcode},
449 ($items, $total_results) = SearchItems($filter);
450 is($total_results, 0, 'found no item with new_status=0 without ifnull');
452 $filter->{filters}[0]->{ifnull} = 0;
453 ($items, $total_results) = SearchItems($filter);
454 is($total_results, 1, 'found all items of library1 with new_status=0 with ifnull = 0');
456 t::lib::Mocks::mock_userenv({ branchcode => $item1->homebranch });
457 my $patron_borrower = $builder->build_object({ class => 'Koha::Patrons' })->unblessed;
458 AddIssue( $patron_borrower, $item1->barcode );
459 # Search item where item is checked out
461 conjunction => 'AND',
469 field => 'homebranch',
470 query => $item1->homebranch,
475 ($items, $total_results) = SearchItems($filter);
476 ok(scalar @$items == 1, 'found 1 checked out item');
478 # When sorting by descending availability, checked out item should show first
480 sortby => 'availability',
484 field => 'homebranch',
485 query => $item1->homebranch,
488 ($items, $total_results) = SearchItems($filter,$params);
489 is($items->[0]->{barcode}, $item1->barcode, 'Items sorted as expected by availability');
491 subtest 'Search items by ISSN and ISBN with variations' => sub {
494 my $marc_record = MARC::Record->new;
495 # Prepare ISBN for biblio:
496 $marc_record->append_fields( MARC::Field->new( '020', '', '', 'a' => '9780136019701' ) );
497 # Prepare ISSN for biblio:
498 $marc_record->append_fields( MARC::Field->new( '022', '', '', 'a' => '2434561X' ) );
499 my ( $isbnissn_biblionumber ) = AddBiblio( $marc_record, '' );
500 my $isbnissn_biblio = Koha::Biblios->find($isbnissn_biblionumber);
502 my $item = $builder->build_sample_item(
504 biblionumber => $isbnissn_biblio->biblionumber,
507 my $item_itemnumber = $item->itemnumber;
511 query => '978013-6019701',
515 t::lib::Mocks::mock_preference('SearchWithISBNVariations', 0);
516 ($items, $total_results) = SearchItems($filter_isbn);
517 is($total_results, 0, "Search items finds ISBN, no variations");
519 t::lib::Mocks::mock_preference('SearchWithISBNVariations', 1);
520 ($items, $total_results) = SearchItems($filter_isbn);
521 is($total_results, 1, "Search items finds ISBN with variations");
525 query => '2434-561X',
529 t::lib::Mocks::mock_preference('SearchWithISSNVariations', 0);
530 ($items, $total_results) = SearchItems($filter_issn);
531 is($total_results, 0, "Search items finds ISSN, no variations");
533 t::lib::Mocks::mock_preference('SearchWithISSNVariations', 1);
534 ($items, $total_results) = SearchItems($filter_issn);
535 is($total_results, 1, "Search items finds ISSN with variations");
538 $schema->storage->txn_rollback;
541 subtest 'Koha::Item(s) tests' => sub {
545 $schema->storage->txn_begin();
547 my $builder = t::lib::TestBuilder->new;
548 my $library1 = $builder->build({
551 my $library2 = $builder->build({
554 my $itemtype = $builder->build({
555 source => 'Itemtype',
558 # Create a biblio and item for testing
559 t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
560 my $biblio = $builder->build_sample_biblio();
561 my $itemnumber = $builder->build_sample_item(
563 biblionumber => $biblio->biblionumber,
564 homebranch => $library1->{branchcode},
565 holdingbranch => $library2->{branchcode},
566 itype => $itemtype->{itemtype}
571 my $item = Koha::Items->find( $itemnumber );
572 is( ref($item), 'Koha::Item', "Got Koha::Item" );
574 my $homebranch = $item->home_branch();
575 is( ref($homebranch), 'Koha::Library', "Got Koha::Library from home_branch method" );
576 is( $homebranch->branchcode(), $library1->{branchcode}, "Home branch code matches homebranch" );
578 my $holdingbranch = $item->holding_branch();
579 is( ref($holdingbranch), 'Koha::Library', "Got Koha::Library from holding_branch method" );
580 is( $holdingbranch->branchcode(), $library2->{branchcode}, "Home branch code matches holdingbranch" );
582 $biblio = $item->biblio();
583 is( ref($item->biblio), 'Koha::Biblio', "Got Koha::Biblio from biblio method" );
584 is( $item->biblio->title(), $biblio->title, 'Title matches biblio title' );
586 $schema->storage->txn_rollback;
589 subtest 'get_hostitemnumbers_of' => sub {
592 $schema->storage->txn_begin;
593 t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
594 my $builder = t::lib::TestBuilder->new;
596 # Host item field without 0 or 9
597 my $bib1 = MARC::Record->new();
598 $bib1->append_fields(
599 MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
600 MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
601 MARC::Field->new('773', ' ', ' ', b => 'b without 0 or 9'),
603 my ($biblionumber1, $bibitemnum1) = AddBiblio($bib1, '');
604 my @itemnumbers1 = C4::Items::get_hostitemnumbers_of( $biblionumber1 );
605 is( scalar @itemnumbers1, 0, '773 without 0 or 9');
607 # Correct host item field, analytical records on
608 t::lib::Mocks::mock_preference('EasyAnalyticalRecords', 1);
609 my $hostitem = $builder->build_sample_item();
610 my $bib2 = MARC::Record->new();
611 $bib2->append_fields(
612 MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
613 MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
614 MARC::Field->new('773', ' ', ' ', 0 => $hostitem->biblionumber , 9 => $hostitem->itemnumber, b => 'b' ),
616 my ($biblionumber2, $bibitemnum2) = AddBiblio($bib2, '');
617 my @itemnumbers2 = C4::Items::get_hostitemnumbers_of( $biblionumber2 );
618 is( scalar @itemnumbers2, 1, '773 with 0 and 9, EasyAnalyticalRecords on');
620 # Correct host item field, analytical records off
621 t::lib::Mocks::mock_preference('EasyAnalyticalRecords', 0);
622 @itemnumbers2 = C4::Items::get_hostitemnumbers_of( $biblionumber2 );
623 is( scalar @itemnumbers2, 0, '773 with 0 and 9, EasyAnalyticalRecords off');
625 $schema->storage->txn_rollback;
628 subtest 'Test logging for ModItem' => sub {
632 t::lib::Mocks::mock_preference('CataloguingLog', 1);
634 $schema->storage->txn_begin;
636 my $builder = t::lib::TestBuilder->new;
637 my $library = $builder->build({
640 my $itemtype = $builder->build({
641 source => 'Itemtype',
644 # Create a biblio instance for testing
645 t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
646 my $biblio = $builder->build_sample_biblio();
649 my $item = $builder->build_sample_item(
651 biblionumber => $biblio->biblionumber,
652 library => $library->{homebranch},
653 location => $location,
654 itype => $itemtype->{itemtype}
658 # False means no logging
659 $schema->resultset('ActionLog')->search()->delete();
660 $item->location($location)->store({ log_action => 0 });
661 is( $schema->resultset('ActionLog')->count(), 0, 'False value does not trigger logging' );
664 $schema->resultset('ActionLog')->search()->delete();
665 $item->location('new location')->store({ log_action => 1 });
666 is( $schema->resultset('ActionLog')->count(), 1, 'True value does trigger logging' );
668 # Undefined defaults to true
669 $schema->resultset('ActionLog')->search()->delete();
670 $item->location($location)->store();
671 is( $schema->resultset('ActionLog')->count(), 1, 'Undefined value defaults to true, triggers logging' );
673 $schema->storage->txn_rollback;
676 subtest 'Check stockrotationitem relationship' => sub {
679 $schema->storage->txn_begin();
681 my $builder = t::lib::TestBuilder->new;
682 my $item = $builder->build_sample_item;
685 source => 'Stockrotationitem',
686 value => { itemnumber_id => $item->itemnumber }
689 my $sritem = Koha::Items->find($item->itemnumber)->stockrotationitem;
690 isa_ok( $sritem, 'Koha::StockRotationItem', "Relationship works and correctly creates Koha::Object." );
692 $schema->storage->txn_rollback;
695 subtest 'Check add_to_rota method' => sub {
698 $schema->storage->txn_begin();
700 my $builder = t::lib::TestBuilder->new;
701 my $item = $builder->build_sample_item;
702 my $rota = $builder->build({ source => 'Stockrotationrota' });
703 my $srrota = Koha::StockRotationRotas->find($rota->{rota_id});
706 source => 'Stockrotationstage',
707 value => { rota_id => $rota->{rota_id} },
710 my $sritem = Koha::Items->find($item->itemnumber);
711 $sritem->add_to_rota($rota->{rota_id});
714 Koha::StockRotationItems->find($item->itemnumber)->stage_id,
715 $srrota->stockrotationstages->next->stage_id,
716 "Adding to a rota a new sritem item being assigned to its first stage."
719 my $newrota = $builder->build({ source => 'Stockrotationrota' });
721 my $srnewrota = Koha::StockRotationRotas->find($newrota->{rota_id});
724 source => 'Stockrotationstage',
725 value => { rota_id => $newrota->{rota_id} },
728 $sritem->add_to_rota($newrota->{rota_id});
731 Koha::StockRotationItems->find($item->itemnumber)->stage_id,
732 $srnewrota->stockrotationstages->next->stage_id,
733 "Moving an item results in that sritem being assigned to the new first stage."
736 $schema->storage->txn_rollback;
739 subtest 'Split subfields in Item2Marc (Bug 21774)' => sub {
741 $schema->storage->txn_begin;
743 my $builder = t::lib::TestBuilder->new;
744 my $item = $builder->build_sample_item({ ccode => 'A|B' });
746 Koha::MarcSubfieldStructures->search({ tagfield => '952', tagsubfield => '8' })->delete; # theoretical precaution
747 Koha::MarcSubfieldStructures->search({ kohafield => 'items.ccode' })->delete;
748 my $mapping = Koha::MarcSubfieldStructure->new(
750 frameworkcode => q{},
753 kohafield => 'items.ccode',
757 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
760 my $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
761 my @subs = $marc->subfield( $mapping->tagfield, $mapping->tagsubfield );
762 is( @subs, 2, 'Expect two subfields' );
763 is( $subs[0], 'A', 'First subfield matches' );
764 is( $subs[1], 'B', 'Second subfield matches' );
766 $schema->storage->txn_rollback;
769 subtest 'ModItemFromMarc' => sub {
771 $schema->storage->txn_begin;
773 my $builder = t::lib::TestBuilder->new;
774 my ($itemfield) = GetMarcFromKohaField( 'items.itemnumber' );
775 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' });
776 my $biblio = $builder->build_sample_biblio;
777 my ( $lost_tag, $lost_sf ) = GetMarcFromKohaField( 'items.itemlost' );
778 my $item_record = MARC::Record->new;
779 $item_record->append_fields(
782 'y' => $itemtype->itemtype,
789 my (undef, undef, $itemnumber) = AddItemFromMarc($item_record,
790 $biblio->biblionumber);
792 my $item = Koha::Items->find($itemnumber);
793 is( $item->itemlost, 1, 'itemlost picked from the item marc');
795 $item->new_status("this is something")->store;
797 my $updated_item_record = MARC::Record->new;
798 $updated_item_record->append_fields(
801 'y' => $itemtype->itemtype,
805 my $updated_item = ModItemFromMarc($updated_item_record, $biblio->biblionumber, $itemnumber);
806 is( $updated_item->{itemlost}, 0, 'itemlost should have been reset to the default value in DB' );
807 is( $updated_item->{new_status}, "this is something", "Non mapped field has not been reset" );
808 is( Koha::Items->find($itemnumber)->new_status, "this is something" );
810 subtest 'cn_sort' => sub {
813 my $item = $builder->build_sample_item;
814 $item->set({ cn_source => 'ddc', itemcallnumber => 'xxx' })->store;
815 is( $item->cn_sort, 'XXX', 'init values set are expected' );
817 my $marc = C4::Items::Item2Marc( $item->get_from_storage->unblessed, $item->biblionumber );
818 ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
819 is( $item->get_from_storage->cn_sort, 'XXX', 'cn_sort has not been updated' );
821 $marc = C4::Items::Item2Marc( { %{$item->unblessed}, itemcallnumber => 'yyy' }, $item->biblionumber );
822 ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
823 is( $item->get_from_storage->cn_sort, 'YYY', 'cn_sort has been updated' );
826 subtest 'onloan' => sub {
829 my $item = $builder->build_sample_item;
830 $item->set({ onloan => '2022-03-19' })->store;
831 is( $item->onloan, '2022-03-19', 'init values set are expected' );
833 my $marc = C4::Items::Item2Marc( $item->get_from_storage->unblessed, $item->biblionumber );
834 my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField( 'items.onloan' );
835 $marc->field($MARCfield)->delete_subfield( code => $MARCsubfield );
836 ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
837 is( $item->get_from_storage->onloan, '2022-03-19', 'onloan has not been updated if not passed' );
839 $marc = C4::Items::Item2Marc( { %{$item->unblessed}, onloan => '2022-03-26' }, $item->biblionumber );
840 ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
841 is( $item->get_from_storage->onloan, '2022-03-26', 'onloan has been updated when passed in' );
844 subtest 'dateaccessioned' => sub {
847 my $item = $builder->build_sample_item;
848 $item->set({ dateaccessioned => '2022-03-19' })->store->discard_changes;
849 is( $item->dateaccessioned, '2022-03-19', 'init values set are expected' );
851 my $marc = C4::Items::Item2Marc( $item->get_from_storage->unblessed, $item->biblionumber );
852 my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField( 'items.dateaccessioned' );
853 $marc->field($MARCfield)->delete_subfield( code => $MARCsubfield );
854 ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
855 is( $item->get_from_storage->dateaccessioned, '2022-03-19', 'dateaccessioned has not been updated if not passed' );
857 $marc = C4::Items::Item2Marc( { %{$item->unblessed}, dateaccessioned => '2022-03-26' }, $item->biblionumber );
858 ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
859 is( $item->get_from_storage->dateaccessioned, '2022-03-26', 'dateaccessioned has been updated when passed in' );
862 subtest 'permanent_location' => sub {
865 # Make sure items.permanent_location is not mapped
866 Koha::MarcSubfieldStructures->search(
868 frameworkcode => q{},
869 kohafield => 'items.permanent_location',
872 Koha::MarcSubfieldStructures->search(
874 frameworkcode => q{},
879 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
881 my $item = $builder->build_sample_item;
883 # By default, setting location to something new should set permanent location to the same thing
884 # with the usual exceptions
885 $item->set({ location => 'A', permanent_location => 'A' })->store;
886 is( $item->location, 'A', 'initial location set as expected' );
887 is( $item->permanent_location, 'A', 'initial permanent location set as expected' );
889 $item->location('B');
890 my $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
891 ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
893 $item = $item->get_from_storage;
894 is( $item->location, 'B', 'new location set as expected' );
895 is( $item->permanent_location, 'B', 'new permanent location set as expected' );
897 # Added a marc mapping for permanent location, allows it to be edited independently
898 my $mapping = Koha::MarcSubfieldStructure->new(
900 frameworkcode => q{},
903 kohafield => 'items.permanent_location',
909 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
911 # Now if we change location, and also pass in a permanent location
912 # the permanent_location will not be overwritten by location
913 $item->location('C');
914 $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
915 ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
916 $item = $item->get_from_storage;
917 is( $item->location, 'C', 'next new location set as expected' );
918 is( $item->permanent_location, 'B', 'permanent location remains unchanged as expected' );
920 $item->permanent_location(undef)->more_subfields_xml(undef)->store;
921 # Clear values from the DB
922 $item = $item->get_from_storage;
924 # Update the location
925 $item->location('D');
926 $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
927 # Remove the permanent_location field from the form
928 $marc->field('952')->delete_subfield("C");
929 ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
930 $item = $item->get_from_storage;
931 is( $item->location, 'D', 'next new location set as expected' );
932 is( $item->permanent_location, 'D', 'permanent location is updated if not previously set and no value passed' );
934 # Clear values from the DB
935 $item->permanent_location(undef)->more_subfields_xml(undef)->store;
936 $item = $item->get_from_storage;
938 # This time nothing is set, but we pass an empty string
939 $item->permanent_location("");
940 $item->location('E');
941 $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
942 $marc->field('952')->add_subfields( "C", "" );
943 ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
944 $item = $item->get_from_storage;
945 is( $item->location, 'E', 'next new location set as expected' );
946 is( $item->permanent_location, undef, 'permanent location is not updated if previously set as blank string' );
949 $schema->storage->txn_rollback;
950 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
953 subtest 'ModDateLastSeen' => sub {
955 $schema->storage->txn_begin;
957 my $builder = t::lib::TestBuilder->new;
958 my $item = $builder->build_sample_item;
959 t::lib::Mocks::mock_preference('CataloguingLog', '1');
960 my $logs_before = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count;
961 ModDateLastSeen($item->itemnumber);
962 my $logs_after = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count;
963 is( $logs_after, $logs_before, "ModDateLastSeen doesn't log if item not lost");
964 $item->itemlost(1)->store({ log_action => 0 });
965 ModDateLastSeen($item->itemnumber, 1);
966 $item->discard_changes;
967 $logs_after = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count;
968 is( $item->itemlost, 1, "Item left lost when parameter is passed");
969 is( $logs_after, $logs_before, "ModDateLastSeen doesn't log if item not lost");
970 ModDateLastSeen($item->itemnumber);
971 $item->discard_changes;
972 $logs_after = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count;
973 is( $item->itemlost, 0, "Item no longer lost when no parameter is passed");
974 is( $logs_after, $logs_before + 1, "ModDateLastSeen logs if item was lost and now found");
977 subtest 'CartToShelf test' => sub {
980 $schema->storage->txn_begin;
981 my $dbh = C4::Context->dbh;
982 my $builder = t::lib::TestBuilder->new;
984 my $item = $builder->build_sample_item();
986 $item->permanent_location('BANANA')->location('CART')->store();
988 CartToShelf( $item->id );
990 $item->discard_changes;
992 is( $item->location, 'BANANA', 'Item is correctly returned to permanent location');
995 my $mock_RTHQ = Test::MockModule->new("Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue");
996 $mock_RTHQ->mock( enqueue => sub { warn "RTHQ" } );
997 t::lib::Mocks::mock_preference('RealTimeHoldsQueue', '1');
999 $item->location('CART')->store({ skip_holds_queue => 1 });
1001 CartToShelf( $item->id );
1002 } [], 'No RTHQ update triggered by CartToShelf';
1004 $schema->storage->txn_rollback;