Bug 31196: Remove 'default_value_for_mod_marc-' clear_from_cache calls
[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 qw( ModItemTransfer SearchItems AddItemFromMarc ModItemFromMarc get_hostitemnumbers_of Item2Marc ModDateLastSeen );
23 use C4::Biblio qw( GetMarcFromKohaField AddBiblio );
24 use C4::Circulation qw( AddIssue );
25 use Koha::Items;
26 use Koha::Database;
27 use Koha::DateUtils qw( dt_from_string );
28 use Koha::Library;
29 use Koha::DateUtils;
30 use Koha::MarcSubfieldStructures;
31 use Koha::Caches;
32 use Koha::AuthorisedValues;
33
34 use t::lib::Mocks;
35 use t::lib::TestBuilder;
36
37 use Test::More tests => 12;
38
39 use Test::Warn;
40
41 my $schema = Koha::Database->new->schema;
42 my $location = 'My Location';
43
44 subtest 'General Add, Get and Del tests' => sub {
45
46     plan tests => 16;
47
48     $schema->storage->txn_begin;
49
50     my $builder = t::lib::TestBuilder->new;
51     my $library = $builder->build({
52         source => 'Branch',
53     });
54     my $itemtype = $builder->build({
55         source => 'Itemtype',
56     });
57
58     # Create a biblio instance for testing
59     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
60     my $biblio = $builder->build_sample_biblio();
61
62     # Add an item.
63     my $item = $builder->build_sample_item(
64         {
65             biblionumber => $biblio->biblionumber,
66             library      => $library->{branchcode},
67             location     => $location,
68             itype        => $itemtype->{itemtype}
69         }
70     );
71     my $itemnumber = $item->itemnumber;
72     cmp_ok($item->biblionumber, '==', $biblio->biblionumber, "New item is linked to correct biblionumber.");
73     cmp_ok($item->biblioitemnumber, '==', $biblio->biblioitem->biblioitemnumber, "New item is linked to correct biblioitemnumber.");
74
75     # Get item.
76     my $getitem = Koha::Items->find($itemnumber);
77     cmp_ok($getitem->itemnumber, '==', $itemnumber, "Retrieved item has correct itemnumber.");
78     cmp_ok($getitem->biblioitemnumber, '==', $item->biblioitemnumber, "Retrieved item has correct biblioitemnumber."); # We are not testing anything useful here
79     is( $getitem->location, $location, "The location should not have been modified" );
80     is( $getitem->permanent_location, $location, "The permanent_location should have been set to the location value" );
81
82
83     # Do not modify anything, and do not explode!
84     $getitem->set({})->store;
85
86     # Modify item; setting barcode.
87     $getitem->barcode('987654321')->store;
88     my $moditem = Koha::Items->find($itemnumber);
89     cmp_ok($moditem->barcode, '==', '987654321', 'Modified item barcode successfully to: '.$moditem->barcode . '.');
90
91     # Delete item.
92     $moditem->delete;
93     my $getdeleted = Koha::Items->find($itemnumber);
94     is($getdeleted, undef, "Item deleted as expected.");
95
96     $itemnumber = $builder->build_sample_item(
97         {
98             biblionumber => $biblio->biblionumber,
99             library      => $library->{branchcode},
100             location     => $location,
101             permanent_location => 'my permanent location',
102             itype        => $itemtype->{itemtype}
103         }
104     )->itemnumber;
105     $getitem = Koha::Items->find($itemnumber);
106     is( $getitem->location, $location, "The location should not have been modified" );
107     is( $getitem->permanent_location, 'my permanent location', "The permanent_location should not have modified" );
108
109     my $new_location = "New location";
110     $getitem->location($new_location)->store;
111     $getitem = Koha::Items->find($itemnumber);
112     is( $getitem->location, $new_location, "The location should have been set to correct location" );
113     is( $getitem->permanent_location, $new_location, "The permanent_location should have been set to location" );
114
115     $getitem->location('CART')->store;
116     $getitem = Koha::Items->find($itemnumber);
117     is( $getitem->location, 'CART', "The location should have been set to CART" );
118     is( $getitem->permanent_location, $new_location, "The permanent_location should not have been set to CART" );
119
120     t::lib::Mocks::mock_preference('item-level_itypes', '1');
121     $getitem = Koha::Items->find($itemnumber);
122     is( $getitem->effective_itemtype, $itemtype->{itemtype}, "Itemtype set correctly when using item-level_itypes" );
123     t::lib::Mocks::mock_preference('item-level_itypes', '0');
124     $getitem = Koha::Items->find($itemnumber);
125     is( $getitem->effective_itemtype, $biblio->biblioitem->itemtype, "Itemtype set correctly when not using item-level_itypes" );
126
127     $schema->storage->txn_rollback;
128 };
129
130 subtest 'ModItemTransfer tests' => sub {
131     plan tests => 8;
132
133     $schema->storage->txn_begin;
134
135     my $builder = t::lib::TestBuilder->new;
136     my $item    = $builder->build_sample_item();
137
138     my $library1 = $builder->build(
139         {
140             source => 'Branch',
141         }
142     );
143     my $library2 = $builder->build(
144         {
145             source => 'Branch',
146         }
147     );
148
149     ModItemTransfer( $item->itemnumber, $library1->{branchcode},
150         $library2->{branchcode}, 'Manual' );
151
152     my $transfers = Koha::Item::Transfers->search(
153         {
154             itemnumber => $item->itemnumber
155         }
156     );
157
158     is( $transfers->count, 1, "One transfer created with ModItemTransfer" );
159     $item->discard_changes;
160     is($item->holdingbranch, $library1->{branchcode}, "Items holding branch was updated to frombranch");
161
162     ModItemTransfer( $item->itemnumber, $library2->{branchcode},
163         $library1->{branchcode}, 'Manual' );
164     $transfers = Koha::Item::Transfers->search(
165         { itemnumber => $item->itemnumber, },
166         { order_by   => { '-asc' => 'branchtransfer_id' } }
167     );
168
169     is($transfers->count, 2, "Second transfer recorded on second call of ModItemTransfer");
170     my $transfer1 = $transfers->next;
171     my $transfer2 = $transfers->next;
172     isnt($transfer1->datecancelled, undef, "First transfer marked as cancelled by ModItemTransfer");
173     like($transfer1->cancellation_reason,qr/^Manual/, "First transfer contains cancellation_reason 'Manual'");
174     is($transfer2->datearrived, undef, "Second transfer is now the active transfer");
175     $item->discard_changes;
176     is($item->holdingbranch, $library2->{branchcode}, "Items holding branch was updated to frombranch");
177
178     # Check 'reason' is populated when passed
179     ModItemTransfer( $item->itemnumber, $library2->{branchcode},
180         $library1->{branchcode}, "Manual" );
181
182     $transfers = Koha::Item::Transfers->search(
183         { itemnumber => $item->itemnumber, },
184         { order_by   => { '-desc' => 'branchtransfer_id' } }
185     );
186
187     my $transfer3 = $transfers->next;
188     is($transfer3->reason, 'Manual', "Reason set via ModItemTransfer");
189
190     $schema->storage->txn_rollback;
191 };
192
193 subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub {
194
195     plan tests => 4;
196
197     $schema->storage->txn_begin;
198
199     my $biblio = $schema->resultset('Biblio')->create({
200         title       => "Test title",
201         datecreated => dt_from_string,
202         biblioitems => [ { itemtype => 'BIB_LEVEL' } ],
203     });
204     my $biblioitem = $biblio->biblioitems->first;
205     my $item = $schema->resultset('Item')->create({
206         biblioitemnumber => $biblioitem->biblioitemnumber,
207         biblionumber     => $biblio->biblionumber,
208         itype            => "ITEM_LEVEL",
209     });
210
211     t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
212     is( $item->effective_itemtype(), 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' );
213
214     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
215     is( $item->effective_itemtype(), 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' );
216
217     # If itemtype is not defined and item-level_level item types are set
218     # fallback to biblio-level itemtype (Bug 14651) and warn
219     $item->itype( undef );
220     $item->update();
221     my $effective_itemtype;
222     warning_is { $effective_itemtype = $item->effective_itemtype() }
223                 "item-level_itypes set but no itemtype set for item (".$item->itemnumber.")",
224                 '->effective_itemtype() raises a warning when falling back to bib-level';
225
226     ok( defined $effective_itemtype &&
227                 $effective_itemtype eq 'BIB_LEVEL',
228         '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' );
229
230     $schema->storage->txn_rollback;
231 };
232
233 subtest 'SearchItems test' => sub {
234     plan tests => 20;
235
236     $schema->storage->txn_begin;
237     my $dbh = C4::Context->dbh;
238     my $builder = t::lib::TestBuilder->new;
239
240     my $library1 = $builder->build({
241         source => 'Branch',
242     });
243     my $library2 = $builder->build({
244         source => 'Branch',
245     });
246     my $itemtype = $builder->build({
247         source => 'Itemtype',
248     });
249
250     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
251     my ($cpl_items_before) = SearchItems( { field => 'homebranch', query => $library1->{branchcode} } );
252
253     my $biblio = $builder->build_sample_biblio({ title => 'Silence in the library' });
254     $builder->build_sample_biblio({ title => 'Silence in the shadow' });
255
256     my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
257
258     # Add two items
259     my $item1 = $builder->build_sample_item(
260         {
261             biblionumber => $biblio->biblionumber,
262             library      => $library1->{branchcode},
263             itype        => $itemtype->{itemtype}
264         }
265     );
266     my $item1_itemnumber = $item1->itemnumber;
267     my $item2_itemnumber = $builder->build_sample_item(
268         {
269             biblionumber => $biblio->biblionumber,
270             library      => $library2->{branchcode},
271             itype        => $itemtype->{itemtype}
272         }
273     )->itemnumber;
274
275     my ($items, $total_results);
276
277     ($items, $total_results) = SearchItems();
278
279     is($total_results, $initial_items_count + 2, "Created 2 new items");
280     is(scalar @$items, $total_results, "SearchItems() returns all items");
281
282     ($items, $total_results) = SearchItems(undef, {rows => 1});
283     is($total_results, $initial_items_count + 2);
284     is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item");
285
286     # Search all items where homebranch = 'CPL'
287     my $filter = {
288         field => 'homebranch',
289         query => $library1->{branchcode},
290         operator => '=',
291     };
292     ($items, $total_results) = SearchItems($filter);
293     ok($total_results > 0, "There is at least one CPL item");
294     my $all_items_are_CPL = 1;
295     foreach my $item (@$items) {
296         if ($item->{homebranch} ne $library1->{branchcode}) {
297             $all_items_are_CPL = 0;
298             last;
299         }
300     }
301     ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
302
303     # Search all items where homebranch != 'CPL'
304     $filter = {
305         field => 'homebranch',
306         query => $library1->{branchcode},
307         operator => '!=',
308     };
309     ($items, $total_results) = SearchItems($filter);
310     ok($total_results > 0, "There is at least one non-CPL item");
311     my $all_items_are_not_CPL = 1;
312     foreach my $item (@$items) {
313         if ($item->{homebranch} eq $library1->{branchcode}) {
314             $all_items_are_not_CPL = 0;
315             last;
316         }
317     }
318     ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
319
320     # Search all items where biblio title (245$a) is like 'Silence in the %'
321     $filter = {
322         field => 'marc:245$a',
323         query => 'Silence in the %',
324         operator => 'like',
325     };
326     ($items, $total_results) = SearchItems($filter);
327     ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'");
328
329     # Search all items where biblio title is 'Silence in the library'
330     # and homebranch is 'CPL'
331     $filter = {
332         conjunction => 'AND',
333         filters => [
334             {
335                 field => 'marc:245$a',
336                 query => 'Silence in the %',
337                 operator => 'like',
338             },
339             {
340                 field => 'homebranch',
341                 query => $library1->{branchcode},
342                 operator => '=',
343             },
344         ],
345     };
346     ($items, $total_results) = SearchItems($filter);
347     my $found = 0;
348     foreach my $item (@$items) {
349         if ($item->{itemnumber} == $item1_itemnumber) {
350             $found = 1;
351             last;
352         }
353     }
354     ok($found, "item1 found");
355
356     my $frameworkcode = q||;
357     my ($itemfield) = GetMarcFromKohaField( 'items.itemnumber' );
358
359     # Create item subfield 'z' without link
360     $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
361     $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", ?)', undef, $itemfield, $frameworkcode);
362
363     # Clear cache
364     my $cache = Koha::Caches->get_instance();
365     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
366     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
367     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
368
369     my $item3_record = MARC::Record->new;
370     $item3_record->append_fields(
371         MARC::Field->new(
372             $itemfield, '', '',
373             'z' => 'foobar',
374             'y' => $itemtype->{itemtype}
375         )
376     );
377     my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
378         $biblio->biblionumber);
379
380     # Search item where item subfield z is "foobar"
381     $filter = {
382         field => 'marc:' . $itemfield . '$z',
383         query => 'foobar',
384         operator => 'like',
385     };
386     ($items, $total_results) = SearchItems($filter);
387     ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
388
389     # Link $z to items.itemnotes (and make sure there is no other subfields
390     # linked to it)
391     $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
392     $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
393
394     # Clear cache
395     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
396     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
397     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
398
399     ModItemFromMarc($item3_record, $biblio->biblionumber, $item3_itemnumber);
400
401     # Make sure the link is used
402     my $item3 = Koha::Items->find($item3_itemnumber);
403     is($item3->itemnotes, 'foobar', 'itemnotes eq "foobar"');
404
405     # Do the same search again.
406     # This time it will search in items.itemnotes
407     ($items, $total_results) = SearchItems($filter);
408     is(scalar(@$items), 1, 'found 1 item with itemnotes = "foobar"');
409
410     my ($cpl_items_after) = SearchItems( { field => 'homebranch', query => $library1->{branchcode} } );
411     is( ( scalar( @$cpl_items_after ) - scalar ( @$cpl_items_before ) ), 1, 'SearchItems should return something' );
412
413     # Issues count = 0
414     $filter = {
415         conjunction => 'AND',
416         filters => [
417             {
418                 field => 'issues',
419                 query => 0,
420                 operator => '=',
421             },
422             {
423                 field => 'homebranch',
424                 query => $library1->{branchcode},
425                 operator => '=',
426             },
427         ],
428     };
429     ($items, $total_results) = SearchItems($filter);
430     is($total_results, 1, "Search items.issues issues = 0 returns result (items.issues defaults to 0)");
431
432     # Is null
433     $filter = {
434         conjunction => 'AND',
435         filters     => [
436             {
437                 field    => 'new_status',
438                 query    => 0,
439                 operator => '='
440             },
441             {
442                 field    => 'homebranch',
443                 query    => $library1->{branchcode},
444                 operator => '=',
445             },
446         ],
447     };
448     ($items, $total_results) = SearchItems($filter);
449     is($total_results, 0, 'found no item with new_status=0 without ifnull');
450
451     $filter->{filters}[0]->{ifnull} = 0;
452     ($items, $total_results) = SearchItems($filter);
453     is($total_results, 1, 'found all items of library1 with new_status=0 with ifnull = 0');
454
455     t::lib::Mocks::mock_userenv({ branchcode => $item1->homebranch });
456     my $patron_borrower = $builder->build_object({ class => 'Koha::Patrons' })->unblessed;
457     AddIssue( $patron_borrower, $item1->barcode );
458     # Search item where item is checked out
459     $filter = {
460         conjunction => 'AND',
461         filters => [
462             {
463                 field => 'onloan',
464                 query => 'not null',
465                 operator => 'is',
466             },
467             {
468                 field => 'homebranch',
469                 query => $item1->homebranch,
470                 operator => '=',
471             },
472         ],
473     };
474     ($items, $total_results) = SearchItems($filter);
475     ok(scalar @$items == 1, 'found 1 checked out item');
476
477     # When sorting by descending availability, checked out item should show first
478     my $params = {
479         sortby => 'availability',
480         sortorder => 'DESC',
481     };
482     $filter = {
483         field => 'homebranch',
484         query => $item1->homebranch,
485         operator => '=',
486     };
487     ($items, $total_results) = SearchItems($filter,$params);
488     is($items->[0]->{barcode}, $item1->barcode, 'Items sorted as expected by availability');
489
490     subtest 'Search items by ISSN and ISBN with variations' => sub {
491         plan tests => 4;
492
493         my $marc_record = MARC::Record->new;
494         # Prepare ISBN for biblio:
495         $marc_record->append_fields( MARC::Field->new( '020', '', '', 'a' => '9780136019701' ) );
496         # Prepare ISSN for biblio:
497         $marc_record->append_fields( MARC::Field->new( '022', '', '', 'a' => '2434561X' ) );
498         my ( $isbnissn_biblionumber ) = AddBiblio( $marc_record, '' );
499         my $isbnissn_biblio = Koha::Biblios->find($isbnissn_biblionumber);
500
501         my $item = $builder->build_sample_item(
502             {
503                 biblionumber => $isbnissn_biblio->biblionumber,
504             }
505         );
506         my $item_itemnumber = $item->itemnumber;
507
508         my $filter_isbn = {
509             field => 'isbn',
510             query => '978013-6019701',
511             operator => 'like',
512         };
513
514         t::lib::Mocks::mock_preference('SearchWithISBNVariations', 0);
515         ($items, $total_results) = SearchItems($filter_isbn);
516         is($total_results, 0, "Search items finds ISBN, no variations");
517
518         t::lib::Mocks::mock_preference('SearchWithISBNVariations', 1);
519         ($items, $total_results) = SearchItems($filter_isbn);
520         is($total_results, 1, "Search items finds ISBN with variations");
521
522         my $filter_issn = {
523             field => 'issn',
524             query => '2434-561X',
525             operator => 'like',
526         };
527
528         t::lib::Mocks::mock_preference('SearchWithISSNVariations', 0);
529         ($items, $total_results) = SearchItems($filter_issn);
530         is($total_results, 0, "Search items finds ISSN, no variations");
531
532         t::lib::Mocks::mock_preference('SearchWithISSNVariations', 1);
533         ($items, $total_results) = SearchItems($filter_issn);
534         is($total_results, 1, "Search items finds ISSN with variations");
535     };
536
537     $schema->storage->txn_rollback;
538 };
539
540 subtest 'Koha::Item(s) tests' => sub {
541
542     plan tests => 7;
543
544     $schema->storage->txn_begin();
545
546     my $builder = t::lib::TestBuilder->new;
547     my $library1 = $builder->build({
548         source => 'Branch',
549     });
550     my $library2 = $builder->build({
551         source => 'Branch',
552     });
553     my $itemtype = $builder->build({
554         source => 'Itemtype',
555     });
556
557     # Create a biblio and item for testing
558     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
559     my $biblio = $builder->build_sample_biblio();
560     my $itemnumber = $builder->build_sample_item(
561         {
562             biblionumber  => $biblio->biblionumber,
563             homebranch    => $library1->{branchcode},
564             holdingbranch => $library2->{branchcode},
565             itype         => $itemtype->{itemtype}
566         }
567     )->itemnumber;
568
569     # Get item.
570     my $item = Koha::Items->find( $itemnumber );
571     is( ref($item), 'Koha::Item', "Got Koha::Item" );
572
573     my $homebranch = $item->home_branch();
574     is( ref($homebranch), 'Koha::Library', "Got Koha::Library from home_branch method" );
575     is( $homebranch->branchcode(), $library1->{branchcode}, "Home branch code matches homebranch" );
576
577     my $holdingbranch = $item->holding_branch();
578     is( ref($holdingbranch), 'Koha::Library', "Got Koha::Library from holding_branch method" );
579     is( $holdingbranch->branchcode(), $library2->{branchcode}, "Home branch code matches holdingbranch" );
580
581     $biblio = $item->biblio();
582     is( ref($item->biblio), 'Koha::Biblio', "Got Koha::Biblio from biblio method" );
583     is( $item->biblio->title(), $biblio->title, 'Title matches biblio title' );
584
585     $schema->storage->txn_rollback;
586 };
587
588 subtest 'get_hostitemnumbers_of' => sub {
589     plan tests => 3;
590
591     $schema->storage->txn_begin;
592     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
593     my $builder = t::lib::TestBuilder->new;
594
595     # Host item field without 0 or 9
596     my $bib1 = MARC::Record->new();
597     $bib1->append_fields(
598         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
599         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
600         MARC::Field->new('773', ' ', ' ', b => 'b without 0 or 9'),
601     );
602     my ($biblionumber1, $bibitemnum1) = AddBiblio($bib1, '');
603     my @itemnumbers1 = C4::Items::get_hostitemnumbers_of( $biblionumber1 );
604     is( scalar @itemnumbers1, 0, '773 without 0 or 9');
605
606     # Correct host item field, analytical records on
607     t::lib::Mocks::mock_preference('EasyAnalyticalRecords', 1);
608     my $hostitem = $builder->build_sample_item();
609     my $bib2 = MARC::Record->new();
610     $bib2->append_fields(
611         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
612         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
613         MARC::Field->new('773', ' ', ' ', 0 => $hostitem->biblionumber , 9 => $hostitem->itemnumber, b => 'b' ),
614     );
615     my ($biblionumber2, $bibitemnum2) = AddBiblio($bib2, '');
616     my @itemnumbers2 = C4::Items::get_hostitemnumbers_of( $biblionumber2 );
617     is( scalar @itemnumbers2, 1, '773 with 0 and 9, EasyAnalyticalRecords on');
618
619     # Correct host item field, analytical records off
620     t::lib::Mocks::mock_preference('EasyAnalyticalRecords', 0);
621     @itemnumbers2 = C4::Items::get_hostitemnumbers_of( $biblionumber2 );
622     is( scalar @itemnumbers2, 0, '773 with 0 and 9, EasyAnalyticalRecords off');
623
624     $schema->storage->txn_rollback;
625 };
626
627 subtest 'Test logging for ModItem' => sub {
628
629     plan tests => 3;
630
631     t::lib::Mocks::mock_preference('CataloguingLog', 1);
632
633     $schema->storage->txn_begin;
634
635     my $builder = t::lib::TestBuilder->new;
636     my $library = $builder->build({
637         source => 'Branch',
638     });
639     my $itemtype = $builder->build({
640         source => 'Itemtype',
641     });
642
643     # Create a biblio instance for testing
644     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
645     my $biblio = $builder->build_sample_biblio();
646
647     # Add an item.
648     my $item = $builder->build_sample_item(
649         {
650             biblionumber => $biblio->biblionumber,
651             library      => $library->{homebranch},
652             location     => $location,
653             itype        => $itemtype->{itemtype}
654         }
655     );
656
657     # False means no logging
658     $schema->resultset('ActionLog')->search()->delete();
659     $item->location($location)->store({ log_action => 0 });
660     is( $schema->resultset('ActionLog')->count(), 0, 'False value does not trigger logging' );
661
662     # True means logging
663     $schema->resultset('ActionLog')->search()->delete();
664     $item->location('new location')->store({ log_action => 1 });
665     is( $schema->resultset('ActionLog')->count(), 1, 'True value does trigger logging' );
666
667     # Undefined defaults to true
668     $schema->resultset('ActionLog')->search()->delete();
669     $item->location($location)->store();
670     is( $schema->resultset('ActionLog')->count(), 1, 'Undefined value defaults to true, triggers logging' );
671
672     $schema->storage->txn_rollback;
673 };
674
675 subtest 'Check stockrotationitem relationship' => sub {
676     plan tests => 1;
677
678     $schema->storage->txn_begin();
679
680     my $builder = t::lib::TestBuilder->new;
681     my $item = $builder->build_sample_item;
682
683     $builder->build({
684         source => 'Stockrotationitem',
685         value  => { itemnumber_id => $item->itemnumber }
686     });
687
688     my $sritem = Koha::Items->find($item->itemnumber)->stockrotationitem;
689     isa_ok( $sritem, 'Koha::StockRotationItem', "Relationship works and correctly creates Koha::Object." );
690
691     $schema->storage->txn_rollback;
692 };
693
694 subtest 'Check add_to_rota method' => sub {
695     plan tests => 2;
696
697     $schema->storage->txn_begin();
698
699     my $builder = t::lib::TestBuilder->new;
700     my $item = $builder->build_sample_item;
701     my $rota = $builder->build({ source => 'Stockrotationrota' });
702     my $srrota = Koha::StockRotationRotas->find($rota->{rota_id});
703
704     $builder->build({
705         source => 'Stockrotationstage',
706         value  => { rota_id => $rota->{rota_id} },
707     });
708
709     my $sritem = Koha::Items->find($item->itemnumber);
710     $sritem->add_to_rota($rota->{rota_id});
711
712     is(
713         Koha::StockRotationItems->find($item->itemnumber)->stage_id,
714         $srrota->stockrotationstages->next->stage_id,
715         "Adding to a rota a new sritem item being assigned to its first stage."
716     );
717
718     my $newrota = $builder->build({ source => 'Stockrotationrota' });
719
720     my $srnewrota = Koha::StockRotationRotas->find($newrota->{rota_id});
721
722     $builder->build({
723         source => 'Stockrotationstage',
724         value  => { rota_id => $newrota->{rota_id} },
725     });
726
727     $sritem->add_to_rota($newrota->{rota_id});
728
729     is(
730         Koha::StockRotationItems->find($item->itemnumber)->stage_id,
731         $srnewrota->stockrotationstages->next->stage_id,
732         "Moving an item results in that sritem being assigned to the new first stage."
733     );
734
735     $schema->storage->txn_rollback;
736 };
737
738 subtest 'Split subfields in Item2Marc (Bug 21774)' => sub {
739     plan tests => 3;
740     $schema->storage->txn_begin;
741
742     my $builder = t::lib::TestBuilder->new;
743     my $item = $builder->build_sample_item({ ccode => 'A|B' });
744
745     Koha::MarcSubfieldStructures->search({ tagfield => '952', tagsubfield => '8' })->delete; # theoretical precaution
746     Koha::MarcSubfieldStructures->search({ kohafield => 'items.ccode' })->delete;
747     my $mapping = Koha::MarcSubfieldStructure->new(
748         {
749             frameworkcode => q{},
750             tagfield      => '952',
751             tagsubfield   => '8',
752             kohafield     => 'items.ccode',
753             repeatable    => 1
754         }
755     )->store;
756     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
757
758     # Start testing
759     my $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
760     my @subs = $marc->subfield( $mapping->tagfield, $mapping->tagsubfield );
761     is( @subs, 2, 'Expect two subfields' );
762     is( $subs[0], 'A', 'First subfield matches' );
763     is( $subs[1], 'B', 'Second subfield matches' );
764
765     $schema->storage->txn_rollback;
766 };
767
768 subtest 'ModItemFromMarc' => sub {
769     plan tests => 7;
770     $schema->storage->txn_begin;
771
772     my $builder = t::lib::TestBuilder->new;
773     my ($itemfield) = GetMarcFromKohaField( 'items.itemnumber' );
774     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' });
775     my $biblio = $builder->build_sample_biblio;
776     my ( $lost_tag, $lost_sf ) = GetMarcFromKohaField( 'items.itemlost' );
777     my $item_record = MARC::Record->new;
778     $item_record->append_fields(
779         MARC::Field->new(
780             $itemfield, '', '',
781             'y' => $itemtype->itemtype,
782         ),
783         MARC::Field->new(
784             $itemfield, '', '',
785             $lost_sf => '1',
786         ),
787     );
788     my (undef, undef, $itemnumber) = AddItemFromMarc($item_record,
789         $biblio->biblionumber);
790
791     my $item = Koha::Items->find($itemnumber);
792     is( $item->itemlost, 1, 'itemlost picked from the item marc');
793
794     $item->new_status("this is something")->store;
795
796     my $updated_item_record = MARC::Record->new;
797     $updated_item_record->append_fields(
798         MARC::Field->new(
799             $itemfield, '', '',
800             'y' => $itemtype->itemtype,
801         )
802     );
803
804     my $updated_item = ModItemFromMarc($updated_item_record, $biblio->biblionumber, $itemnumber);
805     is( $updated_item->{itemlost}, 0, 'itemlost should have been reset to the default value in DB' );
806     is( $updated_item->{new_status}, "this is something", "Non mapped field has not been reset" );
807     is( Koha::Items->find($itemnumber)->new_status, "this is something" );
808
809     subtest 'cn_sort' => sub {
810         plan tests => 3;
811
812         my $item = $builder->build_sample_item;
813         $item->set({ cn_source => 'ddc', itemcallnumber => 'xxx' })->store;
814         is( $item->cn_sort, 'XXX', 'init values set are expected' );
815
816         my $marc = C4::Items::Item2Marc( $item->get_from_storage->unblessed, $item->biblionumber );
817         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
818         is( $item->get_from_storage->cn_sort, 'XXX', 'cn_sort has not been updated' );
819
820         $marc = C4::Items::Item2Marc( { %{$item->unblessed}, itemcallnumber => 'yyy' }, $item->biblionumber );
821         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
822         is( $item->get_from_storage->cn_sort, 'YYY', 'cn_sort has been updated' );
823     };
824
825     subtest 'onloan' => sub {
826         plan tests => 3;
827
828         my $item = $builder->build_sample_item;
829         $item->set({ onloan => '2022-03-19' })->store;
830         is( $item->onloan, '2022-03-19', 'init values set are expected' );
831
832         my $marc = C4::Items::Item2Marc( $item->get_from_storage->unblessed, $item->biblionumber );
833         my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField( 'items.onloan' );
834         $marc->field($MARCfield)->delete_subfield( code => $MARCsubfield );
835         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
836         is( $item->get_from_storage->onloan, '2022-03-19', 'onloan has not been updated if not passed' );
837
838         $marc = C4::Items::Item2Marc( { %{$item->unblessed}, onloan => '2022-03-26' }, $item->biblionumber );
839         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
840         is( $item->get_from_storage->onloan, '2022-03-26', 'onloan has been updated when passed in' );
841     };
842
843     subtest 'permanent_location' => sub {
844         plan tests => 10;
845
846         # Make sure items.permanent_location is not mapped
847         Koha::MarcSubfieldStructures->search(
848             {
849                 frameworkcode => q{},
850                 kohafield     => 'items.permanent_location',
851             }
852         )->delete;
853         Koha::MarcSubfieldStructures->search(
854             {
855                 frameworkcode => q{},
856                 tagfield     => '952',
857                 tagsubfield     => 'C',
858             }
859         )->delete;
860         Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
861
862         my $item = $builder->build_sample_item;
863
864         # By default, setting location to something new should set permanent location to the same thing
865         # with the usual exceptions
866         $item->set({ location => 'A', permanent_location => 'A' })->store;
867         is( $item->location, 'A', 'initial location set as expected' );
868         is( $item->permanent_location, 'A', 'initial permanent location set as expected' );
869
870         $item->location('B');
871         my $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
872         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
873
874         $item = $item->get_from_storage;
875         is( $item->location, 'B', 'new location set as expected' );
876         is( $item->permanent_location, 'B', 'new permanent location set as expected' );
877
878         # Added a marc mapping for permanent location, allows it to be edited independently
879         my $mapping = Koha::MarcSubfieldStructure->new(
880             {
881                 frameworkcode => q{},
882                 tagfield      => '952',
883                 tagsubfield   => 'C',
884                 kohafield     => 'items.permanent_location',
885                 repeatable    => 0,
886                 tab           => 10,
887                 hidden        => 0,
888             }
889         )->store;
890         Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
891
892         # Now if we change location, and also pass in a permanent location
893         # the permanent_location will not be overwritten by location
894         $item->location('C');
895         $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
896         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
897         $item = $item->get_from_storage;
898         is( $item->location, 'C', 'next new location set as expected' );
899         is( $item->permanent_location, 'B', 'permanent location remains unchanged as expected' );
900
901         $item->permanent_location(undef)->more_subfields_xml(undef)->store;
902         # Clear values from the DB
903         $item = $item->get_from_storage;
904
905         # Update the location
906         $item->location('D');
907         $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
908         # Remove the permanent_location field from the form
909         $marc->field('952')->delete_subfield("C");
910         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
911         $item = $item->get_from_storage;
912         is( $item->location, 'D', 'next new location set as expected' );
913         is( $item->permanent_location, 'D', 'permanent location is updated if not previously set and no value passed' );
914
915         # Clear values from the DB
916         $item->permanent_location(undef)->more_subfields_xml(undef)->store;
917         $item = $item->get_from_storage;
918
919         # This time nothing is set, but we pass an empty string
920         $item->permanent_location("");
921         $item->location('E');
922         $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
923         $marc->field('952')->add_subfields( "C", "" );
924         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
925         $item = $item->get_from_storage;
926         is( $item->location, 'E', 'next new location set as expected' );
927         is( $item->permanent_location, undef, 'permanent location is not updated if previously set as blank string' );
928     };
929
930     $schema->storage->txn_rollback;
931     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
932 };
933
934 subtest 'ModDateLastSeen' => sub {
935     plan tests => 5;
936     $schema->storage->txn_begin;
937
938     my $builder = t::lib::TestBuilder->new;
939     my $item = $builder->build_sample_item;
940     t::lib::Mocks::mock_preference('CataloguingLog', '1');
941     my $logs_before = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count;
942     ModDateLastSeen($item->itemnumber);
943     my $logs_after = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count;
944     is( $logs_after, $logs_before, "ModDateLastSeen doesn't log if item not lost");
945     $item->itemlost(1)->store({ log_action => 0 });
946     ModDateLastSeen($item->itemnumber, 1);
947     $item->discard_changes;
948     $logs_after = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count;
949     is( $item->itemlost, 1, "Item left lost when parameter is passed");
950     is( $logs_after, $logs_before, "ModDateLastSeen doesn't log if item not lost");
951     ModDateLastSeen($item->itemnumber);
952     $item->discard_changes;
953     $logs_after = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count;
954     is( $item->itemlost, 0, "Item no longer lost when no parameter is passed");
955     is( $logs_after, $logs_before + 1, "ModDateLastSeen logs if item was lost and now found");
956 };