Bug 36535: (QA follow-up) Use dt_from_string
[koha.git] / t / db_dependent / Items.t
1 #!/usr/bin/perl
2 #
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 use Data::Dumper;
20
21 use MARC::Record;
22 use C4::Items
23     qw( ModItemTransfer SearchItems AddItemFromMarc ModItemFromMarc get_hostitemnumbers_of Item2Marc ModDateLastSeen CartToShelf );
24 use C4::Biblio qw( GetMarcFromKohaField AddBiblio );
25 use C4::Circulation qw( AddIssue );
26 use Koha::BackgroundJobs;
27 use Koha::Items;
28 use Koha::Database;
29 use Koha::DateUtils qw( dt_from_string );
30 use Koha::Library;
31 use Koha::DateUtils;
32 use Koha::MarcSubfieldStructures;
33 use Koha::Caches;
34 use Koha::AuthorisedValues;
35
36 use t::lib::Mocks;
37 use t::lib::TestBuilder;
38
39 use Test::More tests => 13;
40
41 use Test::Warn;
42
43 my $schema = Koha::Database->new->schema;
44 my $location = 'My Location';
45
46 subtest 'General Add, Get and Del tests' => sub {
47
48     plan tests => 16;
49
50     $schema->storage->txn_begin;
51
52     my $builder = t::lib::TestBuilder->new;
53     my $library = $builder->build({
54         source => 'Branch',
55     });
56     my $itemtype = $builder->build({
57         source => 'Itemtype',
58     });
59
60     # Create a biblio instance for testing
61     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
62     my $biblio = $builder->build_sample_biblio();
63
64     # Add an item.
65     my $item = $builder->build_sample_item(
66         {
67             biblionumber => $biblio->biblionumber,
68             library      => $library->{branchcode},
69             location     => $location,
70             itype        => $itemtype->{itemtype}
71         }
72     );
73     my $itemnumber = $item->itemnumber;
74     cmp_ok($item->biblionumber, '==', $biblio->biblionumber, "New item is linked to correct biblionumber.");
75     cmp_ok($item->biblioitemnumber, '==', $biblio->biblioitem->biblioitemnumber, "New item is linked to correct biblioitemnumber.");
76
77     # Get item.
78     my $getitem = Koha::Items->find($itemnumber);
79     cmp_ok($getitem->itemnumber, '==', $itemnumber, "Retrieved item has correct itemnumber.");
80     cmp_ok($getitem->biblioitemnumber, '==', $item->biblioitemnumber, "Retrieved item has correct biblioitemnumber."); # We are not testing anything useful here
81     is( $getitem->location, $location, "The location should not have been modified" );
82     is( $getitem->permanent_location, $location, "The permanent_location should have been set to the location value" );
83
84
85     # Do not modify anything, and do not explode!
86     $getitem->set({})->store;
87
88     # Modify item; setting barcode.
89     $getitem->barcode('987654321')->store;
90     my $moditem = Koha::Items->find($itemnumber);
91     cmp_ok($moditem->barcode, '==', '987654321', 'Modified item barcode successfully to: '.$moditem->barcode . '.');
92
93     # Delete item.
94     $moditem->delete;
95     my $getdeleted = Koha::Items->find($itemnumber);
96     is($getdeleted, undef, "Item deleted as expected.");
97
98     $itemnumber = $builder->build_sample_item(
99         {
100             biblionumber => $biblio->biblionumber,
101             library      => $library->{branchcode},
102             location     => $location,
103             permanent_location => 'my permanent location',
104             itype        => $itemtype->{itemtype}
105         }
106     )->itemnumber;
107     $getitem = Koha::Items->find($itemnumber);
108     is( $getitem->location, $location, "The location should not have been modified" );
109     is( $getitem->permanent_location, 'my permanent location', "The permanent_location should not have modified" );
110
111     my $new_location = "New location";
112     $getitem->location($new_location)->store;
113     $getitem = Koha::Items->find($itemnumber);
114     is( $getitem->location, $new_location, "The location should have been set to correct location" );
115     is( $getitem->permanent_location, $new_location, "The permanent_location should have been set to location" );
116
117     $getitem->location('CART')->store;
118     $getitem = Koha::Items->find($itemnumber);
119     is( $getitem->location, 'CART', "The location should have been set to CART" );
120     is( $getitem->permanent_location, $new_location, "The permanent_location should not have been set to CART" );
121
122     t::lib::Mocks::mock_preference('item-level_itypes', '1');
123     $getitem = Koha::Items->find($itemnumber);
124     is( $getitem->effective_itemtype, $itemtype->{itemtype}, "Itemtype set correctly when using item-level_itypes" );
125     t::lib::Mocks::mock_preference('item-level_itypes', '0');
126     $getitem = Koha::Items->find($itemnumber);
127     is( $getitem->effective_itemtype, $biblio->biblioitem->itemtype, "Itemtype set correctly when not using item-level_itypes" );
128
129     $schema->storage->txn_rollback;
130 };
131
132 subtest 'ModItemTransfer tests' => sub {
133     plan tests => 8;
134
135     $schema->storage->txn_begin;
136
137     my $builder = t::lib::TestBuilder->new;
138     my $item    = $builder->build_sample_item();
139
140     my $library1 = $builder->build(
141         {
142             source => 'Branch',
143         }
144     );
145     my $library2 = $builder->build(
146         {
147             source => 'Branch',
148         }
149     );
150
151     ModItemTransfer( $item->itemnumber, $library1->{branchcode},
152         $library2->{branchcode}, 'Manual' );
153
154     my $transfers = Koha::Item::Transfers->search(
155         {
156             itemnumber => $item->itemnumber
157         }
158     );
159
160     is( $transfers->count, 1, "One transfer created with ModItemTransfer" );
161     $item->discard_changes;
162     is($item->holdingbranch, $library1->{branchcode}, "Items holding branch was updated to frombranch");
163
164     ModItemTransfer( $item->itemnumber, $library2->{branchcode},
165         $library1->{branchcode}, 'Manual' );
166     $transfers = Koha::Item::Transfers->search(
167         { itemnumber => $item->itemnumber, },
168         { order_by   => { '-asc' => 'branchtransfer_id' } }
169     );
170
171     is($transfers->count, 2, "Second transfer recorded on second call of ModItemTransfer");
172     my $transfer1 = $transfers->next;
173     my $transfer2 = $transfers->next;
174     isnt($transfer1->datecancelled, undef, "First transfer marked as cancelled by ModItemTransfer");
175     like($transfer1->cancellation_reason,qr/^Manual/, "First transfer contains cancellation_reason 'Manual'");
176     is($transfer2->datearrived, undef, "Second transfer is now the active transfer");
177     $item->discard_changes;
178     is($item->holdingbranch, $library2->{branchcode}, "Items holding branch was updated to frombranch");
179
180     # Check 'reason' is populated when passed
181     ModItemTransfer( $item->itemnumber, $library2->{branchcode},
182         $library1->{branchcode}, "Manual" );
183
184     $transfers = Koha::Item::Transfers->search(
185         { itemnumber => $item->itemnumber, },
186         { order_by   => { '-desc' => 'branchtransfer_id' } }
187     );
188
189     my $transfer3 = $transfers->next;
190     is($transfer3->reason, 'Manual', "Reason set via ModItemTransfer");
191
192     $schema->storage->txn_rollback;
193 };
194
195 subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub {
196
197     plan tests => 4;
198
199     $schema->storage->txn_begin;
200
201     my $biblio = $schema->resultset('Biblio')->create({
202         title       => "Test title",
203         datecreated => dt_from_string,
204         biblioitems => [ { itemtype => 'BIB_LEVEL' } ],
205     });
206     my $biblioitem = $biblio->biblioitems->first;
207     my $item = $schema->resultset('Item')->create({
208         biblioitemnumber => $biblioitem->biblioitemnumber,
209         biblionumber     => $biblio->biblionumber,
210         itype            => "ITEM_LEVEL",
211     });
212
213     t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
214     is( $item->effective_itemtype(), 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' );
215
216     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
217     is( $item->effective_itemtype(), 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' );
218
219     # If itemtype is not defined and item-level_level item types are set
220     # fallback to biblio-level itemtype (Bug 14651) and warn
221     $item->itype( undef );
222     $item->update();
223     my $effective_itemtype;
224     warning_is { $effective_itemtype = $item->effective_itemtype() }
225                 "item-level_itypes set but no itemtype set for item (".$item->itemnumber.")",
226                 '->effective_itemtype() raises a warning when falling back to bib-level';
227
228     ok( defined $effective_itemtype &&
229                 $effective_itemtype eq 'BIB_LEVEL',
230         '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' );
231
232     $schema->storage->txn_rollback;
233 };
234
235 subtest 'SearchItems test' => sub {
236     plan tests => 20;
237
238     $schema->storage->txn_begin;
239     my $dbh = C4::Context->dbh;
240     my $builder = t::lib::TestBuilder->new;
241
242     my $library1 = $builder->build({
243         source => 'Branch',
244     });
245     my $library2 = $builder->build({
246         source => 'Branch',
247     });
248     my $itemtype = $builder->build({
249         source => 'Itemtype',
250     });
251
252     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
253     my ($cpl_items_before) = SearchItems( { field => 'homebranch', query => $library1->{branchcode} } );
254
255     my $biblio = $builder->build_sample_biblio({ title => 'Silence in the library' });
256     $builder->build_sample_biblio({ title => 'Silence in the shadow' });
257
258     my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
259
260     # Add two items
261     my $item1 = $builder->build_sample_item(
262         {
263             biblionumber => $biblio->biblionumber,
264             library      => $library1->{branchcode},
265             itype        => $itemtype->{itemtype}
266         }
267     );
268     my $item1_itemnumber = $item1->itemnumber;
269     my $item2_itemnumber = $builder->build_sample_item(
270         {
271             biblionumber => $biblio->biblionumber,
272             library      => $library2->{branchcode},
273             itype        => $itemtype->{itemtype}
274         }
275     )->itemnumber;
276
277     my ($items, $total_results);
278
279     ($items, $total_results) = SearchItems();
280
281     is($total_results, $initial_items_count + 2, "Created 2 new items");
282     is(scalar @$items, $total_results, "SearchItems() returns all items");
283
284     ($items, $total_results) = SearchItems(undef, {rows => 1});
285     is($total_results, $initial_items_count + 2);
286     is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item");
287
288     # Search all items where homebranch = 'CPL'
289     my $filter = {
290         field => 'homebranch',
291         query => $library1->{branchcode},
292         operator => '=',
293     };
294     ($items, $total_results) = SearchItems($filter);
295     ok($total_results > 0, "There is at least one CPL item");
296     my $all_items_are_CPL = 1;
297     foreach my $item (@$items) {
298         if ($item->{homebranch} ne $library1->{branchcode}) {
299             $all_items_are_CPL = 0;
300             last;
301         }
302     }
303     ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
304
305     # Search all items where homebranch != 'CPL'
306     $filter = {
307         field => 'homebranch',
308         query => $library1->{branchcode},
309         operator => '!=',
310     };
311     ($items, $total_results) = SearchItems($filter);
312     ok($total_results > 0, "There is at least one non-CPL item");
313     my $all_items_are_not_CPL = 1;
314     foreach my $item (@$items) {
315         if ($item->{homebranch} eq $library1->{branchcode}) {
316             $all_items_are_not_CPL = 0;
317             last;
318         }
319     }
320     ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
321
322     # Search all items where biblio title (245$a) is like 'Silence in the %'
323     $filter = {
324         field => 'marc:245$a',
325         query => 'Silence in the %',
326         operator => 'like',
327     };
328     ($items, $total_results) = SearchItems($filter);
329     ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'");
330
331     # Search all items where biblio title is 'Silence in the library'
332     # and homebranch is 'CPL'
333     $filter = {
334         conjunction => 'AND',
335         filters => [
336             {
337                 field => 'marc:245$a',
338                 query => 'Silence in the %',
339                 operator => 'like',
340             },
341             {
342                 field => 'homebranch',
343                 query => $library1->{branchcode},
344                 operator => '=',
345             },
346         ],
347     };
348     ($items, $total_results) = SearchItems($filter);
349     my $found = 0;
350     foreach my $item (@$items) {
351         if ($item->{itemnumber} == $item1_itemnumber) {
352             $found = 1;
353             last;
354         }
355     }
356     ok($found, "item1 found");
357
358     my $frameworkcode = q||;
359     my ($itemfield) = GetMarcFromKohaField( 'items.itemnumber' );
360
361     # Create item subfield 'z' without link
362     $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
363     $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", ?)', undef, $itemfield, $frameworkcode);
364
365     # Clear cache
366     my $cache = Koha::Caches->get_instance();
367     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
368     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
369     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
370
371     my $item3_record = MARC::Record->new;
372     $item3_record->append_fields(
373         MARC::Field->new(
374             $itemfield, '', '',
375             'z' => 'foobar',
376             'y' => $itemtype->{itemtype}
377         )
378     );
379     my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
380         $biblio->biblionumber);
381
382     # Search item where item subfield z is "foobar"
383     $filter = {
384         field => 'marc:' . $itemfield . '$z',
385         query => 'foobar',
386         operator => 'like',
387     };
388     ($items, $total_results) = SearchItems($filter);
389     ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
390
391     # Link $z to items.itemnotes (and make sure there is no other subfields
392     # linked to it)
393     $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
394     $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
395
396     # Clear cache
397     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
398     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
399     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
400
401     ModItemFromMarc($item3_record, $biblio->biblionumber, $item3_itemnumber);
402
403     # Make sure the link is used
404     my $item3 = Koha::Items->find($item3_itemnumber);
405     is($item3->itemnotes, 'foobar', 'itemnotes eq "foobar"');
406
407     # Do the same search again.
408     # This time it will search in items.itemnotes
409     ($items, $total_results) = SearchItems($filter);
410     is(scalar(@$items), 1, 'found 1 item with itemnotes = "foobar"');
411
412     my ($cpl_items_after) = SearchItems( { field => 'homebranch', query => $library1->{branchcode} } );
413     is( ( scalar( @$cpl_items_after ) - scalar ( @$cpl_items_before ) ), 1, 'SearchItems should return something' );
414
415     # Issues count = 0
416     $filter = {
417         conjunction => 'AND',
418         filters => [
419             {
420                 field => 'issues',
421                 query => 0,
422                 operator => '=',
423             },
424             {
425                 field => 'homebranch',
426                 query => $library1->{branchcode},
427                 operator => '=',
428             },
429         ],
430     };
431     ($items, $total_results) = SearchItems($filter);
432     is($total_results, 1, "Search items.issues issues = 0 returns result (items.issues defaults to 0)");
433
434     # Is null
435     $filter = {
436         conjunction => 'AND',
437         filters     => [
438             {
439                 field    => 'new_status',
440                 query    => 0,
441                 operator => '='
442             },
443             {
444                 field    => 'homebranch',
445                 query    => $library1->{branchcode},
446                 operator => '=',
447             },
448         ],
449     };
450     ($items, $total_results) = SearchItems($filter);
451     is($total_results, 0, 'found no item with new_status=0 without ifnull');
452
453     $filter->{filters}[0]->{ifnull} = 0;
454     ($items, $total_results) = SearchItems($filter);
455     is($total_results, 1, 'found all items of library1 with new_status=0 with ifnull = 0');
456
457     t::lib::Mocks::mock_userenv({ branchcode => $item1->homebranch });
458     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
459     AddIssue( $patron, $item1->barcode );
460     # Search item where item is checked out
461     $filter = {
462         conjunction => 'AND',
463         filters => [
464             {
465                 field => 'onloan',
466                 query => 'not null',
467                 operator => 'is',
468             },
469             {
470                 field => 'homebranch',
471                 query => $item1->homebranch,
472                 operator => '=',
473             },
474         ],
475     };
476     ($items, $total_results) = SearchItems($filter);
477     ok(scalar @$items == 1, 'found 1 checked out item');
478
479     # When sorting by descending availability, checked out item should show first
480     my $params = {
481         sortby => 'availability',
482         sortorder => 'DESC',
483     };
484     $filter = {
485         field => 'homebranch',
486         query => $item1->homebranch,
487         operator => '=',
488     };
489     ($items, $total_results) = SearchItems($filter,$params);
490     is($items->[0]->{barcode}, $item1->barcode, 'Items sorted as expected by availability');
491
492     subtest 'Search items by ISSN and ISBN with variations' => sub {
493         plan tests => 4;
494
495         my $marc_record = MARC::Record->new;
496         # Prepare ISBN for biblio:
497         $marc_record->append_fields( MARC::Field->new( '020', '', '', 'a' => '9780136019701' ) );
498         # Prepare ISSN for biblio:
499         $marc_record->append_fields( MARC::Field->new( '022', '', '', 'a' => '2434561X' ) );
500         my ( $isbnissn_biblionumber ) = AddBiblio( $marc_record, '' );
501         my $isbnissn_biblio = Koha::Biblios->find($isbnissn_biblionumber);
502
503         my $item = $builder->build_sample_item(
504             {
505                 biblionumber => $isbnissn_biblio->biblionumber,
506             }
507         );
508         my $item_itemnumber = $item->itemnumber;
509
510         my $filter_isbn = {
511             field => 'isbn',
512             query => '978013-6019701',
513             operator => 'like',
514         };
515
516         t::lib::Mocks::mock_preference('SearchWithISBNVariations', 0);
517         ($items, $total_results) = SearchItems($filter_isbn);
518         is($total_results, 0, "Search items finds ISBN, no variations");
519
520         t::lib::Mocks::mock_preference('SearchWithISBNVariations', 1);
521         ($items, $total_results) = SearchItems($filter_isbn);
522         is($total_results, 1, "Search items finds ISBN with variations");
523
524         my $filter_issn = {
525             field => 'issn',
526             query => '2434-561X',
527             operator => 'like',
528         };
529
530         t::lib::Mocks::mock_preference('SearchWithISSNVariations', 0);
531         ($items, $total_results) = SearchItems($filter_issn);
532         is($total_results, 0, "Search items finds ISSN, no variations");
533
534         t::lib::Mocks::mock_preference('SearchWithISSNVariations', 1);
535         ($items, $total_results) = SearchItems($filter_issn);
536         is($total_results, 1, "Search items finds ISSN with variations");
537     };
538
539     $schema->storage->txn_rollback;
540 };
541
542 subtest 'Koha::Item(s) tests' => sub {
543
544     plan tests => 9;
545
546     $schema->storage->txn_begin();
547
548     my $builder = t::lib::TestBuilder->new;
549     my $library1 = $builder->build({
550         source => 'Branch',
551     });
552     my $library2 = $builder->build({
553         source => 'Branch',
554     });
555     my $itemtype = $builder->build({
556         source => 'Itemtype',
557     });
558
559     # Create a biblio and item for testing
560     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
561     my $biblio = $builder->build_sample_biblio();
562     my $itemnumber = $builder->build_sample_item(
563         {
564             biblionumber  => $biblio->biblionumber,
565             homebranch    => $library1->{branchcode},
566             holdingbranch => $library2->{branchcode},
567             itype         => $itemtype->{itemtype}
568         }
569     )->itemnumber;
570
571     # Get item.
572     my $item = Koha::Items->find( $itemnumber );
573     is( ref($item), 'Koha::Item', "Got Koha::Item" );
574
575     my $homebranch = $item->home_branch();
576     is( ref($homebranch), 'Koha::Library', "Got Koha::Library from home_branch method" );
577     is( $homebranch->branchcode(), $library1->{branchcode}, "Home branch code matches homebranch" );
578     is( ref( $item->home_library ), 'Koha::Library', 'home_library returns a Koha::Library object' );
579
580     my $holdingbranch = $item->holding_branch();
581     is( ref($holdingbranch), 'Koha::Library', "Got Koha::Library from holding_branch method" );
582     is( $holdingbranch->branchcode(), $library2->{branchcode}, "Home branch code matches holdingbranch" );
583     is( ref( $item->holding_library ), 'Koha::Library', 'holding_library returns a Koha::Library object' );
584
585     $biblio = $item->biblio();
586     is( ref($item->biblio), 'Koha::Biblio', "Got Koha::Biblio from biblio method" );
587     is( $item->biblio->title(), $biblio->title, 'Title matches biblio title' );
588
589     $schema->storage->txn_rollback;
590 };
591
592 subtest 'get_hostitemnumbers_of' => sub {
593     plan tests => 3;
594
595     $schema->storage->txn_begin;
596     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
597     my $builder = t::lib::TestBuilder->new;
598
599     # Host item field without 0 or 9
600     my $bib1 = MARC::Record->new();
601     $bib1->append_fields(
602         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
603         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
604         MARC::Field->new('773', ' ', ' ', b => 'b without 0 or 9'),
605     );
606     my ($biblionumber1, $bibitemnum1) = AddBiblio($bib1, '');
607     my @itemnumbers1 = C4::Items::get_hostitemnumbers_of( $biblionumber1 );
608     is( scalar @itemnumbers1, 0, '773 without 0 or 9');
609
610     # Correct host item field, analytical records on
611     t::lib::Mocks::mock_preference('EasyAnalyticalRecords', 1);
612     my $hostitem = $builder->build_sample_item();
613     my $bib2 = MARC::Record->new();
614     $bib2->append_fields(
615         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
616         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
617         MARC::Field->new('773', ' ', ' ', 0 => $hostitem->biblionumber , 9 => $hostitem->itemnumber, b => 'b' ),
618     );
619     my ($biblionumber2, $bibitemnum2) = AddBiblio($bib2, '');
620     my @itemnumbers2 = C4::Items::get_hostitemnumbers_of( $biblionumber2 );
621     is( scalar @itemnumbers2, 1, '773 with 0 and 9, EasyAnalyticalRecords on');
622
623     # Correct host item field, analytical records off
624     t::lib::Mocks::mock_preference('EasyAnalyticalRecords', 0);
625     @itemnumbers2 = C4::Items::get_hostitemnumbers_of( $biblionumber2 );
626     is( scalar @itemnumbers2, 0, '773 with 0 and 9, EasyAnalyticalRecords off');
627
628     $schema->storage->txn_rollback;
629 };
630
631 subtest 'Test logging for ModItem' => sub {
632
633     plan tests => 3;
634
635     t::lib::Mocks::mock_preference('CataloguingLog', 1);
636
637     $schema->storage->txn_begin;
638
639     my $builder = t::lib::TestBuilder->new;
640     my $library = $builder->build({
641         source => 'Branch',
642     });
643     my $itemtype = $builder->build({
644         source => 'Itemtype',
645     });
646
647     # Create a biblio instance for testing
648     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
649     my $biblio = $builder->build_sample_biblio();
650
651     # Add an item.
652     my $item = $builder->build_sample_item(
653         {
654             biblionumber => $biblio->biblionumber,
655             library      => $library->{homebranch},
656             location     => $location,
657             itype        => $itemtype->{itemtype}
658         }
659     );
660
661     # False means no logging
662     $schema->resultset('ActionLog')->search()->delete();
663     $item->location($location)->store({ log_action => 0 });
664     is( $schema->resultset('ActionLog')->count(), 0, 'False value does not trigger logging' );
665
666     # True means logging
667     $schema->resultset('ActionLog')->search()->delete();
668     $item->location('new location')->store({ log_action => 1 });
669     is( $schema->resultset('ActionLog')->count(), 1, 'True value does trigger logging' );
670
671     # Undefined defaults to true
672     $schema->resultset('ActionLog')->search()->delete();
673     $item->location($location)->store();
674     is( $schema->resultset('ActionLog')->count(), 1, 'Undefined value defaults to true, triggers logging' );
675
676     $schema->storage->txn_rollback;
677 };
678
679 subtest 'Check stockrotationitem relationship' => sub {
680     plan tests => 1;
681
682     $schema->storage->txn_begin();
683
684     my $builder = t::lib::TestBuilder->new;
685     my $item = $builder->build_sample_item;
686
687     $builder->build({
688         source => 'Stockrotationitem',
689         value  => { itemnumber_id => $item->itemnumber }
690     });
691
692     my $sritem = Koha::Items->find($item->itemnumber)->stockrotationitem;
693     isa_ok( $sritem, 'Koha::StockRotationItem', "Relationship works and correctly creates Koha::Object." );
694
695     $schema->storage->txn_rollback;
696 };
697
698 subtest 'Check add_to_rota method' => sub {
699     plan tests => 2;
700
701     $schema->storage->txn_begin();
702
703     my $builder = t::lib::TestBuilder->new;
704     my $item = $builder->build_sample_item;
705     my $rota = $builder->build({ source => 'Stockrotationrota' });
706     my $srrota = Koha::StockRotationRotas->find($rota->{rota_id});
707
708     $builder->build({
709         source => 'Stockrotationstage',
710         value  => { rota_id => $rota->{rota_id} },
711     });
712
713     my $sritem = Koha::Items->find($item->itemnumber);
714     $sritem->add_to_rota($rota->{rota_id});
715
716     is(
717         Koha::StockRotationItems->find($item->itemnumber)->stage_id,
718         $srrota->stockrotationstages->next->stage_id,
719         "Adding to a rota a new sritem item being assigned to its first stage."
720     );
721
722     my $newrota = $builder->build({ source => 'Stockrotationrota' });
723
724     my $srnewrota = Koha::StockRotationRotas->find($newrota->{rota_id});
725
726     $builder->build({
727         source => 'Stockrotationstage',
728         value  => { rota_id => $newrota->{rota_id} },
729     });
730
731     $sritem->add_to_rota($newrota->{rota_id});
732
733     is(
734         Koha::StockRotationItems->find($item->itemnumber)->stage_id,
735         $srnewrota->stockrotationstages->next->stage_id,
736         "Moving an item results in that sritem being assigned to the new first stage."
737     );
738
739     $schema->storage->txn_rollback;
740 };
741
742 subtest 'Split subfields in Item2Marc (Bug 21774)' => sub {
743     plan tests => 3;
744     $schema->storage->txn_begin;
745
746     my $builder = t::lib::TestBuilder->new;
747     my $item = $builder->build_sample_item({ ccode => 'A|B' });
748
749     Koha::MarcSubfieldStructures->search({ tagfield => '952', tagsubfield => '8' })->delete; # theoretical precaution
750     Koha::MarcSubfieldStructures->search({ kohafield => 'items.ccode' })->delete;
751     my $mapping = Koha::MarcSubfieldStructure->new(
752         {
753             frameworkcode => q{},
754             tagfield      => '952',
755             tagsubfield   => '8',
756             kohafield     => 'items.ccode',
757             repeatable    => 1
758         }
759     )->store;
760     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
761
762     # Start testing
763     my $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
764     my @subs = $marc->subfield( $mapping->tagfield, $mapping->tagsubfield );
765     is( @subs, 2, 'Expect two subfields' );
766     is( $subs[0], 'A', 'First subfield matches' );
767     is( $subs[1], 'B', 'Second subfield matches' );
768
769     $schema->storage->txn_rollback;
770 };
771
772 subtest 'ModItemFromMarc' => sub {
773     plan tests => 8;
774     $schema->storage->txn_begin;
775
776     my $builder = t::lib::TestBuilder->new;
777     my ($itemfield) = GetMarcFromKohaField( 'items.itemnumber' );
778     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' });
779     my $biblio = $builder->build_sample_biblio;
780     my ( $lost_tag, $lost_sf ) = GetMarcFromKohaField( 'items.itemlost' );
781     my $item_record = MARC::Record->new;
782     $item_record->append_fields(
783         MARC::Field->new(
784             $itemfield, '', '',
785             'y' => $itemtype->itemtype,
786         ),
787         MARC::Field->new(
788             $itemfield, '', '',
789             $lost_sf => '1',
790         ),
791     );
792     my (undef, undef, $itemnumber) = AddItemFromMarc($item_record,
793         $biblio->biblionumber);
794
795     my $item = Koha::Items->find($itemnumber);
796     is( $item->itemlost, 1, 'itemlost picked from the item marc');
797
798     $item->new_status("this is something")->store;
799
800     my $updated_item_record = MARC::Record->new;
801     $updated_item_record->append_fields(
802         MARC::Field->new(
803             $itemfield, '', '',
804             'y' => $itemtype->itemtype,
805         )
806     );
807
808     my $updated_item = ModItemFromMarc($updated_item_record, $biblio->biblionumber, $itemnumber);
809     is( $updated_item->{itemlost}, 0, 'itemlost should have been reset to the default value in DB' );
810     is( $updated_item->{new_status}, "this is something", "Non mapped field has not been reset" );
811     is( Koha::Items->find($itemnumber)->new_status, "this is something" );
812
813     subtest 'cn_sort' => sub {
814         plan tests => 3;
815
816         my $item = $builder->build_sample_item;
817         $item->set({ cn_source => 'ddc', itemcallnumber => 'xxx' })->store;
818         is( $item->cn_sort, 'XXX', 'init values set are expected' );
819
820         my $marc = C4::Items::Item2Marc( $item->get_from_storage->unblessed, $item->biblionumber );
821         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
822         is( $item->get_from_storage->cn_sort, 'XXX', 'cn_sort has not been updated' );
823
824         $marc = C4::Items::Item2Marc( { %{$item->unblessed}, itemcallnumber => 'yyy' }, $item->biblionumber );
825         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
826         is( $item->get_from_storage->cn_sort, 'YYY', 'cn_sort has been updated' );
827     };
828
829     subtest 'onloan' => sub {
830         plan tests => 3;
831
832         my $item = $builder->build_sample_item;
833         $item->set({ onloan => '2022-03-19' })->store;
834         is( $item->onloan, '2022-03-19', 'init values set are expected' );
835
836         my $marc = C4::Items::Item2Marc( $item->get_from_storage->unblessed, $item->biblionumber );
837         my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField( 'items.onloan' );
838         $marc->field($MARCfield)->delete_subfield( code => $MARCsubfield );
839         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
840         is( $item->get_from_storage->onloan, '2022-03-19', 'onloan has not been updated if not passed' );
841
842         $marc = C4::Items::Item2Marc( { %{$item->unblessed}, onloan => '2022-03-26' }, $item->biblionumber );
843         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
844         is( $item->get_from_storage->onloan, '2022-03-26', 'onloan has been updated when passed in' );
845     };
846
847     subtest 'dateaccessioned' => sub {
848         plan tests => 3;
849
850         my $item = $builder->build_sample_item;
851         $item->set({ dateaccessioned => '2022-03-19' })->store->discard_changes;
852         is( $item->dateaccessioned, '2022-03-19', 'init values set are expected' );
853
854         my $marc = C4::Items::Item2Marc( $item->get_from_storage->unblessed, $item->biblionumber );
855         my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField( 'items.dateaccessioned' );
856         $marc->field($MARCfield)->delete_subfield( code => $MARCsubfield );
857         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
858         is( $item->get_from_storage->dateaccessioned, '2022-03-19', 'dateaccessioned has not been updated if not passed' );
859
860         $marc = C4::Items::Item2Marc( { %{$item->unblessed}, dateaccessioned => '2022-03-26' }, $item->biblionumber );
861         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
862         is( $item->get_from_storage->dateaccessioned, '2022-03-26', 'dateaccessioned has been updated when passed in' );
863     };
864
865     subtest 'permanent_location' => sub {
866         plan tests => 10;
867
868         # Make sure items.permanent_location is not mapped
869         Koha::MarcSubfieldStructures->search(
870             {
871                 frameworkcode => q{},
872                 kohafield     => 'items.permanent_location',
873             }
874         )->delete;
875         Koha::MarcSubfieldStructures->search(
876             {
877                 frameworkcode => q{},
878                 tagfield     => '952',
879                 tagsubfield     => 'C',
880             }
881         )->delete;
882         Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
883
884         my $item = $builder->build_sample_item;
885
886         # By default, setting location to something new should set permanent location to the same thing
887         # with the usual exceptions
888         $item->set({ location => 'A', permanent_location => 'A' })->store;
889         is( $item->location, 'A', 'initial location set as expected' );
890         is( $item->permanent_location, 'A', 'initial permanent location set as expected' );
891
892         $item->location('B');
893         my $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
894         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
895
896         $item = $item->get_from_storage;
897         is( $item->location, 'B', 'new location set as expected' );
898         is( $item->permanent_location, 'B', 'new permanent location set as expected' );
899
900         # Added a marc mapping for permanent location, allows it to be edited independently
901         my $mapping = Koha::MarcSubfieldStructure->new(
902             {
903                 frameworkcode => q{},
904                 tagfield      => '952',
905                 tagsubfield   => 'C',
906                 kohafield     => 'items.permanent_location',
907                 repeatable    => 0,
908                 tab           => 10,
909                 hidden        => 0,
910             }
911         )->store;
912         Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
913
914         # Now if we change location, and also pass in a permanent location
915         # the permanent_location will not be overwritten by location
916         $item->location('C');
917         $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
918         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
919         $item = $item->get_from_storage;
920         is( $item->location, 'C', 'next new location set as expected' );
921         is( $item->permanent_location, 'B', 'permanent location remains unchanged as expected' );
922
923         $item->permanent_location(undef)->more_subfields_xml(undef)->store;
924         # Clear values from the DB
925         $item = $item->get_from_storage;
926
927         # Update the location
928         $item->location('D');
929         $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
930         # Remove the permanent_location field from the form
931         $marc->field('952')->delete_subfield("C");
932         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
933         $item = $item->get_from_storage;
934         is( $item->location, 'D', 'next new location set as expected' );
935         is( $item->permanent_location, 'D', 'permanent location is updated if not previously set and no value passed' );
936
937         # Clear values from the DB
938         $item->permanent_location(undef)->more_subfields_xml(undef)->store;
939         $item = $item->get_from_storage;
940
941         # This time nothing is set, but we pass an empty string
942         $item->permanent_location("");
943         $item->location('E');
944         $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber );
945         $marc->field('952')->add_subfields( "C", "" );
946         ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber );
947         $item = $item->get_from_storage;
948         is( $item->location, 'E', 'next new location set as expected' );
949         is( $item->permanent_location, undef, 'permanent location is not updated if previously set as blank string' );
950     };
951
952     $schema->storage->txn_rollback;
953     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
954 };
955
956 subtest 'ModDateLastSeen' => sub {
957     plan tests => 5;
958     $schema->storage->txn_begin;
959
960     my $builder = t::lib::TestBuilder->new;
961     my $item = $builder->build_sample_item;
962     t::lib::Mocks::mock_preference('CataloguingLog', '1');
963     my $logs_before = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count;
964     ModDateLastSeen($item->itemnumber);
965     my $logs_after = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count;
966     is( $logs_after, $logs_before, "ModDateLastSeen doesn't log if item not lost");
967     $item->itemlost(1)->store({ log_action => 0 });
968     ModDateLastSeen($item->itemnumber, 1);
969     $item->discard_changes;
970     $logs_after = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count;
971     is( $item->itemlost, 1, "Item left lost when parameter is passed");
972     is( $logs_after, $logs_before, "ModDateLastSeen doesn't log if item not lost");
973     ModDateLastSeen($item->itemnumber);
974     $item->discard_changes;
975     $logs_after = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count;
976     is( $item->itemlost, 0, "Item no longer lost when no parameter is passed");
977     is( $logs_after, $logs_before + 1, "ModDateLastSeen logs if item was lost and now found");
978 };
979
980 subtest 'CartToShelf test' => sub {
981     plan tests => 2;
982
983     $schema->storage->txn_begin;
984     my $dbh     = C4::Context->dbh;
985     my $builder = t::lib::TestBuilder->new;
986
987     my $item = $builder->build_sample_item();
988
989     $item->permanent_location('BANANA')->location('CART')->store();
990
991     CartToShelf( $item->id );
992
993     $item->discard_changes;
994
995     is( $item->location, 'BANANA', 'Item is correctly returned to permanent location' );
996
997     my $mock_RTHQ = Test::MockModule->new("Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue");
998     $mock_RTHQ->mock( enqueue => sub { warn "RTHQ" } );
999     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', '1' );
1000
1001     $item->location('CART')->store( { skip_holds_queue => 1 } );
1002     warnings_are {
1003         CartToShelf( $item->id );
1004     }
1005     [], 'No RTHQ update triggered by CartToShelf';
1006
1007     $schema->storage->txn_rollback;
1008
1009 };