MT2527 : Adds default empty value for branches when batch modifying items
[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 under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use CGI;
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use C4::Auth;
25 use C4::Output;
26 use C4::Biblio;
27 use C4::Items;
28 use C4::Context;
29 use C4::Koha; # XXX subfield_is_koha_internal_p
30 use C4::Branch; # XXX subfield_is_koha_internal_p
31 use C4::ClassSource;
32 use C4::Dates;
33 use C4::Debug;
34 use YAML;
35 use Switch;
36 use MARC::File::XML;
37
38 my $input = new CGI;
39 my $dbh = C4::Context->dbh;
40 my $error        = $input->param('error');
41 my @itemnumbers  = $input->param('itemnumber');
42 my $op           = $input->param('op');
43 my $del          = $input->param('del');
44
45 my $template_name;
46 my $template_flag;
47 if (!defined $op) {
48     $template_name = "tools/batchMod.tmpl";
49     $template_flag = { tools => '*' };
50 } else {
51     $template_name = ($del) ? "tools/batchMod-del.tmpl" : "tools/batchMod-edit.tmpl";
52     $template_flag = ($del) ? { tools => 'batchdel' }   : { tools => 'batchmod' };
53 }
54
55
56 my ($template, $loggedinuser, $cookie)
57     = get_template_and_user({template_name => $template_name,
58                  query => $input,
59                  type => "intranet",
60                  authnotrequired => 0,
61                  flagsrequired => $template_flag,
62                  });
63
64
65 my $today_iso = C4::Dates->today('iso');
66 $template->param(today_iso => $today_iso);
67 $template->param(del       => $del);
68
69 my $itemrecord;
70 my $nextop="";
71 my @errors; # store errors found while checking data BEFORE saving item.
72 my $items_display_hashref;
73 my $frameworkcode="";
74 my $tagslib = &GetMarcStructure(1,$frameworkcode);
75
76 my $deleted_items = 0;     # Numbers of deleted items
77 my $not_deleted_items = 0; # Numbers of items that could not be deleted
78 my @not_deleted;           # List of the itemnumbers that could not be deleted
79
80 #--- ----------------------------------------------------------------------------
81 if ($op eq "action") {
82 #-------------------------------------------------------------------------------
83     my @tags      = $input->param('tag');
84     my @subfields = $input->param('subfield');
85     my @values    = $input->param('field_value');
86     # build indicator hash.
87     my @ind_tag   = $input->param('ind_tag');
88     my @indicator = $input->param('indicator');
89
90     # Is there something to modify ?
91     # TODO : We shall use this var to warn the user in case no modification was done to the items
92     my $something_to_modify = scalar(grep {!/^$/} @values);
93     
94     foreach my $itemnumber(@itemnumbers){
95             my $itemdata=GetItem($itemnumber);
96             if ($input->param("del")){
97                     my $return = DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
98                     if ($return == 1) {
99                         $deleted_items++;
100                     } else {
101                         $not_deleted_items++;
102                         push @not_deleted, { itemnumber => $itemdata->{'itemnumber'}, barcode => $itemdata->{'barcode'}, title => $itemdata->{'title'}, $return => 1 };
103                     }
104             } else {
105                 if ($something_to_modify) {
106                     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
107                     my $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
108                     my $localitem = TransformMarcToKoha( $dbh, $marcitem, "", 'items' );
109                     my $localmarcitem=Item2Marc($itemdata);
110                     UpdateMarcWith($marcitem,$localmarcitem);
111                     eval{my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($localmarcitem,$itemdata->{biblionumber},$itemnumber)};
112                 }
113             }
114     }
115     # If we have a reasonable amount of items, we display them
116     if (scalar(@itemnumbers) <= 1000) {
117         $items_display_hashref=BuildItemsData(@itemnumbers);
118     } else {
119         # Else, we only display the barcode
120         my @simple_items_display = map {{ itemnumber => $_, barcode => GetBarcodeFromItemnumber($_), biblionumber => GetBiblionumberFromItemnumber($_) }} @itemnumbers;
121         $template->param("simple_items_display" => \@simple_items_display);
122     }
123 }
124
125 #
126 #-------------------------------------------------------------------------------
127 # build screen with existing items. and "new" one
128 #-------------------------------------------------------------------------------
129
130 if ($op eq "show"){
131         my $filefh = $input->upload('uploadfile');
132         my $filecontent = $input->param('filecontent');
133         my @notfoundbarcodes;
134
135     my @contentlist;
136     if ($filefh){
137         while (my $content=<$filefh>){
138             chomp $content;
139             push @contentlist, $content if $content;
140         }
141
142         switch ($filecontent) {
143             case "barcode_file" {
144                 foreach my $barcode (@contentlist) {
145
146                     my $itemnumber = GetItemnumberFromBarcode($barcode);
147                     if ($itemnumber) {
148                         push @itemnumbers,$itemnumber;
149                     } else {
150                         push @notfoundbarcodes, $barcode;
151                     }
152                 }
153
154             }
155
156             case "itemid_file" {
157                 @itemnumbers = @contentlist;
158             }
159         }
160     } else {
161        if ( my $list=$input->param('barcodelist')){
162         push my @barcodelist, split(/\s\n/, $list);
163
164         foreach my $barcode (@barcodelist) {
165
166             my $itemnumber = GetItemnumberFromBarcode($barcode);
167             if ($itemnumber) {
168                 push @itemnumbers,$itemnumber;
169             } else {
170                 push @notfoundbarcodes, $barcode;
171             }
172         }
173
174     }
175 }
176     # Only display the items if there are no more than 1000
177     if (scalar(@itemnumbers) <= 1000) {
178         $items_display_hashref=BuildItemsData(@itemnumbers);
179     } else {
180         $template->param("too_many_items" => scalar(@itemnumbers));
181         # Even if we do not display the items, we need the itemnumbers
182         my @itemnumbers_hashref = map {{itemnumber => $_}} @itemnumbers;
183         $template->param("itemnumbers_hashref" => \@itemnumbers_hashref);
184     }
185 # now, build the item form for entering a new item
186 my @loop_data =();
187 my $i=0;
188 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
189
190 my $branches = GetBranchesLoop();  # build once ahead of time, instead of multiple times later.
191
192 # Adding a default choice, in case the user does not want to modify the branch
193 my @nochange_branch = { branchname => '', value => '', selected => 1 };
194 unshift (@$branches, @nochange_branch);
195
196 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
197
198
199 foreach my $tag (sort keys %{$tagslib}) {
200     # loop through each subfield
201     foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
202         next if subfield_is_koha_internal_p($subfield);
203         next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
204         # barcode and stocknumber are not meant to be batch-modified
205         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
206         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
207         my %subfield_data;
208  
209         my $index_subfield = int(rand(1000000)); 
210         if ($subfield eq '@'){
211             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
212         } else {
213             $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
214         }
215         $subfield_data{tag}        = $tag;
216         $subfield_data{subfield}   = $subfield;
217         $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
218     #   $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
219         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
220         $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
221         $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
222         my ($x,$value);
223         $value =~ s/"/&quot;/g;
224         unless ($value) {
225             $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
226             # get today date & replace YYYY, MM, DD if provided in the default value
227             my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
228             $value =~ s/YYYY/$year/g;
229             $value =~ s/MM/$month/g;
230             $value =~ s/DD/$day/g;
231         }
232         $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
233         # testing branch value if IndependantBranches.
234
235         my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
236         my $attributes          = qq($attributes_no_value value="$value" );
237
238         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
239         my @authorised_values;
240         my %authorised_lib;
241         # builds list, depending on authorised value...
242   
243         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
244             foreach my $thisbranch (@$branches) {
245                 push @authorised_values, $thisbranch->{value};
246                 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
247                 $value = $thisbranch->{value} if $thisbranch->{selected};
248             }
249         }
250         elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
251             push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
252             my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
253             $sth->execute;
254             while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
255                 push @authorised_values, $itemtype;
256                 $authorised_lib{$itemtype} = $description;
257             }
258
259           #---- class_sources
260       }
261       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
262           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
263             
264           my $class_sources = GetClassSources();
265           my $default_source = C4::Context->preference("DefaultClassificationSource");
266           
267           foreach my $class_source (sort keys %$class_sources) {
268               next unless $class_sources->{$class_source}->{'used'} or
269                           ($value and $class_source eq $value)      or
270                           ($class_source eq $default_source);
271               push @authorised_values, $class_source;
272               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
273           }
274                   $value = $default_source unless ($value);
275
276           #---- "true" authorised value
277       }
278       else {
279           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
280           $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
281           while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
282               push @authorised_values, $value;
283               $authorised_lib{$value} = $lib;
284           }
285       }
286       $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
287           -name     => "field_value",
288           -values   => \@authorised_values,
289           -default  => $value,
290           -labels   => \%authorised_lib,
291           -override => 1,
292           -size     => 1,
293           -multiple => 0,
294           -tabindex => 1,
295           -id       => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
296           -class    => "input_marceditor",
297       );
298     # it's a thesaurus / authority field
299     }
300     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
301         $subfield_data{marc_value} = "<input type=\"text\" $attributes />
302             <a href=\"#\" class=\"buttonDot\"
303                 onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$tagslib->{$tag}->{$subfield}->{authtypecode}."&index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
304     ";
305     # it's a plugin field
306     }
307     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
308         # opening plugin
309         my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
310         if (do $plugin) {
311                         my $temp;
312             my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
313             my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
314             $subfield_data{marc_value} = qq[<input $attributes
315                 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
316                  onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
317                 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
318                 $javascript];
319         } else {
320             warn "Plugin Failed: $plugin";
321             $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
322         }
323     }
324     elsif ( $tag eq '' ) {       # it's an hidden field
325         $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
326     }
327     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
328         $subfield_data{marc_value} = qq(<input type="text" $attributes />);
329     }
330     elsif ( length($value) > 100
331             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
332                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
333             or (C4::Context->preference("marcflavour") eq "MARC21"  and
334                   500 <= $tag && $tag < 600                     )
335           ) {
336         # oversize field (textarea)
337         $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
338     } else {
339         # it's a standard field
340          $subfield_data{marc_value} = "<input $attributes />";
341     }
342 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
343     push (@loop_data, \%subfield_data);
344     $i++
345   }
346 } # -- End foreach tag
347
348
349     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
350     $template->param(item => \@loop_data);
351     if (@notfoundbarcodes) { 
352         my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
353         $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
354     }
355     $nextop="action"
356 } # -- End action="show"
357
358 $template->param(%$items_display_hashref) if $items_display_hashref;
359 $template->param(
360     op      => $nextop,
361     $op => 1,
362 );
363
364 if ($op eq "action") {
365
366     #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
367
368     $template->param(
369         not_deleted_items => $not_deleted_items,
370         deleted_items => $deleted_items,
371         not_deleted_loop => \@not_deleted 
372     );
373 }
374
375 foreach my $error (@errors) {
376     $template->param($error => 1);
377 }
378 output_html_with_http_headers $input, $cookie, $template->output;
379 exit;
380
381
382 # ---------------- Functions
383
384 sub BuildItemsData{
385         my @itemnumbers=@_;
386                 # now, build existiing item list
387                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
388                 my @big_array;
389                 #---- finds where items.itemnumber is stored
390                 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
391                 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
392                 foreach my $itemnumber (@itemnumbers){
393                         my $itemdata=GetItem($itemnumber);
394                         my $itemmarc=Item2Marc($itemdata);
395                         my %this_row;
396                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
397                                 # loop through each subfield
398                                 if (my $itembranchcode=$field->subfield($branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
399                                                 #verifying rights
400                                                 my $userenv = C4::Context->userenv();
401                                                 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
402                                                                 $this_row{'nomod'}=1;
403                                                 }
404                                 }
405                                 my $tag=$field->tag();
406                                 foreach my $subfield ($field->subfields) {
407                                         my ($subfcode,$subfvalue)=@$subfield;
408                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
409                                                         && $tag        ne $itemtagfield 
410                                                         && $subfcode   ne $itemtagsubfield);
411
412                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
413                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
414                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
415                                                                         $subfcode, $subfvalue, '', $tagslib) 
416                                                                         || $subfvalue;
417                                         }
418
419                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
420                                 }
421                         }
422
423             # grab title, author, and ISBN to identify bib that the item
424             # belongs to in the display
425                         my $biblio=GetBiblioData($$itemdata{biblionumber});
426             $this_row{bibinfo} = join("\n", @$biblio{qw(title author ISBN)});
427
428                         if (%this_row) {
429                                 push(@big_array, \%this_row);
430                         }
431                 }
432                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
433
434                 # now, construct template !
435                 # First, the existing items for display
436                 my @item_value_loop;
437                 my @witnesscodessorted=sort keys %witness;
438                 for my $row ( @big_array ) {
439                         my %row_data;
440                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
441                         $row_data{item_value} = [ @item_fields ];
442                         $row_data{itemnumber} = $row->{itemnumber};
443                         #reporting this_row values
444                         $row_data{'nomod'} = $row->{'nomod'};
445             $row_data{bibinfo} = $row->{bibinfo};
446                         push(@item_value_loop,\%row_data);
447                 }
448                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
449
450         return { item_loop        => \@item_value_loop, item_header_loop => \@header_loop };
451 }
452
453 #BE WARN : it is not the general case 
454 # This function can be OK in the item marc record special case
455 # Where subfield is not repeated
456 # And where we are sure that field should correspond
457 # And $tag>10
458 sub UpdateMarcWith($$){
459   my ($marcfrom,$marcto)=@_;
460   #warn "FROM :",$marcfrom->as_formatted;
461         my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
462         my $fieldfrom=$marcfrom->field($itemtag);
463         my @fields_to=$marcto->field($itemtag);
464     foreach my $subfield ($fieldfrom->subfields()){
465                 foreach my $field_to_update (@fields_to){
466                                 $field_to_update->update($$subfield[0]=>$$subfield[1]) if ($$subfield[1]);
467                 }
468     }
469   #warn "TO edited:",$marcto->as_formatted;
470 }
471
472 sub find_value {
473     my ($tagfield,$insubfield,$record) = @_;
474     my $result;
475     my $indicator;
476     foreach my $field ($record->field($tagfield)) {
477         my @subfields = $field->subfields();
478         foreach my $subfield (@subfields) {
479             if (@$subfield[0] eq $insubfield) {
480                 $result .= @$subfield[1];
481                 $indicator = $field->indicator(1).$field->indicator(2);
482             }
483         }
484     }
485     return($indicator,$result);
486 }
487
488
489