Bug 18330: Handle date-time in Koha::Object->TO_JSON
[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::Biblio;
24 use Koha::Database;
25 use Koha::Library;
26
27 use t::lib::Mocks;
28 use t::lib::TestBuilder;
29
30 use Koha::MarcSubfieldStructures;
31 use Koha::Caches;
32
33 use Test::More tests => 12;
34
35 use Test::Warn;
36
37 BEGIN {
38     use_ok('C4::Items');
39     use_ok('Koha::Items');
40 }
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 ($bibnum, $bibitemnum) = get_biblio();
62
63     # Add an item.
64     my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $library->{branchcode}, holdingbranch => $library->{branchcode}, location => $location, itype => $itemtype->{itemtype} } , $bibnum);
65     cmp_ok($item_bibnum, '==', $bibnum, "New item is linked to correct biblionumber.");
66     cmp_ok($item_bibitemnum, '==', $bibitemnum, "New item is linked to correct biblioitemnumber.");
67
68     # Get item.
69     my $getitem = GetItem($itemnumber);
70     cmp_ok($getitem->{'itemnumber'}, '==', $itemnumber, "Retrieved item has correct itemnumber.");
71     cmp_ok($getitem->{'biblioitemnumber'}, '==', $item_bibitemnum, "Retrieved item has correct biblioitemnumber.");
72     is( $getitem->{location}, $location, "The location should not have been modified" );
73     is( $getitem->{permanent_location}, $location, "The permanent_location should have been set to the location value" );
74
75     # Modify item; setting barcode.
76     ModItem({ barcode => '987654321' }, $bibnum, $itemnumber);
77     my $moditem = GetItem($itemnumber);
78     cmp_ok($moditem->{'barcode'}, '==', '987654321', 'Modified item barcode successfully to: '.$moditem->{'barcode'} . '.');
79
80     # Delete item.
81     DelItem({ biblionumber => $bibnum, itemnumber => $itemnumber });
82     my $getdeleted = GetItem($itemnumber);
83     is($getdeleted->{'itemnumber'}, undef, "Item deleted as expected.");
84
85     ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $library->{branchcode}, holdingbranch => $library->{branchcode}, location => $location, permanent_location => 'my permanent location', itype => $itemtype->{itemtype} } , $bibnum);
86     $getitem = GetItem($itemnumber);
87     is( $getitem->{location}, $location, "The location should not have been modified" );
88     is( $getitem->{permanent_location}, 'my permanent location', "The permanent_location should not have modified" );
89
90     ModItem({ location => $location }, $bibnum, $itemnumber);
91     $getitem = GetItem($itemnumber);
92     is( $getitem->{location}, $location, "The location should have been set to correct location" );
93     is( $getitem->{permanent_location}, $location, "The permanent_location should have been set to location" );
94
95     ModItem({ location => 'CART' }, $bibnum, $itemnumber);
96     $getitem = GetItem($itemnumber);
97     is( $getitem->{location}, 'CART', "The location should have been set to CART" );
98     is( $getitem->{permanent_location}, $location, "The permanent_location should not have been set to CART" );
99
100     t::lib::Mocks::mock_preference('item-level_itypes', '1');
101     $getitem = GetItem($itemnumber);
102     is( $getitem->{itype}, $itemtype->{itemtype}, "Itemtype set correctly when using item-level_itypes" );
103     t::lib::Mocks::mock_preference('item-level_itypes', '0');
104     $getitem = GetItem($itemnumber);
105     is( $getitem->{itype}, undef, "Itemtype set correctly when not using item-level_itypes" );
106
107     $schema->storage->txn_rollback;
108 };
109
110 subtest 'GetHiddenItemnumbers tests' => sub {
111
112     plan tests => 9;
113
114     # This sub is controlled by the OpacHiddenItems system preference.
115
116     $schema->storage->txn_begin;
117
118     my $builder = t::lib::TestBuilder->new;
119     my $library1 = $builder->build({
120         source => 'Branch',
121     });
122
123     my $library2 = $builder->build({
124         source => 'Branch',
125     });
126     my $itemtype = $builder->build({
127         source => 'Itemtype',
128     });
129
130     # Create a new biblio
131     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
132     my ($biblionumber, $biblioitemnumber) = get_biblio();
133
134     # Add two items
135     my ( $item1_bibnum, $item1_bibitemnum, $item1_itemnumber ) = AddItem(
136         {
137             homebranch    => $library1->{branchcode},
138             holdingbranch => $library1->{branchcode},
139             withdrawn     => 1,
140             itype         => $itemtype->{itemtype},
141         },
142         $biblionumber
143     );
144     my ( $item2_bibnum, $item2_bibitemnum, $item2_itemnumber ) = AddItem(
145         {
146             homebranch    => $library2->{branchcode},
147             holdingbranch => $library2->{branchcode},
148             withdrawn     => 0,
149             itype         => $itemtype->{itemtype},
150         },
151         $biblionumber
152     );
153
154     my $opachiddenitems;
155     my @itemnumbers = ($item1_itemnumber,$item2_itemnumber);
156     my @hidden;
157     my @items;
158     push @items, GetItem( $item1_itemnumber );
159     push @items, GetItem( $item2_itemnumber );
160
161     # Empty OpacHiddenItems
162     t::lib::Mocks::mock_preference('OpacHiddenItems','');
163     ok( !defined( GetHiddenItemnumbers( @items ) ),
164         "Hidden items list undef if OpacHiddenItems empty");
165
166     # Blank spaces
167     t::lib::Mocks::mock_preference('OpacHiddenItems','  ');
168     ok( scalar GetHiddenItemnumbers( @items ) == 0,
169         "Hidden items list empty if OpacHiddenItems only contains blanks");
170
171     # One variable / value
172     $opachiddenitems = "
173         withdrawn: [1]";
174     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
175     @hidden = GetHiddenItemnumbers( @items );
176     ok( scalar @hidden == 1, "Only one hidden item");
177     is( $hidden[0], $item1_itemnumber, "withdrawn=1 is hidden");
178
179     # One variable, two values
180     $opachiddenitems = "
181         withdrawn: [1,0]";
182     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
183     @hidden = GetHiddenItemnumbers( @items );
184     ok( scalar @hidden == 2, "Two items hidden");
185     is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and withdrawn=0 hidden");
186
187     # Two variables, a value each
188     $opachiddenitems = "
189         withdrawn: [1]
190         homebranch: [$library2->{branchcode}]
191     ";
192     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
193     @hidden = GetHiddenItemnumbers( @items );
194     ok( scalar @hidden == 2, "Two items hidden");
195     is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and homebranch library2 hidden");
196
197     # Valid OpacHiddenItems, empty list
198     @items = ();
199     @hidden = GetHiddenItemnumbers( @items );
200     ok( scalar @hidden == 0, "Empty items list, no item hidden");
201
202     $schema->storage->txn_rollback;
203 };
204
205 subtest 'GetItemsInfo tests' => sub {
206
207     plan tests => 4;
208
209     $schema->storage->txn_begin;
210
211     my $builder = t::lib::TestBuilder->new;
212     my $library1 = $builder->build({
213         source => 'Branch',
214     });
215     my $library2 = $builder->build({
216         source => 'Branch',
217     });
218     my $itemtype = $builder->build({
219         source => 'Itemtype',
220     });
221
222     # Add a biblio
223     my ($biblionumber, $biblioitemnumber) = get_biblio();
224     # Add an item
225     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
226         {
227             homebranch    => $library1->{branchcode},
228             holdingbranch => $library2->{branchcode},
229             itype         => $itemtype->{itemtype},
230         },
231         $biblionumber
232     );
233
234     my $library = Koha::Libraries->find( $library1->{branchcode} );
235     $library->opac_info("homebranch OPAC info");
236     $library->store;
237
238     $library = Koha::Libraries->find( $library2->{branchcode} );
239     $library->opac_info("holdingbranch OPAC info");
240     $library->store;
241
242     my @results = GetItemsInfo( $biblionumber );
243     ok( @results, 'GetItemsInfo returns results');
244     is( $results[0]->{ home_branch_opac_info }, "homebranch OPAC info",
245         'GetItemsInfo returns the correct home branch OPAC info notice' );
246     is( $results[0]->{ holding_branch_opac_info }, "holdingbranch OPAC info",
247         'GetItemsInfo returns the correct holding branch OPAC info notice' );
248     is( exists( $results[0]->{ onsite_checkout } ), 1,
249         'GetItemsInfo returns a onsite_checkout key' );
250
251     $schema->storage->txn_rollback;
252 };
253
254 subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub {
255
256     plan tests => 4;
257
258     $schema->storage->txn_begin;
259
260     my $biblio = $schema->resultset('Biblio')->create({
261         title       => "Test title",
262         biblioitems => [ { itemtype => 'BIB_LEVEL' } ],
263     });
264     my $biblioitem = $biblio->biblioitems->first;
265     my $item = $schema->resultset('Item')->create({
266         biblioitemnumber => $biblioitem->biblioitemnumber,
267         biblionumber     => $biblio->biblionumber,
268         itype            => "ITEM_LEVEL",
269     });
270
271     t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
272     is( $item->effective_itemtype(), 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' );
273
274     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
275     is( $item->effective_itemtype(), 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' );
276
277     # If itemtype is not defined and item-level_level item types are set
278     # fallback to biblio-level itemtype (Bug 14651) and warn
279     $item->itype( undef );
280     $item->update();
281     my $effective_itemtype;
282     warning_is { $effective_itemtype = $item->effective_itemtype() }
283                 "item-level_itypes set but no itemtype set for item (".$item->itemnumber.")",
284                 '->effective_itemtype() raises a warning when falling back to bib-level';
285
286     ok( defined $effective_itemtype &&
287                 $effective_itemtype eq 'BIB_LEVEL',
288         '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' );
289
290     $schema->storage->txn_rollback;
291 };
292
293 subtest 'SearchItems test' => sub {
294     plan tests => 14;
295
296     $schema->storage->txn_begin;
297     my $dbh = C4::Context->dbh;
298     my $builder = t::lib::TestBuilder->new;
299
300     my $library1 = $builder->build({
301         source => 'Branch',
302     });
303     my $library2 = $builder->build({
304         source => 'Branch',
305     });
306     my $itemtype = $builder->build({
307         source => 'Itemtype',
308     });
309
310     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
311     my $cpl_items_before = SearchItemsByField( 'homebranch', $library1->{branchcode});
312
313     my ($biblionumber) = get_biblio();
314
315     my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
316
317     # Add two items
318     my (undef, undef, $item1_itemnumber) = AddItem({
319         homebranch => $library1->{branchcode},
320         holdingbranch => $library1->{branchcode},
321         itype => $itemtype->{itemtype},
322     }, $biblionumber);
323     my (undef, undef, $item2_itemnumber) = AddItem({
324         homebranch => $library2->{branchcode},
325         holdingbranch => $library2->{branchcode},
326         itype => $itemtype->{itemtype},
327     }, $biblionumber);
328
329     my ($items, $total_results);
330
331     ($items, $total_results) = SearchItems();
332     is($total_results, $initial_items_count + 2, "Created 2 new items");
333     is(scalar @$items, $total_results, "SearchItems() returns all items");
334
335     ($items, $total_results) = SearchItems(undef, {rows => 1});
336     is($total_results, $initial_items_count + 2);
337     is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item");
338
339     # Search all items where homebranch = 'CPL'
340     my $filter = {
341         field => 'homebranch',
342         query => $library1->{branchcode},
343         operator => '=',
344     };
345     ($items, $total_results) = SearchItems($filter);
346     ok($total_results > 0, "There is at least one CPL item");
347     my $all_items_are_CPL = 1;
348     foreach my $item (@$items) {
349         if ($item->{homebranch} ne $library1->{branchcode}) {
350             $all_items_are_CPL = 0;
351             last;
352         }
353     }
354     ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
355
356     # Search all items where homebranch != 'CPL'
357     $filter = {
358         field => 'homebranch',
359         query => $library1->{branchcode},
360         operator => '!=',
361     };
362     ($items, $total_results) = SearchItems($filter);
363     ok($total_results > 0, "There is at least one non-CPL item");
364     my $all_items_are_not_CPL = 1;
365     foreach my $item (@$items) {
366         if ($item->{homebranch} eq $library1->{branchcode}) {
367             $all_items_are_not_CPL = 0;
368             last;
369         }
370     }
371     ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
372
373     # Search all items where biblio title (245$a) is like 'Silence in the %'
374     $filter = {
375         field => 'marc:245$a',
376         query => 'Silence in the %',
377         operator => 'like',
378     };
379     ($items, $total_results) = SearchItems($filter);
380     ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'");
381
382     # Search all items where biblio title is 'Silence in the library'
383     # and homebranch is 'CPL'
384     $filter = {
385         conjunction => 'AND',
386         filters => [
387             {
388                 field => 'marc:245$a',
389                 query => 'Silence in the %',
390                 operator => 'like',
391             },
392             {
393                 field => 'homebranch',
394                 query => $library1->{branchcode},
395                 operator => '=',
396             },
397         ],
398     };
399     ($items, $total_results) = SearchItems($filter);
400     my $found = 0;
401     foreach my $item (@$items) {
402         if ($item->{itemnumber} == $item1_itemnumber) {
403             $found = 1;
404             last;
405         }
406     }
407     ok($found, "item1 found");
408
409     my $frameworkcode = q||;
410     my ($itemfield) = GetMarcFromKohaField('items.itemnumber', $frameworkcode);
411
412     # Create item subfield 'z' without link
413     $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
414     $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", ?)', undef, $itemfield, $frameworkcode);
415
416     # Clear cache
417     my $cache = Koha::Caches->get_instance();
418     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
419     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
420     $cache->clear_from_cache("default_value_for_mod_marc-");
421     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
422
423     my $item3_record = new MARC::Record;
424     $item3_record->append_fields(
425         new MARC::Field(
426             $itemfield, '', '',
427             'z' => 'foobar',
428             'y' => $itemtype->{itemtype}
429         )
430     );
431     my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
432         $biblionumber);
433
434     # Search item where item subfield z is "foobar"
435     $filter = {
436         field => 'marc:' . $itemfield . '$z',
437         query => 'foobar',
438         operator => 'like',
439     };
440     ($items, $total_results) = SearchItems($filter);
441     ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
442
443     # Link $z to items.itemnotes (and make sure there is no other subfields
444     # linked to it)
445     $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
446     $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
447
448     # Clear cache
449     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
450     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
451     $cache->clear_from_cache("default_value_for_mod_marc-");
452     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
453
454     ModItemFromMarc($item3_record, $biblionumber, $item3_itemnumber);
455
456     # Make sure the link is used
457     my $item3 = GetItem($item3_itemnumber);
458     ok($item3->{itemnotes} eq 'foobar', 'itemnotes eq "foobar"');
459
460     # Do the same search again.
461     # This time it will search in items.itemnotes
462     ($items, $total_results) = SearchItems($filter);
463     ok(scalar @$items == 1, 'found 1 item with itemnotes = "foobar"');
464
465     my $cpl_items_after = SearchItemsByField( 'homebranch', $library1->{branchcode});
466     is( ( scalar( @$cpl_items_after ) - scalar ( @$cpl_items_before ) ), 1, 'SearchItemsByField should return something' );
467
468     $schema->storage->txn_rollback;
469 };
470
471 subtest 'Koha::Item(s) tests' => sub {
472
473     plan tests => 5;
474
475     $schema->storage->txn_begin();
476
477     my $builder = t::lib::TestBuilder->new;
478     my $library1 = $builder->build({
479         source => 'Branch',
480     });
481     my $library2 = $builder->build({
482         source => 'Branch',
483     });
484     my $itemtype = $builder->build({
485         source => 'Itemtype',
486     });
487
488     # Create a biblio and item for testing
489     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
490     my ($bibnum, $bibitemnum) = get_biblio();
491     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
492         {
493             homebranch    => $library1->{branchcode},
494             holdingbranch => $library2->{branchcode},
495             itype         => $itemtype->{itemtype},
496         },
497         $bibnum
498     );
499
500     # Get item.
501     my $item = Koha::Items->find( $itemnumber );
502     is( ref($item), 'Koha::Item', "Got Koha::Item" );
503
504     my $homebranch = $item->home_branch();
505     is( ref($homebranch), 'Koha::Library', "Got Koha::Library from home_branch method" );
506     is( $homebranch->branchcode(), $library1->{branchcode}, "Home branch code matches homebranch" );
507
508     my $holdingbranch = $item->holding_branch();
509     is( ref($holdingbranch), 'Koha::Library', "Got Koha::Library from holding_branch method" );
510     is( $holdingbranch->branchcode(), $library2->{branchcode}, "Home branch code matches holdingbranch" );
511
512     $schema->storage->txn_rollback;
513 };
514
515 subtest 'C4::Biblio::EmbedItemsInMarcBiblio' => sub {
516     plan tests => 7;
517
518     $schema->storage->txn_begin();
519
520     my $builder = t::lib::TestBuilder->new;
521     my $library1 = $builder->build({
522         source => 'Branch',
523     });
524     my $library2 = $builder->build({
525         source => 'Branch',
526     });
527     my $itemtype = $builder->build({
528         source => 'Itemtype',
529     });
530
531     my ( $biblionumber, $biblioitemnumber ) = get_biblio();
532     my $item_infos = [
533         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
534         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
535         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
536         { homebranch => $library2->{branchcode}, holdingbranch => $library2->{branchcode} },
537         { homebranch => $library2->{branchcode}, holdingbranch => $library2->{branchcode} },
538         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
539         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
540         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
541     ];
542     my $number_of_items = scalar @$item_infos;
543     my $number_of_items_with_homebranch_is_CPL =
544       grep { $_->{homebranch} eq $library1->{branchcode} } @$item_infos;
545
546     my @itemnumbers;
547     for my $item_info (@$item_infos) {
548         my ( undef, undef, $itemnumber ) = AddItem(
549             {
550                 homebranch    => $item_info->{homebranch},
551                 holdingbranch => $item_info->{holdingbanch},
552                 itype         => $itemtype->{itemtype},
553             },
554             $biblionumber
555         );
556         push @itemnumbers, $itemnumber;
557     }
558
559     # Emptied the OpacHiddenItems pref
560     t::lib::Mocks::mock_preference( 'OpacHiddenItems', '' );
561
562     my ($itemfield) =
563       C4::Biblio::GetMarcFromKohaField( 'items.itemnumber', '' );
564     my $record = C4::Biblio::GetMarcBiblio({ biblionumber => $biblionumber });
565     warning_is { C4::Biblio::EmbedItemsInMarcBiblio() }
566     { carped => 'EmbedItemsInMarcBiblio: No MARC record passed' },
567       'Should crap is no record passed.';
568
569     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber );
570     my @items = $record->field($itemfield);
571     is( scalar @items, $number_of_items, 'Should return all items' );
572
573     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber,
574         [ $itemnumbers[1], $itemnumbers[3] ] );
575     @items = $record->field($itemfield);
576     is( scalar @items, 2, 'Should return all items present in the list' );
577
578     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
579     @items = $record->field($itemfield);
580     is( scalar @items, $number_of_items, 'Should return all items for opac' );
581
582     my $opachiddenitems = "
583         homebranch: ['$library1->{branchcode}']";
584     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
585
586     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber );
587     @items = $record->field($itemfield);
588     is( scalar @items,
589         $number_of_items,
590         'Even with OpacHiddenItems set, all items should have been embedded' );
591
592     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
593     @items = $record->field($itemfield);
594     is(
595         scalar @items,
596         $number_of_items - $number_of_items_with_homebranch_is_CPL,
597 'For OPAC, the pref OpacHiddenItems should have been take into account. Only items with homebranch ne CPL should have been embedded'
598     );
599
600     $opachiddenitems = "
601         homebranch: ['$library1->{branchcode}', '$library2->{branchcode}']";
602     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
603     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
604     @items = $record->field($itemfield);
605     is(
606         scalar @items,
607         0,
608 'For OPAC, If all items are hidden, no item should have been embedded'
609     );
610
611     $schema->storage->txn_rollback;
612 };
613
614
615 subtest 'C4::Items::_build_default_values_for_mod_marc' => sub {
616     plan tests => 4;
617
618     $schema->storage->txn_begin();
619
620     my $builder = t::lib::TestBuilder->new;
621     my $framework = $builder->build({ source => 'BiblioFramework' });
622
623     # Link biblio.biblionumber and biblioitems.biblioitemnumber to avoid _koha_marc_update_bib_ids to fail with 'no biblio[item]number tag for framework"
624     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '999', tagsubfield => [ 'c', 'd' ] })->delete;
625     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '999', tagsubfield => 'c', kohafield => 'biblio.biblionumber' })->store;
626     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '999', tagsubfield => 'd', kohafield => 'biblioitems.biblioitemnumber' })->store;
627
628     # Same for item fields: itemnumber, barcode, itype
629     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '952', tagsubfield => [ '9', 'p', 'y' ] })->delete;
630     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => '9', kohafield => 'items.itemnumber' })->store;
631     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => 'p', kohafield => 'items.barcode' })->store;
632     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => 'y', kohafield => 'items.itype' })->store;
633     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
634
635     my $itemtype = $builder->build({ source => 'Itemtype' })->{itemtype};
636
637     # Create a record with a barcode
638     my ($biblionumber) = get_biblio( $framework->{frameworkcode} );
639     my $item_record = new MARC::Record;
640     my $a_barcode = 'a barcode';
641     my $barcode_field = MARC::Field->new(
642         '952', ' ', ' ',
643         p => $a_barcode,
644         y => $itemtype
645     );
646     my $itemtype_field = MARC::Field->new(
647         '952', ' ', ' ',
648         y => $itemtype
649     );
650     $item_record->append_fields( $barcode_field );
651     my (undef, undef, $item_itemnumber) = AddItemFromMarc($item_record, $biblionumber);
652
653     # Make sure everything has been set up
654     my $item = GetItem($item_itemnumber);
655     is( $item->{barcode}, $a_barcode, 'Everything has been set up correctly, the barcode is defined as expected' );
656
657     # Delete the barcode field and save the record
658     $item_record->delete_fields( $barcode_field );
659     $item_record->append_fields( $itemtype_field ); # itemtype is mandatory
660     ModItemFromMarc($item_record, $biblionumber, $item_itemnumber);
661     $item = GetItem($item_itemnumber);
662     is( $item->{barcode}, undef, 'The default value should have been set to the barcode, the field is mapped to a kohafield' );
663
664     # Re-add the barcode field and save the record
665     $item_record->append_fields( $barcode_field );
666     ModItemFromMarc($item_record, $biblionumber, $item_itemnumber);
667     $item = GetItem($item_itemnumber);
668     is( $item->{barcode}, $a_barcode, 'Everything has been set up correctly, the barcode is defined as expected' );
669
670     # Remove the mapping for barcode
671     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '952', tagsubfield => 'p' })->delete;
672
673     # And make sure the caches are cleared
674     my $cache = Koha::Caches->get_instance();
675     $cache->clear_from_cache("default_value_for_mod_marc-");
676     $cache->clear_from_cache("MarcSubfieldStructure-");
677
678     # Update the MARC field with another value
679     $item_record->delete_fields( $barcode_field );
680     my $another_barcode = 'another_barcode';
681     my $another_barcode_field = MARC::Field->new(
682         '952', ' ', ' ',
683         p => $another_barcode,
684     );
685     $item_record->append_fields( $another_barcode_field );
686     # The DB value should not have been updated
687     ModItemFromMarc($item_record, $biblionumber, $item_itemnumber);
688     $item = GetItem($item_itemnumber);
689     is ( $item->{barcode}, $a_barcode, 'items.barcode is not mapped anymore, so the DB column has not been updated' );
690
691     $cache->clear_from_cache("default_value_for_mod_marc-");
692     $cache->clear_from_cache( "MarcSubfieldStructure-" );
693     $schema->storage->txn_rollback;
694 };
695
696 subtest '_mod_item_dates' => sub {
697     plan tests => 11;
698
699     is( C4::Items::_mod_item_dates(), undef, 'Call without parameters' );
700     is( C4::Items::_mod_item_dates(1), undef, 'Call without hashref' );
701
702     my $orgitem;
703     my $item = {
704         itemcallnumber  => 'V II 149 1963',
705         barcode         => '109304',
706     };
707     $orgitem = { %$item };
708     C4::Items::_mod_item_dates($item);
709     is_deeply( $item, $orgitem, 'No dates passed to _mod_item_dates' );
710
711     # add two correct dates
712     t::lib::Mocks::mock_preference('dateformat', 'us');
713     $item->{dateaccessioned} = '01/31/2016';
714     $item->{onloan} =  $item->{dateaccessioned};
715     $orgitem = { %$item };
716     C4::Items::_mod_item_dates($item);
717     is( $item->{dateaccessioned}, '2016-01-31', 'dateaccessioned is fine' );
718     is( $item->{onloan}, '2016-01-31', 'onloan is fine too' );
719
720
721     # add some invalid dates
722     $item->{notexistingcolumndate} = '13/1/2015'; # wrong format
723     $item->{anotherdate} = 'tralala'; # even worse
724     $item->{myzerodate} = '0000-00-00'; # wrong too
725     C4::Items::_mod_item_dates($item);
726     is( $item->{notexistingcolumndate}, undef, 'Invalid date became NULL' );
727     is( $item->{anotherdate}, undef, 'Second invalid date became NULL too' );
728     is( $item->{myzerodate}, undef, '0000-00-00 became NULL too' );
729
730     # check if itemlost_on was not touched
731     $item->{itemlost_on} = '12345678';
732     $item->{withdrawn_on} = '12/31/2015 23:59:00';
733     $orgitem = { %$item };
734     C4::Items::_mod_item_dates($item);
735     is_deeply( $item, $orgitem, 'Colums with _on are not touched' );
736
737     t::lib::Mocks::mock_preference('dateformat', 'metric');
738     $item->{dateaccessioned} = '01/31/2016'; #wrong
739     $item->{yetanotherdatetime} = '20/01/2016 13:58:00'; #okay
740     C4::Items::_mod_item_dates($item);
741     is( $item->{dateaccessioned}, undef, 'dateaccessioned wrong format' );
742     is( $item->{yetanotherdatetime}, '2016-01-20 13:58:00',
743         'yetanotherdatetime is ok' );
744 };
745
746 subtest 'get_hostitemnumbers_of' => sub {
747     plan tests => 1;
748
749     my $bib = MARC::Record->new();
750     $bib->append_fields(
751         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
752         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
753         MARC::Field->new('773', ' ', ' ', b => 'b without 0 or 9'),
754     );
755     my ($biblionumber, $bibitemnum) = AddBiblio($bib, '');
756
757     my @itemnumbers = C4::Items::get_hostitemnumbers_of( $biblionumber );
758     is( @itemnumbers, 0, );
759 };
760
761 # Helper method to set up a Biblio.
762 sub get_biblio {
763     my ( $frameworkcode ) = @_;
764     $frameworkcode //= '';
765     my $bib = MARC::Record->new();
766     $bib->append_fields(
767         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
768         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
769     );
770     my ($bibnum, $bibitemnum) = AddBiblio($bib, $frameworkcode);
771     return ($bibnum, $bibitemnum);
772 }