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