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