Bug 23800: Does not order items by barcode in batch item modification
[koha.git] / tools / batchMod.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use CGI qw ( -utf8 );
22 use Modern::Perl;
23 use C4::Auth;
24 use C4::Output;
25 use C4::Biblio;
26 use C4::Items;
27 use C4::Circulation;
28 use C4::Context;
29 use C4::Koha;
30 use C4::BackgroundJob;
31 use C4::ClassSource;
32 use C4::Debug;
33 use C4::Members;
34 use MARC::File::XML;
35 use List::MoreUtils qw/uniq/;
36
37 use Koha::AuthorisedValues;
38 use Koha::Biblios;
39 use Koha::DateUtils;
40 use Koha::Items;
41 use Koha::ItemTypes;
42 use Koha::Patrons;
43
44 my $input = new CGI;
45 my $dbh = C4::Context->dbh;
46 my $error        = $input->param('error');
47 my @itemnumbers  = $input->multi_param('itemnumber');
48 my $biblionumber = $input->param('biblionumber');
49 my $op           = $input->param('op');
50 my $del          = $input->param('del');
51 my $del_records  = $input->param('del_records');
52 my $completedJobID = $input->param('completedJobID');
53 my $runinbackground = $input->param('runinbackground');
54 my $src          = $input->param('src');
55 my $use_default_values = $input->param('use_default_values');
56
57 my $template_name;
58 my $template_flag;
59 if (!defined $op) {
60     $template_name = "tools/batchMod.tt";
61     $template_flag = { tools => '*' };
62     $op = q{};
63 } else {
64     $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt";
65     $template_flag = ($del) ? { tools => 'items_batchdel' }   : { tools => 'items_batchmod' };
66 }
67
68
69 my ($template, $loggedinuser, $cookie)
70     = get_template_and_user({template_name => $template_name,
71                  query => $input,
72                  type => "intranet",
73                  authnotrequired => 0,
74                  flagsrequired => $template_flag,
75                  });
76
77 # Does the user have a restricted item edition permission?
78 my $uid = $loggedinuser ? Koha::Patrons->find( $loggedinuser )->userid : undef;
79 my $restrictededition = $uid ? haspermission($uid,  {'tools' => 'items_batchmod_restricted'}) : undef;
80 # In case user is a superlibrarian, edition is not restricted
81 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
82
83 $template->param(del       => $del);
84
85 my $itemrecord;
86 my $nextop="";
87 my @errors; # store errors found while checking data BEFORE saving item.
88 my $items_display_hashref;
89 our $tagslib = &GetMarcStructure(1);
90
91 my $deleted_items = 0;     # Number of deleted items
92 my $deleted_records = 0;   # Number of deleted records ( with no items attached )
93 my $not_deleted_items = 0; # Number of items that could not be deleted
94 my @not_deleted;           # List of the itemnumbers that could not be deleted
95 my $modified_items = 0;    # Numbers of modified items
96 my $modified_fields = 0;   # Numbers of modified fields
97
98 my %cookies = parse CGI::Cookie($cookie);
99 my $sessionID = $cookies{'CGISESSID'}->value;
100
101
102 #--- ----------------------------------------------------------------------------
103 if ($op eq "action") {
104 #-------------------------------------------------------------------------------
105     my @tags      = $input->multi_param('tag');
106     my @subfields = $input->multi_param('subfield');
107     my @values    = $input->multi_param('field_value');
108     my @disabled  = $input->multi_param('disable_input');
109     # build indicator hash.
110     my @ind_tag   = $input->multi_param('ind_tag');
111     my @indicator = $input->multi_param('indicator');
112
113     # Is there something to modify ?
114     # TODO : We shall use this var to warn the user in case no modification was done to the items
115     my $values_to_modify = scalar(grep {!/^$/} @values);
116     my $values_to_blank  = scalar(@disabled);
117     my $marcitem;
118
119     # Once the job is done
120     if ($completedJobID) {
121         # If we have a reasonable amount of items, we display them
122     my $max_items = $del ? C4::Context->preference("MaxItemsToDisplayForBatchDel") : C4::Context->preference("MaxItemsToDisplayForBatchMod");
123     if (scalar(@itemnumbers) <= $max_items ){
124         if (scalar(@itemnumbers) <= 1000 ) {
125             $items_display_hashref=BuildItemsData(@itemnumbers);
126         } else {
127             # Else, we only display the barcode
128             my @simple_items_display = map {
129                 my $itemnumber = $_;
130                 my $item = Koha::Items->find($itemnumber);
131                 {
132                     itemnumber   => $itemnumber,
133                     barcode      => $item ? ( $item->barcode // q{} ) : q{},
134                     biblionumber => $item ? $item->biblio->biblionumber : q{},
135                 };
136             } @itemnumbers;
137             $template->param("simple_items_display" => \@simple_items_display);
138         }
139     } else {
140         $template->param( "too_many_items_display" => scalar(@itemnumbers) );
141         $template->param( "job_completed" => 1 );
142     }
143
144         # Setting the job as done
145         my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
146
147         # Calling the template
148         add_saved_job_results_to_template($template, $completedJobID);
149
150     } else {
151     # While the job is getting done
152
153         # Job size is the number of items we have to process
154         my $job_size = scalar(@itemnumbers);
155         my $job = undef;
156
157         # If we asked for background processing
158         if ($runinbackground) {
159             $job = put_in_background($job_size);
160         }
161
162         #initializing values for updates
163     my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
164         if ($values_to_modify){
165             my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
166             $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
167         }
168         if ($values_to_blank){
169             foreach my $disabledsubf (@disabled){
170                 if ($marcitem && $marcitem->field($itemtagfield)){
171                     $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
172                 }
173                 else {
174                     $marcitem = MARC::Record->new();
175                     $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
176                 }
177             }
178         }
179
180         # For each item
181         my $i = 1; 
182         foreach my $itemnumber(@itemnumbers){
183
184                 $job->progress($i) if $runinbackground;
185         my $itemdata = Koha::Items->find($itemnumber);
186         next unless $itemdata; # Should have been tested earlier, but just in case...
187         $itemdata = $itemdata->unblessed;
188         if ( $del ){
189             my $return = DelItemCheck( $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
190                         if ($return == 1) {
191                             $deleted_items++;
192                         } else {
193                             $not_deleted_items++;
194                             push @not_deleted,
195                                 { biblionumber => $itemdata->{'biblionumber'},
196                                   itemnumber => $itemdata->{'itemnumber'},
197                                   barcode => $itemdata->{'barcode'},
198                                   title => $itemdata->{'title'},
199                                   $return => 1
200                                 };
201                         }
202
203                 # If there are no items left, delete the biblio
204                 if ($del_records) {
205                     my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
206                     if ( $itemscount == 0 ) {
207                         my $error = DelBiblio( $itemdata->{'biblionumber'} );
208                         unless ($error) {
209                             $deleted_records++;
210                             if ( $src eq 'CATALOGUING' ) {
211                                 # We are coming catalogue/detail.pl, there were items from a single bib record
212                                 $template->param( biblio_deleted => 1 );
213                             }
214                         }
215                     }
216                 }
217                 } else {
218             if ($values_to_modify || $values_to_blank) {
219                 my $localmarcitem = Item2Marc($itemdata);
220
221                 my $modified = UpdateMarcWith( $marcitem, $localmarcitem );
222                 if ( $modified ) {
223                     eval {
224                         if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
225                             LostItem($itemnumber, 'batchmod') if $item->{itemlost} and not $itemdata->{itemlost};
226                         }
227                     };
228                 }
229                 if ( $runinbackground ) {
230                     $modified_items++ if $modified;
231                     $modified_fields += $modified;
232                     $job->set({
233                         modified_items  => $modified_items,
234                         modified_fields => $modified_fields,
235                     });
236                 }
237                     }
238                 }
239                 $i++;
240         }
241     }
242 }
243 #
244 #-------------------------------------------------------------------------------
245 # build screen with existing items. and "new" one
246 #-------------------------------------------------------------------------------
247
248 if ($op eq "show"){
249     my $filefh = $input->upload('uploadfile');
250     my $filecontent = $input->param('filecontent');
251     my ( @notfoundbarcodes, @notfounditemnumbers);
252
253     my $split_chars = C4::Context->preference('BarcodeSeparators');
254     if ($filefh){
255         binmode $filefh, ':encoding(UTF-8)';
256         my @contentlist;
257         while (my $content=<$filefh>){
258             $content =~ s/[\r\n]*$//;
259             push @contentlist, $content if $content;
260         }
261
262         if ($filecontent eq 'barcode_file') {
263             @contentlist = grep /\S/, ( map { split /[$split_chars]/ } @contentlist );
264             @contentlist = uniq @contentlist;
265             my @existing_items = @{ Koha::Items->search({ barcode => \@contentlist })->unblessed };
266             @existing_items = map {
267                 my $barcode = $_;
268                 grep { $_->{barcode} eq $barcode ? $_ : () } @existing_items
269             } @contentlist;
270             @itemnumbers = map { $_->{itemnumber} } @existing_items;
271             my @barcodes = map { $_->{barcode}    } @existing_items;
272             # to avoid problems with case sensitivity
273             my %exists = map { lc($_) => 1 } @barcodes;
274             @contentlist = map { lc($_) } @contentlist;
275             @notfoundbarcodes = grep { !$exists{$_} } @contentlist;
276         }
277         elsif ( $filecontent eq 'itemid_file') {
278             @contentlist = uniq @contentlist;
279             my @existing_items = @{ Koha::Items->search({ itemnumber => \@contentlist })->unblessed };
280             @existing_items = map {
281                 my $barcode = $_;
282                 grep { $_->{barcode} eq $barcode ? $_ : () } @existing_items
283             } @contentlist;
284             @itemnumbers = map { $_->{itemnumber} } @existing_items;
285             my %exists = map { $_ => 1 } @itemnumbers;
286             @notfounditemnumbers = grep { !$exists{$_} } @contentlist;
287         }
288     } else {
289         if (defined $biblionumber){
290             my @all_items = GetItemsInfo( $biblionumber );
291             foreach my $itm (@all_items) {
292                 push @itemnumbers, $itm->{itemnumber};
293             }
294         }
295         if ( my $list = $input->param('barcodelist') ) {
296             my @barcodelist = grep /\S/, ( split /[$split_chars]/, $list );
297             @barcodelist = uniq @barcodelist;
298
299             my @existing_items = @{ Koha::Items->search({ barcode => \@barcodelist })->unblessed };
300             @existing_items = map {
301                 my $barcode = $_;
302                 grep { $_->{barcode} eq $barcode ? $_ : () } @existing_items
303             } @barcodelist;
304             @itemnumbers = map { $_->{itemnumber} } @existing_items;
305             my @barcodes = map { $_->{barcode}    } @existing_items;
306             # to avoid problems with case sensitivity
307             my %exists = map { lc($_) => 1 } @barcodes;
308             @barcodelist = map { lc($_) } @barcodelist;
309             @notfoundbarcodes = grep { !$exists{$_} } @barcodelist;
310         }
311     }
312
313     # Flag to tell the template there are valid results, hidden or not
314     if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
315     # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
316     my $max_display_items = $del
317         ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
318         : C4::Context->preference("MaxItemsToDisplayForBatchMod");
319     $template->param("too_many_items_process" => scalar(@itemnumbers)) if !$del && scalar(@itemnumbers) >= C4::Context->preference("MaxItemsToProcessForBatchMod");
320     if (scalar(@itemnumbers) <= ( $max_display_items // 1000 ) ) {
321         $items_display_hashref=BuildItemsData(@itemnumbers);
322     } else {
323         $template->param("too_many_items_display" => scalar(@itemnumbers));
324         # Even if we do not display the items, we need the itemnumbers
325         $template->param(itemnumbers_array => \@itemnumbers);
326     }
327 # now, build the item form for entering a new item
328 my @loop_data =();
329 my $i=0;
330 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
331
332 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
333
334 # Adding a default choice, in case the user does not want to modify the branch
335 my $nochange_branch = { branchname => '', value => '', selected => 1 };
336 unshift (@$libraries, $nochange_branch);
337
338 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
339
340 # Getting list of subfields to keep when restricted batchmod edit is enabled
341 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
342 my $allowAllSubfields = (
343     not defined $subfieldsToAllowForBatchmod
344       or $subfieldsToAllowForBatchmod eq q||
345 ) ? 1 : 0;
346 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
347
348 foreach my $tag (sort keys %{$tagslib}) {
349     # loop through each subfield
350     foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
351         next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
352         next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
353         next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
354         # barcode and stocknumber are not meant to be batch-modified
355         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
356         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
357         my %subfield_data;
358  
359         my $index_subfield = int(rand(1000000)); 
360         if ($subfield eq '@'){
361             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
362         } else {
363             $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
364         }
365         $subfield_data{tag}        = $tag;
366         $subfield_data{subfield}   = $subfield;
367         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
368         $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
369         $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
370         my ($x,$value);
371    if ( $use_default_values) {
372             $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
373             # get today date & replace YYYY, MM, DD if provided in the default value
374             my $today = dt_from_string;
375             my $year  = $today->year;
376             my $month = $today->month;
377             my $day   = $today->day;
378             $value =~ s/YYYY/$year/g;
379             $value =~ s/MM/$month/g;
380             $value =~ s/DD/$day/g;
381         }
382         $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
383     # testing branch value if IndependentBranches.
384
385         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
386         my @authorised_values;
387         my %authorised_lib;
388         # builds list, depending on authorised value...
389
390     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
391         foreach my $library (@$libraries) {
392             push @authorised_values, $library->{branchcode};
393             $authorised_lib{$library->{branchcode}} = $library->{branchname};
394         }
395         $value = "";
396     }
397     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
398         push @authorised_values, "";
399         my $itemtypes = Koha::ItemTypes->search_with_localization;
400         while ( my $itemtype = $itemtypes->next ) {
401             push @authorised_values, $itemtype->itemtype;
402             $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
403         }
404         $value = "";
405
406           #---- class_sources
407       }
408       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
409           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
410             
411           my $class_sources = GetClassSources();
412           my $default_source = C4::Context->preference("DefaultClassificationSource");
413           
414           foreach my $class_source (sort keys %$class_sources) {
415               next unless $class_sources->{$class_source}->{'used'} or
416                           ($value and $class_source eq $value)      or
417                           ($class_source eq $default_source);
418               push @authorised_values, $class_source;
419               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
420           }
421                   $value = '';
422
423           #---- "true" authorised value
424       }
425       else {
426           push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
427
428           my @avs = Koha::AuthorisedValues->search({ category => $tagslib->{$tag}->{$subfield}->{authorised_value}, branchcode => $branch_limit },{order_by=>'lib'});
429           for my $av ( @avs ) {
430               push @authorised_values, $av->authorised_value;
431               $authorised_lib{$av->authorised_value} = $av->lib;
432           }
433           $value="";
434       }
435         $subfield_data{marc_value} = {
436             type    => 'select',
437             id      => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
438             name    => "field_value",
439             values  => \@authorised_values,
440             labels  => \%authorised_lib,
441             default => $value,
442         };
443     # it's a thesaurus / authority field
444     }
445     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
446         $subfield_data{marc_value} = {
447             type         => 'text1',
448             id           => $subfield_data{id},
449             value        => $value,
450             authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
451         }
452     }
453     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
454         require Koha::FrameworkPlugin;
455         my $plugin = Koha::FrameworkPlugin->new( {
456             name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
457             item_style => 1,
458         });
459         my $temp;
460         my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
461             id => $subfield_data{id}, tabloop => \@loop_data };
462         $plugin->build( $pars );
463         if( !$plugin->errstr ) {
464             $subfield_data{marc_value} = {
465                 type       => 'text2',
466                 id         => $subfield_data{id},
467                 value      => $value,
468                 javascript => $plugin->javascript,
469                 noclick    => $plugin->noclick,
470             };
471         } else {
472             warn $plugin->errstr;
473             $subfield_data{marc_value} = { # supply default input form
474                 type       => 'text',
475                 id         => $subfield_data{id},
476                 value      => $value,
477             };
478         }
479     }
480     elsif ( $tag eq '' ) {       # it's an hidden field
481             $subfield_data{marc_value} = {
482                 type       => 'hidden',
483                 id         => $subfield_data{id},
484                 value      => $value,
485             };
486     }
487     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
488         $subfield_data{marc_value} = {
489                 type       => 'text',
490                 id         => $subfield_data{id},
491                 value      => $value,
492         };
493     }
494     elsif ( length($value) > 100
495             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
496                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
497             or (C4::Context->preference("marcflavour") eq "MARC21"  and
498                   500 <= $tag && $tag < 600                     )
499           ) {
500         # oversize field (textarea)
501         $subfield_data{marc_value} = {
502                 type       => 'textarea',
503                 id         => $subfield_data{id},
504                 value      => $value,
505         };
506     } else {
507         # it's a standard field
508         $subfield_data{marc_value} = {
509                 type       => 'text',
510                 id         => $subfield_data{id},
511                 value      => $value,
512         };
513     }
514 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
515     push (@loop_data, \%subfield_data);
516     $i++
517   }
518 } # -- End foreach tag
519
520
521
522     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
523     $template->param(
524         item                => \@loop_data,
525         notfoundbarcodes    => \@notfoundbarcodes,
526         notfounditemnumbers => \@notfounditemnumbers
527     );
528     $nextop="action"
529 } # -- End action="show"
530
531 $template->param(%$items_display_hashref) if $items_display_hashref;
532 $template->param(
533     op      => $nextop,
534 );
535 $template->param( $op => 1 ) if $op;
536
537 if ($op eq "action") {
538
539     #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
540
541     $template->param(
542         not_deleted_items => $not_deleted_items,
543         deleted_items => $deleted_items,
544         delete_records => $del_records,
545         deleted_records => $deleted_records,
546         not_deleted_loop => \@not_deleted 
547     );
548 }
549
550 foreach my $error (@errors) {
551     $template->param($error => 1) if $error;
552 }
553 $template->param(src => $src);
554 $template->param(biblionumber => $biblionumber);
555 output_html_with_http_headers $input, $cookie, $template->output;
556 exit;
557
558
559 # ---------------- Functions
560
561 sub BuildItemsData{
562         my @itemnumbers=@_;
563                 # now, build existiing item list
564                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
565                 my @big_array;
566                 #---- finds where items.itemnumber is stored
567     my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
568     my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
569                 foreach my $itemnumber (@itemnumbers){
570             my $itemdata = Koha::Items->find($itemnumber);
571             next unless $itemdata; # Should have been tested earlier, but just in case...
572             $itemdata = $itemdata->unblessed;
573                         my $itemmarc=Item2Marc($itemdata);
574                         my %this_row;
575                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
576                                 # loop through each subfield
577                                 my $itembranchcode=$field->subfield($branchtagsubfield);
578                 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
579                                                 #verifying rights
580                                                 my $userenv = C4::Context->userenv();
581                         unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
582                                                                 $this_row{'nomod'}=1;
583                                                 }
584                                 }
585                                 my $tag=$field->tag();
586                                 foreach my $subfield ($field->subfields) {
587                                         my ($subfcode,$subfvalue)=@$subfield;
588                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
589                                                         && $tag        ne $itemtagfield 
590                                                         && $subfcode   ne $itemtagsubfield);
591
592                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
593                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
594                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
595                                                                         $subfcode, $subfvalue, '', $tagslib) 
596                                                                         || $subfvalue;
597                                         }
598
599                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
600                                 }
601                         }
602
603             # grab title, author, and ISBN to identify bib that the item
604             # belongs to in the display
605             my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
606             $this_row{title}        = $biblio->title;
607             $this_row{author}       = $biblio->author;
608             $this_row{isbn}         = $biblio->biblioitem->isbn;
609             $this_row{biblionumber} = $biblio->biblionumber;
610             $this_row{holds}        = $biblio->holds->count;
611             $this_row{item_holds}   = Koha::Holds->search( itemnumber => $itemnumber )->count;
612
613                         if (%this_row) {
614                                 push(@big_array, \%this_row);
615                         }
616                 }
617                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
618
619                 # now, construct template !
620                 # First, the existing items for display
621                 my @item_value_loop;
622                 my @witnesscodessorted=sort keys %witness;
623                 for my $row ( @big_array ) {
624                         my %row_data;
625                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
626                         $row_data{item_value} = [ @item_fields ];
627                         $row_data{itemnumber} = $row->{itemnumber};
628                         #reporting this_row values
629                         $row_data{'nomod'} = $row->{'nomod'};
630       $row_data{bibinfo} = $row->{bibinfo};
631       $row_data{author} = $row->{author};
632       $row_data{title} = $row->{title};
633       $row_data{isbn} = $row->{isbn};
634       $row_data{biblionumber} = $row->{biblionumber};
635       $row_data{holds}        = $row->{holds};
636       $row_data{item_holds}   = $row->{item_holds};
637       my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
638       $row_data{onloan} = $is_on_loan ? 1 : 0;
639                         push(@item_value_loop,\%row_data);
640                 }
641                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
642
643         return { item_loop        => \@item_value_loop, item_header_loop => \@header_loop };
644 }
645
646 #BE WARN : it is not the general case 
647 # This function can be OK in the item marc record special case
648 # Where subfield is not repeated
649 # And where we are sure that field should correspond
650 # And $tag>10
651 sub UpdateMarcWith {
652   my ($marcfrom,$marcto)=@_;
653     my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
654     my $fieldfrom=$marcfrom->field($itemtag);
655     my @fields_to=$marcto->field($itemtag);
656     my $modified = 0;
657     foreach my $subfield ( $fieldfrom->subfields() ) {
658         foreach my $field_to_update ( @fields_to ) {
659             if ( $subfield->[1] ) {
660                 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
661                     $modified++;
662                     $field_to_update->update( $subfield->[0] => $subfield->[1] );
663                 }
664             }
665             else {
666                 $modified++;
667                 $field_to_update->delete_subfield( code => $subfield->[0] );
668             }
669         }
670     }
671     return $modified;
672 }
673
674 sub find_value {
675     my ($tagfield,$insubfield,$record) = @_;
676     my $result;
677     my $indicator;
678     foreach my $field ($record->field($tagfield)) {
679         my @subfields = $field->subfields();
680         foreach my $subfield (@subfields) {
681             if (@$subfield[0] eq $insubfield) {
682                 $result .= @$subfield[1];
683                 $indicator = $field->indicator(1).$field->indicator(2);
684             }
685         }
686     }
687     return($indicator,$result);
688 }
689
690 # ----------------------------
691 # Background functions
692
693
694 sub add_results_to_template {
695     my $template = shift;
696     my $results = shift;
697     $template->param(map { $_ => $results->{$_} } keys %{ $results });
698 }
699
700 sub add_saved_job_results_to_template {
701     my $template = shift;
702     my $completedJobID = shift;
703     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
704     my $results = $job->results();
705     add_results_to_template($template, $results);
706
707     my $fields = $job->get("modified_fields");
708     my $items = $job->get("modified_items");
709     $template->param(
710         modified_items => $items,
711         modified_fields => $fields,
712     );
713 }
714
715 sub put_in_background {
716     my $job_size = shift;
717
718     my $job = C4::BackgroundJob->new($sessionID, "test", '/cgi-bin/koha/tools/batchMod.pl', $job_size);
719     my $jobID = $job->id();
720
721     # fork off
722     if (my $pid = fork) {
723         # parent
724         # return job ID as JSON
725
726         # prevent parent exiting from
727         # destroying the kid's database handle
728         # FIXME: according to DBI doc, this may not work for Oracle
729         $dbh->{InactiveDestroy}  = 1;
730
731         my $reply = CGI->new("");
732         print $reply->header(-type => 'text/html');
733         print '{"jobID":"' . $jobID . '"}';
734         exit 0;
735     } elsif (defined $pid) {
736         # child
737         # close STDOUT to signal to Apache that
738         # we're now running in the background
739         close STDOUT;
740         close STDERR;
741     } else {
742         # fork failed, so exit immediately
743         warn "fork failed while attempting to run tools/batchMod.pl as a background job";
744         exit 0;
745     }
746     return $job;
747 }
748
749
750