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