Bug 21774: Cloned item subfields disappear when editing an item
[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 => 14;
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 ($bibnum, $bibitemnum) = get_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} } , $bibnum);
63     cmp_ok($item_bibnum, '==', $bibnum, "New item is linked to correct biblionumber.");
64     cmp_ok($item_bibitemnum, '==', $bibitemnum, "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({}, $bibnum, $itemnumber);
78
79     # Modify item; setting barcode.
80     ModItem({ barcode => '987654321' }, $bibnum, $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 => $bibnum, 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} } , $bibnum);
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 }, $bibnum, $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' }, $bibnum, $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}, undef, "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 => 9;
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 ($biblionumber, $biblioitemnumber) = get_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         $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         $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 ) ),
203         "Hidden items list undef if OpacHiddenItems empty");
204
205     # Blank spaces
206     t::lib::Mocks::mock_preference('OpacHiddenItems','  ');
207     ok( scalar GetHiddenItemnumbers( @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 );
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 );
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 );
233     ok( scalar @hidden == 2, "Two items hidden");
234     is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and homebranch library2 hidden");
235
236     # Valid OpacHiddenItems, empty list
237     @items = ();
238     @hidden = GetHiddenItemnumbers( @items );
239     ok( scalar @hidden == 0, "Empty items list, no item hidden");
240
241     $schema->storage->txn_rollback;
242 };
243
244 subtest 'GetItemsInfo tests' => sub {
245
246     plan tests => 4;
247
248     $schema->storage->txn_begin;
249
250     my $builder = t::lib::TestBuilder->new;
251     my $library1 = $builder->build({
252         source => 'Branch',
253     });
254     my $library2 = $builder->build({
255         source => 'Branch',
256     });
257     my $itemtype = $builder->build({
258         source => 'Itemtype',
259     });
260
261     # Add a biblio
262     my ($biblionumber, $biblioitemnumber) = get_biblio();
263     # Add an item
264     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
265         {
266             homebranch    => $library1->{branchcode},
267             holdingbranch => $library2->{branchcode},
268             itype         => $itemtype->{itemtype},
269         },
270         $biblionumber
271     );
272
273     my $library = Koha::Libraries->find( $library1->{branchcode} );
274     $library->opac_info("homebranch OPAC info");
275     $library->store;
276
277     $library = Koha::Libraries->find( $library2->{branchcode} );
278     $library->opac_info("holdingbranch OPAC info");
279     $library->store;
280
281     my @results = GetItemsInfo( $biblionumber );
282     ok( @results, 'GetItemsInfo returns results');
283     is( $results[0]->{ home_branch_opac_info }, "homebranch OPAC info",
284         'GetItemsInfo returns the correct home branch OPAC info notice' );
285     is( $results[0]->{ holding_branch_opac_info }, "holdingbranch OPAC info",
286         'GetItemsInfo returns the correct holding branch OPAC info notice' );
287     is( exists( $results[0]->{ onsite_checkout } ), 1,
288         'GetItemsInfo returns a onsite_checkout key' );
289
290     $schema->storage->txn_rollback;
291 };
292
293 subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub {
294
295     plan tests => 4;
296
297     $schema->storage->txn_begin;
298
299     my $biblio = $schema->resultset('Biblio')->create({
300         title       => "Test title",
301         datecreated => dt_from_string,
302         biblioitems => [ { itemtype => 'BIB_LEVEL' } ],
303     });
304     my $biblioitem = $biblio->biblioitems->first;
305     my $item = $schema->resultset('Item')->create({
306         biblioitemnumber => $biblioitem->biblioitemnumber,
307         biblionumber     => $biblio->biblionumber,
308         itype            => "ITEM_LEVEL",
309     });
310
311     t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
312     is( $item->effective_itemtype(), 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' );
313
314     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
315     is( $item->effective_itemtype(), 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' );
316
317     # If itemtype is not defined and item-level_level item types are set
318     # fallback to biblio-level itemtype (Bug 14651) and warn
319     $item->itype( undef );
320     $item->update();
321     my $effective_itemtype;
322     warning_is { $effective_itemtype = $item->effective_itemtype() }
323                 "item-level_itypes set but no itemtype set for item (".$item->itemnumber.")",
324                 '->effective_itemtype() raises a warning when falling back to bib-level';
325
326     ok( defined $effective_itemtype &&
327                 $effective_itemtype eq 'BIB_LEVEL',
328         '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' );
329
330     $schema->storage->txn_rollback;
331 };
332
333 subtest 'SearchItems test' => sub {
334     plan tests => 14;
335
336     $schema->storage->txn_begin;
337     my $dbh = C4::Context->dbh;
338     my $builder = t::lib::TestBuilder->new;
339
340     my $library1 = $builder->build({
341         source => 'Branch',
342     });
343     my $library2 = $builder->build({
344         source => 'Branch',
345     });
346     my $itemtype = $builder->build({
347         source => 'Itemtype',
348     });
349
350     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
351     my $cpl_items_before = SearchItemsByField( 'homebranch', $library1->{branchcode});
352
353     my ($biblionumber) = get_biblio();
354
355     my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
356
357     # Add two items
358     my (undef, undef, $item1_itemnumber) = AddItem({
359         homebranch => $library1->{branchcode},
360         holdingbranch => $library1->{branchcode},
361         itype => $itemtype->{itemtype},
362     }, $biblionumber);
363     my (undef, undef, $item2_itemnumber) = AddItem({
364         homebranch => $library2->{branchcode},
365         holdingbranch => $library2->{branchcode},
366         itype => $itemtype->{itemtype},
367     }, $biblionumber);
368
369     my ($items, $total_results);
370
371     ($items, $total_results) = SearchItems();
372     is($total_results, $initial_items_count + 2, "Created 2 new items");
373     is(scalar @$items, $total_results, "SearchItems() returns all items");
374
375     ($items, $total_results) = SearchItems(undef, {rows => 1});
376     is($total_results, $initial_items_count + 2);
377     is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item");
378
379     # Search all items where homebranch = 'CPL'
380     my $filter = {
381         field => 'homebranch',
382         query => $library1->{branchcode},
383         operator => '=',
384     };
385     ($items, $total_results) = SearchItems($filter);
386     ok($total_results > 0, "There is at least one CPL item");
387     my $all_items_are_CPL = 1;
388     foreach my $item (@$items) {
389         if ($item->{homebranch} ne $library1->{branchcode}) {
390             $all_items_are_CPL = 0;
391             last;
392         }
393     }
394     ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
395
396     # Search all items where homebranch != 'CPL'
397     $filter = {
398         field => 'homebranch',
399         query => $library1->{branchcode},
400         operator => '!=',
401     };
402     ($items, $total_results) = SearchItems($filter);
403     ok($total_results > 0, "There is at least one non-CPL item");
404     my $all_items_are_not_CPL = 1;
405     foreach my $item (@$items) {
406         if ($item->{homebranch} eq $library1->{branchcode}) {
407             $all_items_are_not_CPL = 0;
408             last;
409         }
410     }
411     ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
412
413     # Search all items where biblio title (245$a) is like 'Silence in the %'
414     $filter = {
415         field => 'marc:245$a',
416         query => 'Silence in the %',
417         operator => 'like',
418     };
419     ($items, $total_results) = SearchItems($filter);
420     ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'");
421
422     # Search all items where biblio title is 'Silence in the library'
423     # and homebranch is 'CPL'
424     $filter = {
425         conjunction => 'AND',
426         filters => [
427             {
428                 field => 'marc:245$a',
429                 query => 'Silence in the %',
430                 operator => 'like',
431             },
432             {
433                 field => 'homebranch',
434                 query => $library1->{branchcode},
435                 operator => '=',
436             },
437         ],
438     };
439     ($items, $total_results) = SearchItems($filter);
440     my $found = 0;
441     foreach my $item (@$items) {
442         if ($item->{itemnumber} == $item1_itemnumber) {
443             $found = 1;
444             last;
445         }
446     }
447     ok($found, "item1 found");
448
449     my $frameworkcode = q||;
450     my ($itemfield) = GetMarcFromKohaField('items.itemnumber', $frameworkcode);
451
452     # Create item subfield 'z' without link
453     $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
454     $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", ?)', undef, $itemfield, $frameworkcode);
455
456     # Clear cache
457     my $cache = Koha::Caches->get_instance();
458     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
459     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
460     $cache->clear_from_cache("default_value_for_mod_marc-");
461     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
462
463     my $item3_record = new MARC::Record;
464     $item3_record->append_fields(
465         new MARC::Field(
466             $itemfield, '', '',
467             'z' => 'foobar',
468             'y' => $itemtype->{itemtype}
469         )
470     );
471     my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
472         $biblionumber);
473
474     # Search item where item subfield z is "foobar"
475     $filter = {
476         field => 'marc:' . $itemfield . '$z',
477         query => 'foobar',
478         operator => 'like',
479     };
480     ($items, $total_results) = SearchItems($filter);
481     ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
482
483     # Link $z to items.itemnotes (and make sure there is no other subfields
484     # linked to it)
485     $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
486     $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
487
488     # Clear cache
489     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
490     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
491     $cache->clear_from_cache("default_value_for_mod_marc-");
492     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
493
494     ModItemFromMarc($item3_record, $biblionumber, $item3_itemnumber);
495
496     # Make sure the link is used
497     my $item3 = GetItem($item3_itemnumber);
498     ok($item3->{itemnotes} eq 'foobar', 'itemnotes eq "foobar"');
499
500     # Do the same search again.
501     # This time it will search in items.itemnotes
502     ($items, $total_results) = SearchItems($filter);
503     ok(scalar @$items == 1, 'found 1 item with itemnotes = "foobar"');
504
505     my $cpl_items_after = SearchItemsByField( 'homebranch', $library1->{branchcode});
506     is( ( scalar( @$cpl_items_after ) - scalar ( @$cpl_items_before ) ), 1, 'SearchItemsByField should return something' );
507
508     $schema->storage->txn_rollback;
509 };
510
511 subtest 'Koha::Item(s) tests' => sub {
512
513     plan tests => 5;
514
515     $schema->storage->txn_begin();
516
517     my $builder = t::lib::TestBuilder->new;
518     my $library1 = $builder->build({
519         source => 'Branch',
520     });
521     my $library2 = $builder->build({
522         source => 'Branch',
523     });
524     my $itemtype = $builder->build({
525         source => 'Itemtype',
526     });
527
528     # Create a biblio and item for testing
529     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
530     my ($bibnum, $bibitemnum) = get_biblio();
531     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
532         {
533             homebranch    => $library1->{branchcode},
534             holdingbranch => $library2->{branchcode},
535             itype         => $itemtype->{itemtype},
536         },
537         $bibnum
538     );
539
540     # Get item.
541     my $item = Koha::Items->find( $itemnumber );
542     is( ref($item), 'Koha::Item', "Got Koha::Item" );
543
544     my $homebranch = $item->home_branch();
545     is( ref($homebranch), 'Koha::Library', "Got Koha::Library from home_branch method" );
546     is( $homebranch->branchcode(), $library1->{branchcode}, "Home branch code matches homebranch" );
547
548     my $holdingbranch = $item->holding_branch();
549     is( ref($holdingbranch), 'Koha::Library', "Got Koha::Library from holding_branch method" );
550     is( $holdingbranch->branchcode(), $library2->{branchcode}, "Home branch code matches holdingbranch" );
551
552     $schema->storage->txn_rollback;
553 };
554
555 subtest 'C4::Biblio::EmbedItemsInMarcBiblio' => sub {
556     plan tests => 7;
557
558     $schema->storage->txn_begin();
559
560     my $builder = t::lib::TestBuilder->new;
561     my $library1 = $builder->build({
562         source => 'Branch',
563     });
564     my $library2 = $builder->build({
565         source => 'Branch',
566     });
567     my $itemtype = $builder->build({
568         source => 'Itemtype',
569     });
570
571     my ( $biblionumber, $biblioitemnumber ) = get_biblio();
572     my $item_infos = [
573         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
574         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
575         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
576         { homebranch => $library2->{branchcode}, holdingbranch => $library2->{branchcode} },
577         { homebranch => $library2->{branchcode}, holdingbranch => $library2->{branchcode} },
578         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
579         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
580         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
581     ];
582     my $number_of_items = scalar @$item_infos;
583     my $number_of_items_with_homebranch_is_CPL =
584       grep { $_->{homebranch} eq $library1->{branchcode} } @$item_infos;
585
586     my @itemnumbers;
587     for my $item_info (@$item_infos) {
588         my ( undef, undef, $itemnumber ) = AddItem(
589             {
590                 homebranch    => $item_info->{homebranch},
591                 holdingbranch => $item_info->{holdingbanch},
592                 itype         => $itemtype->{itemtype},
593             },
594             $biblionumber
595         );
596         push @itemnumbers, $itemnumber;
597     }
598
599     # Emptied the OpacHiddenItems pref
600     t::lib::Mocks::mock_preference( 'OpacHiddenItems', '' );
601
602     my ($itemfield) =
603       C4::Biblio::GetMarcFromKohaField( 'items.itemnumber', '' );
604     my $record = C4::Biblio::GetMarcBiblio({ biblionumber => $biblionumber });
605     warning_is { C4::Biblio::EmbedItemsInMarcBiblio() }
606     { carped => 'EmbedItemsInMarcBiblio: No MARC record passed' },
607       'Should crap is no record passed.';
608
609     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber );
610     my @items = $record->field($itemfield);
611     is( scalar @items, $number_of_items, 'Should return all items' );
612
613     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber,
614         [ $itemnumbers[1], $itemnumbers[3] ] );
615     @items = $record->field($itemfield);
616     is( scalar @items, 2, 'Should return all items present in the list' );
617
618     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
619     @items = $record->field($itemfield);
620     is( scalar @items, $number_of_items, 'Should return all items for opac' );
621
622     my $opachiddenitems = "
623         homebranch: ['$library1->{branchcode}']";
624     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
625
626     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber );
627     @items = $record->field($itemfield);
628     is( scalar @items,
629         $number_of_items,
630         'Even with OpacHiddenItems set, all items should have been embedded' );
631
632     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
633     @items = $record->field($itemfield);
634     is(
635         scalar @items,
636         $number_of_items - $number_of_items_with_homebranch_is_CPL,
637 'For OPAC, the pref OpacHiddenItems should have been take into account. Only items with homebranch ne CPL should have been embedded'
638     );
639
640     $opachiddenitems = "
641         homebranch: ['$library1->{branchcode}', '$library2->{branchcode}']";
642     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
643     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
644     @items = $record->field($itemfield);
645     is(
646         scalar @items,
647         0,
648 'For OPAC, If all items are hidden, no item should have been embedded'
649     );
650
651     $schema->storage->txn_rollback;
652 };
653
654
655 subtest 'C4::Items::_build_default_values_for_mod_marc' => sub {
656     plan tests => 4;
657
658     $schema->storage->txn_begin();
659
660     my $builder = t::lib::TestBuilder->new;
661     my $framework = $builder->build({ source => 'BiblioFramework' });
662
663     # Link biblio.biblionumber and biblioitems.biblioitemnumber to avoid _koha_marc_update_bib_ids to fail with 'no biblio[item]number tag for framework"
664     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '999', tagsubfield => [ 'c', 'd' ] })->delete;
665     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '999', tagsubfield => 'c', kohafield => 'biblio.biblionumber' })->store;
666     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '999', tagsubfield => 'd', kohafield => 'biblioitems.biblioitemnumber' })->store;
667
668     # Same for item fields: itemnumber, barcode, itype
669     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '952', tagsubfield => [ '9', 'p', 'y' ] })->delete;
670     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => '9', kohafield => 'items.itemnumber' })->store;
671     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => 'p', kohafield => 'items.barcode' })->store;
672     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => 'y', kohafield => 'items.itype' })->store;
673     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
674
675     my $itemtype = $builder->build({ source => 'Itemtype' })->{itemtype};
676
677     # Create a record with a barcode
678     my ($biblionumber) = get_biblio( $framework->{frameworkcode} );
679     my $item_record = new MARC::Record;
680     my $a_barcode = 'a barcode';
681     my $barcode_field = MARC::Field->new(
682         '952', ' ', ' ',
683         p => $a_barcode,
684         y => $itemtype
685     );
686     my $itemtype_field = MARC::Field->new(
687         '952', ' ', ' ',
688         y => $itemtype
689     );
690     $item_record->append_fields( $barcode_field );
691     my (undef, undef, $item_itemnumber) = AddItemFromMarc($item_record, $biblionumber);
692
693     # Make sure everything has been set up
694     my $item = GetItem($item_itemnumber);
695     is( $item->{barcode}, $a_barcode, 'Everything has been set up correctly, the barcode is defined as expected' );
696
697     # Delete the barcode field and save the record
698     $item_record->delete_fields( $barcode_field );
699     $item_record->append_fields( $itemtype_field ); # itemtype is mandatory
700     ModItemFromMarc($item_record, $biblionumber, $item_itemnumber);
701     $item = GetItem($item_itemnumber);
702     is( $item->{barcode}, undef, 'The default value should have been set to the barcode, the field is mapped to a kohafield' );
703
704     # Re-add the barcode field and save the record
705     $item_record->append_fields( $barcode_field );
706     ModItemFromMarc($item_record, $biblionumber, $item_itemnumber);
707     $item = GetItem($item_itemnumber);
708     is( $item->{barcode}, $a_barcode, 'Everything has been set up correctly, the barcode is defined as expected' );
709
710     # Remove the mapping for barcode
711     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '952', tagsubfield => 'p' })->delete;
712
713     # And make sure the caches are cleared
714     my $cache = Koha::Caches->get_instance();
715     $cache->clear_from_cache("default_value_for_mod_marc-");
716     $cache->clear_from_cache("MarcSubfieldStructure-");
717
718     # Update the MARC field with another value
719     $item_record->delete_fields( $barcode_field );
720     my $another_barcode = 'another_barcode';
721     my $another_barcode_field = MARC::Field->new(
722         '952', ' ', ' ',
723         p => $another_barcode,
724     );
725     $item_record->append_fields( $another_barcode_field );
726     # The DB value should not have been updated
727     ModItemFromMarc($item_record, $biblionumber, $item_itemnumber);
728     $item = GetItem($item_itemnumber);
729     is ( $item->{barcode}, $a_barcode, 'items.barcode is not mapped anymore, so the DB column has not been updated' );
730
731     $cache->clear_from_cache("default_value_for_mod_marc-");
732     $cache->clear_from_cache( "MarcSubfieldStructure-" );
733     $schema->storage->txn_rollback;
734 };
735
736 subtest '_mod_item_dates' => sub {
737     plan tests => 11;
738
739     is( C4::Items::_mod_item_dates(), undef, 'Call without parameters' );
740     is( C4::Items::_mod_item_dates(1), undef, 'Call without hashref' );
741
742     my $orgitem;
743     my $item = {
744         itemcallnumber  => 'V II 149 1963',
745         barcode         => '109304',
746     };
747     $orgitem = { %$item };
748     C4::Items::_mod_item_dates($item);
749     is_deeply( $item, $orgitem, 'No dates passed to _mod_item_dates' );
750
751     # add two correct dates
752     t::lib::Mocks::mock_preference('dateformat', 'us');
753     $item->{dateaccessioned} = '01/31/2016';
754     $item->{onloan} =  $item->{dateaccessioned};
755     $orgitem = { %$item };
756     C4::Items::_mod_item_dates($item);
757     is( $item->{dateaccessioned}, '2016-01-31', 'dateaccessioned is fine' );
758     is( $item->{onloan}, '2016-01-31', 'onloan is fine too' );
759
760
761     # add some invalid dates
762     $item->{notexistingcolumndate} = '13/1/2015'; # wrong format
763     $item->{anotherdate} = 'tralala'; # even worse
764     $item->{myzerodate} = '0000-00-00'; # wrong too
765     C4::Items::_mod_item_dates($item);
766     is( $item->{notexistingcolumndate}, undef, 'Invalid date became NULL' );
767     is( $item->{anotherdate}, undef, 'Second invalid date became NULL too' );
768     is( $item->{myzerodate}, undef, '0000-00-00 became NULL too' );
769
770     # check if itemlost_on was not touched
771     $item->{itemlost_on} = '12345678';
772     $item->{withdrawn_on} = '12/31/2015 23:59:00';
773     $item->{damaged_on} = '01/20/2017 09:00:00';
774     $orgitem = { %$item };
775     C4::Items::_mod_item_dates($item);
776     is_deeply( $item, $orgitem, 'Colums with _on are not touched' );
777
778     t::lib::Mocks::mock_preference('dateformat', 'metric');
779     $item->{dateaccessioned} = '01/31/2016'; #wrong
780     $item->{yetanotherdatetime} = '20/01/2016 13:58:00'; #okay
781     C4::Items::_mod_item_dates($item);
782     is( $item->{dateaccessioned}, undef, 'dateaccessioned wrong format' );
783     is( $item->{yetanotherdatetime}, '2016-01-20 13:58:00',
784         'yetanotherdatetime is ok' );
785 };
786
787 subtest 'get_hostitemnumbers_of' => sub {
788     plan tests => 1;
789
790     my $bib = MARC::Record->new();
791     $bib->append_fields(
792         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
793         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
794         MARC::Field->new('773', ' ', ' ', b => 'b without 0 or 9'),
795     );
796     my ($biblionumber, $bibitemnum) = AddBiblio($bib, '');
797
798     my @itemnumbers = C4::Items::get_hostitemnumbers_of( $biblionumber );
799     is( @itemnumbers, 0, );
800 };
801
802 subtest 'Test logging for ModItem' => sub {
803
804     plan tests => 3;
805
806     t::lib::Mocks::mock_preference('CataloguingLog', 1);
807
808     $schema->storage->txn_begin;
809
810     my $builder = t::lib::TestBuilder->new;
811     my $library = $builder->build({
812         source => 'Branch',
813     });
814     my $itemtype = $builder->build({
815         source => 'Itemtype',
816     });
817
818     # Create a biblio instance for testing
819     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
820     my ($bibnum, $bibitemnum) = get_biblio();
821
822     # Add an item.
823     my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $library->{branchcode}, holdingbranch => $library->{branchcode}, location => $location, itype => $itemtype->{itemtype} } , $bibnum);
824
825     # False means no logging
826     $schema->resultset('ActionLog')->search()->delete();
827     ModItem({ location => $location }, $bibnum, $itemnumber, { log_action => 0 });
828     is( $schema->resultset('ActionLog')->count(), 0, 'False value does not trigger logging' );
829
830     # True means logging
831     $schema->resultset('ActionLog')->search()->delete();
832     ModItem({ location => $location }, $bibnum, $itemnumber, { log_action => 1 });
833     is( $schema->resultset('ActionLog')->count(), 1, 'True value does trigger logging' );
834
835     # Undefined defaults to true
836     $schema->resultset('ActionLog')->search()->delete();
837     ModItem({ location => $location }, $bibnum, $itemnumber);
838     is( $schema->resultset('ActionLog')->count(), 1, 'Undefined value defaults to true, triggers logging' );
839
840     $schema->storage->txn_rollback;
841 };
842
843 subtest 'Check stockrotationitem relationship' => sub {
844     plan tests => 1;
845
846     $schema->storage->txn_begin();
847
848     my $builder = t::lib::TestBuilder->new;
849     my $item = $builder->build({ source => 'Item' });
850
851     $builder->build({
852         source => 'Stockrotationitem',
853         value  => { itemnumber_id => $item->{itemnumber} }
854     });
855
856     my $sritem = Koha::Items->find($item->{itemnumber})->stockrotationitem;
857     isa_ok( $sritem, 'Koha::StockRotationItem', "Relationship works and correctly creates Koha::Object." );
858
859     $schema->storage->txn_rollback;
860 };
861
862 subtest 'Check add_to_rota method' => sub {
863     plan tests => 2;
864
865     $schema->storage->txn_begin();
866
867     my $builder = t::lib::TestBuilder->new;
868     my $item = $builder->build({ source => 'Item' });
869     my $rota = $builder->build({ source => 'Stockrotationrota' });
870     my $srrota = Koha::StockRotationRotas->find($rota->{rota_id});
871
872     $builder->build({
873         source => 'Stockrotationstage',
874         value  => { rota_id => $rota->{rota_id} },
875     });
876
877     my $sritem = Koha::Items->find($item->{itemnumber});
878     $sritem->add_to_rota($rota->{rota_id});
879
880     is(
881         Koha::StockRotationItems->find($item->{itemnumber})->stage_id,
882         $srrota->stockrotationstages->next->stage_id,
883         "Adding to a rota a new sritem item being assigned to its first stage."
884     );
885
886     my $newrota = $builder->build({ source => 'Stockrotationrota' });
887
888     my $srnewrota = Koha::StockRotationRotas->find($newrota->{rota_id});
889
890     $builder->build({
891         source => 'Stockrotationstage',
892         value  => { rota_id => $newrota->{rota_id} },
893     });
894
895     $sritem->add_to_rota($newrota->{rota_id});
896
897     is(
898         Koha::StockRotationItems->find($item->{itemnumber})->stage_id,
899         $srnewrota->stockrotationstages->next->stage_id,
900         "Moving an item results in that sritem being assigned to the new first stage."
901     );
902
903     $schema->storage->txn_rollback;
904 };
905
906 subtest 'Split subfields in Item2Marc (Bug 21774)' => sub {
907     plan tests => 3;
908     $schema->storage->txn_begin;
909
910     my $builder = t::lib::TestBuilder->new;
911     my $biblio = $builder->build({ source => 'Biblio', value => { frameworkcode => q{} } });
912     my $item = $builder->build({ source => 'Item', value => { biblionumber => $biblio->{biblionumber}, ccode => 'A|B' } });
913
914     Koha::MarcSubfieldStructures->search({ tagfield => '952', tagsubfield => '8' })->delete; # theoretical precaution
915     Koha::MarcSubfieldStructures->search({ kohafield => 'items.ccode' })->delete;
916     my $mapping = Koha::MarcSubfieldStructure->new({ frameworkcode => q{}, tagfield => '952', tagsubfield => '8', kohafield => 'items.ccode' })->store;
917
918     # Start testing
919     my $marc = C4::Items::Item2Marc( $item, $biblio->{biblionumber} );
920     my @subs = $marc->subfield( $mapping->tagfield, $mapping->tagsubfield );
921     is( @subs, 2, 'Expect two subfields' );
922     is( $subs[0], 'A', 'First subfield matches' );
923     is( $subs[1], 'B', 'Second subfield matches' );
924
925     $schema->storage->txn_rollback;
926 };
927
928 # Helper method to set up a Biblio.
929 sub get_biblio {
930     my ( $frameworkcode ) = @_;
931     $frameworkcode //= '';
932     my $bib = MARC::Record->new();
933     $bib->append_fields(
934         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
935         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
936     );
937     my ($bibnum, $bibitemnum) = AddBiblio($bib, $frameworkcode);
938     return ($bibnum, $bibitemnum);
939 }