Bug 34656: Unit test
[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 CartToShelf );
23 use C4::Biblio qw( GetMarcFromKohaField AddBiblio );
24 use C4::Circulation qw( AddIssue );
25 use Koha::BackgroundJobs;
26 use Koha::Items;
27 use Koha::Database;
28 use Koha::DateUtils qw( dt_from_string );
29 use Koha::Library;
30 use Koha::DateUtils;
31 use Koha::MarcSubfieldStructures;
32 use Koha::Caches;
33 use Koha::AuthorisedValues;
34
35 use t::lib::Mocks;
36 use t::lib::TestBuilder;
37
38 use Test::More tests => 13;
39
40 use Test::Warn;
41
42 my $schema = Koha::Database->new->schema;
43 my $location = 'My Location';
44
45 subtest 'General Add, Get and Del tests' => sub {
46
47     plan tests => 16;
48
49     $schema->storage->txn_begin;
50
51     my $builder = t::lib::TestBuilder->new;
52     my $library = $builder->build({
53         source => 'Branch',
54     });
55     my $itemtype = $builder->build({
56         source => 'Itemtype',
57     });
58
59     # Create a biblio instance for testing
60     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
61     my $biblio = $builder->build_sample_biblio();
62
63     # Add an item.
64     my $item = $builder->build_sample_item(
65         {
66             biblionumber => $biblio->biblionumber,
67             library      => $library->{branchcode},
68             location     => $location,
69             itype        => $itemtype->{itemtype}
70         }
71     );
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.");
75
76     # Get item.
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" );
82
83
84     # Do not modify anything, and do not explode!
85     $getitem->set({})->store;
86
87     # Modify item; setting barcode.
88     $getitem->barcode('987654321')->store;
89     my $moditem = Koha::Items->find($itemnumber);
90     cmp_ok($moditem->barcode, '==', '987654321', 'Modified item barcode successfully to: '.$moditem->barcode . '.');
91
92     # Delete item.
93     $moditem->delete;
94     my $getdeleted = Koha::Items->find($itemnumber);
95     is($getdeleted, undef, "Item deleted as expected.");
96
97     $itemnumber = $builder->build_sample_item(
98         {
99             biblionumber => $biblio->biblionumber,
100             library      => $library->{branchcode},
101             location     => $location,
102             permanent_location => 'my permanent location',
103             itype        => $itemtype->{itemtype}
104         }
105     )->itemnumber;
106     $getitem = Koha::Items->find($itemnumber);
107     is( $getitem->location, $location, "The location should not have been modified" );
108     is( $getitem->permanent_location, 'my permanent location', "The permanent_location should not have modified" );
109
110     my $new_location = "New location";
111     $getitem->location($new_location)->store;
112     $getitem = Koha::Items->find($itemnumber);
113     is( $getitem->location, $new_location, "The location should have been set to correct location" );
114     is( $getitem->permanent_location, $new_location, "The permanent_location should have been set to location" );
115
116     $getitem->location('CART')->store;
117     $getitem = Koha::Items->find($itemnumber);
118     is( $getitem->location, 'CART', "The location should have been set to CART" );
119     is( $getitem->permanent_location, $new_location, "The permanent_location should not have been set to CART" );
120
121     t::lib::Mocks::mock_preference('item-level_itypes', '1');
122     $getitem = Koha::Items->find($itemnumber);
123     is( $getitem->effective_itemtype, $itemtype->{itemtype}, "Itemtype set correctly when using item-level_itypes" );
124     t::lib::Mocks::mock_preference('item-level_itypes', '0');
125     $getitem = Koha::Items->find($itemnumber);
126     is( $getitem->effective_itemtype, $biblio->biblioitem->itemtype, "Itemtype set correctly when not using item-level_itypes" );
127
128     $schema->storage->txn_rollback;
129 };
130
131 subtest 'ModItemTransfer tests' => sub {
132     plan tests => 8;
133
134     $schema->storage->txn_begin;
135
136     my $builder = t::lib::TestBuilder->new;
137     my $item    = $builder->build_sample_item();
138
139     my $library1 = $builder->build(
140         {
141             source => 'Branch',
142         }
143     );
144     my $library2 = $builder->build(
145         {
146             source => 'Branch',
147         }
148     );
149
150     ModItemTransfer( $item->itemnumber, $library1->{branchcode},
151         $library2->{branchcode}, 'Manual' );
152
153     my $transfers = Koha::Item::Transfers->search(
154         {
155             itemnumber => $item->itemnumber
156         }
157     );
158
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");
162
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' } }
168     );
169
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");
178
179     # Check 'reason' is populated when passed
180     ModItemTransfer( $item->itemnumber, $library2->{branchcode},
181         $library1->{branchcode}, "Manual" );
182
183     $transfers = Koha::Item::Transfers->search(
184         { itemnumber => $item->itemnumber, },
185         { order_by   => { '-desc' => 'branchtransfer_id' } }
186     );
187
188     my $transfer3 = $transfers->next;
189     is($transfer3->reason, 'Manual', "Reason set via ModItemTransfer");
190
191     $schema->storage->txn_rollback;
192 };
193
194 subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub {
195
196     plan tests => 4;
197
198     $schema->storage->txn_begin;
199
200     my $biblio = $schema->resultset('Biblio')->create({
201         title       => "Test title",
202         datecreated => dt_from_string,
203         biblioitems => [ { itemtype => 'BIB_LEVEL' } ],
204     });
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",
210     });
211
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' );
214
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' );
217
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 );
221     $item->update();
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';
226
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' );
230
231     $schema->storage->txn_rollback;
232 };
233
234 subtest 'SearchItems test' => sub {
235     plan tests => 20;
236
237     $schema->storage->txn_begin;
238     my $dbh = C4::Context->dbh;
239     my $builder = t::lib::TestBuilder->new;
240
241     my $library1 = $builder->build({
242         source => 'Branch',
243     });
244     my $library2 = $builder->build({
245         source => 'Branch',
246     });
247     my $itemtype = $builder->build({
248         source => 'Itemtype',
249     });
250
251     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
252     my ($cpl_items_before) = SearchItems( { field => 'homebranch', query => $library1->{branchcode} } );
253
254     my $biblio = $builder->build_sample_biblio({ title => 'Silence in the library' });
255     $builder->build_sample_biblio({ title => 'Silence in the shadow' });
256
257     my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
258
259     # Add two items
260     my $item1 = $builder->build_sample_item(
261         {
262             biblionumber => $biblio->biblionumber,
263             library      => $library1->{branchcode},
264             itype        => $itemtype->{itemtype}
265         }
266     );
267     my $item1_itemnumber = $item1->itemnumber;
268     my $item2_itemnumber = $builder->build_sample_item(
269         {
270             biblionumber => $biblio->biblionumber,
271             library      => $library2->{branchcode},
272             itype        => $itemtype->{itemtype}
273         }
274     )->itemnumber;
275
276     my ($items, $total_results);
277
278     ($items, $total_results) = SearchItems();
279
280     is($total_results, $initial_items_count + 2, "Created 2 new items");
281     is(scalar @$items, $total_results, "SearchItems() returns all items");
282
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");
286
287     # Search all items where homebranch = 'CPL'
288     my $filter = {
289         field => 'homebranch',
290         query => $library1->{branchcode},
291         operator => '=',
292     };
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;
299             last;
300         }
301     }
302     ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
303
304     # Search all items where homebranch != 'CPL'
305     $filter = {
306         field => 'homebranch',
307         query => $library1->{branchcode},
308         operator => '!=',
309     };
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;
316             last;
317         }
318     }
319     ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
320
321     # Search all items where biblio title (245$a) is like 'Silence in the %'
322     $filter = {
323         field => 'marc:245$a',
324         query => 'Silence in the %',
325         operator => 'like',
326     };
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 %'");
329
330     # Search all items where biblio title is 'Silence in the library'
331     # and homebranch is 'CPL'
332     $filter = {
333         conjunction => 'AND',
334         filters => [
335             {
336                 field => 'marc:245$a',
337                 query => 'Silence in the %',
338                 operator => 'like',
339             },
340             {
341                 field => 'homebranch',
342                 query => $library1->{branchcode},
343                 operator => '=',
344             },
345         ],
346     };
347     ($items, $total_results) = SearchItems($filter);
348     my $found = 0;
349     foreach my $item (@$items) {
350         if ($item->{itemnumber} == $item1_itemnumber) {
351             $found = 1;
352             last;
353         }
354     }
355     ok($found, "item1 found");
356
357     my $frameworkcode = q||;
358     my ($itemfield) = GetMarcFromKohaField( 'items.itemnumber' );
359
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);
363
364     # Clear cache
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");
369
370     my $item3_record = MARC::Record->new;
371     $item3_record->append_fields(
372         MARC::Field->new(
373             $itemfield, '', '',
374             'z' => 'foobar',
375             'y' => $itemtype->{itemtype}
376         )
377     );
378     my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
379         $biblio->biblionumber);
380
381     # Search item where item subfield z is "foobar"
382     $filter = {
383         field => 'marc:' . $itemfield . '$z',
384         query => 'foobar',
385         operator => 'like',
386     };
387     ($items, $total_results) = SearchItems($filter);
388     ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
389
390     # Link $z to items.itemnotes (and make sure there is no other subfields
391     # linked to it)
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);
394
395     # Clear cache
396     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
397     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
398     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
399
400     ModItemFromMarc($item3_record, $biblio->biblionumber, $item3_itemnumber);
401
402     # Make sure the link is used
403     my $item3 = Koha::Items->find($item3_itemnumber);
404     is($item3->itemnotes, 'foobar', 'itemnotes eq "foobar"');
405
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"');
410
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' );
413
414     # Issues count = 0
415     $filter = {
416         conjunction => 'AND',
417         filters => [
418             {
419                 field => 'issues',
420                 query => 0,
421                 operator => '=',
422             },
423             {
424                 field => 'homebranch',
425                 query => $library1->{branchcode},
426                 operator => '=',
427             },
428         ],
429     };
430     ($items, $total_results) = SearchItems($filter);
431     is($total_results, 1, "Search items.issues issues = 0 returns result (items.issues defaults to 0)");
432
433     # Is null
434     $filter = {
435         conjunction => 'AND',
436         filters     => [
437             {
438                 field    => 'new_status',
439                 query    => 0,
440                 operator => '='
441             },
442             {
443                 field    => 'homebranch',
444                 query    => $library1->{branchcode},
445                 operator => '=',
446             },
447         ],
448     };
449     ($items, $total_results) = SearchItems($filter);
450     is($total_results, 0, 'found no item with new_status=0 without ifnull');
451
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');
455
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
460     $filter = {
461         conjunction => 'AND',
462         filters => [
463             {
464                 field => 'onloan',
465                 query => 'not null',
466                 operator => 'is',
467             },
468             {
469                 field => 'homebranch',
470                 query => $item1->homebranch,
471                 operator => '=',
472             },
473         ],
474     };
475     ($items, $total_results) = SearchItems($filter);
476     ok(scalar @$items == 1, 'found 1 checked out item');
477
478     # When sorting by descending availability, checked out item should show first
479     my $params = {
480         sortby => 'availability',
481         sortorder => 'DESC',
482     };
483     $filter = {
484         field => 'homebranch',
485         query => $item1->homebranch,
486         operator => '=',
487     };
488     ($items, $total_results) = SearchItems($filter,$params);
489     is($items->[0]->{barcode}, $item1->barcode, 'Items sorted as expected by availability');
490
491     subtest 'Search items by ISSN and ISBN with variations' => sub {
492         plan tests => 4;
493
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);
501
502         my $item = $builder->build_sample_item(
503             {
504                 biblionumber => $isbnissn_biblio->biblionumber,
505             }
506         );
507         my $item_itemnumber = $item->itemnumber;
508
509         my $filter_isbn = {
510             field => 'isbn',
511             query => '978013-6019701',
512             operator => 'like',
513         };
514
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");
518
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");
522
523         my $filter_issn = {
524             field => 'issn',
525             query => '2434-561X',
526             operator => 'like',
527         };
528
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");
532
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");
536     };
537
538     $schema->storage->txn_rollback;
539 };
540
541 subtest 'Koha::Item(s) tests' => sub {
542
543     plan tests => 7;
544
545     $schema->storage->txn_begin();
546
547     my $builder = t::lib::TestBuilder->new;
548     my $library1 = $builder->build({
549         source => 'Branch',
550     });
551     my $library2 = $builder->build({
552         source => 'Branch',
553     });
554     my $itemtype = $builder->build({
555         source => 'Itemtype',
556     });
557
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(
562         {
563             biblionumber  => $biblio->biblionumber,
564             homebranch    => $library1->{branchcode},
565             holdingbranch => $library2->{branchcode},
566             itype         => $itemtype->{itemtype}
567         }
568     )->itemnumber;
569
570     # Get item.
571     my $item = Koha::Items->find( $itemnumber );
572     is( ref($item), 'Koha::Item', "Got Koha::Item" );
573
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" );
577
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" );
581
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' );
585
586     $schema->storage->txn_rollback;
587 };
588
589 subtest 'get_hostitemnumbers_of' => sub {
590     plan tests => 3;
591
592     $schema->storage->txn_begin;
593     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
594     my $builder = t::lib::TestBuilder->new;
595
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'),
602     );
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');
606
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' ),
615     );
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');
619
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');
624
625     $schema->storage->txn_rollback;
626 };
627
628 subtest 'Test logging for ModItem' => sub {
629
630     plan tests => 3;
631
632     t::lib::Mocks::mock_preference('CataloguingLog', 1);
633
634     $schema->storage->txn_begin;
635
636     my $builder = t::lib::TestBuilder->new;
637     my $library = $builder->build({
638         source => 'Branch',
639     });
640     my $itemtype = $builder->build({
641         source => 'Itemtype',
642     });
643
644     # Create a biblio instance for testing
645     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
646     my $biblio = $builder->build_sample_biblio();
647
648     # Add an item.
649     my $item = $builder->build_sample_item(
650         {
651             biblionumber => $biblio->biblionumber,
652             library      => $library->{homebranch},
653             location     => $location,
654             itype        => $itemtype->{itemtype}
655         }
656     );
657
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' );
662
663     # True means 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' );
667
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' );
672
673     $schema->storage->txn_rollback;
674 };
675
676 subtest 'Check stockrotationitem relationship' => sub {
677     plan tests => 1;
678
679     $schema->storage->txn_begin();
680
681     my $builder = t::lib::TestBuilder->new;
682     my $item = $builder->build_sample_item;
683
684     $builder->build({
685         source => 'Stockrotationitem',
686         value  => { itemnumber_id => $item->itemnumber }
687     });
688
689     my $sritem = Koha::Items->find($item->itemnumber)->stockrotationitem;
690     isa_ok( $sritem, 'Koha::StockRotationItem', "Relationship works and correctly creates Koha::Object." );
691
692     $schema->storage->txn_rollback;
693 };
694
695 subtest 'Check add_to_rota method' => sub {
696     plan tests => 2;
697
698     $schema->storage->txn_begin();
699
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});
704
705     $builder->build({
706         source => 'Stockrotationstage',
707         value  => { rota_id => $rota->{rota_id} },
708     });
709
710     my $sritem = Koha::Items->find($item->itemnumber);
711     $sritem->add_to_rota($rota->{rota_id});
712
713     is(
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."
717     );
718
719     my $newrota = $builder->build({ source => 'Stockrotationrota' });
720
721     my $srnewrota = Koha::StockRotationRotas->find($newrota->{rota_id});
722
723     $builder->build({
724         source => 'Stockrotationstage',
725         value  => { rota_id => $newrota->{rota_id} },
726     });
727
728     $sritem->add_to_rota($newrota->{rota_id});
729
730     is(
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."
734     );
735
736     $schema->storage->txn_rollback;
737 };
738
739 subtest 'Split subfields in Item2Marc (Bug 21774)' => sub {
740     plan tests => 3;
741     $schema->storage->txn_begin;
742
743     my $builder = t::lib::TestBuilder->new;
744     my $item = $builder->build_sample_item({ ccode => 'A|B' });
745
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(
749         {
750             frameworkcode => q{},
751             tagfield      => '952',
752             tagsubfield   => '8',
753             kohafield     => 'items.ccode',
754             repeatable    => 1
755         }
756     )->store;
757     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
758
759     # Start testing
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' );
765
766     $schema->storage->txn_rollback;
767 };
768
769 subtest 'ModItemFromMarc' => sub {
770     plan tests => 8;
771     $schema->storage->txn_begin;
772
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(
780         MARC::Field->new(
781             $itemfield, '', '',
782             'y' => $itemtype->itemtype,
783         ),
784         MARC::Field->new(
785             $itemfield, '', '',
786             $lost_sf => '1',
787         ),
788     );
789     my (undef, undef, $itemnumber) = AddItemFromMarc($item_record,
790         $biblio->biblionumber);
791
792     my $item = Koha::Items->find($itemnumber);
793     is( $item->itemlost, 1, 'itemlost picked from the item marc');
794
795     $item->new_status("this is something")->store;
796
797     my $updated_item_record = MARC::Record->new;
798     $updated_item_record->append_fields(
799         MARC::Field->new(
800             $itemfield, '', '',
801             'y' => $itemtype->itemtype,
802         )
803     );
804
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" );
809
810     subtest 'cn_sort' => sub {
811         plan tests => 3;
812
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' );
816
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' );
820
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' );
824     };
825
826     subtest 'onloan' => sub {
827         plan tests => 3;
828
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' );
832
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' );
838
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' );
842     };
843
844     subtest 'dateaccessioned' => sub {
845         plan tests => 3;
846
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' );
850
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' );
856
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' );
860     };
861
862     subtest 'permanent_location' => sub {
863         plan tests => 10;
864
865         # Make sure items.permanent_location is not mapped
866         Koha::MarcSubfieldStructures->search(
867             {
868                 frameworkcode => q{},
869                 kohafield     => 'items.permanent_location',
870             }
871         )->delete;
872         Koha::MarcSubfieldStructures->search(
873             {
874                 frameworkcode => q{},
875                 tagfield     => '952',
876                 tagsubfield     => 'C',
877             }
878         )->delete;
879         Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
880
881         my $item = $builder->build_sample_item;
882
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' );
888
889         $item->location('B');
890         my $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
891         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
892
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' );
896
897         # Added a marc mapping for permanent location, allows it to be edited independently
898         my $mapping = Koha::MarcSubfieldStructure->new(
899             {
900                 frameworkcode => q{},
901                 tagfield      => '952',
902                 tagsubfield   => 'C',
903                 kohafield     => 'items.permanent_location',
904                 repeatable    => 0,
905                 tab           => 10,
906                 hidden        => 0,
907             }
908         )->store;
909         Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
910
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' );
919
920         $item->permanent_location(undef)->more_subfields_xml(undef)->store;
921         # Clear values from the DB
922         $item = $item->get_from_storage;
923
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' );
933
934         # Clear values from the DB
935         $item->permanent_location(undef)->more_subfields_xml(undef)->store;
936         $item = $item->get_from_storage;
937
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' );
947     };
948
949     $schema->storage->txn_rollback;
950     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
951 };
952
953 subtest 'ModDateLastSeen' => sub {
954     plan tests => 5;
955     $schema->storage->txn_begin;
956
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");
975 };
976
977 subtest 'CartToShelf test' => sub {
978     plan tests => 2;
979
980     $schema->storage->txn_begin;
981     my $dbh = C4::Context->dbh;
982     my $builder = t::lib::TestBuilder->new;
983
984     my $item = $builder->build_sample_item();
985
986     $item->permanent_location('BANANA')->location('CART')->store();
987
988     CartToShelf( $item->id );
989
990     $item->discard_changes;
991
992     is( $item->location, 'BANANA', 'Item is correctly returned to permanent location');
993
994
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');
998
999     $item->location('CART')->store({ skip_holds_queue => 1 });
1000     warnings_are{
1001         CartToShelf( $item->id );
1002     } [], 'No RTHQ update triggered by CartToShelf';
1003
1004     $schema->storage->txn_rollback;
1005
1006 };