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