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