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