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