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