Bug 17512: Improve handling dates in C4::Items
[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 under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 #
18
19 use Modern::Perl;
20
21 use MARC::Record;
22 use C4::Biblio;
23 use Koha::Database;
24 use Koha::Library;
25
26 use t::lib::Mocks;
27 use t::lib::TestBuilder;
28
29 use Test::More tests => 11;
30
31 use Test::Warn;
32
33 BEGIN {
34     use_ok('C4::Items');
35     use_ok('Koha::Items');
36 }
37
38 my $schema = Koha::Database->new->schema;
39 my $location = 'My Location';
40
41 subtest 'General Add, Get and Del tests' => sub {
42
43     plan tests => 14;
44
45     $schema->storage->txn_begin;
46
47     my $builder = t::lib::TestBuilder->new;
48     my $library = $builder->build({
49         source => 'Branch',
50     });
51
52     # Create a biblio instance for testing
53     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
54     my ($bibnum, $bibitemnum) = get_biblio();
55
56     # Add an item.
57     my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $library->{branchcode}, holdingbranch => $library->{branchcode}, location => $location } , $bibnum);
58     cmp_ok($item_bibnum, '==', $bibnum, "New item is linked to correct biblionumber.");
59     cmp_ok($item_bibitemnum, '==', $bibitemnum, "New item is linked to correct biblioitemnumber.");
60
61     # Get item.
62     my $getitem = GetItem($itemnumber);
63     cmp_ok($getitem->{'itemnumber'}, '==', $itemnumber, "Retrieved item has correct itemnumber.");
64     cmp_ok($getitem->{'biblioitemnumber'}, '==', $item_bibitemnum, "Retrieved item has correct biblioitemnumber.");
65     is( $getitem->{location}, $location, "The location should not have been modified" );
66     is( $getitem->{permanent_location}, $location, "The permanent_location should have been set to the location value" );
67
68     # Modify item; setting barcode.
69     ModItem({ barcode => '987654321' }, $bibnum, $itemnumber);
70     my $moditem = GetItem($itemnumber);
71     cmp_ok($moditem->{'barcode'}, '==', '987654321', 'Modified item barcode successfully to: '.$moditem->{'barcode'} . '.');
72
73     # Delete item.
74     DelItem({ biblionumber => $bibnum, itemnumber => $itemnumber });
75     my $getdeleted = GetItem($itemnumber);
76     is($getdeleted->{'itemnumber'}, undef, "Item deleted as expected.");
77
78     ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $library->{branchcode}, holdingbranch => $library->{branchcode}, location => $location, permanent_location => 'my permanent location' } , $bibnum);
79     $getitem = GetItem($itemnumber);
80     is( $getitem->{location}, $location, "The location should not have been modified" );
81     is( $getitem->{permanent_location}, 'my permanent location', "The permanent_location should not have modified" );
82
83     ModItem({ location => $location }, $bibnum, $itemnumber);
84     $getitem = GetItem($itemnumber);
85     is( $getitem->{location}, $location, "The location should have been set to correct location" );
86     is( $getitem->{permanent_location}, $location, "The permanent_location should have been set to location" );
87
88     ModItem({ location => 'CART' }, $bibnum, $itemnumber);
89     $getitem = GetItem($itemnumber);
90     is( $getitem->{location}, 'CART', "The location should have been set to CART" );
91     is( $getitem->{permanent_location}, $location, "The permanent_location should not have been set to CART" );
92
93     $schema->storage->txn_rollback;
94 };
95
96 subtest 'GetHiddenItemnumbers tests' => sub {
97
98     plan tests => 9;
99
100     # This sub is controlled by the OpacHiddenItems system preference.
101
102     $schema->storage->txn_begin;
103
104     my $builder = t::lib::TestBuilder->new;
105     my $library1 = $builder->build({
106         source => 'Branch',
107     });
108
109     my $library2 = $builder->build({
110         source => 'Branch',
111     });
112
113     # Create a new biblio
114     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
115     my ($biblionumber, $biblioitemnumber) = get_biblio();
116
117     # Add two items
118     my ($item1_bibnum, $item1_bibitemnum, $item1_itemnumber) = AddItem(
119             { homebranch => $library1->{branchcode},
120               holdingbranch => $library1->{branchcode},
121               withdrawn => 1 },
122             $biblionumber
123     );
124     my ($item2_bibnum, $item2_bibitemnum, $item2_itemnumber) = AddItem(
125             { homebranch => $library2->{branchcode},
126               holdingbranch => $library2->{branchcode},
127               withdrawn => 0 },
128             $biblionumber
129     );
130
131     my $opachiddenitems;
132     my @itemnumbers = ($item1_itemnumber,$item2_itemnumber);
133     my @hidden;
134     my @items;
135     push @items, GetItem( $item1_itemnumber );
136     push @items, GetItem( $item2_itemnumber );
137
138     # Empty OpacHiddenItems
139     t::lib::Mocks::mock_preference('OpacHiddenItems','');
140     ok( !defined( GetHiddenItemnumbers( @items ) ),
141         "Hidden items list undef if OpacHiddenItems empty");
142
143     # Blank spaces
144     t::lib::Mocks::mock_preference('OpacHiddenItems','  ');
145     ok( scalar GetHiddenItemnumbers( @items ) == 0,
146         "Hidden items list empty if OpacHiddenItems only contains blanks");
147
148     # One variable / value
149     $opachiddenitems = "
150         withdrawn: [1]";
151     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
152     @hidden = GetHiddenItemnumbers( @items );
153     ok( scalar @hidden == 1, "Only one hidden item");
154     is( $hidden[0], $item1_itemnumber, "withdrawn=1 is hidden");
155
156     # One variable, two values
157     $opachiddenitems = "
158         withdrawn: [1,0]";
159     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
160     @hidden = GetHiddenItemnumbers( @items );
161     ok( scalar @hidden == 2, "Two items hidden");
162     is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and withdrawn=0 hidden");
163
164     # Two variables, a value each
165     $opachiddenitems = "
166         withdrawn: [1]
167         homebranch: [$library2->{branchcode}]
168     ";
169     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
170     @hidden = GetHiddenItemnumbers( @items );
171     ok( scalar @hidden == 2, "Two items hidden");
172     is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and homebranch library2 hidden");
173
174     # Valid OpacHiddenItems, empty list
175     @items = ();
176     @hidden = GetHiddenItemnumbers( @items );
177     ok( scalar @hidden == 0, "Empty items list, no item hidden");
178
179     $schema->storage->txn_rollback;
180 };
181
182 subtest 'GetItemsInfo tests' => sub {
183
184     plan tests => 4;
185
186     $schema->storage->txn_begin;
187
188     my $builder = t::lib::TestBuilder->new;
189     my $library1 = $builder->build({
190         source => 'Branch',
191     });
192     my $library2 = $builder->build({
193         source => 'Branch',
194     });
195
196     # Add a biblio
197     my ($biblionumber, $biblioitemnumber) = get_biblio();
198     # Add an item
199     my ($item_bibnum, $item_bibitemnum, $itemnumber)
200         = AddItem({
201                 homebranch    => $library1->{branchcode},
202                 holdingbranch => $library2->{branchcode},
203             }, $biblionumber );
204
205     my $library = Koha::Libraries->find( $library1->{branchcode} );
206     $library->opac_info("homebranch OPAC info");
207     $library->store;
208
209     $library = Koha::Libraries->find( $library2->{branchcode} );
210     $library->opac_info("holdingbranch OPAC info");
211     $library->store;
212
213     my @results = GetItemsInfo( $biblionumber );
214     ok( @results, 'GetItemsInfo returns results');
215     is( $results[0]->{ home_branch_opac_info }, "homebranch OPAC info",
216         'GetItemsInfo returns the correct home branch OPAC info notice' );
217     is( $results[0]->{ holding_branch_opac_info }, "holdingbranch OPAC info",
218         'GetItemsInfo returns the correct holding branch OPAC info notice' );
219     is( exists( $results[0]->{ onsite_checkout } ), 1,
220         'GetItemsInfo returns a onsite_checkout key' );
221
222     $schema->storage->txn_rollback;
223 };
224
225 subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub {
226
227     plan tests => 4;
228
229     $schema->storage->txn_begin;
230
231     my $biblio = $schema->resultset('Biblio')->create({
232         title       => "Test title",
233         biblioitems => [ { itemtype => 'BIB_LEVEL' } ],
234     });
235     my $biblioitem = $biblio->biblioitems->first;
236     my $item = $schema->resultset('Item')->create({
237         biblioitemnumber => $biblioitem->biblioitemnumber,
238         biblionumber     => $biblio->biblionumber,
239         itype            => "ITEM_LEVEL",
240     });
241
242     t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
243     is( $item->effective_itemtype(), 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' );
244
245     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
246     is( $item->effective_itemtype(), 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' );
247
248     # If itemtype is not defined and item-level_level item types are set
249     # fallback to biblio-level itemtype (Bug 14651) and warn
250     $item->itype( undef );
251     $item->update();
252     my $effective_itemtype;
253     warning_is { $effective_itemtype = $item->effective_itemtype() }
254                 "item-level_itypes set but no itemtype set for item ($item->itemnumber)",
255                 '->effective_itemtype() raises a warning when falling back to bib-level';
256
257     ok( defined $effective_itemtype &&
258                 $effective_itemtype eq 'BIB_LEVEL',
259         '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' );
260
261     $schema->storage->txn_rollback;
262 };
263
264 subtest 'SearchItems test' => sub {
265     plan tests => 14;
266
267     $schema->storage->txn_begin;
268     my $dbh = C4::Context->dbh;
269     my $builder = t::lib::TestBuilder->new;
270
271     my $library1 = $builder->build({
272         source => 'Branch',
273     });
274     my $library2 = $builder->build({
275         source => 'Branch',
276     });
277
278     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
279     my $cpl_items_before = SearchItemsByField( 'homebranch', $library1->{branchcode});
280
281     my ($biblionumber) = get_biblio();
282
283     my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
284
285     # Add two items
286     my (undef, undef, $item1_itemnumber) = AddItem({
287         homebranch => $library1->{branchcode},
288         holdingbranch => $library1->{branchcode},
289     }, $biblionumber);
290     my (undef, undef, $item2_itemnumber) = AddItem({
291         homebranch => $library2->{branchcode},
292         holdingbranch => $library2->{branchcode},
293     }, $biblionumber);
294
295     my ($items, $total_results);
296
297     ($items, $total_results) = SearchItems();
298     is($total_results, $initial_items_count + 2, "Created 2 new items");
299     is(scalar @$items, $total_results, "SearchItems() returns all items");
300
301     ($items, $total_results) = SearchItems(undef, {rows => 1});
302     is($total_results, $initial_items_count + 2);
303     is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item");
304
305     # Search all items where homebranch = 'CPL'
306     my $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 CPL item");
313     my $all_items_are_CPL = 1;
314     foreach my $item (@$items) {
315         if ($item->{homebranch} ne $library1->{branchcode}) {
316             $all_items_are_CPL = 0;
317             last;
318         }
319     }
320     ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
321
322     # Search all items where homebranch != 'CPL'
323     $filter = {
324         field => 'homebranch',
325         query => $library1->{branchcode},
326         operator => '!=',
327     };
328     ($items, $total_results) = SearchItems($filter);
329     ok($total_results > 0, "There is at least one non-CPL item");
330     my $all_items_are_not_CPL = 1;
331     foreach my $item (@$items) {
332         if ($item->{homebranch} eq $library1->{branchcode}) {
333             $all_items_are_not_CPL = 0;
334             last;
335         }
336     }
337     ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
338
339     # Search all items where biblio title (245$a) is like 'Silence in the %'
340     $filter = {
341         field => 'marc:245$a',
342         query => 'Silence in the %',
343         operator => 'like',
344     };
345     ($items, $total_results) = SearchItems($filter);
346     ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'");
347
348     # Search all items where biblio title is 'Silence in the library'
349     # and homebranch is 'CPL'
350     $filter = {
351         conjunction => 'AND',
352         filters => [
353             {
354                 field => 'marc:245$a',
355                 query => 'Silence in the %',
356                 operator => 'like',
357             },
358             {
359                 field => 'homebranch',
360                 query => $library1->{branchcode},
361                 operator => '=',
362             },
363         ],
364     };
365     ($items, $total_results) = SearchItems($filter);
366     my $found = 0;
367     foreach my $item (@$items) {
368         if ($item->{itemnumber} == $item1_itemnumber) {
369             $found = 1;
370             last;
371         }
372     }
373     ok($found, "item1 found");
374
375     my $frameworkcode = q||;
376     my ($itemfield) = GetMarcFromKohaField('items.itemnumber', $frameworkcode);
377
378     # Create item subfield 'z' without link
379     $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
380     $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", ?)', undef, $itemfield, $frameworkcode);
381
382     # Clear cache
383     my $cache = Koha::Cache->get_instance();
384     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
385     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
386     $cache->clear_from_cache("default_value_for_mod_marc-$frameworkcode");
387     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
388
389     my $item3_record = new MARC::Record;
390     $item3_record->append_fields(
391         new MARC::Field($itemfield, '', '', 'z' => 'foobar')
392     );
393     my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
394         $biblionumber);
395
396     # Search item where item subfield z is "foobar"
397     $filter = {
398         field => 'marc:' . $itemfield . '$z',
399         query => 'foobar',
400         operator => 'like',
401     };
402     ($items, $total_results) = SearchItems($filter);
403     ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
404
405     # Link $z to items.itemnotes (and make sure there is no other subfields
406     # linked to it)
407     $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
408     $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
409
410     # Clear cache
411     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
412     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
413     $cache->clear_from_cache("default_value_for_mod_marc-$frameworkcode");
414     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
415
416     ModItemFromMarc($item3_record, $biblionumber, $item3_itemnumber);
417
418     # Make sure the link is used
419     my $item3 = GetItem($item3_itemnumber);
420     ok($item3->{itemnotes} eq 'foobar', 'itemnotes eq "foobar"');
421
422     # Do the same search again.
423     # This time it will search in items.itemnotes
424     ($items, $total_results) = SearchItems($filter);
425     ok(scalar @$items == 1, 'found 1 item with itemnotes = "foobar"');
426
427     my $cpl_items_after = SearchItemsByField( 'homebranch', $library1->{branchcode});
428     is( ( scalar( @$cpl_items_after ) - scalar ( @$cpl_items_before ) ), 1, 'SearchItemsByField should return something' );
429
430     $schema->storage->txn_rollback;
431 };
432
433 subtest 'Koha::Item(s) tests' => sub {
434
435     plan tests => 5;
436
437     $schema->storage->txn_begin();
438
439     my $builder = t::lib::TestBuilder->new;
440     my $library1 = $builder->build({
441         source => 'Branch',
442     });
443     my $library2 = $builder->build({
444         source => 'Branch',
445     });
446
447     # Create a biblio and item for testing
448     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
449     my ($bibnum, $bibitemnum) = get_biblio();
450     my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} } , $bibnum);
451
452     # Get item.
453     my $item = Koha::Items->find( $itemnumber );
454     is( ref($item), 'Koha::Item', "Got Koha::Item" );
455
456     my $homebranch = $item->home_branch();
457     is( ref($homebranch), 'Koha::Library', "Got Koha::Library from home_branch method" );
458     is( $homebranch->branchcode(), $library1->{branchcode}, "Home branch code matches homebranch" );
459
460     my $holdingbranch = $item->holding_branch();
461     is( ref($holdingbranch), 'Koha::Library', "Got Koha::Library from holding_branch method" );
462     is( $holdingbranch->branchcode(), $library2->{branchcode}, "Home branch code matches holdingbranch" );
463
464     $schema->storage->txn_rollback;
465 };
466
467 subtest 'C4::Biblio::EmbedItemsInMarcBiblio' => sub {
468     plan tests => 7;
469
470     $schema->storage->txn_begin();
471
472     my $builder = t::lib::TestBuilder->new;
473     my $library1 = $builder->build({
474         source => 'Branch',
475     });
476     my $library2 = $builder->build({
477         source => 'Branch',
478     });
479
480     my ( $biblionumber, $biblioitemnumber ) = get_biblio();
481     my $item_infos = [
482         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
483         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
484         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
485         { homebranch => $library2->{branchcode}, holdingbranch => $library2->{branchcode} },
486         { homebranch => $library2->{branchcode}, holdingbranch => $library2->{branchcode} },
487         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
488         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
489         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
490     ];
491     my $number_of_items = scalar @$item_infos;
492     my $number_of_items_with_homebranch_is_CPL =
493       grep { $_->{homebranch} eq $library1->{branchcode} } @$item_infos;
494
495     my @itemnumbers;
496     for my $item_info (@$item_infos) {
497         my ( undef, undef, $itemnumber ) = AddItem(
498             {
499                 homebranch    => $item_info->{homebranch},
500                 holdingbranch => $item_info->{holdingbanch}
501             },
502             $biblionumber
503         );
504         push @itemnumbers, $itemnumber;
505     }
506
507     # Emptied the OpacHiddenItems pref
508     t::lib::Mocks::mock_preference( 'OpacHiddenItems', '' );
509
510     my ($itemfield) =
511       C4::Biblio::GetMarcFromKohaField( 'items.itemnumber', '' );
512     my $record = C4::Biblio::GetMarcBiblio($biblionumber);
513     warning_is { C4::Biblio::EmbedItemsInMarcBiblio() }
514     { carped => 'EmbedItemsInMarcBiblio: No MARC record passed' },
515       'Should crap is no record passed.';
516
517     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber );
518     my @items = $record->field($itemfield);
519     is( scalar @items, $number_of_items, 'Should return all items' );
520
521     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber,
522         [ $itemnumbers[1], $itemnumbers[3] ] );
523     @items = $record->field($itemfield);
524     is( scalar @items, 2, 'Should return all items present in the list' );
525
526     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
527     @items = $record->field($itemfield);
528     is( scalar @items, $number_of_items, 'Should return all items for opac' );
529
530     my $opachiddenitems = "
531         homebranch: ['$library1->{branchcode}']";
532     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
533
534     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber );
535     @items = $record->field($itemfield);
536     is( scalar @items,
537         $number_of_items,
538         'Even with OpacHiddenItems set, all items should have been embedded' );
539
540     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
541     @items = $record->field($itemfield);
542     is(
543         scalar @items,
544         $number_of_items - $number_of_items_with_homebranch_is_CPL,
545 'For OPAC, the pref OpacHiddenItems should have been take into account. Only items with homebranch ne CPL should have been embedded'
546     );
547
548     $opachiddenitems = "
549         homebranch: ['$library1->{branchcode}', '$library2->{branchcode}']";
550     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
551     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
552     @items = $record->field($itemfield);
553     is(
554         scalar @items,
555         0,
556 'For OPAC, If all items are hidden, no item should have been embedded'
557     );
558
559     $schema->storage->txn_rollback;
560 };
561
562
563 subtest 'C4::Items::_build_default_values_for_mod_marc' => sub {
564     plan tests => 4;
565
566     $schema->storage->txn_begin();
567
568     my $builder = t::lib::TestBuilder->new;
569     my $framework = $builder->build({
570         source => 'BiblioFramework',
571     });
572     # Link biblio.biblionumber and biblioitems.biblioitemnumber to avoid _koha_marc_update_bib_ids to fail with 'no biblio[item]number tag for framework"
573     $builder->build({
574         source => 'MarcSubfieldStructure',
575         value => {
576             frameworkcode => $framework->{frameworkcode},
577             kohafield => 'biblio.biblionumber',
578             tagfield => '999',
579             tagsubfield => 'c',
580         }
581     });
582     $builder->build({
583         source => 'MarcSubfieldStructure',
584         value => {
585             frameworkcode => $framework->{frameworkcode},
586             kohafield => 'biblioitems.biblioitemnumber',
587             tagfield => '999',
588             tagsubfield => 'd',
589         }
590     });
591     my $mss_itemnumber = $builder->build({
592         source => 'MarcSubfieldStructure',
593         value => {
594             frameworkcode => $framework->{frameworkcode},
595             kohafield => 'items.itemnumber',
596             tagfield => '952',
597             tagsubfield => '9',
598         }
599     });
600
601     my $mss_barcode = $builder->build({
602         source => 'MarcSubfieldStructure',
603         value => {
604             frameworkcode => $framework->{frameworkcode},
605             kohafield => 'items.barcode',
606             tagfield => '952',
607             tagsubfield => 'p',
608         }
609     });
610
611     # Create a record with a barcode
612     my ($biblionumber) = get_biblio( $framework->{frameworkcode} );
613     my $item_record = new MARC::Record;
614     my $a_barcode = 'a barcode';
615     my $barcode_field = MARC::Field->new(
616         '952', ' ', ' ',
617         p => $a_barcode,
618     );
619     $item_record->append_fields( $barcode_field );
620     my (undef, undef, $item_itemnumber) = AddItemFromMarc($item_record, $biblionumber);
621
622     # Make sure everything has been set up
623     my $item = GetItem($item_itemnumber);
624     is( $item->{barcode}, $a_barcode, 'Everything has been set up correctly, the barcode is defined as expected' );
625
626     # Delete the barcode field and save the record
627     $item_record->delete_fields( $barcode_field );
628     ModItemFromMarc($item_record, $biblionumber, $item_itemnumber);
629     $item = GetItem($item_itemnumber);
630     is( $item->{barcode}, undef, 'The default value should have been set to the barcode, the field is mapped to a kohafield' );
631
632     # Re-add the barcode field and save the record
633     $item_record->append_fields( $barcode_field );
634     ModItemFromMarc($item_record, $biblionumber, $item_itemnumber);
635     $item = GetItem($item_itemnumber);
636     is( $item->{barcode}, $a_barcode, 'Everything has been set up correctly, the barcode is defined as expected' );
637
638     # Remove the mapping
639     my $dbh = C4::Context->dbh;
640     $dbh->do(q|
641         DELETE FROM marc_subfield_structure
642         WHERE kohafield = 'items.barcode'
643         AND frameworkcode = ?
644     |, undef, $framework->{frameworkcode} );
645
646     # And make sure the caches are cleared
647     my $cache = Koha::Cache->get_instance();
648     $cache->clear_from_cache("MarcStructure-0-" . $framework->{frameworkcode});
649     $cache->clear_from_cache("MarcStructure-1-" . $framework->{frameworkcode});
650     $cache->clear_from_cache("default_value_for_mod_marc-" . $framework->{frameworkcode});
651     $cache->clear_from_cache("MarcSubfieldStructure-" . $framework->{frameworkcode});
652
653     # Update the MARC field with another value
654     $item_record->delete_fields( $barcode_field );
655     my $another_barcode = 'another_barcode';
656     my $another_barcode_field = MARC::Field->new(
657         '952', ' ', ' ',
658         p => $another_barcode,
659     );
660     $item_record->append_fields( $another_barcode_field );
661     # The DB value should not have been updated
662     ModItemFromMarc($item_record, $biblionumber, $item_itemnumber);
663     $item = GetItem($item_itemnumber);
664     is ( $item->{barcode}, $a_barcode, 'items.barcode is not mapped anymore, so the DB column has not been updated' );
665
666     $schema->storage->txn_rollback;
667 };
668
669 subtest '_mod_item_dates' => sub {
670     plan tests => 11;
671
672     is( C4::Items::_mod_item_dates(), undef, 'Call without parameters' );
673     is( C4::Items::_mod_item_dates(1), undef, 'Call without hashref' );
674
675     my $orgitem;
676     my $item = {
677         itemcallnumber  => 'V II 149 1963',
678         barcode         => '109304',
679     };
680     $orgitem = { %$item };
681     C4::Items::_mod_item_dates($item);
682     is_deeply( $item, $orgitem, 'No dates passed to _mod_item_dates' );
683
684     # add two correct dates
685     t::lib::Mocks::mock_preference('dateformat', 'us');
686     $item->{dateaccessioned} = '01/31/2016';
687     $item->{onloan} =  $item->{dateaccessioned};
688     $orgitem = { %$item };
689     C4::Items::_mod_item_dates($item);
690     is( $item->{dateaccessioned}, '2016-01-31', 'dateaccessioned is fine' );
691     is( $item->{onloan}, '2016-01-31', 'onloan is fine too' );
692
693
694     # add some invalid dates
695     $item->{notexistingcolumndate} = '13/1/2015'; # wrong format
696     $item->{anotherdate} = 'tralala'; # even worse
697     $item->{myzerodate} = '0000-00-00'; # wrong too
698     C4::Items::_mod_item_dates($item);
699     is( $item->{notexistingcolumndate}, undef, 'Invalid date became NULL' );
700     is( $item->{anotherdate}, undef, 'Second invalid date became NULL too' );
701     is( $item->{myzerodate}, undef, '0000-00-00 became NULL too' );
702
703     # check if itemlost_on was not touched
704     $item->{itemlost_on} = '12345678';
705     $item->{withdrawn_on} = '12/31/2015 23:59:00';
706     $orgitem = { %$item };
707     C4::Items::_mod_item_dates($item);
708     is_deeply( $item, $orgitem, 'Colums with _on are not touched' );
709
710     t::lib::Mocks::mock_preference('dateformat', 'metric');
711     $item->{dateaccessioned} = '01/31/2016'; #wrong
712     $item->{yetanotherdatetime} = '20/01/2016 13:58:00'; #okay
713     C4::Items::_mod_item_dates($item);
714     is( $item->{dateaccessioned}, undef, 'dateaccessioned wrong format' );
715     is( $item->{yetanotherdatetime}, '2016-01-20 13:58:00',
716         'yetanotherdatetime is ok' );
717 };
718
719 # Helper method to set up a Biblio.
720 sub get_biblio {
721     my ( $frameworkcode ) = @_;
722     $frameworkcode //= '';
723     my $bib = MARC::Record->new();
724     $bib->append_fields(
725         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
726         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
727     );
728     my ($bibnum, $bibitemnum) = AddBiblio($bib, $frameworkcode);
729     return ($bibnum, $bibitemnum);
730 }