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